Repository navigation
Expand file tree
/
Copy pathgit-throw.py
More file actions
executable file
·75 lines (68 loc) · 2.27 KB
/
Copy pathgit-throw.py
File metadata and controls
executable file
·75 lines (68 loc) · 2.27 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
#!/usr/bin/env -S uv run
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "utz[cli]",
# ]
# ///
import shlex
from os import environ as env
from utz import err
from utz import proc
from utz.cli import arg, cmd, flag, opt
@cmd('git-throw')
@flag('-a', '--all', help='Stage all tracked files before committing (pass -a to git commit).')
@opt('-m', '--message', help='Optional message to use for ephemeral commit (before it is squashed onto the commit pointed to by `dst`).')
@opt('-n', '--dry-run', count=True, help="1x: commit changes, print rebase todo list; 2x: don't commit changes, show simulated rebase todo list")
@arg('dst')
def main(all, message, dry_run, dst):
""""Throw" (squash) uncommitted changes onto an arbitrary previous commit."""
dst = proc.line('git', 'log', '-1', '--format=%H', dst)
roots = proc.lines('git', 'rev-list', '--max-parents=0', 'HEAD')
root = roots[0] if len(roots) == 1 else None
if not message:
message = f'Temporary commit, to be squashed into {dst}'
commit_cmd = [ 'git', 'commit' ]
if all:
commit_cmd.append('-a')
commit_cmd.extend(['-m', message])
if dry_run < 2:
proc.run(commit_cmd)
else:
err(f'Would run: {shlex.join(commit_cmd)}')
if root and root == dst:
rebase_args = [ '--root' ]
log_args = []
else:
rebase_args = [ f'{dst}^' ]
log_args = [ f'{dst}^..HEAD' ]
shas = list(reversed(
proc.lines('git', 'log', '--format=%h', *log_args)
))
if dry_run >= 2:
fixup_sha = '<ephemeral commit sha>'
rest_shas = shas[1:]
else:
fixup_sha = shas[-1]
rest_shas = shas[1:-1]
lines = [
f'p {shas[0]}',
f'f {fixup_sha}',
*[
f'p {sha}'
for sha in rest_shas
]
]
todo_list = '\n'.join(lines)
todo_contents = 'echo "%s" >' % todo_list
rebase_cmd = [ 'git', 'rebase', '-i', *rebase_args, ]
if dry_run:
err(f'Would run: `{shlex.join(rebase_cmd)}` with GIT_SEQUENCE_EDITOR containing:\n{todo_contents}')
else:
err("todo list:")
err(todo_list)
err()
err(f"{rebase_cmd=}")
proc.run(rebase_cmd, env={ **env, 'GIT_SEQUENCE_EDITOR': todo_contents, })
if __name__ == '__main__':
main()