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


Python pygit2.clone_repository函数代码示例

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


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

示例1: initRepositories

    def initRepositories(self, repositoryIDs):
        """
            Creates a Review folder in the current directory 
            and then creates a folder for each repository that 
            is specified in the repos dictionary.
        """
        repositories = {}
        isDir = path.isdir(self.absPath + "/Review")
        if not isDir:
            os.mkdir(self.absPath + "/Review")

        for currentID in repositoryIDs.keys():
            currentPath = self.absPath + "/Review/" + currentID
            isDir = path.isdir(currentPath)
            if not isDir:
                os.mkdir(currentPath)
                repositories[currentID] = pygit2.clone_repository(
                    "git://" + repositoryIDs[currentID].getUrl(), currentPath
                )
                repositories[currentID].checkout(
                    repositories[currentID].lookup_reference(repositoryIDs[currentID].getTag())
                )
            else:
                shutil.rmtree(currentPath)
                os.mkdir(currentPath)
                repositories[currentID] = pygit2.clone_repository(
                    "git://" + repositoryIDs[currentID].getUrl(), currentPath
                )
                repositories[currentID].checkout(
                    repositories[currentID].lookup_reference(repositoryIDs[currentID].getTag())
                )
开发者ID:EvilClam,项目名称:PythonCodeReview,代码行数:31,代码来源:Submit.py

示例2: clone_repo

    def clone_repo(cls, url, dest_path, bare=False):
        """ Clone a git repo from the provided url at the specified dest_path.

        :arg url: the url of the git.
        :type url: str
        :arg dest_path: the path where to clone the git repo (including the
            name of the git repo itself, ie: if you clone foo in /home/bb/bar
            the dest_path will be /home/bb/bar/foo).
        :type dest_path: str
        :kwarg bare: a boolean specifying whether the cloned repo should be
            a bare repo or not
        :type bare: bool
        :return: a `GitRepo` object instanciated at the provided path
        :rtype: GitRepo
        :raises OSError: raised when the directory where is cloned the repo
            exists and is not empty
        :raises pygit2.GitError: raised then the url provided is invalid

        """

        if os.path.exists(dest_path):
            raise OSError(
                errno.EEXIST, '%s exists and is not empty' % dest_path)

        pygit2.clone_repository(url, dest_path, bare=bare)

        return cls(path=dest_path)
开发者ID:fedora-infra,项目名称:pygit2_utils,代码行数:27,代码来源:__init__.py

示例3: get_remote_repo_path

def get_remote_repo_path(remote_git, branch_from, loop=False):
    """ Return the path of the remote git repository corresponding to the
    provided information.
    """
    repopath = os.path.join(
        APP.config['REMOTE_GIT_FOLDER'],
        werkzeug.secure_filename('%s_%s' % (remote_git, branch_from))
    )

    if not os.path.exists(repopath):
        try:
            pygit2.clone_repository(
                remote_git, repopath, checkout_branch=branch_from)
        except Exception as err:
            LOG.debug(err)
            LOG.exception(err)
            flask.abort(500, 'Could not clone the remote git repository')
    else:
        repo = pagure.lib.repo.PagureRepo(repopath)
        try:
            repo.pull(branch=branch_from, force=True)
        except pagure.exceptions.PagureException as err:
            LOG.debug(err)
            LOG.exception(err)
            flask.abort(500, err.message)

    return repopath
开发者ID:docent-net,项目名称:pagure,代码行数:27,代码来源:__init__.py

示例4: open_repository

