【问题标题】:How to get the current checked out Git branch name through pygit2?如何通过pygit2获取当前签出的Git分支名称?
【发布时间】:2014-11-25 20:39:00
【问题描述】:

【问题讨论】:

标签: python git pygit2


【解决方案1】:

你可以使用GitPython:

from git import Repo
local_repo = Repo(path=settings.BASE_DIR)
local_branch = local_repo.active_branch.name

【讨论】:

    【解决方案2】:

    如果你不想或不能使用 pygit2

    可能需要更改路径 - 假设您位于 .git 的父目录中

    from pathlib import Path
    
    def get_active_branch_name():
    
        head_dir = Path(".") / ".git" / "HEAD"
        with head_dir.open("r") as f: content = f.read().splitlines()
    
        for line in content:
            if line[0:4] == "ref:":
                return line.partition("refs/heads/")[2]
    

    【讨论】:

      【解决方案3】:

      PyGit Documentation

      这些都应该工作

      #!/usr/bin/python
      from pygit2 import Repository
      
      repo = Repository('/path/to/your/git/repo')
      
      # option 1
      head = repo.head
      print("Head is " + head.name)
      
      # option 2
      head = repo.lookup_reference('HEAD').resolve()
      print("Head is " + head.name)
      

      您将获得包括 /refs/heads/ 在内的全名。如果您不想将其删除或使用简写代替名称。

      ./pygit_test.py  
      Head is refs/heads/master 
      Head is refs/heads/master
      

      【讨论】:

      • 这里的repo 是什么?
      • @BorhanKazimipour 这是对您正在处理的存储库的引用 repo = Repository('path/to/git_repo')
      【解决方案4】:

      要获得传统的“速记”名称:

      from pygit2 import Repository
      
      Repository('.').head.shorthand  # 'master'
      

      【讨论】:

        猜你喜欢
        • 2013-09-10
        • 2023-03-09
        • 2011-09-08
        • 2015-05-14
        • 2011-12-25
        • 2010-11-27
        • 2017-08-11
        • 1970-01-01
        相关资源
        最近更新 更多