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
"""Local branch listing and checkout for the pgt TUI."""
from __future__ import annotations
from pygit2 import Commit, GitError, Repository, reference_is_valid_name
def current_branch_name(repo: Repository) -> str:
if repo.head_is_detached:
return "(detached)"
return repo.head.shorthand or "(detached)"
def list_local_branches(repo: Repository) -> list[str]:
return sorted(repo.branches.local)
def checkout_branch(repo: Repository, branch: str) -> tuple[bool, str]:
try:
repo.checkout(f"refs/heads/{branch}")
except (GitError, KeyError) as exc:
message = str(exc).strip()
return False, message or "Checkout failed"
return True, ""
def create_branch_from_current(repo: Repository, name: str) -> tuple[bool, str]:
branch = name.strip()
if not branch:
return False, "Branch name is empty"
ref_name = f"refs/heads/{branch}"
if not reference_is_valid_name(ref_name):
return False, f"Invalid branch name: {branch}"
if branch in repo.branches.local:
return False, f"Branch already exists: {branch}"
try:
commit = repo.head.peel(Commit)
repo.branches.create(branch, commit)
repo.checkout(ref_name)
except GitError as exc:
message = str(exc).strip()
return False, message or "Failed to create branch"
return True, ""