1 """Python GIT interface
5 Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
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.
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.
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
21 import sys, os, re, gitmergeonefile
22 from shutil import copyfile
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
32 class GitException(StgException):
35 # When a subprocess has a problem, we want the exception to be a
36 # subclass of GitException.
37 class GitRunException(GitException):
41 def __init__(self, *cmd):
42 """Initialise the Run object and insert the 'git' command name.
44 Run.__init__(self, 'git', *cmd)
52 """An author, committer, etc."""
53 def __init__(self, name = None, email = None, date = '',
55 self.name = self.email = self.date = None
56 if name or email or date:
62 assert not (name or email or date)
64 m = re.match(r'^(.+)<(.+)>(.*)$', s)
66 return [x.strip() or None for x in m.groups()]
67 self.name, self.email, self.date = parse_desc(desc)
68 def set_name(self, val):
71 def set_email(self, val):
74 def set_date(self, val):
78 if self.name and self.email:
79 return '%s <%s>' % (self.name, self.email)
81 raise GitException, 'not enough identity data'
84 """Handle the commit objects
86 def __init__(self, id_hash):
87 self.__id_hash = id_hash
89 lines = GRun('cat-file', 'commit', id_hash).output_lines()
90 for i in range(len(lines)):
93 break # we've seen all the header fields
94 key, val = line.split(' ', 1)
99 elif key == 'committer':
100 self.__committer = val
102 pass # ignore other headers
103 self.__log = '\n'.join(lines[i+1:])
105 def get_id_hash(self):
106 return self.__id_hash
111 def get_parent(self):
112 parents = self.get_parents()
118 def get_parents(self):
119 return GRun('rev-list', '--parents', '--max-count=1', self.__id_hash
120 ).output_one_line().split()[1:]
122 def get_author(self):
125 def get_committer(self):
126 return self.__committer
132 return self.get_id_hash()
134 # dictionary of Commit objects, used to avoid multiple calls to git
141 def get_commit(id_hash):
142 """Commit objects factory. Save/look-up them in the __commits
147 if id_hash in __commits:
148 return __commits[id_hash]
150 commit = Commit(id_hash)
151 __commits[id_hash] = commit
155 """Return the list of file conflicts
157 conflicts_file = os.path.join(basedir.get(), 'conflicts')
158 if os.path.isfile(conflicts_file):
159 f = file(conflicts_file)
160 names = [line.strip() for line in f.readlines()]
167 files = [os.path.join(basedir.get(), 'info', 'exclude')]
168 user_exclude = config.get('core.excludesfile')
170 files.append(user_exclude)
173 def ls_files(files, tree = None, full_name = True):
174 """Return the files known to GIT or raise an error otherwise. It also
175 converts the file to the full path relative the the .git directory.
182 args.append('--with-tree=%s' % tree)
184 args.append('--full-name')
188 return GRun('ls-files', '--error-unmatch', *args).output_lines()
189 except GitRunException:
190 # just hide the details of the 'git ls-files' command we use
191 raise GitException, \
192 'Some of the given paths are either missing or not known to GIT'
194 def tree_status(files = None, tree_id = 'HEAD', unknown = False,
195 noexclude = True, verbose = False, diff_flags = []):
196 """Get the status of all changed files, or of a selected set of
197 files. Returns a list of pairs - (status, filename).
199 If 'not files', it will check all files, and optionally all
200 unknown files. If 'files' is a list, it will only check the files
203 assert not files or not unknown
206 out.start('Checking for changes in the working directory')
214 cmd = ['ls-files', '-z', '--others', '--directory',
215 '--no-empty-directory']
217 cmd += ['--exclude=%s' % s for s in
218 ['*.[ao]', '*.pyc', '.*', '*~', '#*', 'TAGS', 'tags']]
219 cmd += ['--exclude-per-directory=.gitignore']
220 cmd += ['--exclude-from=%s' % fn
221 for fn in exclude_files()
222 if os.path.exists(fn)]
224 lines = GRun(*cmd).raw_output().split('\0')
225 cache_files += [('?', line) for line in lines if line]
228 conflicts = get_conflicts()
231 cache_files += [('C', filename) for filename in conflicts
232 if not files or filename in files]
233 reported_files = set(conflicts)
236 args = diff_flags + [tree_id]
238 args += ['--'] + files
239 for line in GRun('diff-index', *args).output_lines():
240 fs = tuple(line.rstrip().split(' ',4)[-1].split('\t',1))
241 if fs[1] not in reported_files:
242 cache_files.append(fs)
243 reported_files.add(fs[1])
245 # files in the index but changed on (or removed from) disk
246 args = list(diff_flags)
248 args += ['--'] + files
249 for line in GRun('diff-files', *args).output_lines():
250 fs = tuple(line.rstrip().split(' ',4)[-1].split('\t',1))
251 if fs[1] not in reported_files:
252 cache_files.append(fs)
253 reported_files.add(fs[1])
260 def local_changes(verbose = True):
261 """Return true if there are local changes in the tree
263 return len(tree_status(verbose = verbose)) != 0
267 hr = re.compile(r'^[0-9a-f]{40} refs/heads/(.+)$')
268 for line in GRun('show-ref', '--heads').output_lines():
270 heads.append(m.group(1))
277 """Verifies the HEAD and returns the SHA1 id that represents it
282 __head = rev_parse('HEAD')
285 class DetachedHeadException(GitException):
287 GitException.__init__(self, 'Not on any branch')
290 """Return the name of the file pointed to by the HEAD symref.
291 Throw an exception if HEAD is detached."""
294 'refs/heads/', GRun('symbolic-ref', '-q', 'HEAD'
296 except GitRunException:
297 raise DetachedHeadException()
299 def set_head_file(ref):
300 """Resets HEAD to point to a new ref
302 # head cache flushing is needed since we might have a different value
306 GRun('symbolic-ref', 'HEAD', 'refs/heads/%s' % ref).run()
307 except GitRunException:
308 raise GitException, 'Could not set head to "%s"' % ref
310 def set_ref(ref, val):
311 """Point ref at a new commit object."""
313 GRun('update-ref', ref, val).run()
314 except GitRunException:
315 raise GitException, 'Could not update %s to "%s".' % (ref, val)
317 def set_branch(branch, val):
318 set_ref('refs/heads/%s' % branch, val)
321 """Sets the HEAD value
325 if not __head or __head != val:
329 # only allow SHA1 hashes
330 assert(len(__head) == 40)
332 def __clear_head_cache():
333 """Sets the __head to None so that a re-read is forced
340 """Refresh index with stat() information from the working directory.
342 GRun('update-index', '-q', '--unmerged', '--refresh').run()
344 def rev_parse(git_id):
345 """Parse the string and return a verified SHA1 id
348 return GRun('rev-parse', '--verify', git_id
349 ).discard_stderr().output_one_line()
350 except GitRunException:
351 raise GitException, 'Unknown revision: %s' % git_id
360 def branch_exists(branch):
361 return ref_exists('refs/heads/%s' % branch)
363 def create_branch(new_branch, tree_id = None):
364 """Create a new branch in the git repository
366 if branch_exists(new_branch):
367 raise GitException, 'Branch "%s" already exists' % new_branch
369 current_head_file = get_head_file()
370 current_head = get_head()
371 set_head_file(new_branch)
372 __set_head(current_head)
374 # a checkout isn't needed if new branch points to the current head
379 # Tree switching failed. Revert the head file
380 set_head_file(current_head_file)
381 delete_branch(new_branch)
384 if os.path.isfile(os.path.join(basedir.get(), 'MERGE_HEAD')):
385 os.remove(os.path.join(basedir.get(), 'MERGE_HEAD'))
387 def switch_branch(new_branch):
388 """Switch to a git branch
392 if not branch_exists(new_branch):
393 raise GitException, 'Branch "%s" does not exist' % new_branch
395 tree_id = rev_parse('refs/heads/%s^{commit}' % new_branch)
396 if tree_id != get_head():
399 GRun('read-tree', '-u', '-m', get_head(), tree_id).run()
400 except GitRunException:
401 raise GitException, 'read-tree failed (local changes maybe?)'
403 set_head_file(new_branch)
405 if os.path.isfile(os.path.join(basedir.get(), 'MERGE_HEAD')):
406 os.remove(os.path.join(basedir.get(), 'MERGE_HEAD'))
409 if not ref_exists(ref):
410 raise GitException, '%s does not exist' % ref
411 sha1 = GRun('show-ref', '-s', ref).output_one_line()
413 GRun('update-ref', '-d', ref, sha1).run()
414 except GitRunException:
415 raise GitException, 'Failed to delete ref %s' % ref
417 def delete_branch(name):
418 delete_ref('refs/heads/%s' % name)
420 def rename_ref(from_ref, to_ref):
421 if not ref_exists(from_ref):
422 raise GitException, '"%s" does not exist' % from_ref
423 if ref_exists(to_ref):
424 raise GitException, '"%s" already exists' % to_ref
426 sha1 = GRun('show-ref', '-s', from_ref).output_one_line()
428 GRun('update-ref', to_ref, sha1, '0'*40).run()
429 except GitRunException:
430 raise GitException, 'Failed to create new ref %s' % to_ref
432 GRun('update-ref', '-d', from_ref, sha1).run()
433 except GitRunException:
434 raise GitException, 'Failed to delete ref %s' % from_ref
436 def rename_branch(from_name, to_name):
437 """Rename a git branch."""
438 rename_ref('refs/heads/%s' % from_name, 'refs/heads/%s' % to_name)
440 if get_head_file() == from_name:
441 set_head_file(to_name)
442 except DetachedHeadException:
443 pass # detached HEAD, so the renamee can't be the current branch
444 reflog_dir = os.path.join(basedir.get(), 'logs', 'refs', 'heads')
445 if os.path.exists(reflog_dir) \
446 and os.path.exists(os.path.join(reflog_dir, from_name)):
447 rename(reflog_dir, from_name, to_name)
450 """Add the files or recursively add the directory contents
452 # generate the file list
455 if not os.path.exists(i):
456 raise GitException, 'Unknown file or directory: %s' % i
459 # recursive search. We only add files
460 for root, dirs, local_files in os.walk(i):
461 for name in [os.path.join(root, f) for f in local_files]:
462 if os.path.isfile(name):
463 files.append(os.path.normpath(name))
464 elif os.path.isfile(i):
465 files.append(os.path.normpath(i))
467 raise GitException, '%s is not a file or directory' % i
471 GRun('update-index', '--add', '--').xargs(files)
472 except GitRunException:
473 raise GitException, 'Unable to add file'
475 def __copy_single(source, target, target2=''):
476 """Copy file or dir named 'source' to name target+target2"""
478 # "source" (file or dir) must match one or more git-controlled file
479 realfiles = GRun('ls-files', source).output_lines()
480 if len(realfiles) == 0:
481 raise GitException, '"%s" matches no git-controled files' % source
483 if os.path.isdir(source):
484 # physically copy the files, and record them to add them in one run
486 re_string='^'+source+'/(.*)$'
487 prefix_regexp = re.compile(re_string)
488 for f in [f.strip() for f in realfiles]:
489 m = prefix_regexp.match(f)
491 raise Exception, '"%s" does not match "%s"' % (f, re_string)
492 newname = target+target2+'/'+m.group(1)
493 if not os.path.exists(os.path.dirname(newname)):
494 os.makedirs(os.path.dirname(newname))
496 newfiles.append(newname)
499 else: # files, symlinks, ...
500 newname = target+target2
501 copyfile(source, newname)
505 def copy(filespecs, target):
506 if os.path.isdir(target):
507 # target is a directory: copy each entry on the command line,
508 # with the same name, into the target
509 target = target.rstrip('/')
511 # first, check that none of the children of the target
512 # matching the command line aleady exist
513 for filespec in filespecs:
514 entry = target+ '/' + os.path.basename(filespec.rstrip('/'))
515 if os.path.exists(entry):
516 raise GitException, 'Target "%s" already exists' % entry
518 for filespec in filespecs:
519 filespec = filespec.rstrip('/')
520 basename = '/' + os.path.basename(filespec)
521 __copy_single(filespec, target, basename)
523 elif os.path.exists(target):
524 raise GitException, 'Target "%s" exists but is not a directory' % target
525 elif len(filespecs) != 1:
526 raise GitException, 'Cannot copy more than one file to non-directory'
529 # at this point: len(filespecs)==1 and target does not exist
531 # check target directory
532 targetdir = os.path.dirname(target)
533 if targetdir != '' and not os.path.isdir(targetdir):
534 raise GitException, 'Target directory "%s" does not exist' % targetdir
536 __copy_single(filespecs[0].rstrip('/'), target)
539 def rm(files, force = False):
540 """Remove a file from the repository
544 if os.path.exists(f):
545 raise GitException, '%s exists. Remove it first' %f
547 GRun('update-index', '--remove', '--').xargs(files)
550 GRun('update-index', '--force-remove', '--').xargs(files)
558 """Return the user information.
562 name=config.get('user.name')
563 email=config.get('user.email')
564 __user = Person(name, email)
568 """Return the author information.
573 # the environment variables take priority over config
575 date = os.environ['GIT_AUTHOR_DATE']
578 __author = Person(os.environ['GIT_AUTHOR_NAME'],
579 os.environ['GIT_AUTHOR_EMAIL'],
586 """Return the author information.
591 # the environment variables take priority over config
593 date = os.environ['GIT_COMMITTER_DATE']
596 __committer = Person(os.environ['GIT_COMMITTER_NAME'],
597 os.environ['GIT_COMMITTER_EMAIL'],
603 def update_cache(files = None, force = False):
604 """Update the cache information for the given files
606 cache_files = tree_status(files, verbose = False)
608 # everything is up-to-date
609 if len(cache_files) == 0:
612 # check for unresolved conflicts
613 if not force and [x for x in cache_files
614 if x[0] not in ['M', 'N', 'A', 'D']]:
615 raise GitException, 'Updating cache failed: unresolved conflicts'
618 add_files = [x[1] for x in cache_files if x[0] in ['N', 'A']]
619 rm_files = [x[1] for x in cache_files if x[0] in ['D']]
620 m_files = [x[1] for x in cache_files if x[0] in ['M']]
622 GRun('update-index', '--add', '--').xargs(add_files)
623 GRun('update-index', '--force-remove', '--').xargs(rm_files)
624 GRun('update-index', '--').xargs(m_files)
628 def commit(message, files = None, parents = None, allowempty = False,
629 cache_update = True, tree_id = None, set_head = False,
630 author_name = None, author_email = None, author_date = None,
631 committer_name = None, committer_email = None):
632 """Commit the current tree to repository
637 # Get the tree status
638 if cache_update and parents != []:
639 changes = update_cache(files)
640 if not changes and not allowempty:
641 raise GitException, 'No changes to commit'
643 # get the commit message
646 elif message[-1:] != '\n':
649 # write the index to repository
651 tree_id = GRun('write-tree').output_one_line()
657 env['GIT_AUTHOR_NAME'] = author_name
659 env['GIT_AUTHOR_EMAIL'] = author_email
661 env['GIT_AUTHOR_DATE'] = author_date
663 env['GIT_COMMITTER_NAME'] = committer_name
665 env['GIT_COMMITTER_EMAIL'] = committer_email
666 commit_id = GRun('commit-tree', tree_id,
667 *sum([['-p', p] for p in parents], [])
668 ).env(env).raw_input(message).output_one_line()
670 __set_head(commit_id)
674 def apply_diff(rev1, rev2, check_index = True, files = None):
675 """Apply the diff between rev1 and rev2 onto the current
676 index. This function doesn't need to raise an exception since it
677 is only used for fast-pushing a patch. If this operation fails,
678 the pushing would fall back to the three-way merge.
681 index_opt = ['--index']
688 diff_str = diff(files, rev1, rev2)
691 GRun('apply', *index_opt).raw_input(
692 diff_str).discard_stderr().no_output()
693 except GitRunException:
698 stages_re = re.compile('^([0-7]+) ([0-9a-f]{40}) ([1-3])\t(.*)$', re.S)
700 def merge_recursive(base, head1, head2):
701 """Perform a 3-way merge between base, head1 and head2 into the
707 # this operation tracks renames but it is slower (used in
708 # general when pushing or picking patches)
710 # discard output to mask the verbose prints of the tool
711 GRun('merge-recursive', base, '--', head1, head2).discard_output()
712 except GitRunException, ex:
716 # check the index for unmerged entries
719 for line in GRun('ls-files', '--unmerged', '--stage', '-z'
720 ).raw_output().split('\0'):
724 mode, hash, stage, path = stages_re.findall(line)[0]
726 if not path in files:
728 files[path]['1'] = ('', '')
729 files[path]['2'] = ('', '')
730 files[path]['3'] = ('', '')
732 files[path][stage] = (mode, hash)
734 if err_output and not files:
735 # if no unmerged files, there was probably a different type of
736 # error and we have to abort the merge
737 raise GitException, err_output
740 raise GitException, 'GIT index merging failed (possible conflicts)'
742 def merge(base, head1, head2):
743 """Perform a 3-way merge between base, head1 and head2 into the
749 # the fast case where we don't track renames (used when the
750 # distance between base and heads is small, i.e. folding or
751 # synchronising patches)
753 GRun('read-tree', '-u', '-m', '--aggressive', base, head1, head2
755 except GitRunException:
756 raise GitException, 'read-tree failed (local changes maybe?)'
758 # check the index for unmerged entries
760 stages_re = re.compile('^([0-7]+) ([0-9a-f]{40}) ([1-3])\t(.*)$', re.S)
762 for line in GRun('ls-files', '--unmerged', '--stage', '-z'
763 ).raw_output().split('\0'):
767 mode, hash, stage, path = stages_re.findall(line)[0]
769 if not path in files:
771 files[path]['1'] = ('', '')
772 files[path]['2'] = ('', '')
773 files[path]['3'] = ('', '')
775 files[path][stage] = (mode, hash)
777 if err_output and not files:
778 # if no unmerged files, there was probably a different type of
779 # error and we have to abort the merge
780 raise GitException, err_output
782 # merge the unmerged files
785 # remove additional files that might be generated for some
786 # newer versions of GIT
787 for suffix in [base, head1, head2]:
790 fname = path + '~' + suffix
791 if os.path.exists(fname):
795 if gitmergeonefile.merge(stages['1'][1], stages['2'][1],
796 stages['3'][1], path, stages['1'][0],
797 stages['2'][0], stages['3'][0]) != 0:
801 raise GitException, 'GIT index merging failed (possible conflicts)'
803 def diff(files = None, rev1 = 'HEAD', rev2 = None, diff_flags = [],
805 """Show the diff between rev1 and rev2
809 if binary and '--binary' not in diff_flags:
810 diff_flags = diff_flags + ['--binary']
813 return GRun('diff-tree', '-p',
814 *(diff_flags + [rev1, rev2, '--'] + files)).raw_output()
818 return GRun('diff-index', '-p', '-R',
819 *(diff_flags + [rev2, '--'] + files)).raw_output()
821 return GRun('diff-index', '-p',
822 *(diff_flags + [rev1, '--'] + files)).raw_output()
826 # TODO: take another parameter representing a diff string as we
827 # usually invoke git.diff() form the calling functions
828 def diffstat(files = None, rev1 = 'HEAD', rev2 = None):
829 """Return the diffstat between rev1 and rev2."""
830 return GRun('apply', '--stat', '--summary'
831 ).raw_input(diff(files, rev1, rev2)).raw_output()
833 def files(rev1, rev2, diff_flags = []):
834 """Return the files modified between rev1 and rev2
838 for line in GRun('diff-tree', *(diff_flags + ['-r', rev1, rev2])
840 result.append('%s %s' % tuple(line.split(' ', 4)[-1].split('\t', 1)))
842 return '\n'.join(result)
844 def barefiles(rev1, rev2):
845 """Return the files modified between rev1 and rev2, without status info
849 for line in GRun('diff-tree', '-r', rev1, rev2).output_lines():
850 result.append(line.split(' ', 4)[-1].split('\t', 1)[-1])
852 return '\n'.join(result)
854 def pretty_commit(commit_id = 'HEAD', flags = []):
855 """Return a given commit (log + diff)
857 return GRun('show', *(flags + [commit_id])).raw_output()
859 def checkout(files = None, tree_id = None, force = False):
860 """Check out the given or all files
864 GRun('read-tree', '--reset', tree_id).run()
865 except GitRunException:
866 raise GitException, 'Failed "git read-tree" --reset %s' % tree_id
868 cmd = ['checkout-index', '-q', '-u']
872 GRun(*(cmd + ['--'])).xargs(files)
874 GRun(*(cmd + ['-a'])).run()
876 def switch(tree_id, keep = False):
877 """Switch the tree to the given id
880 # only update the index while keeping the local changes
881 GRun('read-tree', tree_id).run()
885 GRun('read-tree', '-u', '-m', get_head(), tree_id).run()
886 except GitRunException:
887 raise GitException, 'read-tree failed (local changes maybe?)'
891 def reset(files = None, tree_id = None, check_out = True):
892 """Revert the tree changes relative to the given tree_id. It removes
899 cache_files = tree_status(files, tree_id)
900 # files which were added but need to be removed
901 rm_files = [x[1] for x in cache_files if x[0] in ['A']]
903 checkout(files, tree_id, True)
904 # checkout doesn't remove files
905 map(os.remove, rm_files)
907 # if the reset refers to the whole tree, switch the HEAD as well
911 def fetch(repository = 'origin', refspec = None):
912 """Fetches changes from the remote repository, using 'git fetch'
922 command = config.get('branch.%s.stgit.fetchcmd' % get_head_file()) or \
923 config.get('stgit.fetchcmd')
924 Run(*(command.split() + args)).run()
926 def pull(repository = 'origin', refspec = None):
927 """Fetches changes from the remote repository, using 'git pull'
937 command = config.get('branch.%s.stgit.pullcmd' % get_head_file()) or \
938 config.get('stgit.pullcmd')
939 Run(*(command.split() + args)).run()
941 def rebase(tree_id = None):
942 """Rebase the current tree to the give tree_id. The tree_id
943 argument may be something other than a GIT id if an external
946 command = config.get('branch.%s.stgit.rebasecmd' % get_head_file()) \
947 or config.get('stgit.rebasecmd')
953 raise GitException, 'Default rebasing requires a commit id'
955 # clear the HEAD cache as the custom rebase command will update it
957 Run(*(command.split() + args)).run()
960 reset(tree_id = tree_id)
963 """Repack all objects into a single pack
965 GRun('repack', '-a', '-d', '-f').run()
967 def apply_patch(filename = None, diff = None, base = None,
969 """Apply a patch onto the current or given index. There must not
970 be any local changes in the tree, otherwise the command fails
982 orig_head = get_head()
988 GRun('apply', '--index').raw_input(diff).no_output()
989 except GitRunException:
993 # write the failed diff to a file
994 f = file('.stgit-failed.patch', 'w+')
997 out.warn('Diff written to the .stgit-failed.patch file')
1002 top = commit(message = 'temporary commit used for applying a patch',
1005 merge(base, orig_head, top)
1007 def clone(repository, local_dir):
1008 """Clone a remote repository. At the moment, just use the
1011 GRun('clone', repository, local_dir).run()
1013 def modifying_revs(files, base_rev, head_rev):
1014 """Return the revisions from the list modifying the given files."""
1015 return GRun('rev-list', '%s..%s' % (base_rev, head_rev), '--', *files
1018 def refspec_localpart(refspec):
1019 m = re.match('^[^:]*:([^:]*)$', refspec)
1023 raise GitException, 'Cannot parse refspec "%s"' % line
1025 def refspec_remotepart(refspec):
1026 m = re.match('^([^:]*):[^:]*$', refspec)
1030 raise GitException, 'Cannot parse refspec "%s"' % line
1033 def __remotes_from_config():
1034 return config.sections_matching(r'remote\.(.*)\.url')
1036 def __remotes_from_dir(dir):
1037 d = os.path.join(basedir.get(), dir)
1038 if os.path.exists(d):
1039 return os.listdir(d)
1044 """Return the list of remotes in the repository
1046 return (set(__remotes_from_config())
1047 | set(__remotes_from_dir('remotes'))
1048 | set(__remotes_from_dir('branches')))
1050 def remotes_local_branches(remote):
1051 """Returns the list of local branches fetched from given remote
1055 if remote in __remotes_from_config():
1056 for line in config.getall('remote.%s.fetch' % remote):
1057 branches.append(refspec_localpart(line))
1058 elif remote in __remotes_from_dir('remotes'):
1059 stream = open(os.path.join(basedir.get(), 'remotes', remote), 'r')
1061 # Only consider Pull lines
1062 m = re.match('^Pull: (.*)\n$', line)
1064 branches.append(refspec_localpart(m.group(1)))
1066 elif remote in __remotes_from_dir('branches'):
1067 # old-style branches only declare one branch
1068 branches.append('refs/heads/'+remote);
1070 raise GitException, 'Unknown remote "%s"' % remote
1074 def identify_remote(branchname):
1075 """Return the name for the remote to pull the given branchname
1076 from, or None if we believe it is a local branch.
1079 for remote in remotes_list():
1080 if branchname in remotes_local_branches(remote):
1083 # if we get here we've found nothing, the branch is a local one
1087 """Return the git id for the tip of the parent branch as left by
1092 stream = open(os.path.join(basedir.get(), 'FETCH_HEAD'), "r")
1094 # Only consider lines not tagged not-for-merge
1095 m = re.match('^([^\t]*)\t\t', line)
1098 raise GitException, 'StGit does not support multiple FETCH_HEAD'
1100 fetch_head=m.group(1)
1104 out.warn('No for-merge remote head found in FETCH_HEAD')
1106 # here we are sure to have a single fetch_head
1110 """Return a list of all refs in the current repository.
1113 return [line.split()[1] for line in GRun('show-ref').output_lines()]