说明
比较简单,用python遍历git diff
的结果,文件名作为标题,后边内容作为内容。
发现使用python git
库可以使用自定义的git命令。
代码使用说明
git_url
中保存的是github、gitee的链接,需要替换成自己的用户名。all_git_path
保存的是项目路径,也就是该路径下应该有.git
。log(git_path,git_rep='gitee', start=None, end=None)
中,只给路径时,默认start='HEAD~1',end='HEAD'
。- 中文文件名需要在git中配置,
quotepath = false
。
安装
pip install GitPython
参考
代码
from git import Repo
from pathlib import Path
# 创建版本库对象
path = r'../'
repo = Repo(path)
def show():
res=repo.git.show('head~1')
print(res)
def info():
# 版本库是否为空版本库
print(repo.bare)
# 当前工作区是否干净
print(repo.is_dirty())
# 版本库中未跟踪的文件列表
print(repo.untracked_files)
print(repo.git.logformat())
def full_hash_id(repo,part_id):
res=repo.git.show(part_id)
lines=res.splitlines(keepends=False)
id=lines[0].split(' ')[1]
print(id)
print(lines[3:5])
msg=''
for line in lines[4:]:
if line=='':break
msg+=line.strip()
print(msg)
return id,msg
def log(git_path,git_rep='gitee', start=None, end=None):
repo = Repo(git_path)
prj_name = Path(git_path).name
if end and start is None: start=end+'~1'
if start and end is None: end='HEAD'
if not start and not end:
start='HEAD~1'
end='HEAD'
full_start_id,start_msg= full_hash_id(repo, start)
full_end_id,end_msg=full_hash_id(repo,end)
out_md_file = prj_name + '.md'
res = repo.git.diff(start, end)
# print(len(res))
with open(out_md_file, 'w', encoding='utf-8') as out_md:
out_md.write('[TOC]\n')
out_md.write('# git(%s...%s)\n' % (full_start_id[:6], full_end_id[:6]))
out_md.write(git_url[git_rep]%(start_msg,prj_name,full_start_id))
out_md.write(git_url[git_rep]%(end_msg, prj_name, full_end_id))
out_md.write('# diff\n')
firstFile = True
for line in res.splitlines(keepends=False):
# print(line,end='')
if line.startswith('diff'):
# print(line)
lastPart = line.split(' ')[-1]
filePath = lastPart[lastPart.find('/') + 1:]
fileName = line[line.rfind('/') + 1:]
if not firstFile: # 上一段代码的结束
out_md.write('```' + '\n')
else:
firstFile = False
# out_md.write('# %s(%s)\n'%(fileName,filePath))
out_md.write('## %s\n' % fileName)
out_md.write('```patch' + '\n')
out_md.write(line + '\n')
out_md.write('```')
#只要6位就可显示
git_url = {#替换其中的xxxxx
'github': '- [%s](https://github.com/xxxxx/%s/commit/%s)\n',
'gitee': '- [%s](https://gitee.com/xxxxx/%s/commit/%s)\n'
}
all_git_path={
'nodejs':r'项目目录,下边有.git文件夹'
}
if __name__ == '__main__':
# info()
#show()
#full_hash_id(repo,'HEAD')
log(git_path=all_git_path['nodejs'],start='2354b7',end='5c33b9')
log(git_path=all_git_path['nodejs'],start='c44b')
log(git_path=all_git_path['nodejs'])