7 from cStringIO
import StringIO
9 def git(*args
,**kwargs
):
10 """This is a convenience wrapper around run_cmd that
11 sets things up so that commands are run in the canonical
12 'git command [options] [args]' form."""
13 cmd
= 'git %s' % args
[0]
14 return utils
.run_cmd(cmd
, *args
[1:], **kwargs
)
16 class GitCommand(object):
17 """This class wraps this module so that arbitrary git commands
18 can be dynamically called at runtime."""
19 def __init__(self
, module
):
21 def __getattr__(self
, name
):
22 if hasattr(self
.module
, name
):
23 return getattr(self
.module
, name
)
24 def git_cmd(*args
, **kwargs
):
25 return git(name
.replace('_','-'), *args
, **kwargs
)
28 # At import we replace this module with a GitCommand singleton.
29 gitcmd
= GitCommand(sys
.modules
[__name__
])
30 sys
.modules
[__name__
] = gitcmd
33 #+-------------------------------------------------------------------------
34 #+ A regex for matching the output of git(log|rev-list) --pretty=oneline
35 REV_LIST_REGEX
= re
.compile('([0-9a-f]+)\W(.*)')
38 return ' '.join([ utils
.shell_quote(arg
) for arg
in argv
])
40 def add_or_remove(*to_process
):
41 """Invokes 'git add' to index the filenames in to_process that exist
42 and 'git rm' for those that do not exist."""
45 return 'No files to add or remove.'
50 for filename
in to_process
:
51 if os
.path
.exists(filename
):
52 to_add
.append(filename
)
54 output
= gitcmd
.add(verbose
=True, *to_add
)
56 if len(to_add
) == len(to_process
):
57 # to_process only contained unremoved files --
58 # short-circuit the removal checks
61 # Process files to remote
62 for filename
in to_process
:
63 if not os
.path
.exists(filename
):
64 to_remove
.append(filename
)
65 output
+ '\n\n' + gitcmd
.rm(*to_remove
)
67 def branch(name
=None, remote
=False, delete
=False):
69 return git('branch', name
, D
=True)
71 branches
= map(lambda x
: x
.lstrip('* '),
72 git('branch', r
=remote
).splitlines())
75 for branch
in branches
:
76 if branch
.endswith('/HEAD'):
78 remotes
.append(branch
)
82 def cherry_pick(revs
, commit
=False):
83 """Cherry-picks each revision into the current branch.
84 Returns a list of command output strings (1 per cherry pick)"""
86 if not revs
: return []
88 argv
= [ 'cherry-pick' ]
95 new_argv
= argv
+ [rev
]
96 cherries
.append(git(*new_argv
, **kwargs
))
98 return '\n'.join(cherries
)
100 def commit_with_msg(msg
, amend
=False):
101 """Creates a git commit."""
103 if not msg
.endswith('\n'):
106 # Sure, this is a potential "security risk," but if someone
107 # is trying to intercept/re-write commit messages on your system,
108 # then you probably have bigger problems to worry about.
109 tmpfile
= utils
.get_tmp_filename()
115 # Create the commit message file
116 file = open(tmpfile
, 'w')
121 output
= gitcmd
.commit(F
=tmpfile
, amend
=amend
)
124 return ('git commit -F %s --amend %s\n\n%s'
125 % ( tmpfile
, amend
, output
))
127 def create_branch(name
, base
, track
=False):
128 """Creates a branch starting from base. Pass track=True
129 to create a remote tracking branch."""
130 return git('branch', name
, base
, track
=track
)
132 def current_branch():
133 """Parses 'git branch' to find the current branch."""
134 branches
= git('branch').splitlines()
135 for branch
in branches
:
136 if branch
.startswith('* '):
137 return branch
.lstrip('* ')
138 return 'Detached HEAD'
140 def diff_helper(commit
=None,
144 with_diff_header
=False,
145 suppress_header
=True,
147 "Invokes git diff on a filepath."
151 argv
.append('%s^..%s' % (commit
, commit
))
155 if type(filename
) is list:
156 argv
.extend(filename
)
158 argv
.append(filename
)
165 unified
= defaults
.DIFF_CONTEXT
,
171 del_tag
= 'deleted file mode '
174 deleted
= cached
and not os
.path
.exists(filename
)
176 if not start
and '@@ ' in line
and ' @@' in line
:
178 if start
or(deleted
and del_tag
in line
):
179 output
.write(line
+ '\n')
183 elif not suppress_header
:
184 output
.write(line
+ '\n')
185 result
= output
.getvalue()
188 return('\n'.join(headers
), result
)
195 unified
=defaults
.DIFF_CONTEXT
,
200 unified
=defaults
.DIFF_CONTEXT
,
204 def format_patch_helper(revs
):
205 """writes patches named by revs to the "patches" directory."""
208 for idx
, rev
in enumerate(revs
):
209 real_idx
= idx
+ num_patches
210 revarg
= '%s^..%s' % (rev
,rev
)
215 start_number
=real_idx
,
221 num_patches
+= output
[-1].count('\n')
222 return '\n'.join(output
)
224 def config_dict(local
=True):
228 argv
= ['--global', '--list' ]
229 return config_to_dict(
230 gitcmd
.config(*argv
).splitlines())
232 def config_set(key
=None, value
=None, local
=True):
233 if key
and value
is not None:
234 # git config category.key value
236 if type(value
) is bool:
237 # git uses "true" and "false"
238 strval
= strval
.lower()
240 argv
= [ key
, strval
]
242 argv
= [ '--global', key
, strval
]
243 return gitcmd
.config(*argv
)
245 msg
= "oops in git.config_set(key=%s,value=%s,local=%s"
246 raise Exception(msg
% (key
, value
, local
))
248 def config_to_dict(config_lines
):
249 """parses the lines from git config --list into a dictionary"""
252 for line
in config_lines
:
253 k
, v
= line
.split('=')
254 k
= k
.replace('.','_') # git -> model
255 if v
== 'true' or v
== 'false':
256 v
= bool(eval(v
.title()))
264 def log(oneline
=True, all
=False):
265 """Returns a pair of parallel arrays listing the revision sha1's
266 and commit summaries."""
269 kwargs
['pretty'] = 'oneline'
272 regex
= REV_LIST_REGEX
273 output
= git('log', all
=all
, **kwargs
)
274 for line
in output
.splitlines():
275 match
= regex
.match(line
)
277 revs
.append(match
.group(1))
278 summaries
.append(match
.group(2))
279 return( revs
, summaries
)
282 """Returns a list of(mode, type, sha1, path) tuples."""
283 lines
= git('ls-tree', rev
, r
=True).splitlines()
285 regex
= re
.compile('^(\d+)\W(\w+)\W(\w+)[ \t]+(.*)$')
287 match
= regex
.match(line
)
289 mode
= match
.group(1)
290 objtype
= match
.group(2)
291 sha1
= match
.group(3)
292 filename
= match
.group(4)
293 output
.append((mode
, objtype
, sha1
, filename
,) )
296 def push(remote
, local_branch
, remote_branch
, ffwd
=True, tags
=False):
298 branch_arg
= '%s:%s' % ( local_branch
, remote_branch
)
300 branch_arg
= '+%s:%s' % ( local_branch
, remote_branch
)
301 return git('push', remote
, branch_arg
, with_status
=True, tags
=tags
)
303 def remote_url(name
):
304 return gitcmd
.config('remote.%s.url' % name
, get
=True)
306 def rev_list_range(start
, end
):
307 range = '%s..%s' % ( start
, end
)
308 raw_revs
= gitcmd
.rev_list(range, pretty
='oneline').splitlines()
310 for line
in raw_revs
:
311 match
= REV_LIST_REGEX
.match(line
)
313 rev_id
= match
.group(1)
314 summary
= match
.group(2)
315 revs
.append((rev_id
, summary
,) )
319 """RETURNS: A tuple of staged, unstaged and untracked file lists."""
321 MODIFIED_TAG
= '# Changed but not updated:'
322 UNTRACKED_TAG
= '# Untracked files:'
324 RGX_RENAMED
= re
.compile(
329 RGX_MODIFIED
= re
.compile(
343 current_dest
= staged
345 for status_line
in gitcmd
.status().splitlines():
346 if status_line
== MODIFIED_TAG
:
348 current_dest
= unstaged
351 elif status_line
== UNTRACKED_TAG
:
352 mode
= UNTRACKED_MODE
353 current_dest
= untracked
356 # Staged/unstaged modified/renamed/deleted files
357 if mode
== STAGED_MODE
or mode
== UNSTAGED_MODE
:
358 match
= RGX_MODIFIED
.match(status_line
)
361 filename
= status_line
.replace(tag
, '')
362 current_dest
.append(filename
)
364 match
= RGX_RENAMED
.match(status_line
)
366 oldname
= match
.group(2)
367 newname
= match
.group(3)
368 current_dest
.append(oldname
)
369 current_dest
.append(newname
)
372 elif mode
is UNTRACKED_MODE
:
373 if status_line
.startswith('#\t'):
374 current_dest
.append(status_line
[2:])
376 return( staged
, unstaged
, untracked
)