本文整理汇总了Python中pygit2.Repository.listall_references方法的典型用法代码示例。如果您正苦于以下问题:Python Repository.listall_references方法的具体用法?Python Repository.listall_references怎么用?Python Repository.listall_references使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pygit2.Repository
的用法示例。
在下文中一共展示了Repository.listall_references方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: init
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import listall_references [as 别名]
def init(req):
print "args:", req.args, req.args.path
repo_path = os.path.join(req.args.path,'.git')
if not os.path.isdir(repo_path):
raise Abort("no repository found in '%s' (.git not found)!" % (os.path.abspath(req.args.path)))
repo = Repository(req.args.path)
print "repo references:", repo.listall_references()
xxl_path = os.path.join(req.args.path,'.gitxxl')
if os.path.exists(xxl_path):
print "reinitializing existing XXL repo"
else:
print "initialiling XXL repo"
os.mkdir(xxl_path)
#install commit hooks
dst = os.path.join(repo_path,"hooks","pre-commit")
if not os.path.isfile(dst):
src = os.path.join(sys.exec_prefix,"dist","hooks","pre-commit")
print "installing pre-commit hook from:", src
shutil.copyfile(src, dst)
perm = os.stat(dst)
os.chmod(dst,perm.st_mode | stat.S_IXUSR)
dst = os.path.join(repo_path,"hooks","post-commit")
if not os.path.isfile(dst):
src = os.path.join(sys.exec_prefix,"dist","hooks","post-commit")
print "installing post-commit hook from:", src
shutil.copyfile(src, dst)
perm = os.stat(dst)
os.chmod(dst,perm.st_mode | stat.S_IXUSR)
示例2: init_repo
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import listall_references [as 别名]
def init_repo(repo_path, clone_from=None, clone_refs=False,
alternate_repo_paths=None, is_bare=True):
"""Initialise a new git repository or clone from existing."""
assert is_valid_new_path(repo_path)
init_repository(repo_path, is_bare)
if clone_from:
# The clone_from's objects and refs are in fact cloned into a
# subordinate tree that's then set as an alternate for the real
# repo. This lets git-receive-pack expose available commits as
# extra haves without polluting refs in the real repo.
sub_path = os.path.join(repo_path, 'turnip-subordinate')
clone_repository(clone_from, sub_path, True)
assert is_bare
alt_path = os.path.join(repo_path, 'objects/info/alternates')
with open(alt_path, 'w') as f:
f.write('../turnip-subordinate/objects\n')
if clone_refs:
# With the objects all accessible via the subordinate, we
# can just copy all refs from the origin. Unlike
# pygit2.clone_repository, this won't set up a remote.
# TODO: Filter out internal (eg. MP) refs.
from_repo = Repository(clone_from)
to_repo = Repository(repo_path)
for ref in from_repo.listall_references():
to_repo.create_reference(
ref, from_repo.lookup_reference(ref).target)
if alternate_repo_paths:
write_alternates(repo_path, alternate_repo_paths)
ensure_config(repo_path) # set repository configuration defaults
return repo_path
示例3: git_is_clean
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import listall_references [as 别名]
def git_is_clean(srcdir, project):
repo = Repository(os.path.join(srcdir, project.workspace_path, ".git"))
for _, b in iteritems(repo.status()):
if b != GIT_STATUS_IGNORED and b != GIT_STATUS_CURRENT:
return False, "has uncommitted changes"
if repo.head_is_detached:
return False, "has detached HEAD"
origin = get_origin(repo, project)
if not origin:
return False, "has no upstream remote"
remote_refs = []
local_refs = {}
for refname in repo.listall_references():
if refname.startswith("refs/remotes/%s/" % origin.name):
ref = repo.lookup_reference(refname)
if ref.type == GIT_REF_OID:
remote_refs.append(ref.target)
elif not refname.startswith("refs/remotes/"):
ref = repo.lookup_reference(refname)
if ref.type == GIT_REF_OID:
local_refs[ref.peel().id] = refname
if not remote_refs:
return False, "has no upstream remote branches"
if not local_refs:
return False, "has no local branches"
if not repo.lookup_branch("%s/%s" % (origin.name, project.master_branch), GIT_BRANCH_REMOTE):
return False, "has no upstream master branch"
for remote_ref in remote_refs:
for commit in repo.walk(remote_ref):
if commit.id in local_refs:
del local_refs[commit.id]
if local_refs:
return False, "has local commits: %s" % ", ".join(["'%s'" % name for _, name in iteritems(local_refs)])
return True, ""
示例4: Git
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import listall_references [as 别名]
class Git(object):
r"""
Interact with a git repository.
"""
def __init__(self, gitdir):
r"""
Take a path to the git repository. Other methods interact with
this git repository.
"""
self.repo = Repository(gitdir)
def branches(self):
r"""
Return the list of a branch name and its last commit id.
"""
return self._refs('heads')
def tags(self):
r"""
Return the list of a tag name and its last commit id.
"""
return self._refs('tags')
def _refs(self, type):
refs = {}
pattern = re.compile(r'refs/%s/(.*)$' % type)
for ref in self.repo.listall_references():
m = pattern.match(ref)
if m:
reference = self.repo.lookup_reference(ref)
refs[m.group(1)] = reference.hex
return refs
def create_branch(self, name, target):
r"""
Create new branch.
"""
if not is_valid_value(name):
raise InvalidParamException("name is required")
if not is_valid_hex(target):
raise InvalidParamException("target is required")
target = sha_hex2bin(target)
try:
self.repo.create_reference('refs/heads/%s' % name, target)
except Exception, e:
raise InvalidParamException(str(e))
return True
示例5: GitStorage
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import listall_references [as 别名]
#.........这里部分代码省略.........
return self._get_obj(path, Blob).data
def listdir(self, path):
if path:
tree = self._get_obj(path, Tree)
else:
if self._commit is None:
return []
tree = self._commit.tree
return [entry.name for entry in tree]
def format(self, **kw):
# XXX backwards compatibility??
return kw
def log(self, start, count, branch=None, shortlog=False):
"""
start and branch are literally the same thing.
"""
def _log(iterator):
for pos, commit in iterator:
if pos == count:
raise StopIteration
yield {
'author': commit.committer.name,
'email': self._commit.committer.email,
'date': self.strftime(committer_dt(commit.committer)),
'node': commit.hex,
'rev': commit.hex,
'desc': commit.message
}
if start is None:
# assumption.
start = 'HEAD'
try:
self.repo.revparse_single(start)
except KeyError:
return []
try:
rev = self.repo.revparse_single(start).hex
except KeyError:
raise RevisionNotFoundError('revision %s not found' % start)
iterator = enumerate(self.repo.walk(rev, GIT_SORT_TIME))
return list(_log(iterator))
def pathinfo(self, path):
obj = self._get_obj(path)
if isinstance(obj, Blob):
return self.format(**{
'type': 'file',
'basename': self.basename(path),
'size': obj.size,
'date': self.strftime(committer_dt(self._commit.committer)),
})
elif isinstance(obj, dict):
# special cases are represented as dict.
if obj[''] == '_subrepo':
return self.format(**{
'type': 'subrepo',
'date': '',
'size': 0,
'basename': self.basename(path),
# extra field.
'obj': obj,
})
elif obj[''] == '_empty_root':
return self.format(**{
'type': 'folder',
'date': '',
'size': 0,
'basename': self.basename(path),
})
# Assume this is a Tree.
return self.format(**{
'basename': self.basename(path),
'size': 0,
'type': 'folder',
'date': '',
})
def branches(self):
return tuple(
(b, self.repo.lookup_branch(b).target.hex)
for b in self.repo.listall_branches()
)
def tags(self):
return tuple(
(b[10:], self.repo.lookup_reference(b).target.hex)
for b in self.repo.listall_references()
if b.startswith('refs/tags')
)
示例6: GitRepo
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import listall_references [as 别名]
class GitRepo(object):
''' git repo class '''
def __init__(self, path):
try:
self.__repo = Repository(path)
except Exception as e:
self.__repo = None
print(e)
def get_info(self):
if not self.__repo:
return None
signature = self.__repo.default_signature
result = {
'path': self.__repo.path,
'workdir': self.__repo.workdir,
'bare': self.__repo.is_bare,
'empty': self.__repo.is_empty,
'name': signature.name,
'email': signature.email,
'time': signature.time,
'offset': signature.offset,
}
return result
def get_all_references(self):
return self.__repo.listall_references()
def get_reference(self, name):
if not self.__repo:
return None
ref = None
try:
ref = self.__repo.lookup_reference(name)
except Exception as e:
print(e)
return ref
def get_all_branches(self, branch_type=None):
if not self.__repo:
return None
if branch_type:
return self.__repo.listall_branches(branch_type)
r = self.__repo.listall_branches(GIT_BRANCH_LOCAL | GIT_BRANCH_REMOTE)
return r
def get_branch(self, name, branch_type=GIT_BRANCH_LOCAL):
if not self.__repo:
return None
return self.__repo.lookup_branch(name, branch_type)
def check_branch(self, name, branch_type=None):
if not branch_type:
if '/' in name:
branch_type = GIT_BRANCH_REMOTE
else:
branch_type = GIT_BRANCH_LOCAL
try:
result = self.get_branch(name, branch_type)
return result
except Exception as e:
print(e)
return False
def get_current_commit(self):
if not self.__repo:
return None
commit = self.__repo.revparse_single('HEAD')
return self.get_commit(commit)
def get_commit_by_branch(self, branch):
if not self.__repo:
return None
query = 'refs/'
if hasattr(branch, 'remote_name'):
query += 'remotes/'
else:
query += 'heads/'
query += branch.branch_name
try:
ref = self.get_reference(query)
commit = ref.target
return self.get_commit(commit)
except Exception as e:
print(e)
return None
def get_commit_by_tag(self, tag):
if self.__repo is None:
return None
if tag:
commit = tag.get_object()
return self.get_commit(commit)
return None
def get_commit(self, oid_or_commit):
''' return a commit w/ json '''
if not self.__repo or not oid_or_commit:
#.........这里部分代码省略.........
示例7: Document
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import listall_references [as 别名]
class Document(object):
'''
Class representing a document, interacts with the git
database
'''
def __init__( self, name, create=False, rootPath=None ):
'''
Constructor
Args:
name The name of the document
create If true, will create a document
rootPath The rootPath to use (if not supplied, uses default)
Exceptions:
RepoNotFound if repository isn't found
'''
if not rootPath:
rootPath = DEFAULT_ROOT_PATH
targetDir = os.path.join( rootPath, name + '.git' )
if create:
# Create a bare repository
self.repo = init_repository( targetDir, True )
self._CreateMasterBranch()
else:
try:
self.repo = Repository( targetDir )
except KeyError:
raise RepoNotFound()
def _CreateMasterBranch( self ):
'''
Creates the master branch on the repo w/ default file.
For now this is just a file named layout
'''
commitId = CommitBlob(
self.repo, '', SECTION_INDEX_FILENAME, 'Initial commit'
)
self.repo.create_reference( MASTER_REF, commitId )
@staticmethod
def _IsSectionRef( refName ):
'''
Checks if a refererence name refers to a section
Args:
refName: The reference name
Returns:
A boolean
'''
return refName.startswith( SECTION_REF_PREFIX )
@staticmethod
def _RefNameToSectionName( refName ):
'''
Converts a reference name to a section name
Args:
ref: The reference name
'''
return refName[ len(SECTION_REF_PREFIX) : ]
def _SectionRefs( self ):
'''
Gets an iterator over the section refs
'''
return (
(
self._RefNameToSectionName( ref ),
self.repo.lookup_reference( ref ),
)
for ref in self.repo.listall_references()
if self._IsSectionRef( ref )
)
def Sections( self ):
'''
Gets an iterator over all the sections
'''
return (
Section( name, self.repo[ref.oid], self.repo )
for name, ref in self._SectionRefs()
)
def CurrentSections( self ):
'''
Gets the current sections with their positions
Returns:
A list of tuples ( position, section )
'''
return enumerate( self._CurrentSections() )
def _CurrentSections( self ):
'''
Internal method to get the current sections
in order, without position numbers
Returns:
An iterator over the sections
#.........这里部分代码省略.........
示例8: GitMixin
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import listall_references [as 别名]
class GitMixin(object):
tag_or_remote_regex = re.compile('^refs/(tags|remotes)/(.*)')
def __init__(self):
where = GitOperations.get_repository_location(self.user, self.name)
self.ondisk = Repository(where)
def refresh(self):
creds = GitOperations.get_credentials(self.git_user, self.user)
for remote in self.ondisk.remotes:
remote.credentials = creds
remote.fetch()
# update current reference
master_ref = self.ondisk.lookup_reference('refs/heads/master')
remote_ref = self.ondisk.lookup_reference('refs/remotes/origin/master')
master_ref.set_target(remote_ref.target)
def filter_references(self, regex):
return [ref for ref in self.ondisk.listall_references()
if regex.match(ref)]
def get_commit_time(self, name):
ref = self.ondisk.revparse_single(name)
if isinstance(ref, Tag):
return ref.get_object().commit_time
if isinstance(ref, Commit):
return ref.commit_time
raise GitException('invalid reference: commit time could not be found.') # pragma: no cover
def get_latest_refs(self, count=None):
info = self.filter_references(GitMixin.tag_or_remote_regex)
refs = list(zip(info, map(self.get_commit_time, info)))
refs.sort(key=itemgetter(1), reverse=True)
def ref_info(info):
(ref, commit_time) = info
what, name = GitMixin.tag_or_remote_regex.findall(ref)[0]
return (what, name, commit_time)
refs = map(ref_info, refs)
if not count:
return refs
return islice(refs, count)
def filter_commits(self, flags=0):
all_commits = self.ondisk.walk(self.ondisk.head.target, flags)
emails = [ue.email for ue in self.user.emails.all()]
return filter(lambda commit: commit.author.email in emails, all_commits)
def get_commits(self, count=None):
all_commits = self.filter_commits(GIT_SORT_TOPOLOGICAL)
if not count:
return all_commits
return islice(all_commits, count)
def get_commit_count(self):
return len(list(self.filter_commits()))
def get_shorthand_of_branch(self, branch):
commit = self.ondisk.lookup_branch(branch)
if commit:
return commit.shorthand
return '(none)'
def get_sha1_of_branch(self, branch):
commit = self.ondisk.lookup_branch(branch)
if commit:
return str(commit.get_object().id)[:6]
return '(none)'
def get_numstat(self, commit):
diff = None
try:
previous_commit = self.ondisk.revparse_single(str(commit.id) + '^')
diff = self.ondisk.diff(previous_commit, commit)
except KeyError:
# likely we hit the very first commit.
diff = commit.tree.diff_to_tree(swap=True)
additions, deletions = 0, 0
for patch in diff:
additions += patch.additions
deletions += patch.deletions
return (len(diff), additions, deletions)
def get_first_updated(self):
all_commits = self.ondisk.walk(self.ondisk.head.target,
GIT_SORT_TIME | GIT_SORT_REVERSE)
first_commit = next(all_commits)
return first_commit.commit_time
def get_last_updated(self):
all_commits = self.ondisk.walk(self.ondisk.head.target,
GIT_SORT_TIME)
last_commit = next(all_commits)
return last_commit.commit_time
def get_file_count(self):
diff = self.ondisk.head.get_object().tree.diff_to_tree()
return len([patch.old_file_path for patch in diff])
def get_line_count(self):
#.........这里部分代码省略.........