-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgit.py
More file actions
1823 lines (1476 loc) · 70.9 KB
/
Copy pathgit.py
File metadata and controls
1823 lines (1476 loc) · 70.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Git connector for polling repository changes using GitPython.
"""
import asyncio
import logging
import os
import re
import shutil
import tempfile
from typing import TYPE_CHECKING, Any, ClassVar
from urllib.parse import urlparse
from ruamel.yaml import YAML
from opi.core.config import settings
from opi.utils.age import decrypt_password_smart_auto_sync
if TYPE_CHECKING:
from collections.abc import Callable, Coroutine
logger = logging.getLogger(__name__)
def _obfuscate_git_command(cmd_str: str) -> str:
"""
Obfuscate sensitive information in Git commands for logging.
Args:
cmd_str: The command string to obfuscate
Returns:
Command string with sensitive information replaced by asterisks
"""
# Pattern to match URLs with credentials (https://user:password@host or https://token@host)
# This handles various formats including GitHub personal access tokens (ghp_*)
url_pattern = r"https://([^:/@\s]+):([^@\s]+)@"
# Replace with obfuscated version
obfuscated = re.sub(url_pattern, r"https://\1:***@", cmd_str)
# Also handle the case where there's just a token without username (https://token@host)
token_pattern = r"https://([^@\s]*ghp_[^@\s]+)@"
obfuscated = re.sub(token_pattern, r"https://***@", obfuscated)
return obfuscated
class GitPushConflictError(RuntimeError):
"""Raised when a push fails because a rebase on the remote branch hit a
content conflict that git cannot resolve automatically.
Distinct from generic push failures so callers can react specifically (for
example by re-reading the remote state and re-applying their intended change
instead of failing terminally). See push_changes(reapply=...).
"""
class GitConnector:
"""Connector for interacting with Git repositories using GitPython."""
def __init__(
self,
repo_url: str,
repo_path: str | None = None,
working_dir: str | None = None,
branch: str = "main",
ssh_key_path: str | None = None,
password: str | None = None,
username: str | None = None,
project_name: str | None = None,
name: str | None = None,
):
"""
Initialize the Git connector.
Args:
repo_url: URL for the Git repository (git://, ssh://, https://, git@host:path)
repo_path: Path within the repository (e.g., "/subdir/project")
working_dir: Optional working directory for the local clone
branch: Branch name to monitor (without refs/heads/ prefix)
ssh_key_path: Optional path to SSH private key for authentication
password: Optional password for authentication (HTTPS, may be encrypted)
username: Optional username for authentication (HTTPS)
project_name: Optional project name for better error context reporting
"""
logger.debug(f"Initializing GitConnector {name} for project {project_name} from url {repo_url}")
# Set authentication properties
self.ssh_key_path = ssh_key_path
self.username = username
self.project_name = project_name
self.name = name
# Decrypt password immediately in constructor if provided
if password:
logger.debug("Decrypting password during initialization")
self._decrypted_password = decrypt_password_smart_auto_sync(password)
# Verify password was actually decrypted (not returned as original encrypted value)
if self._decrypted_password == password and (password.startswith(("base64+age:", "age:"))):
logger.error("Password decryption failed, still contains encryption prefix")
raise ValueError("Failed to decrypt password - Age decryption unsuccessful")
logger.debug("Password decryption completed during initialization")
else:
self._decrypted_password = None
# Store basic configuration
self.repo_url = repo_url
self.repo_path = self._normalize_repo_path(repo_path)
# Store the branch name without refs/heads/ prefix for consistency
if branch.startswith("refs/heads/"):
self.branch = branch[len("refs/heads/") :]
else:
self.branch = branch
logger.debug(f"Using branch: {self.branch}")
# Set up working directory
# TODO: rethink cleanup logic!
if working_dir:
self.__working_dir = working_dir
self.should_cleanup = False
logger.debug(f"Using provided working directory: {working_dir}")
else:
self.__working_dir = tempfile.mkdtemp(prefix="git-repo-", dir=settings.TEMP_DIR)
self.should_cleanup = True
logger.debug(f"Created temporary working directory: {self.__working_dir}")
self._repo_cloned = False
self._fetched_in_session = False # Track if we've fetched in this session
self._closed = False
self._git_user_configured = False # Track if git user has been configured
# Initialize URL parsing immediately (synchronous)
self.url_config = self._parse_git_url(self.repo_url)
logger.debug("GitConnector initialization completed")
async def __aenter__(self):
await self.ensure_repo_cloned()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.close()
return False
@property
def password(self) -> str | None:
"""Get the decrypted password."""
return self._decrypted_password
@property
def repo_url_with_path(self) -> str:
"""Get the repository URL with credentials embedded for HTTPS URLs."""
return self._construct_repo_url_with_credentials()
def _parse_git_url(self, url: str) -> dict[str, Any]:
"""
Parse a Git URL and return connection details.
Supports:
- git://host:port/path (Git daemon, no auth)
- ssh://user@host:port/path (SSH with auth)
- git@host:path (SSH shorthand)
- https://host/path (HTTPS)
Args:
url: Git URL to parse
Returns:
Dict with keys: scheme, host, port, user, path, needs_auth
"""
parsed = urlparse(url)
if parsed.scheme == "git":
# Git daemon protocol - no authentication
return {
"scheme": "git",
"host": parsed.hostname,
"port": parsed.port or 9418, # Default git daemon port
"user": None,
"path": parsed.path,
"needs_auth": False,
}
elif parsed.scheme == "ssh":
# ssh:// format
return {
"scheme": "ssh",
"host": parsed.hostname,
"port": parsed.port or 22,
"user": parsed.username or "git",
"path": parsed.path,
"needs_auth": True,
}
elif parsed.scheme in ["http", "https"]:
# HTTP/HTTPS protocol
return {
"scheme": parsed.scheme,
"host": parsed.hostname,
"port": parsed.port or (443 if parsed.scheme == "https" else 80),
"user": parsed.username,
"path": parsed.path,
"needs_auth": bool(parsed.username or self.password),
}
elif not parsed.scheme and "@" in url and ":" in url:
# SSH shorthand format: git@host:path
user_host, path = url.split(":", 1)
if "@" in user_host:
user, host = user_host.split("@", 1)
else:
user, host = None, user_host
return {"scheme": "ssh", "host": host, "port": 22, "user": user or "git", "path": path, "needs_auth": True}
else:
raise ValueError(f"Unsupported Git URL format: {url}")
def _normalize_repo_path(self, repo_path: str | None) -> str:
"""
Normalize repository path to handle different configurations.
Args:
repo_path: Raw repository path from configuration
Returns:
Normalized repository path
"""
if not repo_path:
# None or empty string means root directory
return "/"
# Strip whitespace
repo_path = repo_path.strip()
if repo_path in ("", "."):
# Empty string or "." means current/root directory
return "/"
# Ensure path starts with "/" for consistency
if not repo_path.startswith("/"):
repo_path = f"/{repo_path}"
# Ensure path doesn't end with "/" unless it's just "/"
if repo_path != "/" and repo_path.endswith("/"):
repo_path = repo_path.rstrip("/")
logger.debug(f"Normalized repo path: '{repo_path}'")
return repo_path
def _construct_repo_url_with_credentials(self) -> str:
"""
Construct the repository URL with embedded credentials for HTTPS URLs.
Returns:
Repository URL with credentials and path
"""
base_url = self.repo_url
# For HTTPS URLs, embed credentials if provided
if (
self.url_config
and self.url_config.get("scheme") in ("https", "http")
and (self.username or self._decrypted_password)
):
from urllib.parse import urlparse, urlunparse
parsed = urlparse(self.repo_url)
# Extract existing username from URL if present
existing_username = parsed.username
# Use provided credentials or fall back to existing ones
username = self.username or existing_username
# Use decrypted password if available, otherwise don't embed credentials
password = self._decrypted_password
# Only embed credentials if both username and password are valid strings
if username and password and isinstance(username, str) and isinstance(password, str):
# Construct new netloc with credentials
netloc = f"{username}:{password}@{parsed.hostname}"
if parsed.port:
netloc += f":{parsed.port}"
# Reconstruct URL with credentials
base_url = urlunparse(
(parsed.scheme, netloc, parsed.path, parsed.params, parsed.query, parsed.fragment)
)
# Return the base URL without the repo path
# The repo path is used after cloning to navigate to subdirectories
return base_url
@property
def ssh_port(self) -> int:
"""Get the SSH port from the parsed URL config."""
if self.url_config and self.url_config.get("scheme") == "ssh":
return self.url_config.get("port", 22)
return 22
async def _configure_git_user(self) -> None:
"""
Configure git user identity for commits.
This method sets up the git user.name and user.email configuration
required for making commits.
Only runs once per GitConnector instance.
"""
if self._git_user_configured:
logger.debug("Git user already configured, skipping")
return
# Configure git user identity for commits
config_name_cmd = ["config", "user.name", "Operations Manager"]
stdout, stderr, code = await self._run_git_command(config_name_cmd, cwd=self.__working_dir)
if code != 0:
logger.warning(f"Failed to configure git user name: {stderr}")
config_email_cmd = ["config", "user.email", "operations-manager@example.com"]
stdout, stderr, code = await self._run_git_command(config_email_cmd, cwd=self.__working_dir)
if code != 0:
logger.warning(f"Failed to configure git user email: {stderr}")
self._git_user_configured = True
logger.debug("Git user identity configured successfully")
async def _run_git_command(
self, args: list[str], env: dict[str, str] | None = None, cwd: str | None = None
) -> tuple[str, str, int]:
"""
Run a Git command directly with subprocess.
This is a lightweight alternative to cloning the full repository.
Args:
args: List of Git command arguments
env: Optional environment variables
cwd: Optional working directory
Returns:
Tuple of (stdout, stderr, return_code)
"""
cmd = ["git", *args]
cmd_str = " ".join(cmd)
working_dir = cwd or self.__working_dir
logger.debug(f"Running Git command: {_obfuscate_git_command(cmd_str)} in {working_dir}")
# Set up environment
cmd_env = os.environ.copy()
if env:
cmd_env.update(env)
# Configure SSH if using SSH URL and credentials are provided
if (
self.url_config
and self.url_config.get("needs_auth")
and self.url_config.get("scheme") == "ssh"
and self.ssh_key_path
):
ssh_cmd = f"ssh -i {self.ssh_key_path}"
# Add port if not default
port = self.url_config.get("port", 22)
if port != 22:
ssh_cmd += f" -p {port}"
# Add options for StrictHostKeyChecking
ssh_cmd += " -o StrictHostKeyChecking=no"
logger.debug(f"Using SSH command: {ssh_cmd}")
cmd_env["GIT_SSH_COMMAND"] = ssh_cmd
# Create process
from opi.core.metrics import track_subprocess_memory
process = await asyncio.create_subprocess_exec(
*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=cmd_env, cwd=working_dir
)
# Wait for command to complete, tracking memory delta
async with track_subprocess_memory("git"):
stdout, stderr = await process.communicate()
stdout_str = stdout.decode("utf-8").strip()
stderr_str = stderr.decode("utf-8").strip()
if process.returncode != 0:
# Include git server context in error message
server_info = self._get_server_context()
logger.debug(f"Git command failed with code {process.returncode} for {server_info}: {stderr_str}")
else:
logger.debug("Git command succeeded")
return stdout_str, stderr_str, process.returncode or 0
def _check_git_command_result(self, code: int, stderr: str, operation: str) -> None:
"""
Check git command result and raise RuntimeError if failed.
Args:
code: Return code from git command
stderr: Standard error output
operation: Description of the operation (e.g., "stage all changes")
Raises:
RuntimeError: If git command failed
"""
if code != 0:
server_info = self._get_server_context()
error_msg = f"Failed to {operation} on {server_info}: {stderr}"
logger.error(error_msg)
raise RuntimeError(error_msg)
def _get_server_context(self) -> str:
"""
Get contextual information about the git server for error reporting.
Returns:
String describing the git server context (host, repository, user, project)
"""
try:
context_parts = []
# Add project context if available
if self.project_name:
context_parts.append(f"project={self.project_name}")
if self.url_config:
host = self.url_config.get("host", "unknown-host")
port = self.url_config.get("port")
scheme = self.url_config.get("scheme", "unknown")
# Build server description
server_desc = f"{scheme}://{host}"
if port and ((scheme == "ssh" and port != 22) or (scheme == "https" and port != 443)):
server_desc += f":{port}"
context_parts.append(f"server={server_desc}")
if self.username:
context_parts.append(f"user={self.username}")
# Add obfuscated repo path for context
repo_path = getattr(self, "repo_path", "")
if repo_path and repo_path != "/":
context_parts.append(f"path={repo_path}")
return f"git [{', '.join(context_parts)}]"
else:
# Fallback for unparsed URLs
obfuscated_url = _obfuscate_git_command(self.repo_url)
context_parts.append(f"server={obfuscated_url}")
return f"git [{', '.join(context_parts)}]"
except Exception:
# If anything goes wrong, return a simple fallback
project_part = f" for project {self.project_name}" if self.project_name else ""
return f"git server [URL: {_obfuscate_git_command(self.repo_url)}]{project_part}"
# Dictionary to cache Git references for each repository URL
_ref_cache: ClassVar[dict[str, dict[str, str]]] = {}
async def get_remote_refs(self) -> dict[str, str]:
"""
Get all remote references from the Git repository.
Returns:
Dictionary mapping reference names to commit hashes
"""
logger.debug(f"Fetching remote refs from: {self.repo_url_with_path}")
# Use git ls-remote to get all references
cmd = ["ls-remote", self.repo_url_with_path]
stdout, stderr, code = await self._run_git_command(cmd)
if code != 0:
server_info = self._get_server_context()
error_msg = f"Failed to fetch refs from {server_info}: {stderr}"
logger.error(error_msg)
raise RuntimeError(error_msg)
refs = {}
for line in stdout.splitlines():
if not line.strip():
continue
parts = line.split(maxsplit=1)
if len(parts) == 2:
commit_hash, ref_name = parts
refs[ref_name] = commit_hash
logger.debug(f"Found ref: {ref_name} -> {commit_hash}")
# Cache the refs for this repository
GitConnector._ref_cache[self.repo_url] = refs
logger.info(f"Found {len(refs)} references")
return refs
async def get_latest_commit_hash(self) -> str:
"""
Get the latest commit hash for the branch.
Returns:
Latest commit hash
"""
logger.debug(f"Getting latest commit hash for branch: {self.branch}")
# Get all remote refs
refs = await self.get_remote_refs()
# Only check refs that start with refs/heads/
branch_refs = {ref: hash_val for ref, hash_val in refs.items() if ref.startswith("refs/heads/")}
logger.debug(f"Found {len(branch_refs)} branch references")
# Look for the specified branch using the branch name from config
branch_ref = f"refs/heads/{self.branch}"
if branch_ref in branch_refs:
commit_hash = branch_refs[branch_ref]
logger.debug(f"Latest commit hash for {branch_ref}: {commit_hash}")
return commit_hash
# Check if HEAD is available and pointing to our branch
if "HEAD" in refs:
head_hash = refs["HEAD"]
logger.debug(f"HEAD hash: {head_hash}")
# Check if any branch matches the HEAD hash
for ref, hash_val in branch_refs.items():
if hash_val == head_hash:
logger.debug(f"HEAD is pointing to branch: {ref}")
if ref == branch_ref:
return head_hash
# If we can't find a better match, return HEAD
logger.warning(f"Branch {self.branch} not found, using HEAD")
return head_hash
# If we can't find the branch or HEAD, raise an error
error_msg = f"No commit hash found for branch {self.branch}"
logger.error(error_msg)
raise RuntimeError(error_msg)
async def get_local_commit_hash(self) -> str:
"""
Get the current commit hash from the local clone.
Returns:
Current local commit hash
"""
logger.debug("Getting local commit hash")
# Use git rev-parse HEAD to get the current commit hash
cmd = ["rev-parse", "HEAD"]
stdout, stderr, code = await self._run_git_command(cmd)
if code != 0:
error_msg = f"Failed to get local commit hash: {stderr}"
logger.error(error_msg)
raise RuntimeError(error_msg)
commit_hash = stdout.strip()
logger.debug(f"Local commit hash: {commit_hash}")
return commit_hash
async def ensure_repo_cloned(self) -> None:
"""
Ensure the repository is cloned for operations that require local access.
This handles both existing repositories and empty repositories that need branch creation.
Uses intelligent branch detection to avoid clone failures.
"""
if self._repo_cloned:
# Repo already cloned, fetch updates only once per session
if not self._fetched_in_session:
await self._fetch_latest()
self._fetched_in_session = True
return
logger.debug(f"Cloning repository to {self.__working_dir}")
try:
# Try to detect the remote default branch first
remote_default_branch = await self._get_remote_default_branch()
target_branch = self.branch
# If our configured branch doesn't exist but there's a remote default, try that first
if remote_default_branch != self.branch:
logger.debug(
f"Detected remote default branch '{remote_default_branch}', configured branch is '{self.branch}'"
)
# Strategy 1: Try cloning with the configured branch
clone_cmd = [
"clone",
"--single-branch",
"--branch",
target_branch,
"--depth",
"1",
self.repo_url_with_path,
".", # Clone to current working directory
]
stdout, stderr, code = await self._run_git_command(clone_cmd, cwd=self.__working_dir)
if code != 0:
logger.debug(f"Clone with branch '{target_branch}' failed: {stderr}")
# Strategy 2: If configured branch fails and differs from remote default, try remote default
if remote_default_branch != target_branch:
logger.debug(f"Trying clone with remote default branch: {remote_default_branch}")
clone_cmd_default = [
"clone",
"--single-branch",
"--branch",
remote_default_branch,
"--depth",
"1",
self.repo_url_with_path,
".",
]
stdout, stderr, code = await self._run_git_command(clone_cmd_default, cwd=self.__working_dir)
if code == 0:
# Successfully cloned with remote default, now ensure correct branch
await self._ensure_correct_branch()
self._repo_cloned = True
logger.debug(
f"Repository cloned successfully using remote default branch: {remote_default_branch}"
)
return
# Strategy 3: If specific branch cloning fails, try cloning without branch specification
logger.debug("Trying clone without branch specification")
clone_cmd_no_branch = ["clone", "--depth", "1", self.repo_url_with_path, "."]
stdout, stderr, code = await self._run_git_command(clone_cmd_no_branch, cwd=self.__working_dir)
if code != 0:
# Strategy 4: Try cloning without depth restriction (for completely empty repos)
logger.debug("Trying clone without depth restriction for empty repository")
clone_cmd_no_depth = ["clone", self.repo_url_with_path, "."]
stdout, stderr, code = await self._run_git_command(clone_cmd_no_depth, cwd=self.__working_dir)
if code != 0:
error_msg = f"Failed to clone repository with all strategies. Last error: {stderr}"
logger.error(error_msg)
raise RuntimeError(error_msg)
# Repository cloned with default branch, now handle branch creation/switching
await self._ensure_correct_branch()
# Mark repository as cloned
self._repo_cloned = True
self._fetched_in_session = True # Mark as fetched since we just cloned
logger.debug(f"Repository cloned successfully on branch: {self.branch}")
except Exception as e:
logger.error(f"Failed to clone repository: {e}")
raise
async def _get_remote_default_branch(self) -> str:
"""
Get the default branch of the remote repository.
Returns the remote default branch name or falls back to configured branch.
"""
try:
# Use git ls-remote to get the default branch without cloning
ls_remote_cmd = ["ls-remote", "--symref", self.repo_url_with_path, "HEAD"]
stdout, stderr, code = await self._run_git_command(ls_remote_cmd)
if code == 0 and stdout:
# Parse output to find the default branch
# Format: "ref: refs/heads/main HEAD"
for line in stdout.strip().split("\n"):
if line.startswith("ref: refs/heads/"):
default_branch = line.split("refs/heads/")[1].split("\t")[0]
logger.debug(f"Detected remote default branch: {default_branch}")
return default_branch
logger.debug(f"Could not detect remote default branch, using configured: {self.branch}")
return self.branch
except Exception as e:
logger.debug(f"Error detecting remote default branch: {e}, using configured: {self.branch}")
return self.branch
async def _ensure_correct_branch(self) -> None:
"""
Ensure we're on the correct branch, creating it if necessary.
This handles empty repositories or repositories without the desired branch.
"""
logger.debug(f"Ensuring correct branch: {self.branch}")
try:
# Check if the desired branch exists locally
list_cmd = ["branch", "--list", self.branch]
stdout, stderr, code = await self._run_git_command(list_cmd, cwd=self.__working_dir)
branch_exists_locally = code == 0 and self.branch in stdout
if branch_exists_locally:
# Branch exists, just switch to it
checkout_cmd = ["checkout", self.branch]
stdout, stderr, code = await self._run_git_command(checkout_cmd, cwd=self.__working_dir)
if code != 0:
logger.warning(f"Failed to checkout existing branch {self.branch}: {stderr}")
else:
# Check if we have any commits (repository might be empty)
log_cmd = ["log", "--oneline", "-1"]
stdout, stderr, code = await self._run_git_command(log_cmd, cwd=self.__working_dir)
if code != 0:
# Repository is empty, create initial commit and branch
logger.debug("Repository is empty, creating initial setup")
# Create an initial empty commit
commit_cmd = ["commit", "--allow-empty", "--no-verify", "-m", "Initial commit"]
stdout, stderr, code = await self._run_git_command(commit_cmd, cwd=self.__working_dir)
if code != 0:
logger.warning(f"Failed to create initial commit: {stderr}")
# Rename the current branch to the desired branch name
branch_cmd = ["branch", "-m", self.branch]
stdout, stderr, code = await self._run_git_command(branch_cmd, cwd=self.__working_dir)
if code != 0:
logger.warning(f"Failed to rename branch to {self.branch}: {stderr}")
# Push the branch to establish it on the remote
push_cmd = ["push", "-u", "origin", self.branch]
stdout, stderr, code = await self._run_git_command(push_cmd, cwd=self.__working_dir)
if code != 0:
logger.warning(f"Failed to push initial branch {self.branch}: {stderr}")
else:
logger.debug(f"Successfully pushed initial branch {self.branch} to remote")
else:
# Repository has commits but no desired branch, create new branch
checkout_cmd = ["checkout", "-b", self.branch]
stdout, stderr, code = await self._run_git_command(checkout_cmd, cwd=self.__working_dir)
if code != 0:
logger.warning(f"Failed to create new branch {self.branch}: {stderr}")
logger.debug(f"Successfully ensured branch: {self.branch}")
except Exception as e:
logger.warning(f"Error ensuring correct branch: {e}")
# Don't raise here, as the repository might still be usable
async def _fetch_latest(self) -> None:
"""Fetch the latest changes from the repository."""
if not self._repo_cloned:
await self.ensure_repo_cloned()
return
logger.debug(f"Fetching latest changes for branch: {self.branch}")
try:
# Use git fetch command directly
fetch_cmd = ["fetch", "origin", self.branch]
stdout, stderr, code = await self._run_git_command(fetch_cmd, cwd=self.__working_dir)
self._check_git_command_result(code, stderr, "fetch latest changes")
logger.debug("Latest changes fetched successfully")
self._fetched_in_session = True
except Exception as e:
server_info = self._get_server_context()
logger.error(f"Failed to fetch latest changes from {server_info}: {e}")
raise
async def _pull_latest(self) -> None:
"""Pull the latest changes from the repository."""
if not self._repo_cloned:
await self.ensure_repo_cloned()
return
logger.debug(f"Pulling latest changes for branch: {self.branch}")
try:
# Use git pull command directly
pull_cmd = ["pull", "origin", self.branch]
stdout, stderr, code = await self._run_git_command(pull_cmd, cwd=self.__working_dir)
self._check_git_command_result(code, stderr, "pull latest changes")
logger.debug("Latest changes pulled successfully")
except Exception as e:
server_info = self._get_server_context()
logger.error(f"Failed to pull latest changes from {server_info}: {e}")
raise
async def _rebase_on_remote(self, branch: str | None = None) -> bool:
"""
Rebase local commits on top of remote branch.
This is used to handle non-fast-forward push rejections by rebasing
local commits on top of any new remote commits.
Args:
branch: Branch to rebase on (defaults to configured branch)
Returns:
True if rebase succeeded, False if there were conflicts
Raises:
RuntimeError: If rebase fails for reasons other than conflicts
"""
target_branch = branch or self.branch
logger.info(f"Rebasing local commits on origin/{target_branch}")
try:
# First fetch the latest from remote
fetch_cmd = ["fetch", "origin", target_branch]
stdout, stderr, code = await self._run_git_command(fetch_cmd, cwd=self.__working_dir)
self._check_git_command_result(code, stderr, f"fetch origin/{target_branch}")
# Rebase on the remote branch
rebase_cmd = ["rebase", f"origin/{target_branch}"]
stdout, stderr, code = await self._run_git_command(rebase_cmd, cwd=self.__working_dir)
if code != 0:
# Check if this is a conflict
if "CONFLICT" in stderr or "conflict" in stderr.lower():
logger.error(f"Rebase conflict detected: {stderr}")
# Abort the rebase to leave repo in clean state
abort_cmd = ["rebase", "--abort"]
await self._run_git_command(abort_cmd, cwd=self.__working_dir)
return False
else:
self._check_git_command_result(code, stderr, f"rebase on origin/{target_branch}")
logger.info(f"Successfully rebased on origin/{target_branch}")
return True
except Exception as e:
server_info = self._get_server_context()
logger.error(f"Failed to rebase on {server_info}: {e}")
raise
async def _reset_to_remote(self, branch: str | None = None) -> None:
"""Discard local commits and working-tree changes, hard-resetting to
origin/<branch>.
Used to recover from an unresolvable rebase conflict before re-applying an
intended change on top of the current remote state.
"""
target_branch = branch or self.branch
fetch_cmd = ["fetch", "origin", target_branch]
_, stderr, code = await self._run_git_command(fetch_cmd, cwd=self.__working_dir)
self._check_git_command_result(code, stderr, f"fetch origin/{target_branch}")
reset_cmd = ["reset", "--hard", f"origin/{target_branch}"]
_, stderr, code = await self._run_git_command(reset_cmd, cwd=self.__working_dir)
self._check_git_command_result(code, stderr, f"reset --hard origin/{target_branch}")
logger.info(f"Hard-reset working tree to origin/{target_branch}")
async def file_changed_between_commits(self, file_path: str, old_commit: str, new_commit: str) -> bool:
"""
Check if a specific file was changed between commits using git diff.
Args:
file_path: Path to the file to check
old_commit: Old commit hash
new_commit: New commit hash
Returns:
True if the file changed, False otherwise
"""
logger.debug(f"Checking if {file_path} changed between {old_commit} and {new_commit}")
# Combine repo path and file path
full_path = self._get_full_path(file_path)
# Use git diff --quiet to check if the file changed between commits
# Exit code 0 means no changes, 1 means file changed
diff_cmd = [
"diff",
"--quiet", # Don't produce output, just exit with status code
old_commit,
new_commit,
"--",
full_path,
]
_, stderr, code = await self._run_git_command(diff_cmd)
if code == 0:
# Exit code 0 means no changes
logger.debug(f"File {full_path} was not changed between commits")
return False
elif code == 1:
# Exit code 1 means changes were detected
logger.debug(f"File {full_path} was changed between commits")
return True
else:
# Any other exit code indicates an error
logger.error(f"Failed to check if file changed: {stderr}")
return False
def _get_full_path(self, file_path: str) -> str:
"""Combine repo path and file path."""
if not self.repo_path or self.repo_path == "/":
return file_path.lstrip("/")
file_path = file_path.removeprefix("/")
if self.repo_path.endswith("/"):
return f"{self.repo_path}{file_path}"
else:
return f"{self.repo_path}/{file_path}"
def get_absolute_file_path(self, file_path: str) -> str:
"""
Get the absolute path to a file in the local repository.
Args:
file_path: Path to the file relative to the repository root
Returns:
Absolute path to the file
"""
relative_path = self._get_full_path(file_path)
return os.path.join(self.__working_dir, relative_path)
async def read_file_content(self, file_path: str) -> str:
"""
Read content of a file directly from the local repository.
Args:
file_path: Path to the file in the repository
Returns:
Content of the file as a string
"""
logger.debug(f"Reading file content for {file_path}")
# Ensure the repository is cloned
await self.ensure_repo_cloned()
# Get the absolute path to the file
abs_path = self.get_absolute_file_path(file_path)
try:
with open(abs_path) as f:
content = f.read()
logger.debug(f"Read file content, length: {len(content)}")
return content
except Exception as e:
error_msg = f"Failed to read file {abs_path}: {e}"
logger.error(error_msg)
raise
async def parse_yaml_content(self, content: str) -> dict:
"""
Parse YAML content into a Python dictionary.
Args:
content: YAML content as a string
Returns:
Parsed YAML as a dictionary
"""
logger.debug(f"Parsing YAML content of length {len(content)}")
try:
yaml = YAML()
result = yaml.load(content)
logger.debug("YAML parsing successful")
return result
except Exception as e:
error_msg = f"Error parsing YAML: {e}"
logger.error(error_msg)
raise
async def clone(self) -> None:
"""
Clone the repository. This is an atomic operation that ensures the repository is ready for file operations.
"""
logger.debug("Cloning repository (atomic operation)")
await self.ensure_repo_cloned()
logger.debug("Repository cloned successfully")
async def get_working_dir(self):
await self.ensure_repo_cloned()
return self.__working_dir
async def add_file(self, file_path: str, content: str, overwrite: bool = True) -> None:
"""
Add a file to the git staging area with specified content.
Args:
file_path: Path to the file relative to the repository root
content: Content to write to the file
overwrite: If True, overwrite existing file; if False, fail if file exists
"""
logger.debug(f"Adding file to staging: {file_path} (overwrite={overwrite})")
# Ensure the repository is cloned
await self.ensure_repo_cloned()
# Get the absolute path to the file
abs_path = self.get_absolute_file_path(file_path)