chiark / gitweb /
Properly detect that HEAD is detached
[stgit] / stgit / git.py
1 """Python GIT interface
2 """
3
4 __copyright__ = """
5 Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License version 2 as
9 published by the Free Software Foundation.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 """
20
21 import sys, os, re, gitmergeonefile
22 from shutil import copyfile
23
24 from stgit.exception import *
25 from stgit import basedir
26 from stgit.utils import *
27 from stgit.out import *
28 from stgit.run import *
29 from stgit.config import config
30
31 # git exception class
32 class GitException(StgException):
33     pass
34
35 # When a subprocess has a problem, we want the exception to be a
36 # subclass of GitException.
37 class GitRunException(GitException):
38     pass
39 class GRun(Run):
40     exc = GitRunException
41
42
43 #
44 # Classes
45 #
46
47 class Person:
48     """An author, committer, etc."""
49     def __init__(self, name = None, email = None, date = '',
50                  desc = None):
51         self.name = self.email = self.date = None
52         if name or email or date:
53             assert not desc
54             self.name = name
55             self.email = email
56             self.date = date
57         elif desc:
58             assert not (name or email or date)
59             def parse_desc(s):
60                 m = re.match(r'^(.+)<(.+)>(.*)$', s)
61                 assert m
62                 return [x.strip() or None for x in m.groups()]
63             self.name, self.email, self.date = parse_desc(desc)
64     def set_name(self, val):
65         if val:
66             self.name = val
67     def set_email(self, val):
68         if val:
69             self.email = val
70     def set_date(self, val):
71         if val:
72             self.date = val
73     def __str__(self):
74         if self.name and self.email:
75             return '%s <%s>' % (self.name, self.email)
76         else:
77             raise GitException, 'not enough identity data'
78
79 class Commit:
80     """Handle the commit objects
81     """
82     def __init__(self, id_hash):
83         self.__id_hash = id_hash
84
85         lines = GRun('git-cat-file', 'commit', id_hash).output_lines()
86         for i in range(len(lines)):
87             line = lines[i]
88             if not line:
89                 break # we've seen all the header fields
90             key, val = line.split(' ', 1)
91             if key == 'tree':
92                 self.__tree = val
93             elif key == 'author':
94                 self.__author = val
95             elif key == 'committer':
96                 self.__committer = val
97             else:
98                 pass # ignore other headers
99         self.__log = '\n'.join(lines[i+1:])
100
101     def get_id_hash(self):
102         return self.__id_hash
103
104     def get_tree(self):
105         return self.__tree
106
107     def get_parent(self):
108         parents = self.get_parents()
109         if parents:
110             return parents[0]
111         else:
112             return None
113
114     def get_parents(self):
115         return GRun('git-rev-list', '--parents', '--max-count=1', self.__id_hash
116                     ).output_one_line().split()[1:]
117
118     def get_author(self):
119         return self.__author
120
121     def get_committer(self):
122         return self.__committer
123
124     def get_log(self):
125         return self.__log
126
127     def __str__(self):
128         return self.get_id_hash()
129
130 # dictionary of Commit objects, used to avoid multiple calls to git
131 __commits = dict()
132
133 #
134 # Functions
135 #
136
137 def get_commit(id_hash):
138     """Commit objects factory. Save/look-up them in the __commits
139     dictionary
140     """
141     global __commits
142
143     if id_hash in __commits:
144         return __commits[id_hash]
145     else:
146         commit = Commit(id_hash)
147         __commits[id_hash] = commit
148         return commit
149
150 def get_conflicts():
151     """Return the list of file conflicts
152     """
153     conflicts_file = os.path.join(basedir.get(), 'conflicts')
154     if os.path.isfile(conflicts_file):
155         f = file(conflicts_file)
156         names = [line.strip() for line in f.readlines()]
157         f.close()
158         return names
159     else:
160         return None
161
162 def exclude_files():
163     files = [os.path.join(basedir.get(), 'info', 'exclude')]
164     user_exclude = config.get('core.excludesfile')
165     if user_exclude:
166         files.append(user_exclude)
167     return files
168
169 def tree_status(files = None, tree_id = 'HEAD', unknown = False,
170                   noexclude = True, verbose = False, diff_flags = []):
171     """Get the status of all changed files, or of a selected set of
172     files. Returns a list of pairs - (status, filename).
173
174     If 'files' is None, it will check all files, and optionally all
175     unknown files.  If 'files' is a list, it will only check the files
176     in the list.
177     """
178     assert files == None or not unknown
179
180     if verbose:
181         out.start('Checking for changes in the working directory')
182
183     refresh_index()
184
185     cache_files = []
186
187     # unknown files
188     if unknown:
189         cmd = ['git-ls-files', '-z', '--others', '--directory',
190                '--no-empty-directory']
191         if not noexclude:
192             cmd += ['--exclude=%s' % s for s in
193                     ['*.[ao]', '*.pyc', '.*', '*~', '#*', 'TAGS', 'tags']]
194             cmd += ['--exclude-per-directory=.gitignore']
195             cmd += ['--exclude-from=%s' % fn
196                     for fn in exclude_files()
197                     if os.path.exists(fn)]
198
199         lines = GRun(*cmd).raw_output().split('\0')
200         cache_files += [('?', line) for line in lines if line]
201
202     # conflicted files
203     conflicts = get_conflicts()
204     if not conflicts:
205         conflicts = []
206     cache_files += [('C', filename) for filename in conflicts
207                     if files == None or filename in files]
208
209     # the rest
210     args = diff_flags + [tree_id]
211     if files != None:
212         args += ['--'] + files
213     for line in GRun('git-diff-index', *args).output_lines():
214         fs = tuple(line.rstrip().split(' ',4)[-1].split('\t',1))
215         if fs[1] not in conflicts:
216             cache_files.append(fs)
217
218     if verbose:
219         out.done()
220
221     assert files == None or set(f for s,f in cache_files) <= set(files)
222     return cache_files
223
224 def local_changes(verbose = True):
225     """Return true if there are local changes in the tree
226     """
227     return len(tree_status(verbose = verbose)) != 0
228
229 def get_heads():
230     heads = []
231     hr = re.compile(r'^[0-9a-f]{40} refs/heads/(.+)$')
232     for line in GRun('git-show-ref', '--heads').output_lines():
233         m = hr.match(line)
234         heads.append(m.group(1))
235     return heads
236
237 # HEAD value cached
238 __head = None
239
240 def get_head():
241     """Verifies the HEAD and returns the SHA1 id that represents it
242     """
243     global __head
244
245     if not __head:
246         __head = rev_parse('HEAD')
247     return __head
248
249 class DetachedHeadException(GitException):
250     def __init__(self):
251         GitException.__init__(self, 'Not on any branch')
252
253 def get_head_file():
254     """Return the name of the file pointed to by the HEAD symref.
255     Throw an exception if HEAD is detached."""
256     try:
257         return strip_prefix(
258             'refs/heads/', GRun('git-symbolic-ref', '-q', 'HEAD'
259                                 ).output_one_line())
260     except GitRunException:
261         raise DetachedHeadException()
262
263 def set_head_file(ref):
264     """Resets HEAD to point to a new ref
265     """
266     # head cache flushing is needed since we might have a different value
267     # in the new head
268     __clear_head_cache()
269     try:
270         GRun('git-symbolic-ref', 'HEAD', 'refs/heads/%s' % ref).run()
271     except GitRunException:
272         raise GitException, 'Could not set head to "%s"' % ref
273
274 def set_ref(ref, val):
275     """Point ref at a new commit object."""
276     try:
277         GRun('git-update-ref', ref, val).run()
278     except GitRunException:
279         raise GitException, 'Could not update %s to "%s".' % (ref, val)
280
281 def set_branch(branch, val):
282     set_ref('refs/heads/%s' % branch, val)
283
284 def __set_head(val):
285     """Sets the HEAD value
286     """
287     global __head
288
289     if not __head or __head != val:
290         set_ref('HEAD', val)
291         __head = val
292
293     # only allow SHA1 hashes
294     assert(len(__head) == 40)
295
296 def __clear_head_cache():
297     """Sets the __head to None so that a re-read is forced
298     """
299     global __head
300
301     __head = None
302
303 def refresh_index():
304     """Refresh index with stat() information from the working directory.
305     """
306     GRun('git-update-index', '-q', '--unmerged', '--refresh').run()
307
308 def rev_parse(git_id):
309     """Parse the string and return a verified SHA1 id
310     """
311     try:
312         return GRun('git-rev-parse', '--verify', git_id
313                     ).discard_stderr().output_one_line()
314     except GitRunException:
315         raise GitException, 'Unknown revision: %s' % git_id
316
317 def ref_exists(ref):
318     try:
319         rev_parse(ref)
320         return True
321     except GitException:
322         return False
323
324 def branch_exists(branch):
325     return ref_exists('refs/heads/%s' % branch)
326
327 def create_branch(new_branch, tree_id = None):
328     """Create a new branch in the git repository
329     """
330     if branch_exists(new_branch):
331         raise GitException, 'Branch "%s" already exists' % new_branch
332
333     current_head = get_head()
334     set_head_file(new_branch)
335     __set_head(current_head)
336
337     # a checkout isn't needed if new branch points to the current head
338     if tree_id:
339         switch(tree_id)
340
341     if os.path.isfile(os.path.join(basedir.get(), 'MERGE_HEAD')):
342         os.remove(os.path.join(basedir.get(), 'MERGE_HEAD'))
343
344 def switch_branch(new_branch):
345     """Switch to a git branch
346     """
347     global __head
348
349     if not branch_exists(new_branch):
350         raise GitException, 'Branch "%s" does not exist' % new_branch
351
352     tree_id = rev_parse('refs/heads/%s^{commit}' % new_branch)
353     if tree_id != get_head():
354         refresh_index()
355         try:
356             GRun('git-read-tree', '-u', '-m', get_head(), tree_id).run()
357         except GitRunException:
358             raise GitException, 'git-read-tree failed (local changes maybe?)'
359         __head = tree_id
360     set_head_file(new_branch)
361
362     if os.path.isfile(os.path.join(basedir.get(), 'MERGE_HEAD')):
363         os.remove(os.path.join(basedir.get(), 'MERGE_HEAD'))
364
365 def delete_ref(ref):
366     if not ref_exists(ref):
367         raise GitException, '%s does not exist' % ref
368     sha1 = GRun('git-show-ref', '-s', ref).output_one_line()
369     try:
370         GRun('git-update-ref', '-d', ref, sha1).run()
371     except GitRunException:
372         raise GitException, 'Failed to delete ref %s' % ref
373
374 def delete_branch(name):
375     delete_ref('refs/heads/%s' % name)
376
377 def rename_ref(from_ref, to_ref):
378     if not ref_exists(from_ref):
379         raise GitException, '"%s" does not exist' % from_ref
380     if ref_exists(to_ref):
381         raise GitException, '"%s" already exists' % to_ref
382
383     sha1 = GRun('git-show-ref', '-s', from_ref).output_one_line()
384     try:
385         GRun('git-update-ref', to_ref, sha1, '0'*40).run()
386     except GitRunException:
387         raise GitException, 'Failed to create new ref %s' % to_ref
388     try:
389         GRun('git-update-ref', '-d', from_ref, sha1).run()
390     except GitRunException:
391         raise GitException, 'Failed to delete ref %s' % from_ref
392
393 def rename_branch(from_name, to_name):
394     """Rename a git branch."""
395     rename_ref('refs/heads/%s' % from_name, 'refs/heads/%s' % to_name)
396     try:
397         if get_head_file() == from_name:
398             set_head_file(to_name)
399     except DetachedHeadException:
400         pass # detached HEAD, so the renamee can't be the current branch
401     reflog_dir = os.path.join(basedir.get(), 'logs', 'refs', 'heads')
402     if os.path.exists(reflog_dir) \
403            and os.path.exists(os.path.join(reflog_dir, from_name)):
404         rename(reflog_dir, from_name, to_name)
405
406 def add(names):
407     """Add the files or recursively add the directory contents
408     """
409     # generate the file list
410     files = []
411     for i in names:
412         if not os.path.exists(i):
413             raise GitException, 'Unknown file or directory: %s' % i
414
415         if os.path.isdir(i):
416             # recursive search. We only add files
417             for root, dirs, local_files in os.walk(i):
418                 for name in [os.path.join(root, f) for f in local_files]:
419                     if os.path.isfile(name):
420                         files.append(os.path.normpath(name))
421         elif os.path.isfile(i):
422             files.append(os.path.normpath(i))
423         else:
424             raise GitException, '%s is not a file or directory' % i
425
426     if files:
427         try:
428             GRun('git-update-index', '--add', '--').xargs(files)
429         except GitRunException:
430             raise GitException, 'Unable to add file'
431
432 def __copy_single(source, target, target2=''):
433     """Copy file or dir named 'source' to name target+target2"""
434
435     # "source" (file or dir) must match one or more git-controlled file
436     realfiles = GRun('git-ls-files', source).output_lines()
437     if len(realfiles) == 0:
438         raise GitException, '"%s" matches no git-controled files' % source
439
440     if os.path.isdir(source):
441         # physically copy the files, and record them to add them in one run
442         newfiles = []
443         re_string='^'+source+'/(.*)$'
444         prefix_regexp = re.compile(re_string)
445         for f in [f.strip() for f in realfiles]:
446             m = prefix_regexp.match(f)
447             if not m:
448                 raise Exception, '"%s" does not match "%s"' % (f, re_string)
449             newname = target+target2+'/'+m.group(1)
450             if not os.path.exists(os.path.dirname(newname)):
451                 os.makedirs(os.path.dirname(newname))
452             copyfile(f, newname)
453             newfiles.append(newname)
454
455         add(newfiles)
456     else: # files, symlinks, ...
457         newname = target+target2
458         copyfile(source, newname)
459         add([newname])
460
461
462 def copy(filespecs, target):
463     if os.path.isdir(target):
464         # target is a directory: copy each entry on the command line,
465         # with the same name, into the target
466         target = target.rstrip('/')
467         
468         # first, check that none of the children of the target
469         # matching the command line aleady exist
470         for filespec in filespecs:
471             entry = target+ '/' + os.path.basename(filespec.rstrip('/'))
472             if os.path.exists(entry):
473                 raise GitException, 'Target "%s" already exists' % entry
474         
475         for filespec in filespecs:
476             filespec = filespec.rstrip('/')
477             basename = '/' + os.path.basename(filespec)
478             __copy_single(filespec, target, basename)
479
480     elif os.path.exists(target):
481         raise GitException, 'Target "%s" exists but is not a directory' % target
482     elif len(filespecs) != 1:
483         raise GitException, 'Cannot copy more than one file to non-directory'
484
485     else:
486         # at this point: len(filespecs)==1 and target does not exist
487
488         # check target directory
489         targetdir = os.path.dirname(target)
490         if targetdir != '' and not os.path.isdir(targetdir):
491             raise GitException, 'Target directory "%s" does not exist' % targetdir
492
493         __copy_single(filespecs[0].rstrip('/'), target)
494         
495
496 def rm(files, force = False):
497     """Remove a file from the repository
498     """
499     if not force:
500         for f in files:
501             if os.path.exists(f):
502                 raise GitException, '%s exists. Remove it first' %f
503         if files:
504             GRun('git-update-index', '--remove', '--').xargs(files)
505     else:
506         if files:
507             GRun('git-update-index', '--force-remove', '--').xargs(files)
508
509 # Persons caching
510 __user = None
511 __author = None
512 __committer = None
513
514 def user():
515     """Return the user information.
516     """
517     global __user
518     if not __user:
519         name=config.get('user.name')
520         email=config.get('user.email')
521         __user = Person(name, email)
522     return __user;
523
524 def author():
525     """Return the author information.
526     """
527     global __author
528     if not __author:
529         try:
530             # the environment variables take priority over config
531             try:
532                 date = os.environ['GIT_AUTHOR_DATE']
533             except KeyError:
534                 date = ''
535             __author = Person(os.environ['GIT_AUTHOR_NAME'],
536                               os.environ['GIT_AUTHOR_EMAIL'],
537                               date)
538         except KeyError:
539             __author = user()
540     return __author
541
542 def committer():
543     """Return the author information.
544     """
545     global __committer
546     if not __committer:
547         try:
548             # the environment variables take priority over config
549             try:
550                 date = os.environ['GIT_COMMITTER_DATE']
551             except KeyError:
552                 date = ''
553             __committer = Person(os.environ['GIT_COMMITTER_NAME'],
554                                  os.environ['GIT_COMMITTER_EMAIL'],
555                                  date)
556         except KeyError:
557             __committer = user()
558     return __committer
559
560 def update_cache(files = None, force = False):
561     """Update the cache information for the given files
562     """
563     cache_files = tree_status(files, verbose = False)
564
565     # everything is up-to-date
566     if len(cache_files) == 0:
567         return False
568
569     # check for unresolved conflicts
570     if not force and [x for x in cache_files
571                       if x[0] not in ['M', 'N', 'A', 'D']]:
572         raise GitException, 'Updating cache failed: unresolved conflicts'
573
574     # update the cache
575     add_files = [x[1] for x in cache_files if x[0] in ['N', 'A']]
576     rm_files =  [x[1] for x in cache_files if x[0] in ['D']]
577     m_files =   [x[1] for x in cache_files if x[0] in ['M']]
578
579     GRun('git-update-index', '--add', '--').xargs(add_files)
580     GRun('git-update-index', '--force-remove', '--').xargs(rm_files)
581     GRun('git-update-index', '--').xargs(m_files)
582
583     return True
584
585 def commit(message, files = None, parents = None, allowempty = False,
586            cache_update = True, tree_id = None, set_head = False,
587            author_name = None, author_email = None, author_date = None,
588            committer_name = None, committer_email = None):
589     """Commit the current tree to repository
590     """
591     if not parents:
592         parents = []
593
594     # Get the tree status
595     if cache_update and parents != []:
596         changes = update_cache(files)
597         if not changes and not allowempty:
598             raise GitException, 'No changes to commit'
599
600     # get the commit message
601     if not message:
602         message = '\n'
603     elif message[-1:] != '\n':
604         message += '\n'
605
606     # write the index to repository
607     if tree_id == None:
608         tree_id = GRun('git-write-tree').output_one_line()
609         set_head = True
610
611     # the commit
612     env = {}
613     if author_name:
614         env['GIT_AUTHOR_NAME'] = author_name
615     if author_email:
616         env['GIT_AUTHOR_EMAIL'] = author_email
617     if author_date:
618         env['GIT_AUTHOR_DATE'] = author_date
619     if committer_name:
620         env['GIT_COMMITTER_NAME'] = committer_name
621     if committer_email:
622         env['GIT_COMMITTER_EMAIL'] = committer_email
623     commit_id = GRun('git-commit-tree', tree_id,
624                      *sum([['-p', p] for p in parents], [])
625                      ).env(env).raw_input(message).output_one_line()
626     if set_head:
627         __set_head(commit_id)
628
629     return commit_id
630
631 def apply_diff(rev1, rev2, check_index = True, files = None):
632     """Apply the diff between rev1 and rev2 onto the current
633     index. This function doesn't need to raise an exception since it
634     is only used for fast-pushing a patch. If this operation fails,
635     the pushing would fall back to the three-way merge.
636     """
637     if check_index:
638         index_opt = ['--index']
639     else:
640         index_opt = []
641
642     if not files:
643         files = []
644
645     diff_str = diff(files, rev1, rev2)
646     if diff_str:
647         try:
648             GRun('git-apply', *index_opt).raw_input(
649                 diff_str).discard_stderr().no_output()
650         except GitRunException:
651             return False
652
653     return True
654
655 def merge(base, head1, head2, recursive = False):
656     """Perform a 3-way merge between base, head1 and head2 into the
657     local tree
658     """
659     refresh_index()
660
661     err_output = None
662     if recursive:
663         # this operation tracks renames but it is slower (used in
664         # general when pushing or picking patches)
665         try:
666             # discard output to mask the verbose prints of the tool
667             GRun('git-merge-recursive', base, '--', head1, head2
668                  ).discard_output()
669         except GitRunException, ex:
670             err_output = str(ex)
671             pass
672     else:
673         # the fast case where we don't track renames (used when the
674         # distance between base and heads is small, i.e. folding or
675         # synchronising patches)
676         try:
677             GRun('git-read-tree', '-u', '-m', '--aggressive',
678                  base, head1, head2).run()
679         except GitRunException:
680             raise GitException, 'git-read-tree failed (local changes maybe?)'
681
682     # check the index for unmerged entries
683     files = {}
684     stages_re = re.compile('^([0-7]+) ([0-9a-f]{40}) ([1-3])\t(.*)$', re.S)
685
686     for line in GRun('git-ls-files', '--unmerged', '--stage', '-z'
687                      ).raw_output().split('\0'):
688         if not line:
689             continue
690
691         mode, hash, stage, path = stages_re.findall(line)[0]
692
693         if not path in files:
694             files[path] = {}
695             files[path]['1'] = ('', '')
696             files[path]['2'] = ('', '')
697             files[path]['3'] = ('', '')
698
699         files[path][stage] = (mode, hash)
700
701     if err_output and not files:
702         # if no unmerged files, there was probably a different type of
703         # error and we have to abort the merge
704         raise GitException, err_output
705
706     # merge the unmerged files
707     errors = False
708     for path in files:
709         # remove additional files that might be generated for some
710         # newer versions of GIT
711         for suffix in [base, head1, head2]:
712             if not suffix:
713                 continue
714             fname = path + '~' + suffix
715             if os.path.exists(fname):
716                 os.remove(fname)
717
718         stages = files[path]
719         if gitmergeonefile.merge(stages['1'][1], stages['2'][1],
720                                  stages['3'][1], path, stages['1'][0],
721                                  stages['2'][0], stages['3'][0]) != 0:
722             errors = True
723
724     if errors:
725         raise GitException, 'GIT index merging failed (possible conflicts)'
726
727 def diff(files = None, rev1 = 'HEAD', rev2 = None, diff_flags = []):
728     """Show the diff between rev1 and rev2
729     """
730     if not files:
731         files = []
732
733     if rev1 and rev2:
734         return GRun('git-diff-tree', '-p',
735                     *(diff_flags + [rev1, rev2, '--'] + files)).raw_output()
736     elif rev1 or rev2:
737         refresh_index()
738         if rev2:
739             return GRun('git-diff-index', '-p', '-R',
740                         *(diff_flags + [rev2, '--'] + files)).raw_output()
741         else:
742             return GRun('git-diff-index', '-p',
743                         *(diff_flags + [rev1, '--'] + files)).raw_output()
744     else:
745         return ''
746
747 # TODO: take another parameter representing a diff string as we
748 # usually invoke git.diff() form the calling functions
749 def diffstat(files = None, rev1 = 'HEAD', rev2 = None):
750     """Return the diffstat between rev1 and rev2."""
751     return GRun('git-apply', '--stat', '--summary'
752                 ).raw_input(diff(files, rev1, rev2)).raw_output()
753
754 def files(rev1, rev2, diff_flags = []):
755     """Return the files modified between rev1 and rev2
756     """
757
758     result = []
759     for line in GRun('git-diff-tree', *(diff_flags + ['-r', rev1, rev2])
760                      ).output_lines():
761         result.append('%s %s' % tuple(line.split(' ', 4)[-1].split('\t', 1)))
762
763     return '\n'.join(result)
764
765 def barefiles(rev1, rev2):
766     """Return the files modified between rev1 and rev2, without status info
767     """
768
769     result = []
770     for line in GRun('git-diff-tree', '-r', rev1, rev2).output_lines():
771         result.append(line.split(' ', 4)[-1].split('\t', 1)[-1])
772
773     return '\n'.join(result)
774
775 def pretty_commit(commit_id = 'HEAD', diff_flags = []):
776     """Return a given commit (log + diff)
777     """
778     return GRun('git-diff-tree',
779                 *(diff_flags
780                   + ['--cc', '--always', '--pretty', '-r', commit_id])
781                 ).raw_output()
782
783 def checkout(files = None, tree_id = None, force = False):
784     """Check out the given or all files
785     """
786     if tree_id:
787         try:
788             GRun('git-read-tree', '--reset', tree_id).run()
789         except GitRunException:
790             raise GitException, 'Failed git-read-tree --reset %s' % tree_id
791
792     cmd = ['git-checkout-index', '-q', '-u']
793     if force:
794         cmd.append('-f')
795     if files:
796         GRun(*(cmd + ['--'])).xargs(files)
797     else:
798         GRun(*(cmd + ['-a'])).run()
799
800 def switch(tree_id, keep = False):
801     """Switch the tree to the given id
802     """
803     if not keep:
804         refresh_index()
805         try:
806             GRun('git-read-tree', '-u', '-m', get_head(), tree_id).run()
807         except GitRunException:
808             raise GitException, 'git-read-tree failed (local changes maybe?)'
809
810     __set_head(tree_id)
811
812 def reset(files = None, tree_id = None, check_out = True):
813     """Revert the tree changes relative to the given tree_id. It removes
814     any local changes
815     """
816     if not tree_id:
817         tree_id = get_head()
818
819     if check_out:
820         cache_files = tree_status(files, tree_id)
821         # files which were added but need to be removed
822         rm_files =  [x[1] for x in cache_files if x[0] in ['A']]
823
824         checkout(files, tree_id, True)
825         # checkout doesn't remove files
826         map(os.remove, rm_files)
827
828     # if the reset refers to the whole tree, switch the HEAD as well
829     if not files:
830         __set_head(tree_id)
831
832 def fetch(repository = 'origin', refspec = None):
833     """Fetches changes from the remote repository, using 'git-fetch'
834     by default.
835     """
836     # we update the HEAD
837     __clear_head_cache()
838
839     args = [repository]
840     if refspec:
841         args.append(refspec)
842
843     command = config.get('branch.%s.stgit.fetchcmd' % get_head_file()) or \
844               config.get('stgit.fetchcmd')
845     GRun(*(command.split() + args)).run()
846
847 def pull(repository = 'origin', refspec = None):
848     """Fetches changes from the remote repository, using 'git-pull'
849     by default.
850     """
851     # we update the HEAD
852     __clear_head_cache()
853
854     args = [repository]
855     if refspec:
856         args.append(refspec)
857
858     command = config.get('branch.%s.stgit.pullcmd' % get_head_file()) or \
859               config.get('stgit.pullcmd')
860     GRun(*(command.split() + args)).run()
861
862 def rebase(tree_id = None):
863     """Rebase the current tree to the give tree_id. The tree_id
864     argument may be something other than a GIT id if an external
865     command is invoked.
866     """
867     command = config.get('branch.%s.stgit.rebasecmd' % get_head_file()) \
868                 or config.get('stgit.rebasecmd')
869     if tree_id:
870         args = [tree_id]
871     elif command:
872         args = []
873     else:
874         raise GitException, 'Default rebasing requires a commit id'
875     if command:
876         # clear the HEAD cache as the custom rebase command will update it
877         __clear_head_cache()
878         GRun(*(command.split() + args)).run()
879     else:
880         # default rebasing
881         reset(tree_id = tree_id)
882
883 def repack():
884     """Repack all objects into a single pack
885     """
886     GRun('git-repack', '-a', '-d', '-f').run()
887
888 def apply_patch(filename = None, diff = None, base = None,
889                 fail_dump = True):
890     """Apply a patch onto the current or given index. There must not
891     be any local changes in the tree, otherwise the command fails
892     """
893     if diff is None:
894         if filename:
895             f = file(filename)
896         else:
897             f = sys.stdin
898         diff = f.read()
899         if filename:
900             f.close()
901
902     if base:
903         orig_head = get_head()
904         switch(base)
905     else:
906         refresh_index()
907
908     try:
909         GRun('git-apply', '--index').raw_input(diff).no_output()
910     except GitRunException:
911         if base:
912             switch(orig_head)
913         if fail_dump:
914             # write the failed diff to a file
915             f = file('.stgit-failed.patch', 'w+')
916             f.write(diff)
917             f.close()
918             out.warn('Diff written to the .stgit-failed.patch file')
919
920         raise
921
922     if base:
923         top = commit(message = 'temporary commit used for applying a patch',
924                      parents = [base])
925         switch(orig_head)
926         merge(base, orig_head, top)
927
928 def clone(repository, local_dir):
929     """Clone a remote repository. At the moment, just use the
930     'git-clone' script
931     """
932     GRun('git-clone', repository, local_dir).run()
933
934 def modifying_revs(files, base_rev, head_rev):
935     """Return the revisions from the list modifying the given files."""
936     return GRun('git-rev-list', '%s..%s' % (base_rev, head_rev), '--', *files
937                 ).output_lines()
938
939 def refspec_localpart(refspec):
940     m = re.match('^[^:]*:([^:]*)$', refspec)
941     if m:
942         return m.group(1)
943     else:
944         raise GitException, 'Cannot parse refspec "%s"' % line
945
946 def refspec_remotepart(refspec):
947     m = re.match('^([^:]*):[^:]*$', refspec)
948     if m:
949         return m.group(1)
950     else:
951         raise GitException, 'Cannot parse refspec "%s"' % line
952     
953
954 def __remotes_from_config():
955     return config.sections_matching(r'remote\.(.*)\.url')
956
957 def __remotes_from_dir(dir):
958     d = os.path.join(basedir.get(), dir)
959     if os.path.exists(d):
960         return os.listdir(d)
961     else:
962         return []
963
964 def remotes_list():
965     """Return the list of remotes in the repository
966     """
967     return (set(__remotes_from_config())
968             | set(__remotes_from_dir('remotes'))
969             | set(__remotes_from_dir('branches')))
970
971 def remotes_local_branches(remote):
972     """Returns the list of local branches fetched from given remote
973     """
974
975     branches = []
976     if remote in __remotes_from_config():
977         for line in config.getall('remote.%s.fetch' % remote):
978             branches.append(refspec_localpart(line))
979     elif remote in __remotes_from_dir('remotes'):
980         stream = open(os.path.join(basedir.get(), 'remotes', remote), 'r')
981         for line in stream:
982             # Only consider Pull lines
983             m = re.match('^Pull: (.*)\n$', line)
984             if m:
985                 branches.append(refspec_localpart(m.group(1)))
986         stream.close()
987     elif remote in __remotes_from_dir('branches'):
988         # old-style branches only declare one branch
989         branches.append('refs/heads/'+remote);
990     else:
991         raise GitException, 'Unknown remote "%s"' % remote
992
993     return branches
994
995 def identify_remote(branchname):
996     """Return the name for the remote to pull the given branchname
997     from, or None if we believe it is a local branch.
998     """
999
1000     for remote in remotes_list():
1001         if branchname in remotes_local_branches(remote):
1002             return remote
1003
1004     # if we get here we've found nothing, the branch is a local one
1005     return None
1006
1007 def fetch_head():
1008     """Return the git id for the tip of the parent branch as left by
1009     'git fetch'.
1010     """
1011
1012     fetch_head=None
1013     stream = open(os.path.join(basedir.get(), 'FETCH_HEAD'), "r")
1014     for line in stream:
1015         # Only consider lines not tagged not-for-merge
1016         m = re.match('^([^\t]*)\t\t', line)
1017         if m:
1018             if fetch_head:
1019                 raise GitException, 'StGit does not support multiple FETCH_HEAD'
1020             else:
1021                 fetch_head=m.group(1)
1022     stream.close()
1023
1024     if not fetch_head:
1025         raise GitException, 'No for-merge remote head found in FETCH_HEAD'
1026
1027     # here we are sure to have a single fetch_head
1028     return fetch_head
1029
1030 def all_refs():
1031     """Return a list of all refs in the current repository.
1032     """
1033
1034     return [line.split()[1] for line in GRun('git-show-ref').output_lines()]