我正在编写一个 Python 脚本来循环某个文件夹中的所有 Git 存储库。现在我想在 git-log 结果中包含当前文件夹名称,但我在git-log 文档中找不到如何执行此操作。
如果您对某个存储库执行 Git 命令而不位于该存储库中,是否有办法打印出当前目录?
我当前的 git-log 命令如下所示:
git -C ./%s log --pretty=format:-C,\'"%%H","%%s"\' | grep -E %s >> output.csv
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用git --git-dir=repo/.git log和git -C /repo log来执行子文件夹中的命令。
我也尝试使用$(basename "$PWD"),但它显示当前文件夹,但不显示子文件夹。
关于如何做到这一点有什么想法吗?
根据我从你的问题中了解到的,你想在git log.
由于您标记了 Python,这可能不太可能,但您可以使用GitPython来确定文件夹内的子文件夹是否是 git 存储库。然后,您可以使用 打开git log命令subprocess.Popen(),并从标准输出中打印出包含存储库名称的每一行。
请确保pip install GitPython在运行此代码之前。
这是一个例子:
from os import listdir
from os import chdir
from os import getcwd
from os.path import abspath
from git import Repo
from git import InvalidGitRepositoryError
from subprocess import Popen
from subprocess import PIPE
# Current working directory with all git repositories
# You can change this path to your liking
ROOT_PATH = getcwd()
# Go over each file in current working directory
for file in listdir(ROOT_PATH):
    full_path = abspath(file)
    # Check if file is a git repository
    try:
        Repo(full_path)
        # Change to directory
        chdir(full_path)
        # Run git log command
        with Popen(
            args=['git', 'log', '--pretty=format:"%h - %an, %ar : %s"'],
            shell=False,
            stdout=PIPE,
            bufsize=1,
            universal_newlines=True,
        ) as process:
            # Print out each line from stdout with repo name
            for line in process.stdout:
                print('%s %s' % (file, line.strip()))
        # Change back to path
        chdir(ROOT_PATH)
    # If we hit here, file is not a git repository
    except InvalidGitRepositoryError:
        continue
Run Code Online (Sandbox Code Playgroud)
当我在包含所有 git 存储库的文件夹中运行脚本时,这对我有用。
注意:可能有更好的方法可以使用git命令本身或 bash 来完成此操作。
|   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           1249 次  |  
        
|   最近记录:  |