78aae05ea57f4b3de71ed9929af5a6aedd0fcf33
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
):
48 """An author, committer, etc."""
49 def __init__(self
, name
= None, email
= None, date
= '',
51 self
.name
= self
.email
= self
.date
= None
52 if name
or email
or date
:
58 assert not (name
or email
or date
)
60 m
= re
.match(r
'^(.+)<(.+)>(.*)$', s
)
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
):
67 def set_email(self
, val
):
70 def set_date(self
, val
):
74 if self
.name
and self
.email
:
75 return '%s <%s>' %
(self
.name
, self
.email
)
77 raise GitException
, 'not enough identity data'
80 """Handle the commit objects
82 def __init__(self
, id_hash
):
83 self
.__id_hash
= id_hash
85 lines
= GRun('git-cat-file', 'commit', id_hash
).output_lines()
86 for i
in range(len(lines
)):
89 break # we've seen all the header fields
90 key
, val
= line
.split(' ', 1)
95 elif key
== 'committer':
96 self
.__committer
= val
98 pass # ignore other headers
99 self
.__log
= '\n'.join(lines
[i
+1:])
101 def get_id_hash(self
):
102 return self
.__id_hash
107 def get_parent(self
):
108 parents
= self
.get_parents()
114 def get_parents(self
):
115 return GRun('git-rev-list', '--parents', '--max-count=1', self
.__id_hash
116 ).output_one_line().split()[1:]
118 def get_author(self
):
121 def get_committer(self
):
122 return self
.__committer
128 return self
.get_id_hash()
130 # dictionary of Commit objects, used to avoid multiple calls to git
137 def get_commit(id_hash
):
138 """Commit objects factory. Save/look-up them in the __commits
143 if id_hash
in __commits
:
144 return __commits
[id_hash
]
146 commit
= Commit(id_hash
)
147 __commits
[id_hash
] = commit
151 """Return the list of file conflicts
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()]
163 files
= [os
.path
.join(basedir
.get(), 'info', 'exclude')]
164 user_exclude
= config
.get('core.excludesfile')
166 files
.append(user_exclude
)
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).
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
178 assert files
== None or not unknown
181 out
.start('Checking for changes in the working directory')
189 cmd
= ['git-ls-files', '-z', '--others', '--directory',
190 '--no-empty-directory']
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
)]
199 lines
= GRun(*cmd
).raw_output().split('\0')
200 cache_files
+= [('?', line
) for line
in lines
if line
]
203 conflicts
= get_conflicts()
206 cache_files
+= [('C', filename
) for filename
in conflicts
207 if files
== None or filename
in files
]
210 args
= diff_flags
+ [tree_id
]
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
)
221 assert files
== None or set(f
for s
,f
in cache_files
) <= set(files
)
224 def local_changes(verbose
= True):
225 """Return true if there are local changes in the tree
227 return len(tree_status(verbose
= verbose
)) != 0
231 hr
= re
.compile(r
'^[0-9a-f]{40} refs/heads/(.+)$')
232 for line
in GRun('git-show-ref', '--heads').output_lines():
234 heads
.append(m
.group(1))
241 """Verifies the HEAD and returns the SHA1 id that represents it
246 __head
= rev_parse('HEAD')
249 class DetachedHeadException(GitException
):
251 GitException
.__init__(self
, 'Not on any branch')
254 """Return the name of the file pointed to by the HEAD symref.
255 Throw an exception if HEAD is detached."""
258 'refs/heads/', GRun('git-symbolic-ref', '-q', 'HEAD'
260 except GitRunException
:
261 raise DetachedHeadException()
263 def set_head_file(ref
):
264 """Resets HEAD to point to a new ref
266 # head cache flushing is needed since we might have a different value
270 GRun('git-symbolic-ref', 'HEAD', 'refs/heads/%s' % ref
).run()
271 except GitRunException
:
272 raise GitException
, 'Could not set head to "%s"' % ref
274 def set_ref(ref
, val
):
275 """Point ref at a new commit object."""
277 GRun('git-update-ref', ref
, val
).run()
278 except GitRunException
:
279 raise GitException
, 'Could not update %s to "%s".' %
(ref
, val
)
281 def set_branch(branch
, val
):
282 set_ref('refs/heads/%s' % branch
, val
)
285 """Sets the HEAD value
289 if not __head
or __head
!= val
:
293 # only allow SHA1 hashes
294 assert(len(__head
) == 40)
296 def __clear_head_cache():
297 """Sets the __head to None so that a re-read is forced
304 """Refresh index with stat() information from the working directory.
306 GRun('git-update-index', '-q', '--unmerged', '--refresh').run()
308 def rev_parse(git_id
):
309 """Parse the string and return a verified SHA1 id
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
324 def branch_exists(branch
):
325 return ref_exists('refs/heads/%s' % branch
)
327 def create_branch(new_branch
, tree_id
= None):
328 """Create a new branch in the git repository
330 if branch_exists(new_branch
):
331 raise GitException
, 'Branch "%s" already exists' % new_branch
333 current_head
= get_head()
334 set_head_file(new_branch
)
335 __set_head(current_head
)
337 # a checkout isn't needed if new branch points to the current head
341 if os
.path
.isfile(os
.path
.join(basedir
.get(), 'MERGE_HEAD')):
342 os
.remove(os
.path
.join(basedir
.get(), 'MERGE_HEAD'))
344 def switch_branch(new_branch
):
345 """Switch to a git branch
349 if not branch_exists(new_branch
):
350 raise GitException
, 'Branch "%s" does not exist' % new_branch
352 tree_id
= rev_parse('refs/heads/%s^{commit}' % new_branch
)
353 if tree_id
!= get_head():
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?)'
360 set_head_file(new_branch
)
362 if os
.path
.isfile(os
.path
.join(basedir
.get(), 'MERGE_HEAD')):
363 os
.remove(os
.path
.join(basedir
.get(), 'MERGE_HEAD'))
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()
370 GRun('git-update-ref', '-d', ref
, sha1
).run()
371 except GitRunException
:
372 raise GitException
, 'Failed to delete ref %s' % ref
374 def delete_branch(name
):
375 delete_ref('refs/heads/%s' % name
)
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
383 sha1
= GRun('git-show-ref', '-s', from_ref
).output_one_line()
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
389 GRun('git-update-ref', '-d', from_ref
, sha1
).run()
390 except GitRunException
:
391 raise GitException
, 'Failed to delete ref %s' % from_ref
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
)
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
)
407 """Add the files or recursively add the directory contents
409 # generate the file list
412 if not os
.path
.exists(i
):
413 raise GitException
, 'Unknown file or directory: %s' % 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
))
424 raise GitException
, '%s is not a file or directory' % i
428 GRun('git-update-index', '--add', '--').xargs(files
)
429 except GitRunException
:
430 raise GitException
, 'Unable to add file'
432 def __copy_single(source
, target
, target2
=''):
433 """Copy file or dir named 'source' to name target+target2"""
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
440 if os
.path
.isdir(source
):
441 # physically copy the files, and record them to add them in one run
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
)
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
))
453 newfiles
.append(newname
)
456 else: # files, symlinks, ...
457 newname
= target
+target2
458 copyfile(source
, newname
)
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('/')
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
475 for filespec
in filespecs
:
476 filespec
= filespec
.rstrip('/')
477 basename
= '/' + os
.path
.basename(filespec
)
478 __copy_single(filespec
, target
, basename
)
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'
486 # at this point: len(filespecs)==1 and target does not exist
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
493 __copy_single(filespecs
[0].rstrip('/'), target
)
496 def rm(files
, force
= False):
497 """Remove a file from the repository
501 if os
.path
.exists(f
):
502 raise GitException
, '%s exists. Remove it first' %f
504 GRun('git-update-index', '--remove', '--').xargs(files
)
507 GRun('git-update-index', '--force-remove', '--').xargs(files
)
515 """Return the user information.
519 name
=config
.get('user.name')
520 email
=config
.get('user.email')
521 __user
= Person(name
, email
)
525 """Return the author information.
530 # the environment variables take priority over config
532 date
= os
.environ
['GIT_AUTHOR_DATE']
535 __author
= Person(os
.environ
['GIT_AUTHOR_NAME'],
536 os
.environ
['GIT_AUTHOR_EMAIL'],
543 """Return the author information.
548 # the environment variables take priority over config
550 date
= os
.environ
['GIT_COMMITTER_DATE']
553 __committer
= Person(os
.environ
['GIT_COMMITTER_NAME'],
554 os
.environ
['GIT_COMMITTER_EMAIL'],
560 def update_cache(files
= None, force
= False):
561 """Update the cache information for the given files
563 cache_files
= tree_status(files
, verbose
= False)
565 # everything is up-to-date
566 if len(cache_files
) == 0:
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'
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']]
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
)
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
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'
600 # get the commit message
603 elif message
[-1:] != '\n':
606 # write the index to repository
608 tree_id
= GRun('git-write-tree').output_one_line()
614 env
['GIT_AUTHOR_NAME'] = author_name
616 env
['GIT_AUTHOR_EMAIL'] = author_email
618 env
['GIT_AUTHOR_DATE'] = author_date
620 env
['GIT_COMMITTER_NAME'] = committer_name
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()
627 __set_head(commit_id
)
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.
638 index_opt
= ['--index']
645 diff_str
= diff(files
, rev1
, rev2
)
648 GRun('git-apply', *index_opt
).raw_input(
649 diff_str
).discard_stderr().no_output()
650 except GitRunException
:
655 def merge(base
, head1
, head2
, recursive
= False):
656 """Perform a 3-way merge between base, head1 and head2 into the
663 # this operation tracks renames but it is slower (used in
664 # general when pushing or picking patches)
666 # discard output to mask the verbose prints of the tool
667 GRun('git-merge-recursive', base
, '--', head1
, head2
669 except GitRunException
, ex
:
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)
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?)'
682 # check the index for unmerged entries
684 stages_re
= re
.compile('^([0-7]+) ([0-9a-f]{40}) ([1-3])\t(.*)$', re
.S
)
686 for line
in GRun('git-ls-files', '--unmerged', '--stage', '-z'
687 ).raw_output().split('\0'):
691 mode
, hash, stage
, path
= stages_re
.findall(line
)[0]
693 if not path
in files
:
695 files
[path
]['1'] = ('', '')
696 files
[path
]['2'] = ('', '')
697 files
[path
]['3'] = ('', '')
699 files
[path
][stage
] = (mode
, hash)
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
706 # merge the unmerged files
709 # remove additional files that might be generated for some
710 # newer versions of GIT
711 for suffix
in [base
, head1
, head2
]:
714 fname
= path
+ '~' + suffix
715 if os
.path
.exists(fname
):
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:
725 raise GitException
, 'GIT index merging failed (possible conflicts)'
727 def diff(files
= None, rev1
= 'HEAD', rev2
= None, diff_flags
= []):
728 """Show the diff between rev1 and rev2
734 return GRun('git-diff-tree', '-p',
735 *(diff_flags
+ [rev1
, rev2
, '--'] + files
)).raw_output()
739 return GRun('git-diff-index', '-p', '-R',
740 *(diff_flags
+ [rev2
, '--'] + files
)).raw_output()
742 return GRun('git-diff-index', '-p',
743 *(diff_flags
+ [rev1
, '--'] + files
)).raw_output()
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()
754 def files(rev1
, rev2
, diff_flags
= []):
755 """Return the files modified between rev1 and rev2
759 for line
in GRun('git-diff-tree', *(diff_flags
+ ['-r', rev1
, rev2
])
761 result
.append('%s %s' %
tuple(line
.split(' ', 4)[-1].split('\t', 1)))
763 return '\n'.join(result
)
765 def barefiles(rev1
, rev2
):
766 """Return the files modified between rev1 and rev2, without status info
770 for line
in GRun('git-diff-tree', '-r', rev1
, rev2
).output_lines():
771 result
.append(line
.split(' ', 4)[-1].split('\t', 1)[-1])
773 return '\n'.join(result
)
775 def pretty_commit(commit_id
= 'HEAD', diff_flags
= []):
776 """Return a given commit (log + diff)
778 return GRun('git-diff-tree',
780 + ['--cc', '--always', '--pretty', '-r', commit_id
])
783 def checkout(files
= None, tree_id
= None, force
= False):
784 """Check out the given or all files
788 GRun('git-read-tree', '--reset', tree_id
).run()
789 except GitRunException
:
790 raise GitException
, 'Failed git-read-tree --reset %s' % tree_id
792 cmd
= ['git-checkout-index', '-q', '-u']
796 GRun(*(cmd
+ ['--'])).xargs(files
)
798 GRun(*(cmd
+ ['-a'])).run()
800 def switch(tree_id
, keep
= False):
801 """Switch the tree to the given id
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?)'
812 def reset(files
= None, tree_id
= None, check_out
= True):
813 """Revert the tree changes relative to the given tree_id. It removes
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']]
824 checkout(files
, tree_id
, True)
825 # checkout doesn't remove files
826 map(os
.remove
, rm_files
)
828 # if the reset refers to the whole tree, switch the HEAD as well
832 def fetch(repository
= 'origin', refspec
= None):
833 """Fetches changes from the remote repository, using 'git-fetch'
843 command
= config
.get('branch.%s.stgit.fetchcmd' % get_head_file
()) or \
844 config
.get('stgit.fetchcmd')
845 GRun(*(command
.split() + args
)).run()
847 def pull(repository
= 'origin', refspec
= None):
848 """Fetches changes from the remote repository, using 'git-pull'
858 command
= config
.get('branch.%s.stgit.pullcmd' % get_head_file
()) or \
859 config
.get('stgit.pullcmd')
860 GRun(*(command
.split() + args
)).run()
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
867 command
= config
.get('branch.%s.stgit.rebasecmd' % get_head_file
()) \
868 or config
.get('stgit.rebasecmd')
874 raise GitException
, 'Default rebasing requires a commit id'
876 # clear the HEAD cache as the custom rebase command will update it
878 GRun(*(command
.split() + args
)).run()
881 reset(tree_id
= tree_id
)
884 """Repack all objects into a single pack
886 GRun('git-repack', '-a', '-d', '-f').run()
888 def apply_patch(filename
= None, diff
= None, base
= None,
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
903 orig_head
= get_head()
909 GRun('git-apply', '--index').raw_input(diff
).no_output()
910 except GitRunException
:
914 # write the failed diff to a file
915 f
= file('.stgit-failed.patch', 'w+')
918 out
.warn('Diff written to the .stgit-failed.patch file')
923 top
= commit(message
= 'temporary commit used for applying a patch',
926 merge(base
, orig_head
, top
)
928 def clone(repository
, local_dir
):
929 """Clone a remote repository. At the moment, just use the
932 GRun('git-clone', repository
, local_dir
).run()
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
939 def refspec_localpart(refspec
):
940 m
= re
.match('^[^:]*:([^:]*)$', refspec
)
944 raise GitException
, 'Cannot parse refspec "%s"' % line
946 def refspec_remotepart(refspec
):
947 m
= re
.match('^([^:]*):[^:]*$', refspec
)
951 raise GitException
, 'Cannot parse refspec "%s"' % line
954 def __remotes_from_config():
955 return config
.sections_matching(r
'remote\.(.*)\.url')
957 def __remotes_from_dir(dir):
958 d
= os
.path
.join(basedir
.get(), dir)
959 if os
.path
.exists(d
):
965 """Return the list of remotes in the repository
967 return (set(__remotes_from_config())
968 |
set(__remotes_from_dir('remotes'))
969 |
set(__remotes_from_dir('branches')))
971 def remotes_local_branches(remote
):
972 """Returns the list of local branches fetched from given remote
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')
982 # Only consider Pull lines
983 m
= re
.match('^Pull: (.*)\n$', line
)
985 branches
.append(refspec_localpart(m
.group(1)))
987 elif remote
in __remotes_from_dir('branches'):
988 # old-style branches only declare one branch
989 branches
.append('refs/heads/'+remote
);
991 raise GitException
, 'Unknown remote "%s"' % remote
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.
1000 for remote
in remotes_list():
1001 if branchname
in remotes_local_branches(remote
):
1004 # if we get here we've found nothing, the branch is a local one
1008 """Return the git id for the tip of the parent branch as left by
1013 stream
= open(os
.path
.join(basedir
.get(), 'FETCH_HEAD'), "r")
1015 # Only consider lines not tagged not-for-merge
1016 m
= re
.match('^([^\t]*)\t\t', line
)
1019 raise GitException
, 'StGit does not support multiple FETCH_HEAD'
1021 fetch_head
=m
.group(1)
1025 out
.warn('No for-merge remote head found in FETCH_HEAD')
1027 # here we are sure to have a single fetch_head
1031 """Return a list of all refs in the current repository.
1034 return [line
.split()[1] for line
in GRun('git-show-ref').output_lines()]