| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
import os |
| 5 |
import subprocess |
| 6 |
from collections import OrderedDict |
| 7 |
|
| 8 |
from ._metadata import APP |
| 9 |
from ._without import without |
| 10 |
|
| 11 |
|
| 12 |
class GitException(Exception): |
| 13 |
pass |
| 14 |
|
| 15 |
|
| 16 |
class CheckoutFailed(GitException): |
| 17 |
pass |
| 18 |
|
| 19 |
|
| 20 |
class PullFailed(GitException): |
| 21 |
pass |
| 22 |
|
| 23 |
|
| 24 |
class MergeBaseFailed(GitException): |
| 25 |
pass |
| 26 |
|
| 27 |
|
| 28 |
class Git: |
| 29 |
_GIT = "git" |
| 30 |
_GIT_ENCODING = "utf-8" |
| 31 |
|
| 32 |
_APP_EMAIL = f"{APP}@localhost" |
| 33 |
_ARBITRARY_FIXED_DATETIME = "2005-12-21T00:00:00+00:00" |
| 34 |
_COMMIT_ENVIRON = { |
| 35 |
"GIT_AUTHOR_DATE": _ARBITRARY_FIXED_DATETIME, |
| 36 |
"GIT_AUTHOR_EMAIL": _APP_EMAIL, |
| 37 |
"GIT_AUTHOR_NAME": APP, |
| 38 |
"GIT_COMMITTER_DATE": _ARBITRARY_FIXED_DATETIME, |
| 39 |
"GIT_COMMITTER_EMAIL": _APP_EMAIL, |
| 40 |
"GIT_COMMITTER_NAME": APP, |
| 41 |
} |
| 42 |
|
| 43 |
def __init__(self, messenger, pretend, verbose, work_dir=None): |
| 44 |
self._messenger = messenger |
| 45 |
self._verbose = verbose |
| 46 |
self._pretend = pretend |
| 47 |
self._working_directory = work_dir |
| 48 |
|
| 49 |
@property |
| 50 |
def pretend(self): |
| 51 |
return self._pretend |
| 52 |
|
| 53 |
def _wrap_subprocess(self, subprocess_function, argv, is_write, pretend_result, env): |
| 54 |
pretend = is_write and self._pretend |
| 55 |
if self._verbose: |
| 56 |
comment = "skipped due to --dry-run" if pretend else "" |
| 57 |
display_argv = [a for a in argv if not a.startswith("--format=")] |
| 58 |
display_argv = without(["-c", "column.branch=plain"], display_argv) |
| 59 |
self._messenger.tell_command(display_argv, comment) |
| 60 |
if pretend: |
| 61 |
return pretend_result |
| 62 |
return subprocess_function(argv, cwd=self._working_directory, env=env) |
| 63 |
|
| 64 |
def _subprocess_check_output(self, argv, is_write, env=None): |
| 65 |
return self._wrap_subprocess( |
| 66 |
subprocess.check_output, argv=argv, is_write=is_write, pretend_result=b"", env=env |
| 67 |
) |
| 68 |
|
| 69 |
def _subprocess_check_call(self, argv, is_write, env=None): |
| 70 |
return self._wrap_subprocess( |
| 71 |
subprocess.check_call, argv=argv, is_write=is_write, pretend_result=0, env=env |
| 72 |
) |
| 73 |
|
| 74 |
@classmethod |
| 75 |
def _output_bytes_to_lines(cls, output_bytes) -> list[str]: |
| 76 |
text = output_bytes.decode(cls._GIT_ENCODING).rstrip() |
| 77 |
if not text: |
| 78 |
return [] |
| 79 |
return text.split("\n") |
| 80 |
|
| 81 |
def extract_git_config(self): |
| 82 |
argv = [self._GIT, "config", "--list", "--null"] |
| 83 |
output_bytes = self._subprocess_check_output(argv, is_write=False) |
| 84 |
key_newline_value_list = [ |
| 85 |
chunk.decode(self._GIT_ENCODING) for chunk in output_bytes.split(b"\0") |
| 86 |
] |
| 87 |
git_config = OrderedDict() |
| 88 |
for key_newline_value in key_newline_value_list: |
| 89 |
if not key_newline_value: |
| 90 |
continue |
| 91 |
|
| 92 |
try: |
| 93 |
key, value = key_newline_value.split("\n", 1) |
| 94 |
except ValueError: |
| 95 |
self._messenger.tell_info( |
| 96 |
f"Git config option {key_newline_value!r} lacks assignment of a value." |
| 97 |
) |
| 98 |
continue |
| 99 |
|
| 100 |
git_config[key] = value |
| 101 |
return git_config |
| 102 |
|
| 103 |
def find_remotes(self): |
| 104 |
argv = [self._GIT, "remote"] |
| 105 |
output_bytes = self._subprocess_check_output(argv, is_write=False) |
| 106 |
return self._output_bytes_to_lines(output_bytes) |
| 107 |
|
| 108 |
def _find_branches(self, extra_argv=None, strip_left: int = 2) -> list[str]: |
| 109 |
|
| 110 |
|
| 111 |
argv = [ |
| 112 |
self._GIT, |
| 113 |
"-c", |
| 114 |
"column.branch=plain", |
| 115 |
"branch", |
| 116 |
f"--format=%(refname:lstrip={strip_left})", |
| 117 |
] |
| 118 |
if extra_argv is not None: |
| 119 |
argv += extra_argv |
| 120 |
output_bytes = self._subprocess_check_output(argv, is_write=False) |
| 121 |
lines = self._output_bytes_to_lines(output_bytes) |
| 122 |
return [ |
| 123 |
line for line in lines if not line.endswith("/HEAD") and "HEAD detached at" not in line |
| 124 |
] |
| 125 |
|
| 126 |
def find_local_branches(self) -> list[str]: |
| 127 |
return self._find_branches() |
| 128 |
|
| 129 |
def find_all_branch_refs(self) -> list[str]: |
| 130 |
return self._find_branches(["--all"]) |
| 131 |
|
| 132 |
def find_all_branch_names(self) -> set[str]: |
| 133 |
branch_names = set() |
| 134 |
for line in self._find_branches(["--all"], strip_left=1): |
| 135 |
heads_or_remotes, *remainder = line.split("/") |
| 136 |
if heads_or_remotes == "heads": |
| 137 |
branch_name = "/".join(remainder) |
| 138 |
elif heads_or_remotes == "remotes": |
| 139 |
branch_name = "/".join(remainder[1:]) |
| 140 |
else: |
| 141 |
raise ValueError(f"Reference {line!r} not understood") |
| 142 |
branch_names.add(branch_name) |
| 143 |
return branch_names |
| 144 |
|
| 145 |
def find_remote_branches_at(self, remote_name) -> list[str]: |
| 146 |
assert remote_name |
| 147 |
extra_argv = ["--remote", "--list", f"{remote_name}/*"] |
| 148 |
return self._find_branches(extra_argv) |
| 149 |
|
| 150 |
def find_current_branch(self) -> str | None: |
| 151 |
|
| 152 |
|
| 153 |
argv = [self._GIT, "rev-parse", "--symbolic-full-name", "HEAD"] |
| 154 |
output_bytes = self._subprocess_check_output(argv, is_write=False) |
| 155 |
lines = self._output_bytes_to_lines(output_bytes) |
| 156 |
assert len(lines) == 1 |
| 157 |
|
| 158 |
expected_prefix = "refs/heads/" |
| 159 |
reference = lines[0] |
| 160 |
if not reference.startswith(expected_prefix): |
| 161 |
return None |
| 162 |
return reference[len(expected_prefix) :] |
| 163 |
|
| 164 |
def find_working_tree_branches(self) -> list[str | None]: |
| 165 |
argv = [self._GIT, "worktree", "list", "--porcelain"] |
| 166 |
output_bytes = self._subprocess_check_output(argv, is_write=False) |
| 167 |
lines = self._output_bytes_to_lines(output_bytes) |
| 168 |
|
| 169 |
detached_line_prefix = "detached" |
| 170 |
branch_line_prefix = "branch " |
| 171 |
branch_prefix = "refs/heads/" |
| 172 |
branch_names: list[str | None] = [] |
| 173 |
|
| 174 |
for line in lines: |
| 175 |
if line.startswith(detached_line_prefix): |
| 176 |
branch_names.append(None) |
| 177 |
elif line.startswith(branch_line_prefix): |
| 178 |
branch_name = line[len(branch_line_prefix) :] |
| 179 |
if branch_name.startswith(branch_prefix): |
| 180 |
branch_name = branch_name[len(branch_prefix) :] |
| 181 |
branch_names.append(branch_name) |
| 182 |
|
| 183 |
return branch_names |
| 184 |
|
| 185 |
def has_detached_heads(self) -> bool: |
| 186 |
return None in self.find_working_tree_branches() |
| 187 |
|
| 188 |
def _get_merged_branches_for(self, target_branch: str, remote: bool): |
| 189 |
extra_argv = [] |
| 190 |
if remote: |
| 191 |
extra_argv.append("--remote") |
| 192 |
extra_argv += [ |
| 193 |
"--merged", |
| 194 |
target_branch, |
| 195 |
] |
| 196 |
merged_branches = self._find_branches(extra_argv) |
| 197 |
return (branch for branch in merged_branches if branch != target_branch) |
| 198 |
|
| 199 |
def find_merged_local_branches_for(self, branch_name): |
| 200 |
return self._get_merged_branches_for(branch_name, remote=False) |
| 201 |
|
| 202 |
def find_merged_remote_branches_for(self, remote_name, branch_name): |
| 203 |
return self._get_merged_branches_for(f"{remote_name}/{branch_name}", remote=True) |
| 204 |
|
| 205 |
def delete_local_branches(self, branch_names, force=False): |
| 206 |
if not branch_names: |
| 207 |
return |
| 208 |
|
| 209 |
argv = [self._GIT, "branch", "--delete"] |
| 210 |
if force: |
| 211 |
argv.append("--force") |
| 212 |
argv += sorted(branch_names) |
| 213 |
|
| 214 |
self._subprocess_check_call(argv, is_write=True) |
| 215 |
|
| 216 |
def delete_remote_branches(self, branch_names, remote_name): |
| 217 |
if not branch_names: |
| 218 |
return |
| 219 |
remote_prefix = f"{remote_name}/" |
| 220 |
remote_branches_to_delete = [ |
| 221 |
"refs/heads/" + remote_slash_branch[len(remote_prefix) :] |
| 222 |
for remote_slash_branch in branch_names |
| 223 |
if remote_slash_branch.startswith(remote_prefix) |
| 224 |
] |
| 225 |
if not remote_branches_to_delete: |
| 226 |
return |
| 227 |
argv = [ |
| 228 |
self._GIT, |
| 229 |
"push", |
| 230 |
"--delete", |
| 231 |
"--force-with-lease", |
| 232 |
remote_name, |
| 233 |
] + remote_branches_to_delete |
| 234 |
|
| 235 |
self._subprocess_check_output(argv, is_write=True) |
| 236 |
|
| 237 |
def set_config(self, key, value): |
| 238 |
argv = [self._GIT, "config"] |
| 239 |
|
| 240 |
if value is None: |
| 241 |
argv += ["--unset", key] |
| 242 |
else: |
| 243 |
argv += [key, value] |
| 244 |
|
| 245 |
self._subprocess_check_output(argv, is_write=True) |
| 246 |
|
| 247 |
def update_and_prune_remote(self, remote_name: str) -> None: |
| 248 |
argv = [self._GIT, "remote", "update", "--prune", remote_name] |
| 249 |
self._subprocess_check_output(argv, is_write=True) |
| 250 |
|
| 251 |
def checkout(self, committish: str) -> None: |
| 252 |
argv = [self._GIT, "checkout", "-q"] |
| 253 |
argv.append(committish) |
| 254 |
try: |
| 255 |
self._subprocess_check_output(argv, is_write=True) |
| 256 |
except subprocess.CalledProcessError as e: |
| 257 |
if e.returncode == 1: |
| 258 |
raise CheckoutFailed |
| 259 |
raise |
| 260 |
|
| 261 |
def pull_ff_only(self) -> None: |
| 262 |
argv = [self._GIT, "pull", "--ff-only"] |
| 263 |
try: |
| 264 |
self._subprocess_check_output(argv, is_write=True) |
| 265 |
except subprocess.CalledProcessError as e: |
| 266 |
if e.returncode == 1: |
| 267 |
raise PullFailed |
| 268 |
raise |
| 269 |
|
| 270 |
def _has_changes(self, extra_argv: list[str] | None = None) -> bool: |
| 271 |
argv = [self._GIT, "diff", "--exit-code", "--quiet"] |
| 272 |
if extra_argv: |
| 273 |
argv += extra_argv |
| 274 |
|
| 275 |
try: |
| 276 |
self._subprocess_check_output(argv, is_write=False) |
| 277 |
return False |
| 278 |
except subprocess.CalledProcessError as e: |
| 279 |
if e.returncode == 1: |
| 280 |
return True |
| 281 |
raise |
| 282 |
|
| 283 |
def has_staged_changes(self) -> bool: |
| 284 |
return self._has_changes(["--cached"]) |
| 285 |
|
| 286 |
def has_uncommitted_changes(self) -> bool: |
| 287 |
if self._has_changes(): |
| 288 |
return True |
| 289 |
return self.has_staged_changes() |
| 290 |
|
| 291 |
def cherry(self, target_branch, topic_branch) -> list[str]: |
| 292 |
argv = [self._GIT, "cherry", target_branch, topic_branch] |
| 293 |
output_bytes = self._subprocess_check_output(argv, is_write=False) |
| 294 |
return self._output_bytes_to_lines(output_bytes) |
| 295 |
|
| 296 |
def has_unpushed_commits_on(self, branch, with_regard_to): |
| 297 |
cherry_lines = self.cherry(with_regard_to, branch) |
| 298 |
return any(line.startswith("+") for line in cherry_lines) |
| 299 |
|
| 300 |
def commit_tree(self, message: str, parent_committish: str, tree: str) -> str: |
| 301 |
argv = [self._GIT, "commit-tree", "-m", message, "-p", parent_committish, tree] |
| 302 |
env = os.environ.copy() |
| 303 |
env.update(self._COMMIT_ENVIRON) |
| 304 |
|
| 305 |
|
| 306 |
|
| 307 |
|
| 308 |
output_bytes = self._subprocess_check_output(argv, env=env, is_write=False) |
| 309 |
lines = self._output_bytes_to_lines(output_bytes) |
| 310 |
assert len(lines) == 1 |
| 311 |
return lines[0] |
| 312 |
|
| 313 |
def merge_base(self, target_branch, topic_branch) -> str: |
| 314 |
argv = [self._GIT, "merge-base", target_branch, topic_branch] |
| 315 |
|
| 316 |
try: |
| 317 |
output_bytes = self._subprocess_check_output(argv, is_write=False) |
| 318 |
except subprocess.CalledProcessError as e: |
| 319 |
if e.returncode == 1: |
| 320 |
raise MergeBaseFailed |
| 321 |
raise |
| 322 |
|
| 323 |
lines = self._output_bytes_to_lines(output_bytes) |
| 324 |
assert len(lines) == 1 |
| 325 |
return lines[0] |