当前位置: 首页>>代码示例>>Python>>正文


Python Git.checkout方法代码示例

本文整理汇总了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)
开发者ID:she11c0de,项目名称:seed,代码行数:36,代码来源:seed.py

示例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)    
开发者ID:juju-solutions,项目名称:layer-binary-builder,代码行数:12,代码来源:buildutils.py

示例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
开发者ID:qrntz,项目名称:pool,代码行数:53,代码来源:pool.py

示例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')
开发者ID:d0ugal,项目名称:mkdocs-versioned,代码行数:31,代码来源:cli.py

示例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)
开发者ID:j-be,项目名称:vj-control-server-buildenv,代码行数:17,代码来源:checkout-repos.py

示例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.")
开发者ID:ralberts,项目名称:Gerrit-Submodule-Hooks,代码行数:45,代码来源:supermodulecommit.py

示例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
开发者ID:barrysfinalhome,项目名称:pythonStudy,代码行数:21,代码来源:deploy_server.py

示例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
开发者ID:bcarpio,项目名称:docker_build_service,代码行数:44,代码来源:docker_build.py

示例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
开发者ID:denimgroup,项目名称:threadfix-examples,代码行数:22,代码来源:visualize.py

示例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', '--', '.')
开发者ID:apache,项目名称:incubator-mynewt-site,代码行数:42,代码来源:build.py

示例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
开发者ID:jlindsey,项目名称:git-pm,代码行数:73,代码来源:initialize.py

示例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)
开发者ID:bgiori,项目名称:incubator-mynewt-site,代码行数:32,代码来源:build.py

示例13: changegittag

# 需要导入模块: from git import Git [as 别名]
# 或者: from git.Git import checkout [as 别名]
def changegittag(directory,tag):
  g = Git(directory)
  g.checkout(tag)
开发者ID:njuap,项目名称:python-smells,代码行数:5,代码来源:util.py

示例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)
开发者ID:denimgroup,项目名称:threadfix-examples,代码行数:32,代码来源:git_dump.py

示例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()
开发者ID:alison985,项目名称:women-in-tech-datasets,代码行数:32,代码来源:github_extractor.py


注:本文中的git.Git.checkout方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。