本文整理汇总了Python中git.Repo.merge_base方法的典型用法代码示例。如果您正苦于以下问题:Python Repo.merge_base方法的具体用法?Python Repo.merge_base怎么用?Python Repo.merge_base使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类git.Repo
的用法示例。
在下文中一共展示了Repo.merge_base方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: checkVersionBranches
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import merge_base [as 别名]
def checkVersionBranches(version):
"""Check that the branches for a given version were created properly."""
parser = VersionParser(version)
repo = Repo(os.getcwd(), search_parent_directories=True)
assert not repo.bare
# Verify the branches' existance
if parser.remote_previous_rc_branch not in repo.refs:
raise ValueError("Previous RC branch not found: {}".format(parser.remote_previous_rc_branch))
if parser.remote_base_branch not in repo.refs:
raise ValueError("Base branch not found: {}".format(parser.remote_base_branch))
if parser.remote_rc_branch not in repo.refs:
raise ValueError("RC branch not found: {}".format(parser.remote_rc_branch))
previous_rc = repo.refs[parser.remote_previous_rc_branch]
current_rc_base = repo.refs[parser.remote_base_branch]
current_rc = repo.refs[parser.remote_rc_branch]
master = repo.refs[remote_master_branch]
# Check the base branch is an ancestor of the rc branch
if not repo.is_ancestor(current_rc_base, current_rc):
raise ValueError("{} is not an ancesctor of {}".format(current_rc_base, current_rc))
# Check that the base branch is the merge base of the previous and current RCs
merge_base = repo.merge_base(previous_rc, current_rc)
if current_rc_base.commit not in merge_base:
raise ValueError("Base branch is not the merge base between {} and {}".format(previous_rc, current_rc))
# For patch releases, warn if the base commit is not the previous RC commit
if parser.is_patch_release:
if parser.previous_version not in repo.tags:
logging.warning("The tag {0} does not exist, which suggests {0} has not been released.".format(parser.previous_version))
if current_rc_base.commit != previous_rc.commit:
logging.warning("Previous version has commits not in this patch");
logging.warning("Type \"git diff {}..{}\" to see the commit list".format(current_rc_base, previous_rc));
# Check base branch is part of the previous RC
previous_rc_base_commit = repo.merge_base(previous_rc, master)
if repo.is_ancestor(current_rc_base, previous_rc_base_commit):
raise ValueError("{} is older than {}".format(current_rc_base, previous_rc))
print("[SUCCESS] Checked {}".format(parser.version))
示例2: GitFlow
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import merge_base [as 别名]
#.........这里部分代码省略.........
for b in self.git.branch('-a', '--contains', commit).splitlines()]
def must_be_uptodate(self, branch, fetch):
remote_branch = self.origin_name(branch)
if remote_branch in self.branch_names(remote=True):
if fetch:
self.origin().fetch(branch)
self.require_branches_equal(branch, remote_branch)
@requires_repo
def _compare_branches(self, branch1, branch2):
"""
Tests whether branches and their 'origin' counterparts have
diverged and need merging first. It returns error codes to
provide more detail, like so:
0 Branch heads point to the same commit
1 First given branch needs fast-forwarding
2 Second given branch needs fast-forwarding
3 Branch needs a real merge
4 There is no merge base, i.e. the branches have no common ancestors
"""
try:
commit1 = self.repo.rev_parse(branch1)
commit2 = self.repo.rev_parse(branch2)
except (git.BadObject, git.BadName) as e:
raise NoSuchBranchError(e.args[0])
if commit1 == commit2:
return 0
try:
# merge_base() returns a list of Commit objects
# this list will have at max one Commit
# or it will be empty if no common merge base exists
base = self.repo.merge_base(commit1, commit2)[0]
except (GitCommandError, IndexError):
return 4
if base == commit1:
return 1
elif base == commit2:
return 2
else:
return 3
@requires_repo
def require_branches_equal(self, branch1, branch2):
status = self._compare_branches(branch1, branch2)
if status == 0:
# branches are equal
return
else:
warn("Branches '%s' and '%s' have diverged." % (branch1, branch2))
if status == 1:
raise SystemExit("And branch '%s' may be fast-forwarded." % branch1)
elif status == 2:
# Warn here, since there is no harm in being ahead
warn("And local branch '%s' is ahead of '%s'." % (branch1, branch2))
else:
raise SystemExit("Branches need merging first.")
@requires_repo
def start_transaction(self, message=None):
if message:
info(message)
@requires_initialized
def tag(self, tagname, commit, message=None, sign=False, signingkey=None):
示例3: print
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import merge_base [as 别名]
except:
print("Unable to find pull request refs at %s." % pull_ref_prefix, file=sys.stderr)
print("Is your repo set up to fetch them? Try adding", file=sys.stderr)
print(" fetch = +refs/pull/*/head:%s/*" % pull_ref_prefix, file=sys.stderr)
print("to the GitHub remote section of .git/config.", file=sys.stderr)
exit(0)
### Reading data from repository ###
def identify_commit(commit):
return '%s ("%s", %s)' % (
commit.hexsha, commit.message.split('\n',1)[0],
datetime.datetime.fromtimestamp(commit.committed_date).ctime())
# Is the first commit reachable from the current one?
base = repo.merge_base(firstCommit, commit)
if len(base) == 0:
print("error: %s:%s\nand %s:%s\nhave no common ancestor" % (
options.from_commit, identify_commit(firstCommit),
options.until_commit, identify_commit(commit)), file=sys.stderr)
exit(1)
commonParent = base[0]
if firstCommit != commonParent:
print("warning: %s:%s\nis not an ancestor of %s:%s!" % (
options.from_commit, identify_commit(firstCommit),
options.until_commit, identify_commit(commit)), file=sys.stderr)
print(file=sys.stderr)
ageindays = int((firstCommit.committed_date - commonParent.committed_date)/86400)
prevlen = sum((1 for x in repo.iter_commits(commonParent.hexsha + '...' + firstCommit.hexsha)))
print("The first common ancestor is %s" % identify_commit(commonParent), file=sys.stderr)
print("which is %d commits older than %s:%s\nand %d days older. Using that as origin." %\
示例4: __init__
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import merge_base [as 别名]
class GitHandler:
def __init__(self, project, repo_address, cache={}):
self.name = project
self.repo = Repo(repo_address, odbt=GitCmdObjectDB)
# Local in-memory cache used for caching commit stats
self.cache = cache
def format_commit_info(self, commit):
# Use a cache for stats.total information as that API requires
# significant processing time and is static information that does not
# change for a commit object.
if not self.cache.get(commit.hexsha, None):
self.cache[commit.hexsha] = commit.stats.total
commit_stats = self.cache[commit.hexsha]
return {
'hash': commit.hexsha,
'lines': commit_stats,
'author': commit.author.name,
'author_email': commit.author.email.lower(),
'authored_date': commit.authored_date, # seconds since epoch
'author_tz_offset': commit.author_tz_offset, # seconds west of utc
'committer': commit.committer.name,
'committer_email': commit.committer.email.lower(),
'committed_date': commit.committed_date, # seconds since epoch
'committer_tz_offset': commit.committer_tz_offset, # seconds west of utc
'message': commit.message,
}
def _fetch_commits(self, revision, filters=None):
"""Convenience function to fetch comments from a revision
This function also automatically strips out commits from Gerrit Code
Review that automatically update submodules as well as Merge commits as
that causes contributors in a project that is imported as a submodule
of another project to appear as contributed multiple times in stats.
"""
commits = []
for commit in self.repo.iter_commits(rev=revision):
if (commit.committer.name == 'Gerrit Code Review' and
# Skip counting Gerrit Code Review auto submodule updates
(commit.message.startswith('Updated {0}\nProject:'.format(self.name)) or
commit.message.startswith('Updated git submodules\n\nProject:'.format(self.name)) or
# Skip counting Gerrit Code Review Merge commits
commit.message.startswith('Merge \"'))):
continue
if filters:
# Filter for author by email
author = filters.get('author', None)
if author and author != commit.author.email:
continue
# Filter for organization by email
organization = filters.get('organization', None)
if (organization and organization != commit.author.email.split('@', 1)[-1]): # noqa
continue
# Finally pass on the commit object
commit_dic = self.format_commit_info(commit)
commits.append(commit_dic)
return commits
def branches(self):
"""Returns a list of branches in the repo."""
branches = [b.name for b in self.repo.branches]
return branches
def commits(self, branch, filters=None):
"""Returns a list of commit data from a repository.
Keyword arguments:
branch -- Branch of repo to pull data from.
"""
return self._fetch_commits(branch, filters=filters)
def commits_since_ref(self, ref1, ref2, filters=None):
"""Returns a list of commits in branch until common parent of ref
Searches Git for a common_parent between *branch* and *ref* and returns
a the commit log of all the commits until the common parent excluding
the common_parent commit itself.
Arguments:
ref1 -- The main reference point to query data from
ref2 -- Reference point in which to compare ref1 from
"""
commits = []
try:
common_parent = self.repo.merge_base(ref1, ref2)[0]
except GitCommandError:
# If we fail to get the merge base simply return empty list as we
# can no longer proceed any further.
return commits
# Order is important here. A..B will show you all commits that B has
# excluding A. Spectrometer is interested in finding all commits since
# the common parent of ref1 and ref2
revision = "{parent}..{ref1}".format(ref1=ref1, parent=common_parent.hexsha)
commits.extend(self._fetch_commits(revision, filters=filters))
#.........这里部分代码省略.........
示例5: createVersionBranches
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import merge_base [as 别名]
def createVersionBranches(version):
"""Create the branches for a given version."""
parser = VersionParser(version)
repo = Repo(os.getcwd(), search_parent_directories=True)
assert not repo.bare
# Validate the user is on a local branch that has the right merge base
if repo.head.is_detached:
raise ValueError("You must not run this script in a detached HEAD state")
# Validate the user has no pending changes
if repo.is_dirty():
raise ValueError("Your working tree has pending changes. You must have a clean working tree before proceeding.")
# Make sure the remote is up to date
remote = repo.remotes[remote_name]
remote.fetch(prune=True)
# Verify the previous RC branch exists
if parser.remote_previous_rc_branch not in repo.refs:
raise ValueError("Previous RC branch not found: {}".format(parser.remote_previous_rc_branch))
# Verify the branches don't already exist
if parser.remote_base_branch in repo.refs:
raise ValueError("Base branch already exists: {}".format(parser.remote_base_branch))
if parser.remote_rc_branch in repo.refs:
raise ValueError("RC branch already exists: {}".format(parser.remote_rc_branch))
if parser.base_branch in repo.refs:
raise ValueError("Base branch already exists locally: {}".format(parser.base_branch))
if parser.rc_branch in repo.refs:
raise ValueError("RC branch already exists locally: {}".format(parser.rc_branch))
# Save current branch name
current_branch_name = repo.active_branch
# Create the RC branches
if parser.is_patch_release:
# Check tag exists, if it doesn't, print warning and ask for comfirmation
if parser.previous_version not in repo.tags:
logging.warning("The tag {0} does not exist, which suggests {0} has not yet been released.".format(parser.previous_version))
logging.warning("Creating the branches now means that {0} will diverge from {1} if anything is merged into {1}.".format(parser.version, parser.previous_version))
logging.warning("This is not recommended unless necessary.")
validAnswer = False
askCount = 0
while not validAnswer and askCount < 3:
answer = input("Are you sure you want to do this? [y/n] ").strip().lower()
askCount += 1
validAnswer = answer == "y" or answer == "n"
if not validAnswer:
raise ValueError("Did not understand response")
if answer == "n":
print("Aborting")
return
else:
print("Creating branches")
previous_rc = repo.refs[parser.remote_previous_rc_branch]
repo.create_head(parser.base_branch, previous_rc)
remote.push("{0}:{0}".format(parser.base_branch))
repo.create_head(parser.rc_branch, previous_rc)
remote.push("{0}:{0}".format(parser.rc_branch))
else:
previous_rc = repo.refs[parser.remote_previous_rc_branch]
master = repo.refs[remote_master_branch]
merge_base = repo.merge_base(previous_rc, master)
repo.create_head(parser.base_branch, merge_base[0])
remote.push("{0}:{0}".format(parser.base_branch))
repo.create_head(parser.rc_branch, master)
remote.push("{0}:{0}".format(parser.rc_branch))
print("[SUCCESS] Created {} and {}".format(parser.base_branch, parser.rc_branch))
print("[SUCCESS] You can make the PR from the following webpage:")
print("[SUCCESS] https://github.com/highfidelity/hifi/compare/{}...{}".format(parser.base_branch, parser.rc_branch))
if parser.is_patch_release:
print("[SUCCESS] NOTE: You will have to wait for the first fix to be merged into the RC branch to be able to create the PR")