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


Python git.Repo类代码示例

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


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

示例1: process_exception

    def process_exception(request, exception):
        exception_traceback = sys.exc_traceback

        stack = traceback.extract_tb(exception_traceback)

        repo_dir = settings.EXCEPTION_BLAME['REPO_DIR']
        repo = Repo(repo_dir)

        first_file_project = None
        for stack_file in reversed(stack):
            file_path = stack_file[0]

            if repo.git.ls_files(file_path, {'error-unmatch':True}):
                first_file_project = stack_file
                break

        if first_file_project:
            file_path = first_file_project[0]
            abs_linenumber = first_file_project[1]
            blame = repo.blame(None, file_path)

            # blame returns array with lists [commit, [lines]]
            blame_commit = [commit[0]
                            for commit in blame
                                for _ in commit[1]][abs_linenumber-1]


            author = blame_commit.author.name
            if author == 'Not Committed Yet':
                author = author + ', probably your modifications'
            else:
                author = '{} - {}'.format(author, blame_commit.author.email)

            request.META['BLAMED_DEVELOPER'] = author
开发者ID:gdelfresno,项目名称:django-exception-blame,代码行数:34,代码来源:middleware.py

示例2: close_working_branch

def close_working_branch(branch, 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

    print "Summary of actions:"
    master = repo.heads.master
    master.checkout()

    repo.git.merge(branch, '--no-ff')
    print ("- Branch " + branch + " was merged into master.")

    repo.delete_head(branch, force=True)
    print ("- Branch " + branch + " was deleted.")

    ret = remote.push(":" + branch)
    print ("- Remote branch " + branch + " on " + remote_name + " was deleted.")

    remote.push(master)
    print ("- Merged changes on master were pushed to " + remote_name + ".")

    print "- You are now on branch master."

    return 0
开发者ID:ChrisCummins,项目名称:pip-db,代码行数:29,代码来源:pipbot.py

示例3: update

    def update(self):
        """Update the local cloudlet git repo on disk from any origin."""

        print "Updating cloudlet: %s" % (self.path)
        repo = Repo(self.path)
        repo.remotes.origin.pull()
        repo.submodule_update()
开发者ID:robparrott,项目名称:nepho,代码行数:7,代码来源:cloudlet.py

示例4: init

 def init(rid):
     """
     Initialize a new repository.
     """
     directory = os.path.join(settings.REPO_DIR, str(rid))
     Repo.init(directory)
     return PasteRepo(rid)
开发者ID:MaienM,项目名称:PasteGit,代码行数:7,代码来源:pasterepo.py

示例5: rebase

    def rebase(self, issue, branch=None):
        if not issue.pull_request:
            return "Rebase is just supported in PR for now"

        pr = issue.repository.get_pull(issue.number)

        branch_name = pr.head.ref
        branched_sdk_id = pr.head.repo.full_name+'@'+branch_name

        upstream_url = 'https://github.com/{}.git'.format(pr.base.repo.full_name)
        upstream_base = pr.base.ref if not branch else branch

        with tempfile.TemporaryDirectory() as temp_dir, \
                manage_git_folder(self.gh_token, Path(temp_dir) / Path("sdk"), branched_sdk_id) as sdk_folder:

            sdk_repo = Repo(str(sdk_folder))
            configure_user(self.gh_token, sdk_repo)

            upstream = sdk_repo.create_remote('upstream', url=upstream_url)
            upstream.fetch()

            msg = sdk_repo.git.rebase('upstream/{}'.format(upstream_base))
            _LOGGER.debug(msg)
            msg = sdk_repo.git.push(force=True)
            _LOGGER.debug(msg)

            return "Rebase done and pushed to the branch"
开发者ID:lmazuel,项目名称:swagger-to-sdk,代码行数:27,代码来源:sdkbot.py

示例6: main

def main(source, dest):
    """Rename a Git repository and update its remote accordingly."""
    basicConfig(level=DEBUG)
    try:
        repo = Repo(source)
    except OSError as error:
        logger.exception('Error:')
        exit(1)
    else:
        dest = Path(dest)
        try:
            dest = dest.with_suffix('.git')
        except ValueError:
            logger.exception('Error:')
            exit(1)
        logger.info('Using dest: %s', dest)

        remote = repo.remote()
        logger.debug('Old URL: %s', remote.url)
        origin = Path(remote.url)
        logger.debug('Parent: %s', origin.parent)

        new = origin.parent / dest
        logger.info('Using URL: %s', new)

        conf = remote.config_writer
        conf.set('url', str(new))
        conf.release()

        Path(source).rename(dest)
        exit(0)
开发者ID:NoviceLive,项目名称:unish,代码行数:31,代码来源:gmv.py

示例7: tarbell_install_template

def tarbell_install_template(args):
    """Install a project template."""
    with ensure_settings(args) as settings:
        template_url = args.get(0)

        matches = [template for template in settings.config["project_templates"] if template["url"] == template_url]
        if matches:
            puts("\n{0} already exists. Nothing more to do.\n".format(
                colored.yellow(template_url)
            ))
            sys.exit()

        puts("\nInstalling {0}".format(colored.cyan(template_url))) 
        tempdir = tempfile.mkdtemp()
        puts("\n- Cloning repo to {0}".format(colored.green(tempdir))) 
        Repo.clone_from(template_url, tempdir)
        base_path = os.path.join(tempdir, "_base/")
        filename, pathname, description = imp.find_module('base', [base_path])
        base = imp.load_module('base', filename, pathname, description)
        puts("\n- Found _base/base.py")
        try:
            name = base.NAME
            puts("\n- Name specified in base.py: {0}".format(colored.yellow(name)))
        except AttributeError:
            name = template_url.split("/")[-1]
            puts("\n- No name specified in base.py, using '{0}'".format(colored.yellow(name)))

        settings.config["project_templates"].append({"name": name, "url": template_url})
        settings.save()

        _delete_dir(tempdir)

        puts("\n+ Added new project template: {0}".format(colored.yellow(name)))
开发者ID:aepton,项目名称:flask-tarbell,代码行数:33,代码来源:cli.py

示例8: closeEvent

    def closeEvent(self, event):
        """
            Catching the close event to do some cleanup
        """
        def run_command(command):
            handle = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)
            handle.wait()

        a_repo = Repo(self._directory)
        os.chdir(self._directory)

        try:
            active_branch_name = a_repo.active_branch.name
            should_be_cleaned = a_repo.active_branch.name == 'gitbuster_rebase'
        except TypeError:
            should_be_cleaned = True

        if should_be_cleaned:
            if a_repo.is_dirty():
                run_command("git reset --hard")

            fallback_branch_name = [branch.name for branch in a_repo.branches
                                    if branch.name != 'gitbuster_rebase'][0]
            run_command("git checkout %s" % fallback_branch_name)
            run_command("git branch -D gitbuster_rebase")
