forked from jisaacks/GitGutter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgit_gutter_handler.py
282 lines (251 loc) · 9.68 KB
/
git_gutter_handler.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
import os
import sublime
import subprocess
import encodings
import re
try:
from . import git_helper
from .view_collection import ViewCollection
except (ImportError, ValueError):
import git_helper
from view_collection import ViewCollection
class GitGutterHandler:
def __init__(self, view):
self.load_settings()
self.view = view
self.git_temp_file = ViewCollection.git_tmp_file(self.view)
self.buf_temp_file = ViewCollection.buf_tmp_file(self.view)
if self.on_disk():
self.git_tree = git_helper.git_tree(self.view)
self.git_dir = git_helper.git_dir(self.git_tree)
self.git_path = git_helper.git_file_path(self.view, self.git_tree)
def _get_view_encoding(self):
# get encoding and clean it for python ex: "Western (ISO 8859-1)"
# NOTE(maelnor): are we need regex here?
pattern = re.compile(r'.+\((.*)\)')
encoding = self.view.encoding()
if pattern.match(encoding):
encoding = pattern.sub(r'\1', encoding)
encoding = encoding.replace('with BOM', '')
encoding = encoding.replace('Windows', 'cp')
encoding = encoding.replace('-', '_')
encoding = encoding.replace(' ', '')
return encoding
def on_disk(self):
# if the view is saved to disk
return self.view.file_name() is not None
def reset(self):
if self.on_disk() and self.git_path and self.view.window():
self.view.window().run_command('git_gutter')
def get_git_path(self):
return self.git_path
def update_buf_file(self):
chars = self.view.size()
region = sublime.Region(0, chars)
# Try conversion
try:
contents = self.view.substr(
region).encode(self._get_view_encoding())
except UnicodeError:
# Fallback to utf8-encoding
contents = self.view.substr(region).encode('utf-8')
except LookupError:
# May encounter an encoding we don't have a codec for
contents = self.view.substr(region).encode('utf-8')
contents = contents.replace(b'\r\n', b'\n')
contents = contents.replace(b'\r', b'\n')
f = open(self.buf_temp_file.name, 'wb')
f.write(contents)
f.close()
def update_git_file(self):
# the git repo won't change that often
# so we can easily wait 5 seconds
# between updates for performance
if ViewCollection.git_time(self.view) > 5:
open(self.git_temp_file.name, 'w').close()
args = [
self.git_binary_path,
'--git-dir=' + self.git_dir,
'--work-tree=' + self.git_tree,
'show',
ViewCollection.get_compare() + ':' + self.git_path,
]
try:
contents = self.run_command(args)
contents = contents.replace(b'\r\n', b'\n')
contents = contents.replace(b'\r', b'\n')
f = open(self.git_temp_file.name, 'wb')
f.write(contents)
f.close()
ViewCollection.update_git_time(self.view)
except Exception:
pass
def total_lines(self):
chars = self.view.size()
region = sublime.Region(0, chars)
lines = self.view.lines(region)
return len(lines)
# Parse unified diff with 0 lines of context.
# Hunk range info format:
# @@ -3,2 +4,0 @@
# Hunk originally starting at line 3, and occupying 2 lines, now
# starts at line 4, and occupies 0 lines, i.e. it was deleted.
# @@ -9 +10,2 @@
# Hunk size can be omitted, and defaults to one line.
# Dealing with ambiguous hunks:
# "A\nB\n" -> "C\n"
# Was 'A' modified, and 'B' deleted? Or 'B' modified, 'A' deleted?
# Or both deleted? To minimize confusion, let's simply mark the
# hunk as modified.
def process_diff(self, diff_str):
inserted = []
modified = []
deleted = []
hunk_re = '^@@ \-(\d+),?(\d*) \+(\d+),?(\d*) @@'
hunks = re.finditer(hunk_re, diff_str, re.MULTILINE)
for hunk in hunks:
start = int(hunk.group(3))
old_size = int(hunk.group(2) or 1)
new_size = int(hunk.group(4) or 1)
if not old_size:
inserted += range(start, start + new_size)
elif not new_size:
deleted += [start + 1]
else:
modified += range(start, start + new_size)
if len(inserted) == self.total_lines() and not self.show_untracked:
# All lines are "inserted"
# this means this file is either:
# - New and not being tracked *yet*
# - Or it is a *gitignored* file
return ([], [], [])
else:
return (inserted, modified, deleted)
def diff(self):
if self.on_disk() and self.git_path:
self.update_git_file()
self.update_buf_file()
args = [
self.git_binary_path, 'diff', '-U0', '--no-color',
self.ignore_whitespace,
self.patience_switch,
self.git_temp_file.name,
self.buf_temp_file.name,
]
args = list(filter(None, args)) # Remove empty args
results = self.run_command(args)
encoding = self._get_view_encoding()
try:
decoded_results = results.decode(encoding.replace(' ', ''))
except UnicodeError:
decoded_results = results.decode("utf-8")
return self.process_diff(decoded_results)
else:
return ([], [], [])
def untracked(self):
return self.handle_files([])
def ignored(self):
return self.handle_files(['-i'])
def handle_files(self, additionnal_args):
if self.show_untracked and self.on_disk() and self.git_path:
args = [
self.git_binary_path,
'--git-dir=' + self.git_dir,
'--work-tree=' + self.git_tree,
'ls-files', '--other', '--exclude-standard',
] + additionnal_args + [
os.path.join(self.git_tree, self.git_path),
]
args = list(filter(None, args)) # Remove empty args
results = self.run_command(args)
encoding = self._get_view_encoding()
try:
decoded_results = results.decode(encoding.replace(' ', ''))
except UnicodeError:
decoded_results = results.decode("utf-8")
return (decoded_results != "")
else:
return False
def git_commits(self):
args = [
self.git_binary_path,
'--git-dir=' + self.git_dir,
'--work-tree=' + self.git_tree,
'log', '--all',
'--pretty=%s\a%h %an <%aE>\a%ad (%ar)',
'--date=local', '--max-count=9000'
]
results = self.run_command(args)
return results
def git_branches(self):
args = [
self.git_binary_path,
'--git-dir=' + self.git_dir,
'--work-tree=' + self.git_tree,
'for-each-ref',
'--sort=-committerdate',
'--format=%(subject)\a%(refname)\a%(objectname)',
'refs/heads/'
]
results = self.run_command(args)
return results
def git_tags(self):
args = [
self.git_binary_path,
'--git-dir=' + self.git_dir,
'--work-tree=' + self.git_tree,
'show-ref',
'--tags',
'--abbrev=7'
]
results = self.run_command(args)
return results
def git_current_branch(self):
args = [
self.git_binary_path,
'--git-dir=' + self.git_dir,
'--work-tree=' + self.git_tree,
'rev-parse',
'--abbrev-ref',
'HEAD'
]
result = self.run_command(args)
return result
def run_command(self, args):
startupinfo = None
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
proc = subprocess.Popen(args, stdout=subprocess.PIPE,
startupinfo=startupinfo, stderr=subprocess.PIPE)
return proc.stdout.read()
def load_settings(self):
self.settings = sublime.load_settings('GitGutter.sublime-settings')
self.user_settings = sublime.load_settings(
'Preferences.sublime-settings')
# Git Binary Setting
self.git_binary_path = 'git'
git_binary = self.user_settings.get(
'git_binary') or self.settings.get('git_binary')
if git_binary:
self.git_binary_path = git_binary
# Ignore White Space Setting
self.ignore_whitespace = self.settings.get('ignore_whitespace')
if self.ignore_whitespace == 'all':
self.ignore_whitespace = '-w'
elif self.ignore_whitespace == 'eol':
self.ignore_whitespace = '--ignore-space-at-eol'
else:
self.ignore_whitespace = ''
# Patience Setting
self.patience_switch = ''
patience = self.settings.get('patience')
if patience:
self.patience_switch = '--patience'
# Untracked files
self.show_untracked = self.settings.get(
'show_markers_on_untracked_file')
# Show information in status bar
self.show_status = self.user_settings.get('show_status') or self.settings.get('show_status')
if self.show_status != 'all' and self.show_status != 'none':
self.show_status = 'default'