本文整理汇总了Python中git.Git.checkout方法的典型用法代码示例。如果您正苦于以下问题:Python Git.checkout方法的具体用法?Python Git.checkout怎么用?Python Git.checkout使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类git.Git
的用法示例。
在下文中一共展示了Git.checkout方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plant_seed
# 需要导入模块: from git import Git [as 别名]
# 或者: from git.Git import checkout [as 别名]
def plant_seed(self, seed_id=None, target_dir=None):
if not seed_id or not target_dir:
self.rage_quit("Missing arguments, seed plant failed")
seeds = self.get_seeds()
tagref = seeds.get(seed_id, None)
if not tagref:
self.rage_quit("Seed id {} not found".format(seed_id))
git = Git(tagref.repo.working_dir)
current_commit = str(Repo(tagref.repo.working_dir).commit())
cprint("Current commit: {}".format(current_commit), Fore.GREEN)
dirty = tagref.repo.is_dirty()
cprint("Working directory {}".format('dirty' if dirty else 'clean'), Fore.GREEN)
if dirty:
cprint("--> git stash", Fore.YELLOW)
git.stash()
cprint("--> git checkout {}".format(seed_id), Fore.YELLOW)
git.checkout(seed_id)
try:
cprint("Copying seed directory: {}".format(tagref.repo.working_dir), Fore.GREEN)
call(["cp", "-r", tagref.repo.working_dir, target_dir])
except OSError as error:
cprint("Copying directory failed:\n{}".format(error), Fore.RED)
finally:
if dirty:
cprint("--> git stash apply", Fore.YELLOW)
git.stash('apply')
cprint("--> git checkout {}".format(current_commit), Fore.YELLOW)
git.checkout(current_commit)
示例2: checkout_source
# 需要导入模块: from git import Git [as 别名]
# 或者: from git.Git import checkout [as 别名]
def checkout_source(self, git_path, checkout_options = None):
'''
Checkout source and switch to the right tag
'''
shutil.rmtree(self.workspace, ignore_errors=True)
os.mkdir(self.workspace)
os.chdir(self.workspace)
Repo.clone_from(git_path, self.target_name)
g = Git(self.source_path)
g.checkout(checkout_options)
示例3: _get_workdir
# 需要导入模块: from git import Git [as 别名]
# 或者: from git.Git import checkout [as 别名]
def _get_workdir(self):
"""Return an initialized workdir path.
If the stock links to a plain directory, the workdir is simply its path.
If the stock links to a git repository, the workdir will point to a
persistent lightweight checkout of the desired branch.
"""
if not self.branch:
return self.link
orig = Git(self.link)
checkout_path = self.paths.checkout
if not exists(checkout_path):
mkdir(checkout_path)
checkout = Git.init_create(checkout_path)
checkout.set_alternates(orig)
else:
checkout = Git(checkout_path)
def dup_branch(branch):
# checkout latest changes
commit = orig.rev_parse(branch)
if not commit:
raise self.Error("no such branch `%s' at %s" % (branch, self.link))
checkout.update_ref("refs/heads/" + branch, commit)
dup_branch(self.branch)
checkout.checkout("-q", "-f", self.branch)
if exists(join(checkout_path, "arena.internals")):
dup_branch(self.branch + "-thin")
command = "cd %s && sumo-open" % commands.mkarg(checkout_path)
error = os.system(command)
if error:
raise self.Error("failed command: " + command)
return join(checkout_path, "arena")
# update tags
for tag in checkout.list_tags():
checkout.remove_tag(tag)
for tag in orig.list_tags():
try:
checkout.update_ref("refs/tags/" + tag, orig.rev_parse(tag))
except:
continue
return checkout_path
示例4: build_command
# 需要导入模块: from git import Git [as 别名]
# 或者: from git.Git import checkout [as 别名]
def build_command(config_file, strict, site_dir, tags, default, latest):
"""Build the MkDocs documentation"""
cli.configure_logging(level=logging.INFO)
g = Git()
tags = tags or g.tag().splitlines()
log.info("Building %s to /", default)
g.checkout(default)
_build(_load_config(config_file, strict, site_dir), default, tags)
log.info("Building %s to /latest", latest)
g.checkout(default)
_build(_load_config(config_file, strict, site_dir), latest, tags, 'latest')
for tag in sorted(tags):
g.checkout(tag)
if not os.path.exists("mkdocs.yml"):
log.warning("Unable to build %s, as no mkdocs.yml was found", tag)
continue
site_dir = "v{0}".format(tag)
log.info("Building %s to /%s", tag, site_dir)
_build(_load_config(config_file, strict, site_dir), tag, tags, site_dir)
g.checkout('master')
示例5: cloneOrCheckout
# 需要导入模块: from git import Git [as 别名]
# 或者: from git.Git import checkout [as 别名]
def cloneOrCheckout(base_path, repo):
git = Git()
repo_path = os.path.join(base_path, repo['name'])
print (repo_path)
try:
os.chdir(repo_path)
except OSError:
os.chdir(base_path)
git.clone(repo['base_url'] + repo['name'])
os.chdir(repo_path)
cloned = True
finally:
git.fetch()
git.checkout(repo['branch'])
os.chdir(base_path)
示例6: addSuperModuleCommit
# 需要导入模块: from git import Git [as 别名]
# 或者: from git.Git import checkout [as 别名]
def addSuperModuleCommit(self, id, hash, url, who, branch, project):
self.log.debug("branch: " + branch + ", project:" + project)
hasSuperModule = False
isSuperModuleBr = False
self.log.debug("Project names: " + str(self.config.projects))
projectNames = self.config.projects.keys()
for proj in projectNames:
self.log.debug("project: " + project + " proj: " + proj)
if project.lower() == proj:
hasSuperModule = True
break
for br in self.config.branches:
if branch == br:
isSuperModuleBr = True
break
self.log.debug("isSuperModuleBr: " + str(isSuperModuleBr) + " hasSuperModule: " + str(hasSuperModule))
if isSuperModuleBr and hasSuperModule:
self.log.debug("Git Profile Path: " + str(self.config.profile))
git = Git(self.config.profile)
self.checkoutTrackingBranch(git, branch)
git.pull()
git.submodule("update","--init")
gitSubmoduleProfile = {'git':self.config.superRepoPath + self.config.projects[project.lower()]}
gitSubmodule = Git(gitSubmoduleProfile)
self.log.debug("checking out hash: " + hash)
gitSubmodule.fetch()
if self.isOptOut(gitSubmodule, hash):
return
gitSubmodule.checkout(hash, True)
git.add(".")
commitMsg = "Auto checkin: " + self.getCommitMessage(gitSubmodule, hash) + "\nuser:" + who + "\nhash:" + hash + "\nproject: " + project
self.log.debug("commiting in super module: " + commitMsg)
git.commit(commitMsg)
self.log.debug("pushing super module to branch: " + branch)
git.push(branch)
else:
self.log.debug("No super module commit is required.")
示例7: branch
# 需要导入模块: from git import Git [as 别名]
# 或者: from git.Git import checkout [as 别名]
def branch(branch_name):
# branch_name = 'remotes/ssh/' + branch_name
g = Git(PROJECT_DIR)
send('重新获取远程分支中.....')
g.fetch(REMOTE_NAME)
send('获取成功')
branch_names = g.branch('-a').split('\n')
branch_names = [_.strip() for _ in branch_names]
if branch_name not in branch_names:
return '你的这个branch啊,鹅母鸡鸭'
try:
send('重置分支')
g.reset('--hard')
send('切换分支中')
g.checkout(branch_name)
send('切换分支完成')
except Exception as e:
return str(e)
return branch_name
示例8: post
# 需要导入模块: from git import Git [as 别名]
# 或者: from git.Git import checkout [as 别名]
def post(self):
parser = reqparse.RequestParser()
parser.add_argument('app_name', required=True)
parser.add_argument('git_url', required=True)
parser.add_argument('git_ref', required=True)
args = parser.parse_args()
if mongo.db.docker_apps.find_one({'app_name':args['app_name']}):
abort(500, message='App Already Exists')
r = requests.get(args['git_url'])
if r.status_code == int('200'):
git_clone_dir = git_base+args['app_name']
try:
if os.path.isdir(git_clone_dir):
shutil.rmtree(git_clone_dir, ignore_errors=True)
Repo.clone_from(args['git_url'], git_clone_dir, branch='master')
g = Git(git_clone_dir)
g.checkout(args['git_ref'])
except:
abort(500, message='Failed To Clone Git Repo')
try:
repo = Repo(git_clone_dir)
sha = repo.head.object.hexsha
short_sha = repo.git.rev_parse(sha, short=7)
response = [line for line in cli.build(path=git_clone_dir, tag=args['app_name']+'/'+short_sha+'/'+args['git_ref'])]
pprint(response) # Need to add to mongodb log database
except:
abort(500, message='Failed To Build Docker Container')
try:
mongo.db.docker_apps.create_index('app_name',unique=True)
mongo_insert = mongo.db.docker_apps.insert({'app_name':args['app_name'],'git_url':args['git_url']},{'_id': 0})
except:
abort(500, message='Database Updage Failed')
else:
abort(500, message="Invalid GIT URL")
return args
示例9: compare_git_commits
# 需要导入模块: from git import Git [as 别名]
# 或者: from git.Git import checkout [as 别名]
def compare_git_commits(repo_path, branch, start_commit, end_commit):
# print 'Repo path: ' + repo_path + ' and branch: ' + branch
# print 'Starting commit: ' + start_commit + ', Ending commit: ' + end_commit
repo = Repo(repo_path)
git = Git(repo_path)
head = repo.heads[0]
git.checkout(start_commit)
cmd_str = 'java -jar bin/threadfix-endpoint-cli-2.4-SNAPSHOT-jar-with-dependencies.jar ' + pipes.quote(repo_path) + ' -json 2>/dev/null > ' + pipes.quote(make_attack_surface_filename(start_commit))
print 'About to generate start attack surface with command: ' + cmd_str
os.system(cmd_str)
git.checkout(end_commit)
cmd_str = 'java -jar bin/threadfix-endpoint-cli-2.4-SNAPSHOT-jar-with-dependencies.jar ' + pipes.quote(repo_path) + ' -json 2>/dev/null > ' + pies.quote(make_attack_surface_filename(end_commit))
print 'About to generate end attack surface with command: ' + cmd_str
os.system(cmd_str)
ret_val = diff_attack_surface_files(make_attack_surface_filename(start_commit), make_attack_surface_filename(end_commit))
return ret_val
示例10: buildForReal
# 需要导入模块: from git import Git [as 别名]
# 或者: from git.Git import checkout [as 别名]
def buildForReal(site_branch):
# make sure there are no local mods outstanding
repo = Repo(os.getcwd())
if repo.is_dirty() or repo.untracked_files:
print "ERROR: Your working directory has outstanding changes."
print "Commit or stash them."
return
mygit = Git(os.getcwd())
cfg = config.load_config()
# sanity check that the version branches exist as named
for version in cfg['extra']['versions']:
print 'Verifying branch %s' % (version['branch'])
mygit.checkout(version['branch'])
# sanity check - only one latest
latest = False
for version in cfg['extra']['versions']:
if not latest and version['latest']:
print 'Latest is %s' % (version['branch'])
latest = True
elif latest and version['latest']:
print 'ERROR: More than one version is latest.'
print 'Only one version can be latest: True.'
print 'Check mkdocs.yml.'
return
mygit.checkout(site_branch)
print "Building site pages from: %s..." % (site_branch)
sh.rm('-rf', 'site')
sh.mkdocs('build', '--clean')
for version in cfg['extra']['versions']:
sh.git('checkout', version['branch'], '--', 'docs', 'mkdocs.yml')
deployVersion(version)
sh.git('reset', 'HEAD', '.')
sh.git('checkout', '--', '.')
sh.git('reset', 'HEAD', '.')
sh.git('checkout', '--', '.')
示例11: initialize
# 需要导入模块: from git import Git [as 别名]
# 或者: from git.Git import checkout [as 别名]
def initialize(path, branch):
try:
repo = Repo(path)
git = Git(path)
except InvalidGitRepositoryError as err:
print "Not a valid Git repo: %s" % err
sys.exit("Run `git init %s` first" % err)
output = ['Initializing in %s [%s]' % (path, branch)]
current_branch = repo.active_branch
if branch in [b.name for b in repo.branches]:
output.append("error: A branch named '%s' already exists in this repo!"
% branch)
return output
output.append("--> Stashing current branch contents [%s]" % current_branch)
try:
cmd = git.stash(u=True)
for line in cmd.splitlines():
output.append(" %s" % line)
except GitCommandError as err:
output.append("error: %s" % err)
return output
output.append("--> Switching to branch '%s'" % branch)
try:
git.checkout(B=branch)
except GitCommandError as err:
output.append("error: %s" % err)
return output
output.append("--> Clearing current files and committing")
try:
files = os.listdir(path)
files.remove('.git')
for entry in files:
git.rm(entry, r=True, f=True)
cmd = git.commit(m="Clearing files in preparation for git-pm")
for line in cmd.splitlines():
output.append(" %s" % line)
except GitCommandError as err:
output.append("error: %s" % err)
return output
output.append("--> Creating git-pm file structure and committing")
try:
for directory in DIRECTORIES:
dir_path = os.path.join(path, directory)
gitkeep = os.path.join(dir_path, '.gitkeep')
os.mkdir(dir_path)
with open(gitkeep, 'a'):
os.utime(gitkeep, None)
cmd = git.commit(m="Created git-pm file structure")
for line in cmd.splitlines():
output.append(" %s" % line)
except GitCommandError as err:
output.append("error: %s" % err)
return output
output.append("--> Returning to previous branch and popping stash")
try:
git.checkout(current_branch)
git.stash("pop")
except GitCommandError as err:
output.append("error: %s" % err)
return output
return output
示例12: buildTo
# 需要导入模块: from git import Git [as 别名]
# 或者: from git.Git import checkout [as 别名]
if version['latest']:
buildTo('latest')
def buildTo(branch):
print 'Building doc pages for: %s...' % (branch)
branchCfg = config.load_config()
if branchCfg['extra']['version'] != branch:
updateConfigVersion(branch)
sh.mkdocs('build', '--site-dir', 'site/%s' % (branch))
if branchCfg['extra']['version'] != branch:
sh.git('checkout', '--', 'mkdocs.yml')
def updateConfigVersion(branch):
updated = False
for line in fileinput.input('mkdocs.yml', inplace=True):
line = line.rstrip()
if line.find(" version:") == 0:
line = " version: '%s'" % (branch)
updated = True
print line
assert updated, "Could not fix the version field on %s" % (branch)
if __name__ == '__main__':
repo = Repo(os.getcwd())
branch = repo.active_branch
mygit = Git(os.getcwd())
try:
build()
finally:
mygit.checkout(branch.name)
示例13: changegittag
# 需要导入模块: from git import Git [as 别名]
# 或者: from git.Git import checkout [as 别名]
def changegittag(directory,tag):
g = Git(directory)
g.checkout(tag)
示例14: OptionParser
# 需要导入模块: from git import Git [as 别名]
# 或者: from git.Git import checkout [as 别名]
import pipes
parser = OptionParser()
parser.add_option('--repolocation', dest='repolocation', help='Path to Git repository location')
parser.add_option('--branch', dest='branch', help='Branch in the Git repository')
parser.add_option('--project', dest='project', help='Name of the project')
(options, args) = parser.parse_args()
repo_path = options.repolocation
project = options.project
branch = 'master'
if options.branch:
branch = options.branch
print 'Repo path: ' + repo_path + ' and branch: ' + branch
repo = Repo(repo_path)
git = Git(repo_path)
head = repo.heads[0]
commits = list(repo.iter_commits(branch))
commits.reverse()
for commit in commits:
print 'Commit: ' + commit.hexsha + ' with date: ' + str(commit.committed_date)
git.checkout(commit.hexsha)
cmd_str = 'java -jar bin/threadfix-endpoint-cli-2.4-SNAPSHOT-jar-with-dependencies.jar ' + pipes.quote(repo_path) + ' -json > work/' + pipes.quote(project) + '_attacksurface_' + pipes.quote(str(commit.committed_date)) + '.json'
print 'About to generate attack surface with command: ' + cmd_str
os.system(cmd_str)
示例15: pull
# 需要导入模块: from git import Git [as 别名]
# 或者: from git.Git import checkout [as 别名]
import git
from git import Git
from shutil import copyfile
import datetime
# Grab todays date
now = datetime.datetime.now()
now = now.strftime("%Y-%m-%d")
# Git pull (cron job)
cloned_repo = git.cmd.Git("/women-in-tech-datasets/triketora")
cloned_repo1 = Git("/women-in-tech-datasets/triketora")
# Getting sha for historic commits since last successfull run
loginfo = cloned_repo.log('--format=format:%H', '--since=%s' % now, '--', 'data.txt')
# Converting it into an array
loginfo_array = loginfo.split('\n')
# Run only if there have been commits
ntp = open("/datasets/tracy_data/new_to_parse.txt")
if len(loginfo_array) > 1:
for hexsha in loginfo_array:
cloned_repo1.checkout(hexsha)
copyfile("/women-in-tech-datasets/triketora/data.txt", "/datasets/company_coder_gender_stats/data_%s.txt" % hexsha)
ntp.append("data_%s.txt" % hexsha)
ntp.close()
f = open("/datasets/tracy_data/success_runDate.txt", "w+")
f.write(now)
f.close()