def open_repository(url,
                    target_directory):
    """
    Make a connection from a remote git repository into a local
    directory.

    Args:
        url(string): The remote github url of the repository
        target_directory(string): The local target directory

    Returns:
        pygit2.repo: The repository object created
    """
    git_url = urlparse.urlparse(url)
    username = git_url.netloc.split('@')[0]\
        if '@' in git_url.netloc else 'git'
    try:
        credentials = pygit2.credentials.KeypairFromAgent(username)
    except AttributeError as e:
        pygit2_parse_error(e)

    # If local directory exists, then make a connection to it
    # Otherwise, clone the remote repo into the new directory
    if os.path.isdir(target_directory):
        shaker.libs.logger.Logger().debug("open_repository: "
                                          "Opening url '%s' "
                                          "with existing local repository '%s'"
                                          % (url, target_directory))
        repo = pygit2.Repository(target_directory)
    else:
        # Try to use pygit2 0.22 cloning
        try:
            shaker.libs.logger.Logger().debug("open_repository: "
                                              "Trying to open repository "
                                              "using pygit2 0.22 format")
            repo = pygit2.clone_repository(url,
                                           target_directory,
                                           credentials=credentials)
        except TypeError as e:
            shaker.libs.logger.Logger().debug("open_repository: "
                                              "Failed to detect pygit2 0.22")
            shaker.libs.logger.Logger().debug("open_repository: "
                                              "Trying to open repository "
                                              "using pygit2 0.23 format")
            # Try to use pygit2 0.23 cloning
            callbacks = pygit2.RemoteCallbacks(credentials)
            repo = pygit2.clone_repository(url,
                                           target_directory,
                                           callbacks=callbacks)

        shaker.libs.logger.Logger().debug(":open_repository: "
                                          "Cloning url '%s' into local repository '%s'"
                                          % (url, target_directory))
    origin = filter(lambda x: x.name == 'origin', repo.remotes)
    if not origin:
        repo.create_remote('origin', url)
        origin = filter(lambda x: x.name == 'origin', repo.remotes)
    origin[0].credentials = credentials

    return repo
开发者ID:ministryofjustice,项目名称:salt-shaker,代码行数:60,代码来源:github.py

示例5: clone

def clone(repo_name, internal):
    clone_directory = os.environ['git_clone_dir']
    uniq_path = hashlib.sha224(repo_name).hexdigest()
    
    if os.path.isdir(os.path.join(clone_directory, uniq_path)):
        shutil.rmtree(os.path.join(clone_directory, uniq_path))

    if internal:
        repo_url = '%s/%s.git' % (os.environ['int_git_url'], repo_name)
    else:
        repo_url = '%s/%s.git' % (os.environ['ext_git_url'], repo_name)

    try:
        clone_dir = clone_directory
        if not os.path.isdir(clone_dir):
            os.makedirs(clone_dir)
        repo_path = os.path.join(clone_dir, uniq_path)

        if internal==True:
            username = os.environ['int_git_user']
            password = os.environ['int_git_token']
            login_info = git.UserPass(username, password)
            git_obj = git.clone_repository(repo_url, repo_path, credentials=login_info)
        else:
            #username = os.environ['ext_git_user']
            #password = os.environ['ext_git_token']
            git_obj = git.clone_repository(repo_url, repo_path)

        return repo_path
    except Exception, e:
        if str(e).find('Unexpected HTTP status code: 404'):
            log.logger.error("repo doesn't exists")
            return "Repo doesn't exists"
        log.logger.error(e)
开发者ID:FreelancePentester,项目名称:raptor,代码行数:34,代码来源:init.py

示例6: init_repo

def init_repo(repo_path, clone_from=None, clone_refs=False,
              alternate_repo_paths=None, is_bare=True):
    """Initialise a new git repository or clone from existing."""
    assert is_valid_new_path(repo_path)
    init_repository(repo_path, is_bare)

    if clone_from:
        # The clone_from's objects and refs are in fact cloned into a
        # subordinate tree that's then set as an alternate for the real
        # repo. This lets git-receive-pack expose available commits as
        # extra haves without polluting refs in the real repo.
        sub_path = os.path.join(repo_path, 'turnip-subordinate')
        clone_repository(clone_from, sub_path, True)
        assert is_bare
        alt_path = os.path.join(repo_path, 'objects/info/alternates')
        with open(alt_path, 'w') as f:
            f.write('../turnip-subordinate/objects\n')

        if clone_refs:
            # With the objects all accessible via the subordinate, we
            # can just copy all refs from the origin. Unlike
            # pygit2.clone_repository, this won't set up a remote.
            # TODO: Filter out internal (eg. MP) refs.
            from_repo = Repository(clone_from)
            to_repo = Repository(repo_path)
            for ref in from_repo.listall_references():
                to_repo.create_reference(
                    ref, from_repo.lookup_reference(ref).target)

    if alternate_repo_paths:
        write_alternates(repo_path, alternate_repo_paths)
    ensure_config(repo_path)  # set repository configuration defaults
    return repo_path
