• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python sh.git函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sh.git函数的典型用法代码示例。如果您正苦于以下问题:Python git函数的具体用法?Python git怎么用?Python git使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了git函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: set_remote_url

def set_remote_url(git_dir, url):
    try:
        git('-C', git_dir, 'remote', 'set-url', 'origin', url)
    except ErrorReturnCode as e:
        return failed_util_call_results(e)
    else:
        return succeeded_util_call_results(None) 
开发者ID:MyPureCloud,项目名称:translation-process-automation,代码行数:7,代码来源:commands.py


示例2: pull

    def pull(self, remote, env={}, branch=None):
        """
        Pull a branch from a given remote

        Given a remote, env and branch, pull branch
        from remote and add the environment variables
        in the env dict to the environment of the
        "git pull" command.

        If no branch is given, the current branch
        will be updated.
        """
        if branch:
            branch_to_pull = branch
        else:
            branch_to_pull = self.current_branch()

        # if there is no PKEY, we don't need to override env
        # We are explicit about what we are pushing, since the default behavior
        # is different in different versions of Git and/or by configuration
        if env["PKEY"]:
            new_env = os.environ.copy()
            new_env.update(env)
            git(self.gitdir, self.gitwd, "pull", remote, "{}:{}".format(branch_to_pull,branch_to_pull), _env=new_env)
        else:
            git(self.gitdir, self.gitwd, "pull", remote, "{}:{}".format(branch_to_pull,branch_to_pull))

        new_sha      = git(self.gitdir, self.gitwd, "rev-parse","HEAD")
        return new_sha.strip()
开发者ID:OpenTreeOfLife,项目名称:phylesystem-api,代码行数:29,代码来源:gitdata.py


示例3: branch_exists

 def branch_exists(self, branch):
     """Returns true or false depending on if a branch exists"""
     try:
         git(self.gitdir, self.gitwd, "rev-parse", branch)
     except sh.ErrorReturnCode:
         return False
     return True
开发者ID:OpenTreeOfLife,项目名称:peyotl,代码行数:7,代码来源:git_action.py


示例4: setUp

 def setUp(self):
     super(TestServerOk, self).setUp()
     self.dir = tempfile.mkdtemp()
     sh.cd(self.dir)
     sh.git.init()
     sh.git('config', 'user.name', '"Guido"')
     sh.git('config', 'user.email', '"[email protected]"')
     sh.touch('README')
     sh.git.add('.')
     sh.git.commit('-am', 'first commit')
     sh.git.tag('-a', 'jenkins-release-1', '-m', 'Release 1')
     sh.touch('file1')
     sh.git.add('.')
     sh.git.commit('-am', 'second commit #777 #123')
     sh.git.tag('-a', 'jenkins-release-2', '-m', 'Release 2', _env={"GIT_COMMITTER_DATE": "2006-04-07T22:13:13"})
     sh.touch('file2')
     sh.git.add('.')
     sh.git.commit('-am', '#67 third commit')
     sh.git.tag('-a', 'jenkins-release-3', '-m', 'Release 3')
     self.prepare_client()
     self.valid_data = {
         'build_number': '42',
         'build_tag': 'jenkins-release-2',
         'previous_tag': 'jenkins-release-1',
         'job_url': 'http://jenkins_url/jobs/2/',
         'repo': self.dir,
         'instance': 'TestServer',
     }
开发者ID:futurecolors,项目名称:redmine-releasedate,代码行数:28,代码来源:test_releasedate.py


