model + controllers: fix bugs from run_cmd refactor
[ugit.git] / ugitlibs / git.py
bloba2db24989aa9a72cd56562c7a60c18000c18a888
1 '''TODO: "import stgit"'''
2 import os
3 import re
4 import types
5 import utils
6 import defaults
7 from cStringIO import StringIO
9 # A regex for matching the output of git(log|rev-list) --pretty=oneline
10 REV_LIST_REGEX = re.compile('([0-9a-f]+)\W(.*)')
12 def quote(argv):
13 return ' '.join([ utils.shell_quote(arg) for arg in argv ])
15 def git(*args,**kwargs):
16 gitcmd = 'git %s' % args[0]
17 return utils.run_cmd(gitcmd, *args[1:], **kwargs)
19 def add(to_add, verbose=True):
20 '''Invokes 'git add' to index the filenames in to_add.'''
21 if not to_add:
22 return 'No files to add.'
23 return git('add', verbose=verbose, *to_add)
25 def add_or_remove(to_process):
26 '''Invokes 'git add' to index the filenames in to_process that exist
27 and 'git rm' for those that do not exist.'''
29 if not to_process:
30 return 'No files to add or remove.'
32 to_add = []
33 to_remove = []
35 for filename in to_process:
36 if os.path.exists(filename):
37 to_add.append(filename)
39 output = add(to_add)
41 if len(to_add) == len(to_process):
42 # to_process only contained unremoved files --
43 # short-circuit the removal checks
44 return output
46 # Process files to remote
47 for filename in to_process:
48 if not os.path.exists(filename):
49 to_remove.append(filename)
50 output + '\n\n' + git('rm',*to_remove)
52 def apply(filename, indexonly=True, reverse=False):
53 kwargs = {}
54 if reverse:
55 kwargs['reverse'] = True
56 if indexonly:
57 kwargs['index'] = True
58 kwargs['cached'] = True
59 argv = ['apply', filename]
60 return git(*argv, **kwargs)
62 def branch(name=None, remote=False, delete=False):
63 if delete and name:
64 return git('branch', name, D=True)
65 else:
66 branches = map(lambda x: x.lstrip('* '),
67 git('branch', r=remote).splitlines())
68 if remote:
69 remotes = []
70 for branch in branches:
71 if branch.endswith('/HEAD'):
72 continue
73 remotes.append(branch)
74 return remotes
75 return branches
77 def cat_file(objtype, sha1):
78 return git('cat-file', objtype, sha1, raw=True)
80 def cherry_pick(revs, commit=False):
81 """Cherry-picks each revision into the current branch.
82 Returns a list of command output strings (1 per cherry pick)"""
84 if not revs: return []
86 argv = [ 'cherry-pick' ]
87 kwargs = {}
88 if not commit:
89 kwargs['n'] = True
91 cherries = []
92 for rev in revs:
93 new_argv = argv + [rev]
94 cherries.append(git(*new_argv, **kwargs))
96 return '\n'.join(cherries)
98 def checkout(*args):
99 return git('checkout', *args)
101 def commit(msg, amend=False):
102 '''Creates a git commit.'''
104 if not msg.endswith('\n'):
105 msg += '\n'
107 # Sure, this is a potential "security risk," but if someone
108 # is trying to intercept/re-write commit messages on your system,
109 # then you probably have bigger problems to worry about.
110 tmpfile = utils.get_tmp_filename()
111 kwargs = {
112 'F': tmpfile,
113 'amend': amend,
116 # Create the commit message file
117 file = open(tmpfile, 'w')
118 file.write(msg)
119 file.close()
121 # Run 'git commit'
122 output = git('commit', F=tmpfile, amend=amend)
123 os.unlink(tmpfile)
125 return ('git commit -F %s --amend %s\n\n%s'
126 % ( tmpfile, amend, output ))
128 def create_branch(name, base, track=False):
129 """Creates a branch starting from base. Pass track=True
130 to create a remote tracking branch."""
131 return git('branch', name, base, track=track)
133 def current_branch():
134 '''Parses 'git branch' to find the current branch.'''
135 branches = git('branch').splitlines()
136 for branch in branches:
137 if branch.startswith('* '):
138 return branch.lstrip('* ')
139 return 'Detached HEAD'
141 def diff(commit=None,filename=None, color=False,
142 cached=True, with_diff_header=False,
143 suppress_header=True, reverse=False):
144 "Invokes git diff on a filepath."
146 argv = []
147 if commit:
148 argv.append('%s^..%s' % (commit, commit))
150 if filename:
151 argv.append('--')
152 if type(filename) is list:
153 argv.extend(filename)
154 else:
155 argv.append(filename)
157 kwargs = {
158 'patch-with-raw': True,
159 'unified': defaults.DIFF_CONTEXT,
162 diff = git('diff',
163 R=reverse,
164 color=color,
165 cached=cached,
166 *argv,
167 **kwargs)
169 diff_lines = diff.splitlines()
171 output = StringIO()
172 start = False
173 del_tag = 'deleted file mode '
175 headers = []
176 deleted = cached and not os.path.exists(filename)
177 for line in diff_lines:
178 if not start and '@@ ' in line and ' @@' in line:
179 start = True
180 if start or(deleted and del_tag in line):
181 output.write(line + '\n')
182 else:
183 if with_diff_header:
184 headers.append(line)
185 elif not suppress_header:
186 output.write(line + '\n')
187 result = output.getvalue()
188 output.close()
189 if with_diff_header:
190 return('\n'.join(headers), result)
191 else:
192 return result
194 def diffstat():
195 return git('diff', 'HEAD^',
196 unified=defaults.DIFF_CONTEXT,
197 stat=True)
199 def diffindex():
200 return git('diff',
201 unified=defaults.DIFF_CONTEXT,
202 stat=True,
203 cached=True)
205 def format_patch(revs):
206 '''writes patches named by revs to the "patches" directory.'''
207 num_patches = 1
208 output = []
209 kwargs = {
210 'o': 'patches',
211 'n': len(revs) > 1,
212 'thread': True,
213 'patch-with-stat': True,
215 for idx, rev in enumerate(revs):
216 real_idx = idx + num_patches
217 kwargs['start-number'] = real_idx
218 revarg = '%s^..%s'%(rev,rev)
219 output.append(git('format-patch', revarg, **kwargs))
220 num_patches += output[-1].count('\n')
221 return '\n'.join(output)
223 def config(key, value=None, local=True):
224 argv = ['config', key]
225 kwargs = {
226 'global': not local,
227 'get': value is not None,
229 if kwargs['get']:
230 # git config category.key value
231 if type(value) is bool:
232 value = str(value).lower()
233 argv.append(str(value))
234 return git(*argv, **kwargs)
236 def log(oneline=True, all=False):
237 '''Returns a pair of parallel arrays listing the revision sha1's
238 and commit summaries.'''
239 kwargs = {}
240 if oneline:
241 kwargs['pretty'] = 'oneline'
242 revs = []
243 summaries = []
244 regex = REV_LIST_REGEX
245 output = git('log', all=all, **kwargs)
246 for line in output.splitlines():
247 match = regex.match(line)
248 if match:
249 revs.append(match.group(1))
250 summaries.append(match.group(2))
251 return( revs, summaries )
253 def ls_files():
254 return git('ls-files').splitlines()
256 def ls_tree(rev):
257 '''Returns a list of(mode, type, sha1, path) tuples.'''
258 lines = git('ls-tree', '-r', rev).splitlines()
259 output = []
260 regex = re.compile('^(\d+)\W(\w+)\W(\w+)[ \t]+(.*)$')
261 for line in lines:
262 match = regex.match(line)
263 if match:
264 mode = match.group(1)
265 objtype = match.group(2)
266 sha1 = match.group(3)
267 filename = match.group(4)
268 output.append((mode, objtype, sha1, filename,) )
269 return output
271 def push(remote, local_branch, remote_branch, ffwd=True, tags=False):
272 if ffwd:
273 branch_arg = '%s:%s' % ( local_branch, remote_branch )
274 else:
275 branch_arg = '+%s:%s' % ( local_branch, remote_branch )
276 return git('push', remote, branch_arg, with_status=True, tags=tags)
278 def rebase(newbase):
279 if not newbase:
280 return 'No base branch specified to rebase.'
281 return git('rebase', newbase)
283 def remote(*args):
284 return git('remote', without_stderr=True, *args).splitlines()
286 def remote_url(name):
287 return config('remote.%s.url' % name)
289 def reset(to_unstage):
290 '''Use 'git reset' to unstage files from the index.'''
291 if not to_unstage:
292 return 'No files to reset.'
294 argv = [ 'reset', '--' ]
295 argv.extend(to_unstage)
296 return git(*argv)
298 def rev_list_range(start, end):
299 argv = [ 'rev-list', '--pretty=oneline', start, end ]
300 raw_revs = git(*argv).splitlines()
301 revs = []
302 for line in raw_revs:
303 match = REV_LIST_REGEX.match(line)
304 if match:
305 rev_id = match.group(1)
306 summary = match.group(2)
307 revs.append((rev_id, summary,) )
308 return revs
310 def show(sha1):
311 return git('show',sha1)
313 def show_cdup():
314 '''Returns a relative path to the git project root.'''
315 return git('rev-parse','--show-cdup')
317 def status():
318 '''RETURNS: A tuple of staged, unstaged and untracked files.
319 ( array(staged), array(unstaged), array(untracked) )'''
321 status_lines = git('status').splitlines()
323 unstaged_header_seen = False
324 untracked_header_seen = False
326 modified_header = '# Changed but not updated:'
327 modified_regex = re.compile('(#\tmodified:\s+'
328 '|#\tnew file:\s+'
329 '|#\tdeleted:\s+)')
331 renamed_regex = re.compile('(#\trenamed:\s+)(.*?)\s->\s(.*)')
333 untracked_header = '# Untracked files:'
334 untracked_regex = re.compile('#\t(.+)')
336 staged = []
337 unstaged = []
338 untracked = []
340 # Untracked files
341 for status_line in status_lines:
342 if untracked_header in status_line:
343 untracked_header_seen = True
344 continue
345 if not untracked_header_seen:
346 continue
347 match = untracked_regex.match(status_line)
348 if match:
349 filename = match.group(1)
350 untracked.append(filename)
352 # Staged, unstaged, and renamed files
353 for status_line in status_lines:
354 if modified_header in status_line:
355 unstaged_header_seen = True
356 continue
357 match = modified_regex.match(status_line)
358 if match:
359 tag = match.group(0)
360 filename = status_line.replace(tag, '')
361 if unstaged_header_seen:
362 unstaged.append(filename)
363 else:
364 staged.append(filename)
365 continue
366 # Renamed files
367 match = renamed_regex.match(status_line)
368 if match:
369 oldname = match.group(2)
370 newname = match.group(3)
371 staged.append(oldname)
372 staged.append(newname)
374 return( staged, unstaged, untracked )
376 def tag():
377 return git('tag').splitlines()