Current branch and detached head handling

This commit is contained in:
Christos Choutouridis 2025-06-27 13:56:33 +03:00
parent 46390729a4
commit eebe11901d

View File

@ -90,18 +90,27 @@ def sync_repo(nick, from_entry, to_entry, use_mirror, dry_run=False):
else: else:
if not dry_run: if not dry_run:
try: try:
current_branch = subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=local_dir).decode().strip() try:
current_branch = subprocess.check_output(
["git", "symbolic-ref", "--short", "HEAD"],
cwd=local_dir,
stderr=subprocess.DEVNULL
).decode().strip()
except subprocess.CalledProcessError:
current_branch = None # detached HEAD
remotes = subprocess.check_output(["git", "branch", "-r"], cwd=local_dir).decode().splitlines() remotes = subprocess.check_output(["git", "branch", "-r"], cwd=local_dir).decode().splitlines()
for r in remotes: for r in remotes:
if f'{from_remote}/' in r and '->' not in r: if f'{from_remote}/' in r and '->' not in r:
branch = r.strip().split(f'{from_remote}/')[1] branch = r.strip().split(f'{from_remote}/')[1]
if branch == current_branch: if current_branch and branch == current_branch:
print(f"[INFO] Merging into current branch: {branch}")
try: try:
subprocess.run(["git", "checkout", f"{from_remote}/{branch}"], cwd=local_dir, check=True) subprocess.run(["git", "merge", f"{from_remote}/{branch}"], cwd=local_dir, check=True)
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError:
print(f"Warning: Could not update currently checked-out branch '{branch}' in {local_dir}. Possible uncommitted changes.") print(f"Warning: Could not merge changes into current branch '{branch}' in {local_dir}. Possibly due to local edits.")
else: else:
subprocess.run(["git", "branch", "-f", branch, f"{from_remote}/{branch}"], cwd=local_dir) subprocess.run(["git", "branch", "-f", branch, f"{from_remote}/{branch}"], cwd=local_dir, check=True)
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
print(f"Error: Failed to create or update tracking branches in {local_dir}\nMessage: {e}") print(f"Error: Failed to create or update tracking branches in {local_dir}\nMessage: {e}")
sys.exit(1) sys.exit(1)