开发者ID:Waverbase,项目名称:turnip,代码行数:33,代码来源:store.py

示例7: get_remote_repo_path

def get_remote_repo_path(remote_git, branch_from, loop=False):
    """ Return the path of the remote git repository corresponding to the
    provided information.
    """
    repopath = os.path.join(
        APP.config["REMOTE_GIT_FOLDER"], werkzeug.secure_filename("%s_%s" % (remote_git, branch_from))
    )

    if not os.path.exists(repopath):
        try:
            pygit2.clone_repository(remote_git, repopath, checkout_branch=branch_from)
        except Exception as err:
            LOG.exception(err)
            flask.abort(500, "The following error was raised when trying to clone the " "remote repo: %s" % str(err))
    else:
        repo = pagure.lib.repo.PagureRepo(repopath)
        try:
            repo.pull(branch=branch_from, force=True)
        except pygit2.GitError as err:
            LOG.exception(err)
            flask.abort(
                500, "The following error was raised when trying to pull the " "changes from the remote: %s" % str(err)
            )
        except pagure.exceptions.PagureException as err:
            LOG.exception(err)
            flask.abort(500, str(err))

    return repopath
开发者ID:pypingou,项目名称:pagure,代码行数:28,代码来源:__init__.py

示例8: prepare_git

def prepare_git(url, path):
    ''' Prepare git pkgbuild directory '''
    try:
        pygit2.clone_repository(url=url, path=path)
    except pygit2.GitError as error:
        print('Failed to clone repository')
        error_print_exit(error)

    print('Successfully cloned repository: ' + url)
开发者ID:bfritz,项目名称:nfnty-dockerfiles,代码行数:9,代码来源:builder.py

示例9: test_clone_with_checkout_branch

 def test_clone_with_checkout_branch(self):
     # create a test case which isolates the remote
     test_repo = clone_repository('./test/data/testrepo.git',
                                  os.path.join(self._temp_dir, 'testrepo-orig.git'),
                                  bare=True)
     test_repo.create_branch('test', test_repo[test_repo.head.target])
     repo = clone_repository(test_repo.path,
                             os.path.join(self._temp_dir, 'testrepo.git'),
                             checkout_branch='test', bare=True)
     self.assertEqual(repo.lookup_reference('HEAD').target, 'refs/heads/test')
开发者ID:mrasskazov,项目名称:pygit2,代码行数:10,代码来源:test_repository.py

示例10: before_all

def before_all(context):
    """Do the preparation that can be done at the very beginning.

    The "tito" executable must be available.

    :param context: the context as described in the environment file
    :type context: behave.runner.Context
    :raises exceptions.IOError: if the tito-enabled project cannot be
       created
    :raises exceptions.ValueError: if the tito-enabled project cannot be
       created
    :raises exceptions.OSError: if the executable cannot be executed
    :raises subprocess.CalledProcessError: if the tito-enabled project
       cannot be created

    """
    signature = pygit2.Signature(
        stackci.NAME, '{}@example.com'.format(stackci.NAME))
    context.titodn = tempfile.mkdtemp()
    dst_spec = os.path.join(context.titodn, b'foo.spec')
    shutil.copy(
        os.path.join(os.path.dirname(__file__), b'resources', b'foo.spec'),
        dst_spec)
    try:
        titorepo = pygit2.init_repository(context.titodn)
        titorepo.index.add(os.path.relpath(dst_spec, titorepo.workdir))
        titorepo.index.write()
        titorepo.create_commit(
            'refs/heads/master', signature, signature, 'Add a spec file.',
            titorepo.index.write_tree(), [])
    # FIXME: https://github.com/libgit2/pygit2/issues/531
    except Exception as err:
        raise ValueError('Git repository creation failed: {}'.format(err))
    # FIXME: https://github.com/dgoodwin/tito/issues/171
    subprocess.check_call(['tito', 'init'], cwd=context.titodn)
    context.librepodn = tempfile.mkdtemp()
    try:
        libreporepo = pygit2.clone_repository(
            'https://github.com/rpm-software-management/librepo.git',
            context.librepodn)
        libreporepo.reset(
            'd9bed0d9f96b505fb86a1adc50b3d6f8275fab93', pygit2.GIT_RESET_HARD)
    # FIXME: https://github.com/libgit2/pygit2/issues/531
    except Exception as err:
        raise ValueError('Git repository creation failed: {}'.format(err))
    context.libcompsdn = tempfile.mkdtemp()
    try:
        libcompsrepo = pygit2.clone_repository(
            'https://github.com/rpm-software-management/libcomps.git',
            context.libcompsdn)
        libcompsrepo.reset(
            'eb966bc43097c0d00e154abe7f40f4d1d75fbcd1', pygit2.GIT_RESET_HARD)
    # FIXME: https://github.com/libgit2/pygit2/issues/531
    except Exception as err:
        raise ValueError('Git repository creation failed: {}'.format(err))
