-
Notifications
You must be signed in to change notification settings - Fork 3
/
git-prebase
executable file
·148 lines (113 loc) · 4.63 KB
/
git-prebase
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
#!/usr/bin/env python
"Improve on 'git rebase -i' by adding information per commit regarding which files it touched."
from __future__ import print_function
import sys
import os
from subprocess import check_call, check_output
from itertools import count, chain
from collections import defaultdict
from string import digits, ascii_letters
SYMBOLS = dict(enumerate(chain(digits, ascii_letters)))
SPACER = "_"
def parse_log(first, last):
gitlog = check_output([
'git', 'log', '--name-only', '--oneline', '--no-color',
'--format=#commit %h {idx:4}:%s',
"%s^..%s" % (first, last)],
universal_newlines=True)
lines = iter(gitlog.splitlines())
line = next(lines)
while True:
prefix, _, commit = line.partition(" ")
assert prefix == "#commit"
files = set()
for line in lines:
if line.startswith("#commit"):
yield (commit, sorted(files))
break # for
elif line:
files.add(line)
else:
yield (commit, sorted(files))
break # while
def compact(line, length, ellipsis="....", suffix_length=10):
if len(line) <= length:
return line
return line[:length-len(ellipsis)-suffix_length] + ellipsis + line[-suffix_length:]
def symbol(idx):
return SYMBOLS[idx % len(SYMBOLS)]
def write_todo(file, first, last, comments, sort_file_list=False):
c = count(0)
file_indices = defaultdict(lambda: next(c))
lines = []
log = list(parse_log(first, last))
width = min(120, max(len(c) for (c, _) in log) if log else 80)
for commit, files in log:
indices = {file_indices[f] for f in files}
placements = "".join(symbol(i) if i in indices else SPACER for i in range(max(indices)+1)) if indices else ""
lines.append((compact(commit, width).ljust(width), placements))
lines.reverse()
placements_width = max(file_indices.values()) + 2
for i, (commit, placements) in enumerate(lines, 1):
print("pick", commit.format(idx=i), placements.ljust(placements_width, SPACER), file=file)
print("", file=file)
sortby = 0 if sort_file_list else 1
for f, i in sorted(file_indices.items(), key=lambda p: p[sortby]):
pos = symbol(i).rjust(1+i, SPACER).ljust(placements_width, SPACER)
f = "[%s] %s" % (symbol(i), f)
fname = compact("# %s" % f, width+2).ljust(width+2)
print(fname, pos, file=file)
print("", file=file)
for line in comments:
print(line, file=file, end="")
def usage():
print("usage: %s [options] <branch>\n\n"
"Options:\n"
" -F, --sort-file-list Show file list sorted by file name, instead of order of appearance\n"
% os.path.basename(sys.argv[0]))
sys.exit(1)
if __name__ == '__main__':
if len(sys.argv) <= 1:
usage()
if 'GIT_ORIG_EDITOR' not in os.environ:
base_commit = None
for arg in sys.argv[1:]:
if arg.startswith("-"):
if arg in ("-F", "--sort-file-list"):
os.environ['GIT_PREBASE_SORT_FILE_LIST'] = "1"
else:
usage()
elif base_commit:
usage()
else:
base_commit = arg
if not base_commit:
usage()
git_editor = (
os.environ.get("GIT_SEQUENCE_EDITOR")
or check_output(["git", "config", "--get", "sequence.editor"], universal_newlines=True).strip()
or check_output(["git", "var", "GIT_EDITOR"], universal_newlines=True).strip())
os.environ['GIT_ORIG_EDITOR'] = os.path.expanduser(git_editor)
os.environ['GIT_SEQUENCE_EDITOR'] = __file__
os.execlpe("git", "git", "rebase", "-i", base_commit, os.environ)
todo_file = sys.argv[1]
os.environ['GIT_EDITOR'] = editor = os.environ['GIT_ORIG_EDITOR']
sort_file_list = bool(int(os.getenv("GIT_PREBASE_SORT_FILE_LIST", 0)))
if not todo_file.endswith("git-rebase-todo"):
os.execlpe(editor, editor, todo_file, os.environ)
commits = []
with open(todo_file) as f:
for line in f:
if line.strip() == "noop":
break
if not line.strip():
comments = list(f)
break
commits.append(line.split()[1])
if commits:
first, last = commits[0], commits[-1]
with open(todo_file, "w") as file:
write_todo(file, first, last, comments, sort_file_list=sort_file_list)
sh = os.getenv("SHELL")
assert sh, "Is this windows?... it'd be nice if someone can make this work :)"
check_call([sh, "-c", "%s %s" % (editor, todo_file)])