我正在编写一个 Python 脚本来循环某个文件夹中的所有 Git 存储库。现在我想在 git-log 结果中包含当前文件夹名称,但我在 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 log 和 git -C/repo log 来执行子文件夹中的命令。
我还尝试使用 $(basename "$PWD")
但它显示当前文件夹,但不显示子文件夹。
知道如何做到这一点吗?
最佳答案
据我从您的问题中了解到,您希望在 git log
的每一行中添加当前的 git 存储库名称。
既然你标记了Python,这可能是一个不太可能的选择,但你可以使用 GitPython确定文件夹内的子文件夹是否是 git 存储库。然后你可以用subprocess.Popen()
打开一个git log
命令,并从标准输出中打印出包含存储库名称的每一行。
确保在运行此代码之前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 来完成此操作。
关于python - 不在存储库中执行 Git 命令并输出当前目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53373523/