Repository navigation
Expand file tree
/
Copy pathgit.py
More file actions
434 lines (357 loc) · 13.1 KB
/
Copy pathgit.py
File metadata and controls
434 lines (357 loc) · 13.1 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
"""Git helper functions for the release tool."""
import contextlib
import subprocess
from collections.abc import Iterator
from dev.release.shell import run_cmd
class Git:
"""Git helper class for the release tool.
Operates on a specific git repository path.
"""
def __init__(self, repo: str):
"""Initializes the Git helper.
Args:
repo: The path to the git repository.
"""
self._repo = repo
def _run_git(
self, *args: str, check: bool = True, capture_output: bool = True
) -> str | None:
"""Runs a git command in the repository directory.
Args:
*args: Arguments passed to the git command.
check: If True, raises CalledProcessError on failure.
capture_output: If True, captures and returns stdout.
Returns:
The stdout of the command, stripped, or None if capture_output is
False.
"""
return run_cmd(
"git",
*args,
check=check,
capture_output=capture_output,
cwd=self._repo,
)
def get_tags(self) -> list[str]:
"""Returns a list of all git tags in the repository.
Returns:
A list of tag names (strings).
"""
output = self._run_git("tag")
return output.splitlines() if output else []
@contextlib.contextmanager
def checkout(
self,
ref: str,
create_branch: bool = False,
track_remote: str | None = None,
) -> Iterator[None]:
"""Checks out a git reference and restores the previous branch on exit.
Args:
ref: The git reference (tag, branch, or commit) to checkout.
create_branch: If True, creates the branch before checking it out.
track_remote: If specified, checks out the branch tracking this
remote's corresponding branch.
Yields:
None.
"""
previous_branch = self.get_current_branch()
cmd = ["checkout"]
if create_branch:
cmd.append("-b")
should_reset_hard = False
if track_remote:
if self.branch_exists(ref):
cmd.append(ref)
should_reset_hard = True
else:
cmd.extend(["--track", f"{track_remote}/{ref}"])
else:
cmd.append(ref)
self._run_git(*cmd, capture_output=False)
if should_reset_hard:
self.reset_hard(reset_to=f"{track_remote}/{ref}")
try:
yield
finally:
if previous_branch:
self._run_git("checkout", previous_branch, capture_output=False)
def add(self, *files: str) -> None:
"""Stages files for commit.
Args:
*files: Paths to files to stage.
"""
self._run_git("add", *files, capture_output=False)
def add_modified_and_deleted(self) -> None:
"""Stages all modified and deleted tracked files."""
self._run_git("add", "--update", capture_output=False)
def commit(self, message: str, amend: bool = False, no_edit: bool = False) -> None:
"""Commits staged changes, optionally amending the previous commit.
Args:
message: The commit message.
amend: If True, amends the previous commit.
no_edit: If True, uses the existing commit message without editing.
"""
cmd = ["commit"]
if amend:
cmd.append("--amend")
if no_edit:
cmd.append("--no-edit")
if message:
cmd.extend(["-m", message])
self._run_git(*cmd, capture_output=False)
def push(
self,
remote: str,
ref: str,
set_upstream: bool = False,
force: bool = False,
) -> None:
"""Pushes a reference to a remote repository.
Args:
remote: The remote repository name (e.g., 'origin').
ref: The reference to push (e.g., a branch name).
set_upstream: If True, sets the upstream tracking branch.
force: If True, force pushes the changes.
"""
cmd = ["push"]
if set_upstream:
cmd.append("--set-upstream")
if force:
cmd.append("--force")
cmd.extend([remote, ref])
self._run_git(*cmd, capture_output=False)
def fetch(
self,
remote: str = "origin",
refspec: str | None = None,
tags: bool = False,
force: bool = False,
) -> None:
"""Fetches updates from a remote repository.
Args:
remote: The remote repository name. Defaults to 'origin'.
refspec: The refspec to fetch.
tags: If True, fetches all tags.
force: If True, force fetches updates.
"""
cmd = ["fetch", remote]
if refspec:
cmd.append(refspec)
if tags:
cmd.append("--tags")
if force:
cmd.append("--force")
self._run_git(*cmd, capture_output=False)
def merge(self, commit_ref: str, ff_only: bool = True) -> None:
"""Merges a commit into the current branch.
Args:
commit_ref: The commit reference to merge.
ff_only: If True, only allows fast-forward merges.
"""
cmd = ["merge", commit_ref]
if ff_only:
cmd.append("--ff-only")
self._run_git(*cmd, capture_output=False)
def tag(self, tag_name: str, commit_ref: str) -> None:
"""Creates a local tag pointing to a specific commit.
Args:
tag_name: The name of the tag to create.
commit_ref: The commit reference the tag should point to.
"""
self._run_git("tag", tag_name, commit_ref, capture_output=False)
def cherry_pick(self, sha: str) -> None:
"""Cherry-picks a commit.
Args:
sha: The commit SHA to cherry-pick.
"""
self._run_git("cherry-pick", "-x", sha, capture_output=False)
def cherry_pick_abort(self) -> None:
"""Aborts an in-progress cherry-pick operation."""
self._run_git("cherry-pick", "--abort", capture_output=False)
def reset_hard(self, *, reset_to: str = "HEAD") -> None:
"""Resets the index and working tree to a specific reference.
Args:
reset_to: The git reference to reset to. Defaults to 'HEAD'.
"""
self._run_git("reset", "--hard", reset_to, capture_output=False)
def status(self) -> str:
"""Returns the output of git status --porcelain.
Returns:
The porcelain status output.
"""
output = self._run_git("status", "--porcelain")
return output if output else ""
def get_commit_sha(self, ref: str = "HEAD", short: bool = False) -> str:
"""Returns the commit SHA of a given reference.
Args:
ref: The git reference. Defaults to 'HEAD'.
short: If True, returns a short SHA.
Returns:
The commit SHA.
"""
cmd = ["rev-parse"]
if short:
cmd.append("--short")
cmd.append(ref)
output = self._run_git(*cmd)
return output if output else ""
def get_commit_message(self, ref: str = "HEAD") -> str:
"""Returns the commit message of a given reference.
Args:
ref: The git reference. Defaults to 'HEAD'.
Returns:
The commit message.
"""
output = self._run_git("log", "-1", "--format=%B", ref)
return output if output else ""
def branch_exists(self, branch_name: str) -> bool:
"""Returns True if a local branch exists.
Args:
branch_name: The name of the branch to check.
Returns:
True if the branch exists, False otherwise.
"""
try:
self._run_git("show-ref", "--verify", f"refs/heads/{branch_name}")
return True
except subprocess.CalledProcessError:
return False
def tag_exists(self, tag_name: str) -> bool:
"""Returns True if a local tag exists.
Args:
tag_name: The name of the tag to check.
Returns:
True if the tag exists, False otherwise.
"""
try:
self._run_git("show-ref", "--verify", f"refs/tags/{tag_name}")
return True
except subprocess.CalledProcessError:
return False
def sort_commits_chronologically(self, shas: list[str]) -> list[str]:
"""Sorts a list of commit SHAs chronologically (oldest first).
Args:
shas: A list of commit SHAs to sort.
Returns:
The sorted list of commit SHAs.
"""
output = self._run_git("log", "--no-walk", "--reverse", "--format=%H", *shas)
return output.splitlines() if output else []
def get_current_branch(self) -> str:
"""Returns the current git branch name.
Returns:
The current branch name.
"""
output = self._run_git("rev-parse", "--abbrev-ref", "HEAD")
return output if output else ""
def remote_branch_exists(self, remote: str, branch_name: str) -> bool:
"""Returns True if a remote branch exists.
Args:
remote: The name of the remote.
branch_name: The name of the branch.
Returns:
True if the remote branch exists, False otherwise.
"""
try:
self._run_git(
"show-ref",
"--verify",
f"refs/remotes/{remote}/{branch_name}",
)
return True
except subprocess.CalledProcessError:
return False
def is_ancestor(self, ancestor: str, descendant: str) -> bool:
"""Returns True if ancestor is an ancestor of descendant.
Args:
ancestor: The commit reference that might be an ancestor.
descendant: The commit reference that might be a descendant.
Returns:
True if ancestor is an ancestor of descendant, False otherwise.
"""
try:
self._run_git("merge-base", "--is-ancestor", ancestor, descendant)
return True
except subprocess.CalledProcessError:
return False
def get_remote_tags(self, remote: str) -> list[str]:
"""Returns a list of tags present on the specified remote repository.
Args:
remote: The name of the git remote to query (e.g., 'origin',
'upstream').
Returns:
A list of tag names (strings) found on the remote, excluding peeled
tags.
"""
output = self._run_git("ls-remote", "--tags", remote)
tags = []
if not output:
return tags
for line in output.splitlines():
if not line:
continue
parts = line.split()
if len(parts) < 2:
continue
ref = parts[1]
if ref.startswith("refs/tags/"):
tag = ref[len("refs/tags/") :]
# Skip peeled tags (e.g. tag^{}) to avoid
# duplicate tag names in the output.
if not tag.endswith("^{}"):
tags.append(tag)
return tags
def get_modified_files(self, ref: str) -> list[str]:
"""Returns a list of files modified in a given reference.
Args:
ref: The git reference.
Returns:
A list of file paths.
"""
output = self._run_git("show", "--name-only", "--format=", ref)
return [line for line in output.splitlines() if line.strip()] if output else []
def diff(self) -> str:
"""Returns the diff of unstaged changes.
Returns:
The diff output as a string.
"""
output = self._run_git("diff")
return output if output else ""
def apply(self, patch_file: str) -> None:
"""Applies a patch file.
Args:
patch_file: The path to the patch file.
"""
self._run_git("apply", patch_file, capture_output=False)
def apply_check(self, patch_file: str) -> bool:
"""Verifies if a patch can be applied cleanly.
Args:
patch_file: The path to the patch file.
Returns:
True if the patch can be applied cleanly, False otherwise.
"""
try:
self._run_git("apply", "--check", patch_file, capture_output=False)
return True
except subprocess.CalledProcessError:
return False
def get_remote_branches(self, remote: str = "origin") -> list[str]:
"""Returns a list of remote branches.
Args:
remote: The name of the remote.
Returns:
A list of branch names (without the remote prefix).
"""
output = self._run_git("branch", "-r")
branches = []
if not output:
return branches
for line in output.splitlines():
line = line.strip()
if "->" in line:
continue
parts = line.split("/")
if len(parts) >= 2 and parts[0] == remote:
branches.append("/".join(parts[1:]))
return branches