示例5: create_or_checkout_branch

    def create_or_checkout_branch(self, gh_user, study_id, parent_sha, force_branch_name=False):
        if force_branch_name:
            #@TEMP deprecated
            branch = "{ghu}_study_{rid}".format(ghu=gh_user, rid=study_id)
            if not self.branch_exists(branch):
                try:
                    git(self.gitdir, self.gitwd, "branch", branch, parent_sha)
                    _LOG.debug('Created branch "{b}" with parent "{a}"'.format(b=branch, a=parent_sha))
                except:
                    raise ValueError('parent sha not in git repo')
            self.checkout(branch)
            return branch

        frag = "{ghu}_study_{rid}_".format(ghu=gh_user, rid=study_id)
        branch = self._find_head_sha(frag, parent_sha)
        _LOG.debug('Found branch "{b}" for sha "{s}"'.format(b=branch, s=parent_sha))
        if not branch:
            branch = frag + '0'
            i = 1
            while self.branch_exists(branch):
                branch = frag + str(i)
                i += 1
            _LOG.debug('lowest non existing branch =' + branch)
            try:
                git(self.gitdir, self.gitwd, "branch", branch, parent_sha)
                _LOG.debug('Created branch "{b}" with parent "{a}"'.format(b=branch, a=parent_sha))
            except:
                raise ValueError('parent sha not in git repo')
        self.checkout(branch)
        _LOG.debug('Checked out branch "{b}"'.format(b=branch))
        return branch
开发者ID:rvosa,项目名称:peyotl,代码行数:31,代码来源:git_actions.py


示例6: _create_simple_commit

 def _create_simple_commit(self, message):
     """ Creates a simple commit with an empty test file.
         :param message: Commit message for the commit. """
     test_filename = "test-file-" + str(uuid4())
     touch(test_filename, _cwd=self.tmp_git_repo)
     git("add", test_filename, _cwd=self.tmp_git_repo)
     git("commit", "-m", message, _cwd=self.tmp_git_repo)
开发者ID:Hawatel,项目名称:gitlint,代码行数:7,代码来源:integration_test.py


示例7: isRepo

def isRepo():
    """ Returns if the cwd is a git repo """
    try:
        git("rev-parse", "--is-inside-work-tree")
        return 1
    except:
        return 0
开发者ID:Alpha59,项目名称:GitHub,代码行数:7,代码来源:gitCommands.py


示例8: grab_changesets

    def grab_changesets(self, path, url, changesets):
        """
        Inherited method :func:`~DepotOperations.grab_changesets`
        """
        logger.debug('Grabbing changesets from %s to %s' % (url, path))
        # Force handling it as a bare repository so even current branch can be
        # overwritten by fetch
        git_path = os.path.join(
            path,
            sh.git('rev-parse', '--git-dir', _cwd=path).strip())
        logger.debug("Executing git -c core.bare=true fetch " + url + " +refs/*:refs/* on " + git_path)
        output = sh.git('-c', 'core.bare=true', 'fetch',
                        url,
                        '+refs/*:refs/*',
                        _cwd=git_path,
                        _err_to_out=True)
        logger.debug("Output:\n%s" % output)
        if sh.git('rev-parse', '--is-bare-repository', _cwd=path).strip() == 'false':
            self._clear_working_copy(path)
        self._save_state(path)

        for c in changesets:
            try:
                sh.git('log', '-1', c, _cwd=path, _tty_out=False)
            except sh.ErrorReturnCode as e:
                logger.debug('Error checking changeset %s: %s', c, e)
                return False
        return True
开发者ID:mrodm,项目名称:python-repoman,代码行数:28,代码来源:depot_operations.py


示例9: fetch

    def fetch(self):
        LOG.debug('Fetching repo uri %s' % self.repo['uri'])

        if os.path.exists(self.folder):
            os.chdir(self.folder)
            uri = str(sh.git('config', '--get', 'remote.origin.url')).strip()
            if uri != self.repo['uri']:
                LOG.debug('Repo uri %(uri)s differs from cloned %(old)s',
                          {'uri': self.repo['uri'], 'old': uri})
                os.chdir('..')
                shutil.rmtree(self.folder)

        if not os.path.exists(self.folder):
            os.chdir(self.sources_root)
            try:
                sh.git('clone', self.repo['uri'])
            except sh.ErrorReturnCode as e:
                LOG.error('Unable to clone git repo %s. Ignore it',
                          self.repo['uri'])
                LOG.exception(e)
            os.chdir(self.folder)
        else:
            os.chdir(self.folder)
            try:
                sh.git('fetch')
            except sh.ErrorReturnCode as e:
                LOG.error('Unable to fetch git repo %s. Ignore it',
                          self.repo['uri'])
                LOG.exception(e)

        self.get_release_index()
