如何创建一个 version.py 文件,每次通过 git 推送任何文件时都会更新该文件

问题描述 投票:0回答:1

我希望 git 创建一个看起来像这样的 version.py 文件(其中版本每次提交都会递增):

# This file is created by the pre-push script
class Version:
    comment = "git commit comment"
    hash = "some git hash"
    version = "0.8.9"

我试过这个:

#!/usr/bin/env /usr/bin/python
import os
import subprocess
import re
import sys

commit_msg_file = sys.argv[1]

with open(commit_msg_file, 'r') as file:
    commit_msg = file.read().strip()

version_file = os.path.abspath('version.py')
hashed_code = subprocess.check_output(['git', 'rev-parse', 'HEAD']).strip().decode('utf-8')

if os.path.exists(version_file):
    print(f'Reading previous {version_file}')

    with open(version_file, 'r') as f:
        content = f.read()
        major, minor, patch = map(int, re.search(r'version = "(\d+)\.(\d+)\.(\d+)"', content).groups())

    patch += 1
else:
    print(f'Creating new {version_file}')
    major, minor, patch = 0, 0, 1

print(f'Writing contents of {version_file} with "{commit_msg}"')

with open(version_file, 'w') as f:
    f.write(f'''# This file is created by the pre-push script
class Version:
    comment = "{commit_msg}"
    hash = "{hashed_code}"
    version = "{major}.{minor}.{patch}"


if __name__ == "__main__":
    print(Version.version)
''')
    f.close()

print(f'adding {version_file}')
subprocess.call(['git', 'add', version_file])
# subprocess.call(['git', 'commit', '-m',  comment])
print(f'adding {version_file}')
subprocess.call(['git', 'add', version_file])
# subprocess.call(['git', 'commit', '-m', comment])

我在预推送和修复提交消息中尝试过此操作,但无济于事...是否有更好的方法或方法来修复我所拥有的? 预先感谢

python git
1个回答
0
投票

我尝试了你的脚本,如果我直接从 git 而不是从文件获取提交消息,它对我有用。按照您编码的方式,您期望挂钩调用者向您传递一个带有文件名的参数,但我已经使用预提交挂钩进行了测试,它没有传递任何参数。

我把它改为:

commit_msg = subprocess.check_output(['git','log','-1','--pretty=%B']).strip().decode('utf-8')

对我来说效果很好。

© www.soinside.com 2019 - 2024. All rights reserved.