开发者ID:mike-perdide,项目名称:gitbuster,代码行数:25,代码来源:main_window.py

示例9: update_repo

    def update_repo(self, project):
        from ostracker.models import Commit, Contributor
        proj_dir = project.get_local_repo_dir()

        # checkout or update project
        if not os.path.exists(proj_dir):
            print 'cloning %s' % project
            os.system('git clone -q %s %s' % (project.get_remote_repo_url(),
                                              proj_dir))
        else:
            print 'updating %s' % project
            os.system('cd %s && git pull -q' % proj_dir)

        # process new commits
        repo = Repo(proj_dir)
        added = 0
        for c in repo.iter_commits():
            try:
                Commit.objects.get(id=c.sha)
            except Commit.DoesNotExist:
                added += 1
                stats = c.stats.total

                cdate = datetime.datetime.fromtimestamp(c.committed_date)

                author = Contributor.objects.lookup(c.author.name, c.author.email)

                Commit.objects.create(id=c.sha, project=project, author=author,
                                      message=c.message, time_committed=cdate,
                                      deletions=stats['deletions'],
                                      files=stats['files'],
                                      insertions=stats['insertions'],
                                      lines=stats['lines'])
        print 'added %s commits to %s' % (added, project)
开发者ID:pombredanne,项目名称:django-ostracker,代码行数:34,代码来源:github.py

示例10: clone_git_repo

def clone_git_repo(repo, checkout_dir):
    parsedrepo = giturlparse.parse(repo, False)
    directory = os.path.join(checkout_dir, parsedrepo.repo)
    if not os.path.isdir(directory):
        Repo.clone_from(repo, directory)

    return directory
开发者ID:paulczar,项目名称:giftwrap,代码行数:7,代码来源:util.py

示例11: cloneGitHub

    def cloneGitHub(self):
        if not os.path.isdir(self.output_path + "rtl"):
            os.mkdir(self.output_path + "rtl")
        for file in os.listdir(self.output_path + "rtl"):
            if file == Repo_clone.repo:
                shutil.rmtree(self.output_path + "rtl/" + Repo_clone.repo)
        try:
            Repo.clone_from("https://github.com/{user}/{repo}".format(user=Repo_clone.user, repo=Repo_clone.repo),
                            self.output_path + "rtl/" + Repo_clone.repo)
        except:
            self.is_manual_url = input("We couldn't find the source files defined in the " + Repo_clone.repo + " core file.\n Would you like to add the URL manually? (y/n)\n")

            # No interaction with the user, if auto mode is on
            if self.is_interactive == "A":
                self.is_manual_url = "no"

            if re.match(r"[yY][eE][sS]", self.is_manual_url) or self.is_manual_url == "y":
                manual_url = input("Please add the URL: ")
                try:
                    Repo.clone_from(manual_url, self.output_path + "rtl" + Repo_clone.repo)
                except:
                    print("We couldn't find the source files.\nThe core will be skipped")
            else:
                print("We skipped the " + Repo_clone.repo + " core. Please fix the top gen config and .core files to make this core work")


        # Add files to source list
        for root, dirs, files in os.walk(self.output_path + "rtl/" + Repo_clone.repo, topdown=False, onerror=None, followlinks=False):
            for file in files:
                if file == (self.repo + ".v"):
                    self.source_list.append(os.path.join(root, file))
                    print(file)
