-
Notifications
You must be signed in to change notification settings - Fork 16
/
git-blame.py
354 lines (300 loc) · 11.7 KB
/
git-blame.py
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
import sublime
import sublime_plugin
import os
import re
import functools
import subprocess
from subprocess import check_output as shell
PHANTOM_KEY_ALL = 'git-blame-all'
SETTING_PHANTOM_ALL_DISPLAYED = 'git-blame-all-displayed'
stylesheet_one = '''
<style>
div.phantom-arrow {
border-top: 0.4rem solid transparent;
border-left: 0.5rem solid color(var(--bluish) blend(var(--background) 30%));
width: 0;
height: 0;
}
div.phantom {
padding: 0.4rem 0 0.4rem 0.7rem;
margin: 0 0 0.2rem;
border-radius: 0 0.2rem 0.2rem 0.2rem;
background-color: color(var(--bluish) blend(var(--background) 30%));
}
div.phantom span.message {
padding-right: 0.7rem;
}
div.phantom a {
text-decoration: inherit;
}
div.phantom a.close {
padding: 0.35rem 0.7rem 0.45rem 0.8rem;
position: relative;
bottom: 0.05rem;
border-radius: 0 0.2rem 0.2rem 0;
font-weight: bold;
}
html.dark div.phantom a.close {
background-color: #00000018;
}
html.light div.phantom a.close {
background-color: #ffffff18;
}
</style>
'''
template_one = '''
<body id="inline-git-blame">
{stylesheet}
<div class="phantom-arrow"></div>
<div class="phantom">
<span class="message">
<strong>Git Blame</strong> ({user})
{date} {time} |
{sha}
<a href="copy-{sha}">[Copy]</a>
<a href="show-{sha}">[Show]</a>
<a class="close" href="close">''' + chr(0x00D7) + '''</a>
</span>
</div>
</body>
'''
stylesheet_all = '''
<style>
div.phantom {
padding: 0;
margin: 0;
background-color: color(var(--bluish) blend(var(--background) 30%));
}
div.phantom .user {
width: 10em;
}
div.phantom a.close {
padding: 0.35rem 0.7rem 0.45rem 0.8rem;
position: relative;
bottom: 0.05rem;
font-weight: bold;
}
html.dark div.phantom a.close {
background-color: #00000018;
}
html.light div.phantom a.close {
background-color: #ffffff18;
}
</style>
'''
template_all = '''
<body id="inline-git-blame">
{stylesheet}
<div class="phantom">
<span class="message">
{sha} (<span class="user">{user}</span> {date} {time})
<a class="close" href="close">''' + chr(0x00D7) + '''</a>
</span>
</div>
</body>
'''
# Sometimes this fails on other OS, just error silently
try:
si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
except:
si = None
class BlameCommand(sublime_plugin.TextCommand):
def __init__(self, view):
self.view = view
self.phantom_set = sublime.PhantomSet(view, 'git-blame')
@functools.lru_cache(128, False)
def get_blame(self, line, path):
try:
return shell(["git", "blame", "--minimal", "-w",
"-L {0},{0}".format(line), path],
cwd=os.path.dirname(os.path.realpath(path)),
startupinfo=si,
stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
print("Git blame: git error {}:\n{}".format(e.returncode, e.output.decode("UTF-8")))
except Exception as e:
print("Git blame: Unexpected error:", e)
def parse_blame(self, blame):
sha, file_path, user, date, time, tz_offset, *_ = blame.decode('utf-8').split()
# Was part of the inital commit so no updates
if file_path[0] == '(':
user, date, time, tz_offset = file_path, user, date, time
file_path = None
# Fix an issue where the username has a space
# Im going to need to do something better though if people
# start to have multiple spaces in their names.
if not date[0].isdigit():
user = "{0} {1}".format(user, date)
date, time = time, tz_offset
return(sha, user[1:], date, time)
def get_commit(self, sha, path):
try:
return shell(["git", "show", sha],
cwd=os.path.dirname(os.path.realpath(path)),
startupinfo=si)
except Exception as e:
return
def on_phantom_close(self, href):
href_parts = href.split('-')
if len(href_parts) > 1:
intent = href_parts[0]
sha = href_parts[1]
# The SHA output by git-blame may have a leading caret to indicate
# that it is a "boundary commit". That useful information has
# already been shown in the phantom, so strip it before going on to
# use the SHA programmatically.
sha = sha.strip('^')
if intent == "copy":
sublime.set_clipboard(sha)
sublime.status_message('Git SHA copied to clipboard')
elif intent == "show":
desc = self.get_commit(sha, self.view.file_name()).decode('utf-8')
buf = self.view.window().new_file()
buf.run_command('insert_commit_description', {'desc': desc})
else:
self.view.erase_phantoms('git-blame')
else:
self.view.erase_phantoms('git-blame')
def run(self, edit):
phantoms = []
self.view.erase_phantoms('git-blame')
#Before adding the phantom, see if the current phantom that is displayed is at the same spot at the selection
if self.phantom_set.phantoms and self.view.line(self.view.sel()[0]) == self.view.line(self.phantom_set.phantoms[0].region):
self.phantom_set.update(phantoms)
return
for region in self.view.sel():
line = self.view.line(region)
(row, col) = self.view.rowcol(region.begin())
full_path = self.view.file_name()
result = self.get_blame(int(row) + 1, full_path)
if not result:
# Unable to get blame
return
sha, user, date, time = self.parse_blame(result)
body = template_one.format(sha=sha, user=user, date=date, time=time, stylesheet=stylesheet_one)
phantom = sublime.Phantom(line, body, sublime.LAYOUT_BLOCK, self.on_phantom_close)
phantoms.append(phantom)
self.phantom_set.update(phantoms)
class BlameShowAllCommand(sublime_plugin.TextCommand):
# The fixed length for author names
NAME_LENGTH = 10
def __init__(self, view):
super().__init__(view)
self.phantom_set = sublime.PhantomSet(self.view, PHANTOM_KEY_ALL)
self.pattern = None
def run(self, edit):
if self.view.is_dirty():
sublime.status_message("The file needs to be saved for git blame.")
return
self.view.erase_phantoms(PHANTOM_KEY_ALL)
blame_lines = self.get_blame_lines(self.view.file_name())
if not blame_lines:
return
phantoms = []
for l in blame_lines:
parsed = self.parse_blame(l)
if not parsed:
continue
sha, author, date, time, line_number = parsed
body = template_all.format(sha=sha,
user=self.format_name(author),
date=date,
time=time,
stylesheet=stylesheet_all)
line_point = self.get_line_point(line_number - 1)
phantom = sublime.Phantom(line_point,
body,
sublime.LAYOUT_INLINE,
self.on_phantom_close)
phantoms.append(phantom)
self.phantom_set.update(phantoms)
self.view.settings().set(SETTING_PHANTOM_ALL_DISPLAYED, True)
def get_blame_lines(self, path):
'''Run `git blame` and get the output lines.
'''
try:
# The option --show-name is necessary to force file name display.
command = ["git", "blame", "--show-name", "--minimal", "-w", path]
output = shell(command,
cwd=os.path.dirname(os.path.realpath(path)),
startupinfo=si,
stderr=subprocess.STDOUT)
return output.decode("UTF-8").splitlines()
except subprocess.CalledProcessError as e:
print("Git blame: git error {}:\n{}".format(e.returncode, e.output.decode("UTF-8")))
except Exception as e:
print("Git blame: Unexpected error:", e)
def parse_blame(self, blame):
'''Parses git blame output.
'''
if not self.pattern:
self.prepare_pattern()
m = self.pattern.match(blame)
if m:
sha = m.group('sha')
# Currently file is not used.
# file = m.group('file')
author = m.group('author')
date = m.group('date')
time = m.group('time')
line_number = int(m.group('line_number'))
return sha, author, date, time, line_number
else:
return None
def prepare_pattern(self):
'''Prepares the regex pattern to parse git blame output.
'''
# The SHA output by git-blame may have a leading caret to indicate
# that it is a "boundary commit".
p_sha = r'(?P<sha>\^?\w+)'
p_file = r'((?P<file>[\S ]+)\s+)'
p_author = r'(?P<author>.+?)'
p_date = r'(?P<date>\d{4}-\d{2}-\d{2})'
p_time = r'(?P<time>\d{2}:\d{2}:\d{2})'
p_timezone = r'(?P<timezone>[\+-]\d+)'
p_line = r'(?P<line_number>\d+)'
s = r'\s+'
self.pattern = re.compile(r'^' + p_sha + s + p_file + r'\(' +
p_author + s + p_date + s + p_time + s +
p_timezone + s + p_line + r'\) ')
def format_name(self, name):
'''Formats author names so that widths of phantoms become equal.
'''
ellipsis = '...'
if len(name) > self.NAME_LENGTH:
return name[:self.NAME_LENGTH] + ellipsis
else:
return name + '.' * (self.NAME_LENGTH - len(name)) + ellipsis
def get_line_point(self, line):
'''Get the point of specified line in a view.
'''
return self.view.line(self.view.text_point(line, 0))
def on_phantom_close(self, href):
'''Closes opened phantoms.
'''
if href == 'close':
self.view.run_command('blame_erase_all')
class BlameEraseAllCommand(sublime_plugin.TextCommand):
def run(self, edit):
'''Erases the blame results.
'''
sublime.status_message("The git blame result is cleared.")
self.view.erase_phantoms(PHANTOM_KEY_ALL)
class BlameEraseAllListener(sublime_plugin.ViewEventListener):
@classmethod
def is_applicable(cls, settings):
'''Checks if the blame_erase_all command is applicable.
'''
return settings.get(SETTING_PHANTOM_ALL_DISPLAYED, False)
def on_modified_async(self):
'''Automatically erases the blame results to prevent mismatches.
'''
self.view.run_command('blame_erase_all')
self.view.settings().erase(SETTING_PHANTOM_ALL_DISPLAYED)
class InsertCommitDescriptionCommand(sublime_plugin.TextCommand):
def run(self, edit, desc):
view = self.view
view.set_scratch(True)
view.set_syntax_file('Packages/Diff/Diff.sublime-syntax')
view.insert(edit, 0, desc)