开发者ID:Mingkii,项目名称:stackalytics,代码行数:31,代码来源:vcs.py


示例10: skipUnlessHasGit

def skipUnlessHasGit(obj):
    # Test git presence
    try:
        sh.git(version=True, _out='/dev/null')
        return lambda func: func
    except sh.CommandNotFound:
        return unittest.skip("Git is not installed")
开发者ID:affinitic,项目名称:BitBucket-api,代码行数:7,代码来源:repository.py


示例11: test_write

    def test_write(self):
        def cleanup_write():
            git.checkout("master")
            git.branch("-D","johndoe_study_9998")
            git.branch("-D","johndoe_study_9999")

        self.addCleanup(cleanup_write)

        author   = "John Doe <[email protected]>"
        content  = '{"foo":"bar"}'
        study_id = 9999
        branch   = "johndoe_study_%s" % study_id
        new_sha  = self.gd.write_study(study_id,content,branch,author)
        self.assertTrue( new_sha != "", "new_sha is non-empty")
        self.assertEqual(len(new_sha), 40, "SHA is 40 chars")
        self.assertEqual( content, self.gd.fetch_study(9999), "correct content found via fetch_study")

        author   = "John Doe <[email protected]>"
        content  = '{"foo2":"bar2"}'
        study_id = 9998
        branch   = "johndoe_study_%s" % study_id
        new_sha  = self.gd.write_study(study_id,content,branch,author)

        merge_base_sha1 = git("merge-base","johndoe_study_9999","johndoe_study_9998").strip()

        master_sha1     = git("rev-parse","master").strip()

        self.assertEqual(master_sha1, merge_base_sha1, "Verify that writing new study branches from master and not the current branch")
开发者ID:infosucker,项目名称:api.opentreeoflife.org,代码行数:28,代码来源:test_gitdata.py


示例12: test_git_dir_from_subdir

    def test_git_dir_from_subdir(self):
        sh.git('init')
        sh.mkdir('foo')
        expected = os.path.join(os.getcwd(), '.git')

        sh.cd('foo')
        self.assertEqual(expected, git_dir())
开发者ID:themalkolm,项目名称:git-boots,代码行数:7,代码来源:test_git_dir.py


示例13: main

def main():
    if len(sys.argv) == 2:
        sh.cd(sys.argv[1])
        print(sh.git("status"))
        print("(Y/n): Are you sure you want to reset this directory?")
        temp = str(input("Local changes will be deleted: "))
        if temp=="y" or temp =="Y":
            print(sh.git.reset("--hard", "HEAD"))
            print(sh.git.clean("-f"))
            print(sh.git.pull)
            print(sh.git("status"))
        else:
            sys.exit(0)

    else:
        print(sh.git("status"))
        print("(Y/n): Are you sure you want to reset this directory?")
        temp = str(input("Local changes will be deleted: "))
        if temp=="y" or temp =="Y":
            print(sh.git.reset("--hard", "HEAD"))
            print(sh.git.clean("-f"))
            print(sh.git.pull)
            print(sh.git("status"))
        else:
            sys.exit(0)
开发者ID:michaelrinos,项目名称:Python-Personal,代码行数:25,代码来源:BashScript.py


示例14: clone

