执行Git命令而不在存储库中并输出当前目录

2024-05-20 10:59:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个Python脚本来循环某个文件夹中的所有Git存储库。现在,我想在git日志结果中包含当前文件夹名,但在git-log documentation中找不到如何执行此操作。你知道吗

如果对存储库执行Git命令而不在该存储库中,有没有打印当前目录的方法?你知道吗

我当前的git log命令如下所示:

git -C ./%s log --pretty=format:-C,\'"%%H","%%s"\' | grep -E %s >> output.csv

我知道我可以同时使用git --git-dir=repo/.git loggit -C /repo log在子文件夹中执行命令。你知道吗

我还尝试使用$(basename "$PWD"),但它显示的是当前文件夹,而不是子文件夹。你知道吗

你知道怎么做吗?你知道吗


Tags: csv方法git命令脚本文件夹logformat
2条回答

根据我对您问题的理解,您希望在git log的每一行中添加当前的git repo名称。你知道吗

既然您为Python添加了标签,这可能是一个长期的选择,但是您可以使用GitPython来确定文件夹中的子文件夹是否是git存储库。然后您可以用^{}打开一个git log命令,并用stdout中的repos名称打印出每一行。你知道吗

运行此代码之前,请确保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

当我在一个包含所有git存储库的文件夹中运行脚本时,这对我很有用。你知道吗

注意:使用git命令本身或bash可能有更好的方法来实现这一点。你知道吗

如果您正在寻找一个快速的GNU findutils+GNU Bash解决方案,请不要再深入了解: 你知道吗

find -type d -name '*.git' -execdir bash -c 'cd $0; cd ..; git  no-pager log  pretty=format:"${PWD##*/},%H,%s"' {} \;

相关问题 更多 >