-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathgit-recent-branches
More file actions
executable file
·294 lines (236 loc) · 8.89 KB
/
git-recent-branches
File metadata and controls
executable file
·294 lines (236 loc) · 8.89 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
#!/usr/bin/env python3
# coding: utf-8
#
# git recent-branches shows a list of recently checked-out branches.
#
import git
import re
import os
import sys
import time
import logging
import gettext
import argparse
import configparser
import termcolor
class reflog(dict):
pass
def git_config_noauto(setting):
"""Convert true/false/"auto" state into a boolean"""
return setting is True or (setting == "auto" and sys.stdout.isatty())
def error(msg):
print(msg, file=sys.stderr)
def reltime_to_now(t, tzoff):
utc_sec = t - tzoff;
now_utc_sec = time.time() - time.timezone
delta = int(now_utc_sec - utc_sec)
if delta < 0:
logging.error("Date is in the future?")
return "in the future?"
datewords = (
(60 * 60 * 24 * 365, lambda n : gettext.ngettext("year", "years", n)),
(60 * 60 * 24 * 30, lambda n : gettext.ngettext("month", "months", n)),
(60 * 60 * 24 * 7, lambda n : gettext.ngettext("week", "weeks", n)),
(60 * 60 * 24, lambda n : gettext.ngettext("day", "days", n)),
(60 * 60, lambda n : gettext.ngettext("hour", "hours", n)),
(60, lambda n : gettext.ngettext("minute", "minutes", n)),
)
count = 0
for (secs, word) in datewords:
count = delta//secs
if count > 1: # better to have 8 days than 1 week
break
return "%d %s ago" % (count, word(count))
def find_repo():
"""Run up from $PWD until the end of the filesystem, trying to find the
git repo. This emulates what git does by default."""
across_fs = os.environ.get("GIT_DISCOVERY_ACROSS_FILESYSTEM", False)
cwd = os.getcwd()
dev = os.stat(cwd).st_dev
gitdir = os.path.join(cwd, ".git")
while not git.repo.fun.is_git_dir(gitdir):
oldcwd = cwd
cwd = os.path.abspath(os.path.join(cwd, os.pardir))
if cwd == oldcwd:
break;
gitdir = os.path.join(cwd, ".git")
stat = os.stat(cwd)
if not across_fs and stat.st_dev != dev:
error("Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).")
break;
return gitdir
def init_repo():
gitdir = os.environ.get("GIT_DIR", find_repo())
if not git.repo.fun.is_git_dir(gitdir):
error("fatal: Not a git repository")
sys.exit(1)
repo = git.Repo(path = gitdir)
repo.branches_set = { head.name for head in repo.branches }
return repo
def is_sha1sum(s):
# 40-byte sha1sum, a direct checkout. This is safe
# there are no 40-char english words with a-f
m = re.match(r"[a-f0-9]{40}", s)
if m != None:
logging.debug("%s is a sha1sum" % s)
return m != None
def is_sha1sum_short(s):
m = re.match(r"[a-f0-9]{7}", s)
if m == None:
return False
# could be a word. check for at least two numbers, not as the first or
# last char. if you name your 7-letter branches a23dead, your fault.
# second condition: digit + letter + digit + letter
m = re.match(r".+[0-9]+.*[0-9]+.+", s)
if m == None:
m = re.match(r".?[0-9]+.+[0-9]+", s)
if m != None:
logging.debug("%s is a short sha1sum" % s)
return m != None
def is_tag(repo, s):
if s in repo.tags:
logging.debug("%s is a tag" % s)
return True
return False
def is_removed(repo, s):
if s not in repo.branches_set:
logging.debug("%s is removed" % s)
return True
return False
def is_remote(repo, s):
for r in git.remote.Remote.iter_items(repo):
m = re.match(r"%s/.*" % r.name, s)
if m != None:
logging.debug("%s is a remote branch" % s)
return True
return False
def is_headN(s):
m = re.match(r"HEAD@{[0-9]+}", s)
if m != None:
logging.debug("%s is direct HEAD checkout" % s)
return m != None
# Drop direct checkouts, tag names, etc.
def filter_logs(args, repo, log_entries):
flogs = [] # filtered logs as dict(from, to, log)
uniq = {}
logged_count = 0
for l in log_entries:
m = re.match(r".*checkout: moving from (.*) to (.*)", l.message)
if m == None:
continue
log = reflog()
log.fro = m.group(1)
log.to = m.group(2)
log.log = l
if log.to in uniq:
continue
uniq[log.to] = 1
if is_headN(log.to):
continue
# skip direct checkouts
if is_sha1sum(log.to):
continue
if is_sha1sum_short(log.to):
continue
if is_remote(repo, log.to):
continue
if is_tag(repo, log.to):
continue
if is_removed(repo, log.to):
continue
flogs.append(log)
logged_count += 1
if args.limit > 0 and logged_count >= args.limit:
break
return flogs
def last_commit(repo, reflog):
commit = repo.commit(reflog.log.newhexsha)
reflog.reltime_commit = reltime_to_now(commit.committed_date, commit.committer_tz_offset)
reflog.commit_msg = commit.message.split("\n")[0]
reflog.commit = commit
def print_commit(args, commit):
g = git.cmd.Git()
opts = ["-n 1"] # git handles -n 1 -n 4 correctly so the user can override this
try:
config = repo.config_reader()
if git_config_noauto(config.get_value("color", "pager", sys.stdout.isatty())):
opts.append(["--color=always"])
except configparser.ParsingError:
logging.debug("Parsing error in config")
opts.append(args.log_options)
try:
print("")
print(g.log(opts, commit.hexsha))
print("")
except git.exc.GitCommandError as e:
print(e)
sys.exit(1)
def print_description(args, repo, reflog):
config = repo.config_reader()
try:
section = "branch \"%s\"" % reflog.to
desc = config.get_value(section, "description", None)
if desc:
print("")
for line in desc.split("\\n"):
print(" " + line)
except configparser.ParsingError:
logging.debug("Parsing error in config")
pass
def walk_reflog(args, repo):
head = repo.head
log = head.log()
log.reverse()# sort as most recent first
log = filter_logs(args, repo, log)
config = repo.config_reader()
for l in log:
l.reltime = reltime_to_now(*l.log.time)
last_commit(repo, l)
branch = l.to
try:
if git_config_noauto(config.get_value("color", "branch", sys.stdout.isatty())):
branch = termcolor.colored(branch, "yellow")
except configparser.ParsingError:
logging.debug("Parsing error in config")
print("{:<45} {:<20} last commit {:<15}".format(branch, l.reltime, l.reltime_commit))
if args.print_description:
print_description(args, repo, l)
if args.last_commit:
print_commit(args, l.commit)
def get_configured_limit(repo):
config = repo.config_reader()
value = config.get_value("recent-branches", "limit", 20)
return value
if __name__ == "__main__":
logging.basicConfig(level=logging.ERROR)
repo = init_repo()
default_limit = get_configured_limit(repo)
parser = argparse.ArgumentParser(description="Show a list of recently used branches",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="Output is in the form of\n\n"
" branchname most recent checkout most recent commit date\n\n"
"Branches are filtered\n"
" * if it looks like a sha1sum\n"
" * if it is a remote branch\n"
" * if it is a HEAD@{3}-like reflog\n"
" * if it is a tag name\n"
"Branches that do not exist anymore in the local repository are not shown")
parser.add_argument("--print-description",
action="store_true",
default=False,
help="Show branch description (if available)")
parser.add_argument("--last-commit",
action="store_true",
default=False,
help="Show top commit on each branch. Uses git log, use git log options for formatting the output")
parser.add_argument("--limit",
type=int,
default=default_limit,
help="Limit output to N branches")
parser.add_argument("log_options",
nargs="*",
metavar="-- --pretty=oneline ...",
help="Options passed to git log. Separate these with "
"a -- from the other options")
args = parser.parse_args(sys.argv[1:])
walk_reflog(args, repo)