本文整理汇总了Python中git.Repo.create_head方法的典型用法代码示例。如果您正苦于以下问题:Python Repo.create_head方法的具体用法?Python Repo.create_head怎么用?Python Repo.create_head使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类git.Repo
的用法示例。
在下文中一共展示了Repo.create_head方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: do_update
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import create_head [as 别名]
def do_update(sub_modules=None):
sub_mods = [_sm for _sm in main_repo.submodules if sub_modules is None or _sm.name in sub_modules]
for sub_mod in sub_mods:
if sub_mod.module_exists():
sr = Repo(sub_mod.abspath)
sr.git.checkout(sub_mod.branch.name)
if 'localcompiled' not in sr.branches:
sr.create_head('localcompiled', 'HEAD')
sub_mod.update(recursive=True, to_latest_revision=True, progress=progress, dry_run=False, force=True)
else:
sub_mod.update(recursive=True, to_latest_revision=True, progress=progress, dry_run=False, force=True)
sr = Repo(sub_mod.abspath)
sr.create_head('localcompiled', first_commit(sr))
示例2: create_new_working_branch
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import create_head [as 别名]
def create_new_working_branch(branch, base, remote_name):
repo = Repo(get_project_root())
remote = repo.remotes[remote_name]
if repo.is_dirty() == True:
print "The working tree contains uncommitted changes, commit or stash "
print "these and try again."
return 1
try:
head = repo.create_head(branch, base)
print "Summary of actions:"
print "- A new branch " + branch + " was created, based on " + base + "."
except OSError:
print "A branch " + branch + " already exists!"
return 1
ret = remote.push(head)
info = ret[0]
print ("- A new remote branch " + branch + " was created on " +
remote_name + ".")
head.set_tracking_branch(info.remote_ref)
print ("- Branch " + branch + " tracks remote branch " + branch +
" from " + remote_name + ".")
head.checkout()
print "- You are now on branch " + branch + "."
return 0
示例3: RepoHandler
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import create_head [as 别名]
class RepoHandler():
def __init__(self, mcRepoPath):
try:
self.repo = Repo(os.path.realpath(mcRepoPath))
self.isGit = True
except:
self.isGit = False
self.repoPath = mcRepoPath
def checkoutDefault(self, baseCommit):
print("Checking out default")
if self.isGit:
if self.repo.active_branch.name != "default":
self.repo.heads.default.checkout()
else:
runProcess(["hg", "update", baseCommit], self.repoPath,
"Failed to check out default branch: %s")
def createBranch(self, branch):
print("Creating new branch %s" % branch)
if self.isGit:
self.repo.create_head(branch)
self.repo.heads[branch].checkout()
else:
runProcess(["hg", "bookmark", branch], self.repoPath,
"Failed to create branch: %s")
def createCommit(self, subDir, commitMessage):
print("Creating commit...")
if self.isGit:
# Can't find a way to do this via gitPython APIs, so do it manually.
self.repo.git.execute(["git", "add", subDir])
index = self.repo.index
index.commit(commitMessage)
else:
runProcess(["hg", "add", subDir], self.repoPath,
"Failed to add files for commit: %s")
runProcess(["hg", "commit", "-m %s" % commitMessage], self.repoPath,
"Failed to add files for commit: %s")
示例4: create_release_branch
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import create_head [as 别名]
def create_release_branch(repo: Repo, version: Version) -> Tuple[Remote, Head]:
print("create release branch from upstream master")
upstream = get_upstream(repo)
upstream.fetch()
branch_name = f"release-{version}"
release_branch = repo.create_head(branch_name, upstream.refs.master, force=True)
upstream.push(refspec=f"{branch_name}:{branch_name}", force=True)
release_branch.set_tracking_branch(repo.refs[f"{upstream.name}/{branch_name}"])
release_branch.checkout()
return upstream, release_branch
示例5: checkout
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import create_head [as 别名]
def checkout(self, commit='master'):
# If commit is none, we'll get the latest
try:
repo = Repo(self.local_path)
except NoSuchPathError:
# I guess it was never cloned...
repo = Repo.init(self.local_path)
repo.create_remote('origin', url=self.url)
repo.remotes.origin.fetch()
bare_master = repo.create_head('master', repo.remotes.origin.refs.master)
repo.head.set_reference(bare_master)
repo.head.reset(index=True, working_tree=True)
return repo
示例6: git_create_checkout_branch
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import create_head [as 别名]
def git_create_checkout_branch(repo_path, branch, remote):
"""Create and checkout tracking branch"""
try:
repo = Repo(repo_path)
except:
repo_path_output = colored(repo_path, 'cyan')
message = colored("Failed to create Repo instance for ", 'red')
print(message + repo_path_output)
else:
branch_output = colored('(' + branch + ')', 'magenta')
remote_output = colored(remote, attrs=['bold'])
print(' - Create and checkout branch ' + branch_output)
try:
origin = repo.remotes[remote]
origin.fetch()
except:
message = colored(' - Failed to fetch from remote ', 'red')
print(message + remote_output)
else:
try:
default_branch = repo.create_head(branch, origin.refs[branch])
except:
message = colored(' - Failed to create branch ', 'red')
print(message + branch_output)
else:
try:
default_branch.set_tracking_branch(origin.refs[branch])
except:
message = colored(' - Failed to set tracking branch ', 'red')
print(message + branch_output)
else:
try:
default_branch.checkout()
except:
message = colored(' - Failed to checkout branch ', 'red')
print(message + branch_output)
示例7: __init__
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import create_head [as 别名]
class GitManager:
def __init__(self, gitSettings, cleanDirty=False):
self.localRepoDir = gitSettings["local"]
try:
# Getting the "fetching" URL
#print("local repository:", self.localRepoDir)
gitPath = os.path.abspath(self.localRepoDir)
if not os.path.exists(gitPath):
os.makedirs(gitPath)
g = cmd.Git(gitPath)
urlInUse = ":".join(g.execute(["git", "remote", "show", "origin"]).split("\n")[1].split(":")[1:]).strip()
urlToUse = gitSettings["protocol"] + "://" + gitSettings["user"] + "@" + gitSettings["remote"]
if urlInUse != urlToUse:
#print("Changing URL in use...")
g.execute(["git", "remote", "set-url", "origin", urlToUse])
urlInUse = ":".join(g.execute(["git", "remote", "show", "origin"]).split("\n")[1].split(":")[1:]).strip()
except exc.GitCommandError:
# Generally, get here when the repo has not been created yet. It is
# ok, it will be created below.
pass
except:
raise
#if not os.path.isdir(self.localRepoDir):
# os.makedirs(self.localRepoDir)
self.offline = False
try:
self.repo = Repo(self.localRepoDir)
assert not self.repo.bare
except (exc.InvalidGitRepositoryError,exc.NoSuchPathError):
self.repo = Repo.clone_from(gitSettings["protocol"] + "://" + gitSettings["user"] + "@" + gitSettings["remote"], self.localRepoDir)
self.tryToFetch()
try:
# Setup a local tracking branch of a remote branch
self.repo.create_head('master', self.origin.refs.master).set_tracking_branch(self.origin.refs.master)
except:
pass
self.pull(cleanDirty)
def tryToFetch(self):
try:
self.repo.remotes.origin.fetch()
except:
if not self.offline:
errMsg = "An error occured while trying to access the GIT" + \
" server. Going in offline mode. Check Internet" + \
" connectivity. If connectivity is OK, Running" + \
" 'git pull' in the curator_DB folder may provide"+ \
" more detailed information about the issue."
"""
msgBox = QtGui.QMessageBox()
msgBox.setWindowTitle("Error pulling from GIT")
msgBox.setText(errMsg)
msgBox.setStandardButtons(QtGui.QMessageBox.Ok)
msgBox.exec_()
"""
raise ValueError(errMsg)
self.offline = True
return
if self.offline:
self.offline = False
def canRunRemoteCmd(self, cleanDirty=True):
if self.repo.is_dirty():
#modifiedFiles = [os.path.join(self.repo.working_tree_dir, diff.a_path) for diff in self.repo.index.diff(None)]
modifiedFiles = [diff.a_path for diff in self.repo.index.diff(None)]
if cleanDirty:
self.addFiles(modifiedFiles)
else:
errMsg = "GIT database of annotations is dirty. Do you want to commit uncommited changes" + \
" or to cancel the operation? Here is a list of modified files: \n\n" + "\n".join(modifiedFiles)
raise GitMngError(errMsg)
if self.offline:
self.tryToFetch()
if self.offline:
return False
return True
#.........这里部分代码省略.........
示例8: GitFlow
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import create_head [as 别名]
class GitFlow(object):
"""
Creates a :class:`GitFlow` instance.
:param working_dir:
The directory where the Git repo is located. If not specified, the
current working directory is used.
When a :class:`GitFlow` class is instantiated, it auto-discovers all
subclasses of :class:`gitflow.branches.BranchManager`, so there is no
explicit registration required.
"""
def _discover_branch_managers(self):
managers = {}
for cls in itersubclasses(BranchManager):
# TODO: Initialize managers with the gitflow branch prefixes
managers[cls.identifier] = cls(self)
return managers
def __init__(self, working_dir='.'):
# Allow Repos to be passed in instead of strings
self.repo = None
if isinstance(working_dir, Repo):
self.working_dir = working_dir.working_dir
else:
self.working_dir = working_dir
self.git = Git(self.working_dir)
try:
self.repo = Repo(self.working_dir)
except InvalidGitRepositoryError:
pass
self.managers = self._discover_branch_managers()
self.defaults = {
'gitflow.branch.master': 'master',
'gitflow.branch.develop': 'develop',
'gitflow.prefix.versiontag': '',
'gitflow.origin': 'origin',
'gitflow.release.versionmatcher': '[0-9]+([.][0-9]+){2}',
}
for identifier, manager in self.managers.items():
self.defaults['gitflow.prefix.%s' % identifier] = manager.DEFAULT_PREFIX
def _init_config(self, master=None, develop=None, prefixes={}, names={},
force_defaults=False):
for setting, default in self.defaults.items():
if force_defaults:
value = default
elif setting == 'gitflow.branch.master':
value = master
elif setting == 'gitflow.branch.develop':
value = develop
elif setting.startswith('gitflow.prefix.'):
name = setting[len('gitflow.prefix.'):]
value = prefixes.get(name, None)
else:
name = setting[len('gitflow.'):]
value = names.get(name, None)
if value is None:
value = self.get(setting, default)
self.set(setting, value)
def _init_initial_commit(self):
master = self.master_name()
if master in self.repo.branches:
# local `master` branch exists
return
elif self.origin_name(master) in self.repo.refs:
# the origin branch counterpart exists
origin = self.repo.refs[self.origin_name(master)]
branch = self.repo.create_head(master, origin)
branch.set_tracking_branch(origin)
elif self.repo.heads:
raise NotImplementedError('Local and remote branches exist, '
'but neither %s nor %s'
% (master, self.origin_name(master) ))
else:
# Create 'master' branch
info('Creating branch %r' % master)
c = self.repo.index.commit('Initial commit', head=False)
self.repo.create_head(master, c)
def _init_develop_branch(self):
# assert master already exists
assert self.master_name() in self.repo.refs
develop = self.develop_name()
if develop in self.repo.branches:
# local `develop` branch exists, but do not switch there
return
if self.origin_name(develop) in self.repo.refs:
# the origin branch counterpart exists
origin = self.repo.refs[self.origin_name(develop)]
branch = self.repo.create_head(develop, origin)
branch.set_tracking_branch(origin)
else:
# Create 'develop' branch
info('Creating branch %r' % develop)
#.........这里部分代码省略.........
示例9: __init__
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import create_head [as 别名]
#.........这里部分代码省略.........
LOG.warning("Unauthorize repository access for %s" % self.user)
exit(1)
def view(self):
"""List repository entries for current user"""
tree = self.repo.heads.master.commit
return [f for f in tree]
def archive(self):
"""Archive the repository contents to a tar file"""
self.check_credentials()
return self.repo.archive(open(os.path.join(self.full_path, "%s.tar" % self.user)), "wb")
def add_cookbook(self, path):
"""
Adds files from path to user repo
:param path: local path to add from
:return: current path and head version
"""
cb_path = os.path.join(self.full_path, os.path.basename(path))
if os.path.exists(cb_path):
shutil.rmtree(cb_path)
shutil.copytree(path, cb_path)
com = self.repo.git.add(A=True)
self.repo.index.add(com)
self.repo.index.commit("Updated %s" % path)
self.version = self.repo.head.commit.tree.hexsha
LOG.info("Commited at version %s" % self.version)
return cb_path, self.repo.index.version
def browse_file(self, file):
"""
Returns sha1 index of file in repo
:param file: file path
:return: current file version id
"""
item = None
tree = self.repo.head.commit.tree
for item in tree.traverse():
if item.type == 'blob' and item.name == file:
break
return item
def browse_repository(self):
"""Shows repository contents"""
tree = self.repo.commit.tree
return [c for c in tree]
def check_branches(self):
"""Shows repository branches"""
return self.repo.heads
def check_tags(self):
"""Shows repository tags"""
return self.repo.tags
def link_commit(self, message):
"""Commit Repository changes"""
return self.repo.commit(message)
def checkout(self, url):
self.repo.clone_from(url, self.full_path)
def statistics(self):
"""Show several usage statistics"""
message = u""
file_count = 0
tree_count = 0
tree = self.repo.commit.tree
for item in tree.traverse():
file_count += item.type == 'blob'
tree_count += item.type == 'tree'
message += u"files: %d, directories: %d\n" % (len(tree.blobs), len(tree.trees))
message += u"Current head: %s" % self.repo.heads.master
return message
def upload_coobook(self, path):
"""
Uploads a validated cookbook to the official Github repo
Authentication must be enabled via external shared keys
:param path: cookbook path
:return: status message
"""
dest_url = None
if chef_client.check_chef_cookbook(path):
dest_url = CONF.clients_chef.github_url
elif puppet_client.check_puppet_module(path):
dest_url = CONF.clients_puppet.github_url
elif murano_client.check_murano_blueprint(path):
dest_url = CONF.clients_murano.github_url
if dest_url:
LOG.info("Pushing cookbook to %s" % dest_url)
dest = self.repo.create_remote(self.user, dest_url)
self.repo.create_head('remote', dest.refs.master).set_tracking_branch(dest.refs.master)
message = dest.push()
else:
LOG.warning("Error detecting cookbook type for %s" % path)
message = "Error"
return message
示例10: len
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import create_head [as 别名]
# Get all parent commits of the tip of develop
revs = repo.git.rev_list(DEVELOP_BRANCH).split("\n")
for rev in revs:
commit = repo.commit(rev)
message = commit.message.split("\n")[0].strip().replace(" ","").replace(".","").replace(":","")
message = message[:75] if len(message) > 75 else message
print "Creating a branch for:", message
# Create a new branch with the same name as the commit
new_branch = repo.create_head(message)
new_branch.set_commit(rev)
# Checkout and clean that branch
new_branch.checkout()
repo.git.clean("-fd")
print "Pushing:", message
origin.push(new_branch)
# Copy the state of the repository to temp dir
target_dir = os.path.join(temp_dir,new_branch.name)
shutil.copytree(repo_dir, target_dir, ignore=shutil.ignore_patterns(*IGNORE_PATTERNS))
print "Checking out master and copying in the snapshots"
示例11: DesignerGit
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import create_head [as 别名]
#.........这里部分代码省略.........
content=content, title='Git - Branches', size_hint=(None, None),
size=(popup_width, popup_height), auto_dismiss=False)
content.bind(on_apply=self._perform_do_branches,
on_cancel=d.close_popup)
content.selected_items = [self.repo.active_branch.name]
content.show_items()
d.popup = popup
popup.open()
@ignore_proj_watcher
def _perform_do_branches(self, instance, branches, *args):
'''If the branch name exists, try to checkout. If a new name, create
the branch and checkout.
If the code has modification, shows an alert and stops
'''
get_designer().close_popup()
if self.repo.is_dirty():
show_alert('Git checkout',
'Please, commit your changes before '
'switch branches.')
return
if not branches:
return
branch = branches[0]
try:
if branch in self.repo.heads:
self.repo.heads[branch].checkout()
else:
self.repo.create_head(branch)
self.repo.heads[branch].checkout()
branch_name = self.repo.active_branch.name
self.dispatch('on_branch', branch_name)
except GitCommandError as e:
show_alert('Git Branches', 'Failed to switch branch!\n' + str(e))
def on_branch(self, *args):
'''Dispatch the branch name
'''
pass
def do_diff(self, *args):
'''Open a CodeInput with git diff
'''
diff = self.repo.git.diff()
if not diff:
diff = 'Empty diff'
d = get_designer()
panel = d.designer_content.tab_pannel
inputs = d.code_inputs
# check if diff is visible on tabbed panel.
# if so, update the text content
for i, code_input in enumerate(panel.tab_list):
if code_input == self.diff_code_input:
panel.switch_to(panel.tab_list[len(panel.tab_list) - i - 2])
code_input.content.code_input.text = diff
return
# if not displayed, create or add it to the screen
if self.diff_code_input is None:
示例12: GitHistoryRewriter
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import create_head [as 别名]
class GitHistoryRewriter(object):
def __init__(self, repo=None, yapf_args=None):
self.working_branch = None
self.repo = repo
if repo is None:
# self.repo = Repo(odbt=GitDB)
self.repo = Repo()
if yapf_args is None:
self.yapf_args = ['yapf', '--in-place']
else:
self.yapf_args = ['yapf'] + yapf_args
self.exclude_refs = {'HEAD'} # todo: hook this up to command line args
self.graph = set()
self.blob_map = {}
self.converted = {}
self.headcount = 0
self.convert_errors = []
def run(self):
self.build_heads()
self.visit_commits()
self.finish()
return
def finish(self):
# we've done a whole bunch to the repo. clean it up a bit
log.info('*** Repacking ***')
self.repo.git.repack('-a', '-d', '-f', '--depth=250', '--window=250')
return
def new_head(self, name=None, checkout=False):
if name is None:
name = 'gitreformat-{}'.format(self.headcount)
branch = self.repo.create_head(name)
self.headcount += 1
if checkout:
branch.checkout()
return branch
def build_heads(self):
# create branches for each remote reference
for remote in self.repo.remotes:
headlist = list(self.repo.heads) # gonna create heads so copy
for o in remote.refs:
name = o.name.split('/')[-1]
if name not in headlist and name not in self.exclude_refs:
try:
self.repo.create_head(name, remote.refs[name])
except Exception as e:
log.error('build_heads problem with: {} {}'.format(
name, str(e)))
@staticmethod
def topo_sort(start):
"""
Depth first search to build graph and child dictionary DAGs,
then modified topographic sort (exploit child graph)
:param start:
:return:
"""
stack, visited, ordered = list(start), set(), set()
graph, children = {}, defaultdict(set)
while stack:
vertex = stack.pop()
if vertex not in visited:
visited.add(vertex)
graph[vertex] = ps = set(vertex.parents)
for p in ps:
children[p].add(vertex)
stack.extend(ps - visited)
if not ps:
ordered.add(vertex)
while ordered:
for o in ordered:
yield o
childs = set(chain(*(children[p] for p in ordered)))
ordered2 = set()
for commit in childs:
d = graph[commit] - ordered
if not d:
ordered2.add(commit)
else:
graph[commit] = d
ordered = ordered2
def visit_commits(self):
"""
Depth First Search from a head (branch) to init. Commits are
applied in order as children maintain references to parents
(Merkle tree).
:return: None
"""
yapf_map, start_commits = {}, set()
for head in [x for x in self.repo.heads if x.name[-5:] != '-yapf']:
start_commits.add(head.commit)
yapf_name = head.name + '-yapf'
#.........这里部分代码省略.........
示例13: releaseMozillaCentral
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import create_head [as 别名]
def releaseMozillaCentral(bugzilla, repoDir, useSystem, mcRepoPath, version,
username, ircNick):
print "Exporting to m-c"
if not mcRepoPath:
print >> sys.stderr, "mozilla-central repository not supplied!"
sys.exit(1)
if not ircNick:
print >> sys.stderr, "irc nick not supplied!"
sys.exit(1)
pushToTry = getInput("Push result to try (assumes git-cinnibar)?") == "y"
os.environ["EXPORT_MC_LOCATION"] = mcRepoPath
mcRepo = Repo(os.path.realpath(mcRepoPath))
# XXX Drop this, prompt user
if mcRepo.active_branch.name != "default":
print "Checking out default"
mcRepo.heads.default.checkout()
print "Creating new branch for version %s" % version
mcRepo.create_head(version)
mcRepo.heads[version].checkout()
print "Doing a git export..."
runProcess(['make', 'clean'], repoDir, "Failed to make clean: %s")
runProcess(['make', 'export_mc'], repoDir, "Failed to make export_mc: %s")
# Can't find a way to do this via gitPython APIs, so do it manually.
mcRepo.git.execute(["git", "add", "browser/extensions/loop"])
print "Building..."
runProcess(['./mach', 'build'], mcRepoPath, "Failed to build in mc repo: %s")
runProcess(['./browser/extensions/loop/run-all-loop-tests.sh'], mcRepoPath,
"Tests failed! %s \nTree left in unclean state.")
print "Filing bug..."
baseVersionText = "Land version %s of the Loop system add-on in mozilla-central" % version
bug = bugsy.Bug()
bug.summary = baseVersionText
bug.add_comment("Changelog: https://github.com/mozilla/loop/blob/release/CHANGELOG.md")
bug.assigned_to = username
bug.product = DEFAULTS[useSystem]["product"]
bug.component = "Client"
bug.platform = "All"
bug._bug["url"] = "https://github.com/mozilla/loop/releases/tag/v%s" % version
bug._bug["whiteboard"] = "[btpp-fix-now]"
bug._bug["priority"] = "P1"
bug._bug["cf_rank"] = 1
bugzilla.put(bug)
print "Bug id is: %s" % bug.id
print "Bug url: https://%s/show_bug.cgi?id=%s" % (DEFAULTS[useSystem]["bugzilla"], bug.id)
print "Attaching patch to bug"
index = mcRepo.index
index.commit("Bug %s - %s, rs=%s for already reviewed code." % (bug.id, baseVersionText, ircNick))
bugzillaHost = DEFAULTS[useSystem]["bugzilla"]
runProcess(["git-bz", "attach", "-n", bugzillaHost + ":" + str(bug.id), "HEAD"],
mcRepoPath, "Failed to attach file: %s")
if pushToTry:
print "Pushing to try"
runProcess(["git", "commit", "-m",
"try: -b do -p linux,linux64,macosx64,win32,win64 -u xpcshell," +
"marionette,marionette-e10s,mochitest-bc,mochitest-dt," +
"mochitest-e10s-bc,mochitest-e10s-devtools-chrome -t none",
"--allow-empty"])
runProcess(["git", "push", "try"])
print "Done, please:"
print "- Check the diffs in the bug"
print "- Add r+ as the review flag"
print "- Merge branch %s and push to fx-team" % version
示例14: createVersionBranches
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import create_head [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")
示例15: GitFlow
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import create_head [as 别名]
class GitFlow(object):
"""
Creates a :class:`GitFlow` instance.
:param working_dir:
The directory where the Git repo is located. If not specified, the
current working directory is used.
When a :class:`GitFlow` class is instantiated, it auto-discovers all
subclasses of :class:`gitflow.branches.BranchManager`, so there is no
explicit registration required.
"""
def _discover_branch_managers(self):
managers = {}
for cls in itersubclasses(BranchManager):
# TODO: Initialize managers with the gitflow branch prefixes
managers[cls.identifier] = cls(self)
return managers
def __init__(self, working_dir='.'):
# Allow Repos to be passed in instead of strings
self.repo = None
if isinstance(working_dir, Repo):
self.working_dir = working_dir.working_dir
else:
self.working_dir = working_dir
self.git = Git(self.working_dir)
try:
self.repo = Repo(self.working_dir)
except InvalidGitRepositoryError:
pass
self.managers = self._discover_branch_managers()
self.defaults = {
'gitflow.branch.master': 'master',
'gitflow.branch.develop': 'develop',
'gitflow.prefix.versiontag': '',
'gitflow.origin': 'origin',
}
for identifier, manager in self.managers.items():
self.defaults['gitflow.prefix.%s' % identifier] = manager.DEFAULT_PREFIX
def _init_config(self, master=None, develop=None, prefixes={}, names={},
force_defaults=False):
for setting, default in self.defaults.items():
if force_defaults:
value = default
elif setting == 'gitflow.branch.master':
value = master
elif setting == 'gitflow.branch.develop':
value = develop
elif setting.startswith('gitflow.prefix.'):
name = setting[len('gitflow.prefix.'):]
value = prefixes.get(name, None)
else:
name = setting[len('gitflow.'):]
value = names.get(name, None)
if value is None:
value = self.get(setting, default)
self.set(setting, value)
def _init_initial_commit(self):
master = self.master_name()
if master in self.repo.branches:
# local `master` branch exists
return
elif self.origin_name(master) in self.repo.refs:
# the origin branch counterpart exists
origin = self.repo.refs[self.origin_name(master)]
branch = self.repo.create_head(master, origin)
branch.set_tracking_branch(origin)
elif self.repo.heads:
raise NotImplementedError(
'Local and remote branches exist, but neither %s nor %s' % (
master, self.origin_name(master)
))
else:
# Create 'master' branch
info('Creating branch %r' % master)
c = self.repo.index.commit('Initial commit', head=False)
self.repo.create_head(master, c)
def _init_develop_branch(self):
# assert master already exists
assert self.master_name() in self.repo.refs
develop = self.develop_name()
if develop in self.repo.branches:
# local `develop` branch exists, but do not switch there
return
if self.origin_name(develop) in self.repo.refs:
# the origin branch counterpart exists
origin = self.repo.refs[self.origin_name(develop)]
branch = self.repo.create_head(develop, origin)
branch.set_tracking_branch(origin)
else:
# Create 'develop' branch
info('Creating branch %r' % develop)
branch = self.repo.create_head(develop, self.master())
#.........这里部分代码省略.........