存储库信息(如 url ,工作分支)存储在 .git 文件夹中的哪里?

Where is the repository information(like url , working branch) stored in .git folder?

我正在尝试编写一个 git 集线器自动化脚本,但我面临一个问题,即我不知道存储库信息存储在 .git 文件夹中的什么位置。通过手动搜索文件,我发现 .git\config 文件有一些信息,但它确实不一致,因为有时信息不存在。有人可以告诉我应该查看哪个文件以获取存储库信息(即 URL ,工作分支)。

这是我从 .git\config 文件获取 URL 和分支的代码:-

import os
mypath = os.getcwd()
infofile = mypath + '/.git/config'

def takeInfo():
    print('No Existing repo info found\n')
    url = str(input('Enter the Github Repo URL: '))
    branch = str(input('Enter the branch: '))
    info = ['n' , url , branch]
    return info

def checkinfoInDir():
    if (os.path.exists(infofile)):
        print('Repo Info Found:-')
        with open(infofile, "r") as f:
            info = f.readlines()
            # print(info)
            for ele in info:
                if('url' in ele):
                    url = info[info.index(ele)].split()[2]

                if('branch' in ele):
                    branch = info[info.index(ele)].split()[1].split('"')[1]
            info = [url , branch]
    else:
        info = takeInfo()
    return info

这是一个示例配置文件

[core]
    repositoryformatversion = 0
    filemode = false
    bare = false
    logallrefupdates = true
    symlinks = false
    ignorecase = true
[submodule]
    active = .
[remote "origin"]
    url = https://gitlab.com/sample/sample.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master

它有 ini 文件格式,所以你使用一个简单的 ini python 库来解析这个文件。

要读取当前分支,请使用 git symbolic-refgit rev-parse:

  • git symbolic-ref 适用于 HEAD 是符号引用的所有情况,包括它是尚不存在的分支的符号名称的情况。1 当分离 HEAD 时失败,即直接指向提交。

  • git rev-parse --symbolic-full-name HEAD 适用于 HEAD 标识某些提交的所有情况。当 HEAD 是尚不存在的分支的符号名称时失败,并且当 HEAD 分离时,它会出现名称 HEAD.

要为某个遥控器找到 URL,请使用 git config --get remote.<em>remote</em>.url。请注意,如果 Git 配置为三角工作流,则这是 fetch URL,而不是 push URL, 所以检查 git config --get remote.<em>remote</em>.pushurl 的结果看看有没有单独推送URL.

请注意,可以有任意数量的遥控器,包括 none。


1Git 称其为 孤儿分支未出生分支 ,取决于 Git 的哪一部分正在进行调用。要进入这种状态,请创建一个新的空存储库——您将使用您选择的任何分支名称作为初始名称,但它不会存在,因为没有提交,并且在有提交之前不会存在任何分支名称——或者使用 git checkout --orphangit switch --orphan.

要进入 分离的 HEAD 状态,请使用 git checkout 和任何不是分支名称的有效提交标识符,或者使用 git checkout --detachgit switch --detach 有或没有任何有效的提交标识符。

要获得 out 分离的 HEAD 状态,请使用 git checkoutgit switch 和有效的分支名称(包括这些命令创建新建分支名称,然后附加HEAD