本文整理汇总了Python中pygit2.Repository.lookup_reference方法的典型用法代码示例。如果您正苦于以下问题:Python Repository.lookup_reference方法的具体用法?Python Repository.lookup_reference怎么用?Python Repository.lookup_reference使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pygit2.Repository
的用法示例。
在下文中一共展示了Repository.lookup_reference方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: git_is_clean
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import lookup_reference [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, ""
示例2: init_repo
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import lookup_reference [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: sync_handler
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import lookup_reference [as 别名]
def sync_handler(fork_from: str, from_sha: str, repo_name: str,
ticket_id: int, pr_url: str):
output_path = '{}.txt'.format(pr_url.split('/', 3)[3].rsplit('/', 2)[0])
output_path = os.path.join(WORK_DIR, output_path.replace('/', '_'))
work_tree = os.path.join(WORK_DIR, fork_from)
parent_path = os.path.dirname(work_tree)
if not os.path.exists(parent_path):
os.makedirs(parent_path)
if not os.path.exists(work_tree):
repo = clone_repository(
'{0}{1}.git'.format(GITHUB_URL, fork_from), work_tree)
else:
repo = Repository(work_tree)
remote_name = repo_name.split('/')[0]
update_remote(work_tree, repo, repo_name, remote_name)
if remote_name == 'origin':
commit = repo.revparse_single(from_sha)
repo.checkout_tree(commit, strategy=GIT_CHECKOUT_FORCE)
else:
ref_name = 'refs/pull/{0}/head'.format(ticket_id)
try:
repo.create_reference(ref_name, from_sha)
except ValueError:
pass
ref = repo.lookup_reference(ref_name)
repo.checkout(ref, strategy=GIT_CHECKOUT_FORCE)
cwd = os.getcwd()
os.chdir(work_tree)
subprocess.call(
'{} . --output-file={}'.format(FLAKE8_EXECUTABLE, output_path),
shell=True)
os.chdir(cwd)
return output_path
示例4: get_current_branch
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import lookup_reference [as 别名]
def get_current_branch(path_to_repository):
"""Utility method for getting the current branch from a Git repository.
Args:
path_to_repository (str): Path to the Git repository
Returns:
str: The current branch in the provided repository.
"""
repo = Repository(path_to_repository)
head = repo.lookup_reference("HEAD").resolve()
return head.shorthand
示例5: Git
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import lookup_reference [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
示例6: shift
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import lookup_reference [as 别名]
def shift(amount, repo_path):
repo = Repository(repo_path)
head = repo.lookup_reference('HEAD').resolve()
adder = partial(add, amount=amount)
changelog = dict()
reference = REF_FMT.format(time=time(), pid=getpid())
for commit in repo.walk(head.oid, GIT_SORT_REVERSE | GIT_SORT_TOPOLOGICAL):
newmsg, nsubs = ISSUE_RE.subn(adder, commit.message)
if nsubs != 0 or any(pnt.oid in changelog for pnt in commit.parents):
parents = [changelog.get(c.oid, c.oid) for c in commit.parents]
new_oid = repo.create_commit(reference, commit.author,
commit.committer, newmsg, commit.tree.oid, parents)
changelog[commit.oid] = new_oid
return changelog, reference
示例7: _fast_forward
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import lookup_reference [as 别名]
def _fast_forward(self, local_path, merge_target, branch):
# fast-forward all the branches.
# pygit2 repo
repo = Repository(discover_repository(local_path))
# convert merge_target from hex into oid.
fetch_head = repo.revparse_single(merge_target)
# try to resolve a common anscestor between fetched and local
try:
head = repo.revparse_single(branch)
except KeyError:
# Doesn't exist. Create and done.
repo.create_reference(branch, fetch_head.oid)
return True, 'Created new branch: %s' % branch
if head.oid == fetch_head.oid:
return True, 'Source and target are identical.'
# raises KeyError if no merge bases found.
common_oid = repo.merge_base(head.oid, fetch_head.oid)
# Three different outcomes between the remaining cases.
if common_oid.hex not in (head.oid.hex, fetch_head.oid.hex):
# common ancestor is beyond both of these, not going to
# attempt a merge here and will assume this:
return False, 'Branch will diverge.'
elif common_oid.hex == fetch_head.oid.hex:
# Remote is also the common ancestor, so nothing to do.
return True, 'No new changes found.'
# This case remains: common_oid.hex == head.oid.hex, meaning
# this local repository is the ancestor of further changes
# fetched from the remote - remote newer, so fast-forward.
ref = repo.lookup_reference(branch)
ref.delete()
repo.create_reference(branch, fetch_head.oid)
return True, 'Fast-forwarded branch: %s' % branch
示例8: ChangeCtxDefault
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import lookup_reference [as 别名]
class ChangeCtxDefault(ChangeCtx):
"""Class with the specific implementation details for the change context
of the default revision state of the repository. It inherits the common
implementation from the class :class:`ChangeCtxBase`.
"""
def __init__(self, repo_path):
self._repo_path = repo_path
self._repo = Repository(self._repo_path)
self._ctx = self._repo[self.revision_id]
@locked_cached_property
def files(self):
def r(_files, repo, tree, prefix=None):
for entry in tree:
obj = repo[entry.oid]
filename = prefix and (prefix + '/' + entry.name) or entry.name
if obj.type == GIT_OBJ_TREE:
r(_files, repo, obj, filename)
elif obj.type == GIT_OBJ_BLOB:
_files.append(filename)
else:
raise RuntimeError('Invalid object: %s' % filename)
f = []
r(f, self._repo, self._ctx.tree)
return sorted(f)
@locked_cached_property
def revision_id(self):
"""This property should be cached because the lookup_reference method
reloads itself.
"""
try:
ref = self._repo.lookup_reference('refs/heads/master')
except Exception:
raise RuntimeError('Branch "master" not found!')
return ref.target
def needs_reload(self):
try:
ref = self._repo.lookup_reference('refs/heads/master')
except Exception:
return True
return self.revision_id != ref.target
def filectx_needs_reload(self, filectx):
try:
ref = self._repo.lookup_reference('refs/heads/master')
except Exception:
raise RuntimeError('Branch "master" not found!')
return filectx._changectx.oid != ref.target
def published(self, date, now):
return date <= now
def etag(self, filectx):
return 'blohg-%i-%i-%s' % (filectx.mdate or filectx.date,
len(filectx.data), adler32(filectx.path)
& 0xffffffff)
def get_filectx(self, path):
return FileCtx(self._repo, self._ctx, path)
示例9: GitStorage
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import lookup_reference [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')
)
示例10: Repository
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import lookup_reference [as 别名]
conn.commit()
# Loop through the projects in the config file
for repo_name in config.sections():
# Attempt to open an existing local repo
try:
local_dir = os.path.join(base_path, 'repos', repo_name + '.git')
repo = Repository(local_dir)
# Fetch the latest commits (equivalent to "git fetch origin")
progress = repo.remotes["origin"].fetch()
# Update HEAD with the new commits (equivalent to "git update-ref HEAD FETCH_HEAD")
head = repo.head
fetch_head = repo.lookup_reference('FETCH_HEAD')
new_head = head.set_target(fetch_head.target)
# Notice new branches added to the origin
os.chdir(local_dir)
update_result = subprocess.call(["git", "remote", "update", "origin"])
# Prune local branches no longer present on the origin
prune_result = subprocess.call(["git", "remote", "prune", "origin"])
# Run git gc, to stop potential unlimited repo growth from accumulating dead objects over time
gc_result = subprocess.call(["git", "gc"])
except KeyError:
# Opening a local repo failed, so we assume it's not been cloned yet. Do the cloning now
示例11: Project1Test
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import lookup_reference [as 别名]
#.........这里部分代码省略.........
def run_lisod(self, tree):
path = self.get_path()
liso = self.liso_name()
port = self.get_port()
tls_port = self.get_tls_port()
if not path: path = self.find_path('Makefile', tree)
print 'switching to: %s' % path
os.chdir(path)
check_both('make clean', False, False)
check_output('make')
self.ran = True
resource.setrlimit(resource.RLIMIT_STACK, (resource.RLIM_INFINITY, resource.RLIM_INFINITY))
cmd = '%s %d %d %slisod.log %slisod.lock %s %s %s %s&' % (liso, port, tls_port, self.grader.tmp_dir, self.grader.tmp_dir, self.grader.www[:-1], self.grader.cgi, self.grader.priv_key, self.grader.cert)
#cmd = 'nohup ' + cmd
#cmd = cmd + " > /dev/null"
print cmd
self.pAssertEqual(0, os.system(cmd))
return liso
def git_clone(self, repourl):
with open('/dev/null', 'w') as f:
self.pAssertEqual(0, check_call(['git','clone', repourl], stderr=f,
stdout=f))
def git_checkout(self, commit_hex):
with open('/dev/null', 'w') as f:
self.pAssertEqual(0,
check_call(['git','checkout','%s' % commit_hex],
stdout=f, stderr=f))
def resolve_tag(self):
try:
tag = self.repository.lookup_reference('refs/tags/checkpoint-%d' % self.grader.cp_num)
except KeyError:
try:
tag = self.repository.lookup_reference('refs/tags/checkpoint_%d' % self.grader.cp_num)
except KeyError:
tag = self.repository.lookup_reference('refs/tags/checkpoint%d' % self.grader.cp_num)
#tag = self.repository.lookup_reference('refs/tags/regrade')
commit = self.repository[tag.target]
while isinstance(commit, Tag): commit = self.repository[commit.target]
return commit
def check_headers(self, response_type, headers, length_content, ext):
self.pAssertEqual(headers['Server'].lower(), 'liso/1.0')
try:
datetime.datetime.strptime(headers['Date'], '%a, %d %b %Y %H:%M:%S %Z')
except KeyError:
self.print_str('Bad Date header')
except:
self.print_str('Bad Date header: %s' % (headers['Date']))
self.pAssertEqual(int(headers['Content-Length']), length_content)
#self.pAssertEqual(headers['Connection'].lower(), 'close')
if response_type == 'GET' or response_type == 'HEAD':
header_set = set(['connection', 'content-length',
'date', 'last-modified',
'server', 'content-type'])
self.pAssertEqual(set(), header_set - set(headers.keys()))
if headers['Content-Type'].lower() != MIME[ext]:
self.print_str('MIME got %s expected %s' % (headers['Content-Type'].lower(), MIME[ext]))
self.pAssertTrue(headers['Content-Type'].lower() == MIME[ext] or
示例12: get_default_branch
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import lookup_reference [as 别名]
def get_default_branch(repo_path):
repo = Repository(repo_path)
return repo.lookup_reference('HEAD').target
示例13: DictRepository
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import lookup_reference [as 别名]
class DictRepository(object):
"""The :class:`DictRepository <DictRepository>` object.
:param repo_or_path:
The path to a repository, or an existing pygit2.Repository object.
If it is a path that does not exist, a new bare git repository will
be initialized there. If it is a path that does exist, then the
directory will be used as a bare git repository.
:type repo_or_path: string or pygit2.Repository
"""
def __init__(self, repo_or_path=None):
self._default_author = get_default_author()
if isinstance(repo_or_path, Repository):
self._repo = repo_or_path
elif os.path.isdir(repo_or_path):
self._repo = Repository(repo_or_path)
else:
self._repo = init_repository(repo_or_path, True) # bare repo
def _key_to_ref(self, key):
return "refs/%s/HEAD" % key
def get_commit_oid_for_key(self, key):
return self._repo[self._repo.lookup_reference(self._key_to_ref(key)).oid].oid
def get_raw_dict_for_commit_oid(self, commit_oid):
return json.loads(self._repo[self._repo[commit_oid].tree[DATA].oid].data)
def get_parent_oids_for_commit_oid(self, commit_oid):
return [parent.oid for parent in self._repo[commit_oid].parents]
def raw_commit(self, key, raw_dict, author, committer, message, parents):
"""Commit a dict to this :class:`DictRepository <DictRepository>`.
It is recommended that you use the :class:`GitDict <GitDict>` commit
method instead.
:param raw_dict: the data to commit.
:type raw_dict: dict
:param author:
The author of the commit. If None, will be replaced with default.
:type author: pygit2.Signature
:param committer:
The committer of this commit. If None, will be replaced with author.
:type committer: pygit2.Signature
:param message: The commit message.
:type message: string
:param parents:
A list of 20-byte object IDs of parent commits. An empty list
means this is the first commit.
:return: The oid of the new commit.
:rtype: 20 bytes
"""
if not isinstance(raw_dict, dict):
raise ValueError("%s is not a dict" % raw_dict)
author = author or self._default_author.signature()
committer = committer or author
blob_id = self._repo.write(GIT_OBJ_BLOB, json.dumps(raw_dict))
# TreeBuilder doesn't support inserting into trees, so we roll our own
tree_id = self._repo.write(GIT_OBJ_TREE, "100644 %s\x00%s" % (DATA, blob_id))
return self._repo.create_commit(self._key_to_ref(key), author, committer, message, tree_id, parents)
def create(self, key, dict={}, autocommit=False, message="first commit", author=None, committer=None):
"""Create a new :class:`GitDict <GitDict>`
:param key: The key of the new :class:`GitDict <GitDict>`
:type key: :class:`GitDict <GitDict>`
:param dict: (optional) The value of the dict. Defaults to empty.
:type dict: dict
:param autocommit:
(optional) Whether the :class:`GitDict <GitDict>` should
automatically commit. Defaults to false.
:type autocommit: boolean
:param message:
(optional) Message for first commit. Defaults to "first commit".
:type message: string
:param author:
(optional) The signature for the author of the first commit.
Defaults to global author.
:type author: pygit2.Signature
:param committer:
(optional) The signature for the committer of the first commit.
Defaults to author.
:type author: pygit2.Signature
:returns: the GitDict
:rtype: :class:`GitDict <GitDict>`
"""
self.raw_commit(key, dict, author, committer, message, [])
return self.get(key, autocommit=autocommit)
def has(self, key):
"""Determine whether there is an entry for key in this repository.
#.........这里部分代码省略.........
示例14: GitRepo
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import lookup_reference [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:
#.........这里部分代码省略.........
示例15: Document
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import lookup_reference [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
#.........这里部分代码省略.........