【问题标题】:Python - how to check whether the path is under a git repo? and extract the repo namePython - 如何检查路径是否在 git repo 下?并提取 repo 名称
【发布时间】:2018-06-23 00:07:03
【问题描述】:

我正在尝试在 python rollin.py 中开发一个 Gatekeeping 脚本,具有以下要求:

  1. 假设用户将在其本地 git 克隆区域内的任何位置启动 rollin.py 脚本,以将其提交推送到主存储库

  2. 现在,rollin.py 脚本将

    • 从 master 克隆一个 repo
    • 拉取用户提交并合并到克隆的仓库中
    • 运行合规性测试
    • 如果通过,则将这些更改推送到主存储库,否则丢弃并通知用户

现在在rolloin.py 脚本中,我将如何检查 repo 名称和用户的 git clone 路径? (因为用户可以从他当地的任何地方启动rolloin.py 脚本)

是否有任何现有的功能或方法可用?否则我正在考虑从cwd 实现反向递归搜索以找到.git,然后从它的配置文件中找到url。

【问题讨论】:

    标签: gitpython


    【解决方案1】:

    使用GitPython

    您可以使用已经编写好的 GitPython 模块来实现这一点。 Read the docs.

    $ pip install GitPython

    Python sn-p 打印基本 git 路径和 origin 远程 url。

    import git
    
    # Raises InvalidGitRepositoryError when not in a repo
    repo = git.Repo(".", search_parent_directories=True) 
    print "Location "+ repo.working_tree_dir
    print "Remote: " + repo.remote("origin").url
    

    创建一个新的 git 仓库

    import git 
    
    newRepo = git.Repo.init("my-git-repo", mkdir=True)
    

    【讨论】:

      【解决方案2】:

      您可以使用os.system 运行git rev-parse --git-dir,这将返回运行该命令的存储库的.git 文件夹的路径。欲了解更多信息,请参阅How to find the path of the local git repository when I am possibly in a subdirectory

      【讨论】:

      • 感谢@Ari Lotter。上面的指针帮助了我并且它有效。现在,我正在尝试找出合并回购中的合并冲突,我发现有一个帖子stackoverflow.com/questions/34030400/…除了这个还有更好的解决方案吗?
      猜你喜欢
      • 1970-01-01
      • 2011-07-16
      • 1970-01-01
      • 1970-01-01
      • 2015-12-26
      • 2015-12-07
      • 2013-08-25
      • 2014-04-22
      • 1970-01-01
      相关资源
      最近更新 更多