Nas*_*Ohi 2 python git git-log gitpython
在python中,我想获取git存储库中文件的所有提交的日志并解析日志中的信息(哈希、作者姓名、作者邮件、作者日期、提交者姓名、提交者邮件、提交日期和提交消息) . 目前,我可以使用 gitpython 或通过子进程调用 shell 命令来获取原始 git 日志。
使用 gitpython:
g=git.Git(path)
loginfo=g.log("--pretty=fuller",'--follow',"<filename>")
Run Code Online (Sandbox Code Playgroud)
使用子过程调用:
lines = subprocess.check_output(
['git', 'log','--follow',"--pretty=fuller","
<filename"],stderr=subprocess.STDOUT)
Run Code Online (Sandbox Code Playgroud)
但是,在那之后我想解析原始日志,但我无法在 gitpython 中找到合适的库/方法。此外,我还希望以 python 日期时间格式解析日期。你能帮我吗?
您可以使用以下方法获取所有存储库提交:
import git
repo = git.Repo("/home/user/.emacs.d")
commits = list(repo.iter_commits("master", max_count=5))
Run Code Online (Sandbox Code Playgroud)
然后你可以确定自己 gitpython 提供什么样的数据:
dir(commits[0])
Run Code Online (Sandbox Code Playgroud)
他们之中有一些是:
举个例子:
>>> commits[0].author
<git.Actor "azzamsa <foo@bar.com>">
>>> commits[0].hexsha
'fe4326e94eca2e651bf0081bee02172fedaf0b90'
>>> commits[0].message
'Add ocaml mode\n'
>>> commits[0].committed_datetime
datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=<git.objects.util.tzoffset object at 0x7fb4fcd01790>)
Run Code Online (Sandbox Code Playgroud)
(committed_datetime 输出带有语言环境对象的日期时间对象)
如果您想检查提交是否包含文件(如果您想从该文件中获取所有提交,则可以使用该文件)。您可以使用:
def is_exists(filename, sha):
"""Check if a file in current commit exist."""
files = repo.git.show("--pretty=", "--name-only", sha)
if filename in files:
return True
Run Code Online (Sandbox Code Playgroud)
然后从文件中获取所有提交:
def get_file_commits(filename):
file_commits = []
for commit in commits:
if is_exists(filename, commit.hexsha):
file_commits.append(commit)
return file_commits
Run Code Online (Sandbox Code Playgroud)
例如,我想从“init.el”文件中获取所有提交:
initel_file_commits = get_file_commits('init.el')
>>> initel_file_commits
[<git.Commit "fe4326e94eca2e651bf0081bee02172fedaf0b90">, <git.Commit
"e4f39891fb484a95ea76e8e07244b908e732e7b3">]
Run Code Online (Sandbox Code Playgroud)
查看函数是否正常工作:
>>> initel_file_commits[0].stats.files
{'init.el': {'insertions': 1, 'deletions': 0, 'lines': 1}, 'modules/aza-ocaml.el': {'insertions': 28, 'deletions': 0, 'lines': 28}}
>>> initel_file_commits[1].stats.files
{'init.el': {'insertions': 1, 'deletions': 0, 'lines': 1}, 'modules/aza-calfw.el': {'insertions': 65, 'deletions': 0, 'lines': 65}, 'modules/aza-home.el': {'insertions': 0, 'deletions': 57, 'lines': 57}}
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你。
| 归档时间: |
|
| 查看次数: |
6461 次 |
| 最近记录: |