开发者ID:janosmurai,项目名称:top_gen_fusesoc,代码行数:32,代码来源:repo_clone.py

示例12: run

    def run(self):
        env = self.state.document.settings.env
        config = env.config
        repodir = env.srcdir + '/' + config["git_repository_root"]

        doc_path = env.srcdir + '/' + env.docname + config["source_suffix"]

        if self.options.get('dir', False) == None:
            doc_path = '/'.join(doc_path.split('/')[:-1])

        repo = Repo(repodir)
        commits = repo.iter_commits(paths=doc_path)
        l = nodes.bullet_list()
        revisions_to_display = self.options.get('revisions', 10)

        for commit in list(commits)[:revisions_to_display]:
            date_str = datetime.fromtimestamp(commit.authored_date)
            if '\n' in commit.message:
                message, detailed_message = commit.message.split('\n', 1)
            else:
                message = commit.message
                detailed_message = None

            item = nodes.list_item()
            item += [
                nodes.strong(text=message),
                nodes.inline(text=" by "),
                nodes.emphasis(text=str(commit.author)),
                nodes.inline(text=" at "),
                nodes.emphasis(text=str(date_str))
            ]
            if detailed_message:
                item.append(nodes.caption(text=detailed_message.strip()))
            l.append(item)
        return [l]
开发者ID:xiu,项目名称:sphinx-git,代码行数:35,代码来源:sphinx_git.py

示例13: _clone_repos

    def _clone_repos(self, all_repos):
        """Given a list of repositories, make sure they're all cloned.

        Should be called from the subclassed `Catalog` objects, passed a list
        of specific repository names.

        Arguments
        ---------
        all_repos : list of str
            *Absolute* path specification of each target repository.

        """
        for repo in all_repos:
            if not os.path.isdir(repo):
                try:
                    repo_name = os.path.split(repo)[-1]
                    self.log.warning(
                        'Cloning "' + repo + '" (only needs to be done ' +
                        'once, may take few minutes per repo).')
                    Repo.clone_from("https://github.com/astrocatalogs/" +
                                    repo_name + ".git", repo,
                                    **({'depth': self.args.clone_depth} if
                                       self.args.clone_depth > 0 else {}))
                except:
                    self.log.error("CLONING '{}' INTERRUPTED".format(repo))
                    raise

        return
开发者ID:crawfordsm,项目名称:astrocats,代码行数:28,代码来源:catalog.py

示例14: Git

class Git(BaseBackend):
    """
    GIT Backend for asset versions.
    """

    def __init__(self):
        """
        Git backend constructor.
        """
        repo_dir = settings.BASE_DIR
        if hasattr(settings, 'ASSET_REPO_DIR'):
            repo_dir = settings.REPO_DIR
        self.repo = Repo(repo_dir)

    def version_long(self):
        """
        Returns the full hash of the latest commit found.

        :return: Latest commit hash (full)
        :rtype: str
        """
        return self.repo.commit().hexsha

    def version_short(self):
        """
        Returns the short hash of the latest commit found.

        :return: Latest commit hash (short)
        :rtype: str
        """
        return self.repo.commit().hexsha[:6]
开发者ID:samupl,项目名称:django-asset-versions,代码行数:31,代码来源:version_git.py

示例15: clone_repos

def clone_repos(students, syspath=os.path.join("..","repos"), url="[email protected]:%s/SoftwareDesign.git"):
  """
  Recursively removes previous copies of the repo (requires user confirmation)
  Clones the repos from the urls to a folder called repos/<username>

    students : list of student objects
    syspath : system path to copy repos to
  """
  if (raw_input("Remove current repositories? (y/n) ")) != "y":
    raise Exception("Failed to confirm. Failed to clone repos")
  
  # if other repos exist, remove them
  if os.path.exists(syspath):
    shutil.rmtree(syspath) # remove existing repos
    print "Successfully removed repos from \"%s\"" % syspath

  for s in students:
    path = syspath + s.user
    
    print "Cloning Repo: %s to %s" % (s.name, path)

    if not os.path.exists(path):
      os.makedirs(path)
    
    Repo.clone_from(url % s.user, path)

  print "Successfully cloned repos"
开发者ID:sihrc,项目名称:Software-Design-Ninja,代码行数:27,代码来源:gitpy.py


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