开发者ID:jhdulaney,项目名称:dnf,代码行数:55,代码来源:environment.py

示例11: clone_worker

def clone_worker(git_remote_callback, protocol, dry_run, part):
    project, path = part[0], part[1]
    try:
        if not dry_run:
            clone_repository(project.url[protocol], path, callbacks=git_remote_callback)
        else:
            msg("@{cf}[email protected]|: %s\n" % escape(textify(project.url[protocol])))
    except (GitError, AuthorizationFailed) as e:
        shutil.rmtree(path, ignore_errors=True)
        return project, str(e)
    return project, ""
开发者ID:fkie,项目名称:rosrepo,代码行数:11,代码来源:cmd_git.py

示例12: git_clone

def git_clone(repo_url, branch='master'):
    '''
    clones repo to a /tmp/ dir
    '''

    if repo_url == '' or not check_available_repo(repo_url):
        return False

    _tmp_dir = tempfile.mkdtemp(prefix='armada', dir='/tmp')
    pygit2.clone_repository(repo_url, _tmp_dir, checkout_branch=branch)

    return _tmp_dir
开发者ID:v1k0d3n,项目名称:armada,代码行数:12,代码来源:git.py

示例13: collectRepo

def collectRepo(repo):
	repo_url = repo
	urlChunks = repo_url.split('/')
	repo_path = 'repos/' + urlChunks[len(urlChunks)-1].replace('.git', '').lower()

	if not os.path.exists(repo_path):
		print 'Checking out ' + repo_path
		clone_repository(repo_url, repo_path)
	else:
		print 'Repository ' + repo_path + ' already exists!'

	return repo_path + '/.git'
开发者ID:dtg3,项目名称:sevo-git-research,代码行数:12,代码来源:gitreap.py

示例14: create_repository

 def create_repository(user, git_repo):
     from .models import Repository as LocalRepository
     try:
         git_user, git_name = GitOperations.git_uri_parse(git_repo)
         creds = GitOperations.get_credentials(git_user, user)
         where = GitOperations.get_repository_location(user, git_name)
         clone_repository(git_repo, where, bare=True, credentials=creds)
         repo = LocalRepository(user, git_user, git_name, git_repo).save()
         return repo
     except GitError as e:
         raise GitException(e.args)
     except ValueError as e: # pragma: no cover
         raise GitException(e.args)
开发者ID:cantsin,项目名称:git-tracker,代码行数:13,代码来源:git.py

示例15: initialize

def initialize(request):
    if path.exists(settings.MODREPO_DIR) and path.exists(path.join(settings.MODREPO_DIR, ".git")):
        repo = pygit2.Repository(settings.MODREPO_DIR)
        for remote in repo.remotes:
            if remote.name == 'origin':
                result = remote.fetch()
        repo.checkout('refs/remotes/origin/master')
    else:
        shutil.rmtree(settings.MODREPO_DIR)

        cred = pygit2.UserPass(settings.MODREPO_USER, settings.MODREPO_PASS)
        pygit2.clone_repository(settings.MODREPO_REMOTE, settings.MODREPO_DIR, credentials=cred)

    return redirect(modrepo)
开发者ID:mosconidebugging,项目名称:TechnicAntani,代码行数:14,代码来源:views.py


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