def clone(root, uniqname, project):
	into='/tmp/'+root
	mkdir('-p', into)
	url='[email protected]:' + uniqname + '/' + project
	to_path=into + '/' + uniqname

	if 'rerun' in sys.argv:
		if os.path.exists(to_path):
			print('cached {}'.format(to_path))
			repo = git.Repo(to_path)
			return repo, to_path

	print('clone {}/{}'.format(uniqname, project))
	try:
		repo = git.Repo.clone_from(
				url=url,
				to_path=to_path,
				)
		return repo, to_path
	except:
		# Fall back to sh path to grab the error
		try:
			sh.git('clone', url, to_path)
		except sh.ErrorReturnCode as e:
			if 'Connection closed by remote host' in e.stderr.decode('utf8'):
				# gitlab rate-limited us
				time.sleep(3)
				return clone(root, uniqname, project)
			raise

		# Since we're hammering the gitlab server, rarely the first will
		# timeout, but this second chance will succeed. Create a repo object
		# from the path in that case.
		repo = git.Repo(to_path)
		return repo, to_path
开发者ID:c4cs,项目名称:assignments,代码行数:35,代码来源:grade.py


示例15: give_user_ztanesh

def give_user_ztanesh(unix_user):
    """
    Make sure our UNIX user runs ZtaneSH shell it is more productive to work with Plone sites.

    https://github.com/miohtama/ztanesh
    """
    from sh import git
    from sh import chsh

    home = get_unix_user_home(unix_user)

    # Install ZtaneSH
    if not os.path.exists("%s/tools" % home):

        print "Installing ZtaneSH for user %s" % unix_user

        with sudo(i=True, u=unix_user, _with=True):
            cd(home)
            git("clone", "git://github.com/miohtama/ztanesh.git", "tools")
            setup = "%s/tools/zsh-scripts/setup.zsh" % home
            run = Command(setup)
            run()

    # Set user default shell
    with sudo:
        chsh("-s", "/bin/zsh", unix_user)
开发者ID:miohtama,项目名称:senorita.plonetool,代码行数:26,代码来源:main.py


示例16: run_init

def run_init(*args, **kwargs):

    # initialize the git repository if not already done
    try:
        git("rev-parse", "--dir-list")
    except ErrorReturnCode_128:
        git("init")

    exclude = kwargs.get('exclude')
    hooks_added = []

    for hook in SUPPORTED_HOOKS:
        if exclude and hook not in exclude or not exclude:
            try:
                os.symlink(path_to_the_script, '.git/hooks/{}'.format(hook))
            except OSError, e:
                if e.errno == 17:
                    logging.info('Already initialized')

            # create a temporary hook key/val
            key = 'hooks.{hook_type}.placeholder'.format(hook_type=hook)
            val = 'true'
            try:
                git.config('--get', key)
            except ErrorReturnCode_1:
                git.config('--add', key, val)

        hooks_added.append(hook)
开发者ID:nityaoberoi,项目名称:githooks,代码行数:28,代码来源:core.py


示例17: remove_study

    def remove_study(self, first_arg, sec_arg, third_arg, fourth_arg=None, commit_msg=None):
        """Remove a study
        Given a study_id, branch and optionally an
        author, remove a study on the given branch
        and attribute the commit to author.
        Returns the SHA of the commit on branch.
        """
        if fourth_arg is None:
            study_id, branch_name, author = first_arg, sec_arg, third_arg
            gh_user = branch_name.split('_study_')[0]
            parent_sha = self.get_master_sha()
        else:
            gh_user, study_id, parent_sha, author = first_arg, sec_arg, third_arg, fourth_arg
        study_filepath = self.path_for_study(study_id)
        study_dir = os.path.split(study_filepath)[0]

        branch = self.create_or_checkout_branch(gh_user, study_id, parent_sha)
        prev_file_sha = None
        if commit_msg is None:
            msg = "Delete Study #%s via OpenTree API" % study_id
        else:
            msg = commit_msg
        if os.path.exists(study_filepath):
            prev_file_sha = self.get_blob_sha_for_file(study_filepath)
            git(self.gitdir, self.gitwd, "rm", "-rf", study_dir)
            git(self.gitdir,
                self.gitwd,
                "commit",
                author=author,
                message=msg)
        new_sha = git(self.gitdir, self.gitwd, "rev-parse", "HEAD").strip()
        return {'commit_sha': new_sha,
                'branch': branch,
                'prev_file_sha': prev_file_sha,
               }
开发者ID:rvosa,项目名称:peyotl,代码行数:35,代码来源:git_actions.py


示例18: setUp

    def setUp(self):
        self.powerline = mock.MagicMock()
        git.Color = mock.MagicMock()

        self.dirname = tempfile.mkdtemp()
        sh.cd(self.dirname)
        sh.git("init", ".")
开发者ID:Bragaman,项目名称:powerline-shell,代码行数:7,代码来源:git_test.py


示例19: check_update

def check_update():
    """
    Check if there is a later version of Screenly OSE
    available. Only do this update once per day.
    Return True if up to date was written to disk,
    False if no update needed and None if unable to check.
    """

    sha_file = path.join(settings.get_configdir(), 'latest_screenly_sha')
    device_id_file = path.join(settings.get_configdir(), 'device_id')

    if path.isfile(sha_file):
        sha_file_mtime = path.getmtime(sha_file)
        last_update = datetime.fromtimestamp(sha_file_mtime)
    else:
        last_update = None

    if not path.isfile(device_id_file):
        device_id = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(15))
        with open(device_id_file, 'w') as f:
            f.write(device_id)
    else:
        with open(device_id_file, 'r') as f:
            device_id = f.read()

    logging.debug('Last update: %s' % str(last_update))

    git_branch = sh.git('rev-parse', '--abbrev-ref', 'HEAD').strip()
    git_hash = sh.git('rev-parse', '--short', 'HEAD').strip()

    if last_update is None or last_update < (datetime.now() - timedelta(days=1)):

        if not settings['analytics_opt_out'] and not is_ci():
            mp = Mixpanel('d18d9143e39ffdb2a4ee9dcc5ed16c56')
            try:
                mp.track(device_id, 'Version', {
                    'Branch': str(git_branch),
                    'Hash': str(git_hash),
                })
            except MixpanelException:
                pass
            except AttributeError:
                pass

        if remote_branch_available(git_branch):
            latest_sha = fetch_remote_hash(git_branch)

            if latest_sha:
                with open(sha_file, 'w') as f:
                    f.write(latest_sha)
                return True
            else:
                logging.debug('Unable to fetch latest hash.')
                return
        else:
            touch(sha_file)
            logging.debug('Unable to check if branch exist. Checking again tomorrow.')
            return
    else:
        return False
开发者ID:viaict,项目名称:screenly-ose,代码行数:60,代码来源:viewer.py


示例20: test_master_grab_changesets

    def test_master_grab_changesets(self):
        # Grabs branch from a "remote" depot.

        # Remote repository
        self.add_content_to_repo(
            os.path.join(FIXTURE_PATH, 'fixture-2.git.bundle'), 'remote')

        dcvs = DepotOperations()

        dcvs.init_depot(
            os.path.join(self.environment_path, 'master'),
            parent=None,
            source=os.path.join(self.environment_path, 'remote'))

        # Changeset both there
        self.assertEquals(
            True, dcvs.grab_changesets(
                os.path.join(self.environment_path, 'master'),
                os.path.join(self.environment_path, 'remote'),
                ['my-branch1']))

        # Check availability
        sh.git('log', '4632aa0b30c65cd1c6ec978d2905836ae65509ed',
               _cwd=os.path.join(self.environment_path, 'master'))

        # Changesets not there
        self.assertTrue(
            dcvs.grab_changesets(
                os.path.join(self.environment_path, 'master'),
                os.path.join(self.environment_path, 'remote'),
                ['c377d40d21153bdcc4ec0b24bba48af3899fcc7x',
                    'b93d349f220d892047817f7ab29b2e8bfc5569bx']))
开发者ID:angelnan,项目名称:python-repoman,代码行数:32,代码来源:test_gitdepotoperations.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python sh.glob函数代码示例发布时间:2022-05-27
下一篇:
Python sh.echo函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap