5 Star 6 Fork 3

zstackio/zstack-vyos

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
.gitconfig
hooks
commit-msg
prepare-commit-msg
gitmessage
data
docs
plugin
prlimit
scripts
server
test
utils
zvr
zvrboot
.gitignore
COPYRIGHT
LICENSE
autoconf
go.mod
go.sum
go.work
makefile
mk_euler2203_with_zsn.sh
mkvyos_with_zsn.sh
package-config.json
package.go
克隆/下载
prepare-commit-msg 8.80 KB
一键复制 编辑 原始数据 按行查看 历史
#!/usr/bin/env python
#
# An example hook script to prepare the commit log message.
# Called by "git commit" with the name of the file that has the
# commit message, followed by the description of the commit
# message's source. The hook's purpose is to edit the commit
# message file. If the hook fails with a non-zero status,
# the commit is aborted.
#
# To enable this hook, rename this file to "prepare-commit-msg".
# This hook includes three examples. The first comments out the
# "Conflicts:" part of a merge commit.
#
# The second includes the output of "git diff --name-status -r"
# into the message, just before the "git status" output. It is
# commented because it doesn't cope with --amend or with squashed
# commits.
#
# The third example adds a Signed-off-by line to the message, that can
# still be edited. This is rarely a good idea.
import binascii
import random
import os
import re
import string
import subprocess
import sys
import traceback
from collections import Counter
def main():
try:
if not auto_commit_msg_enabled():
return
commit_msg_file = sys.argv[1]
changed_folders, changed_paths = process_metadata(commit_msg_file)
scope = get_scope(changed_folders, changed_paths)
type = get_type(changed_folders, changed_paths)
tags = get_tags(changed_folders, changed_paths)
jiras = get_jiras()
change_id = get_change_id()
write_commit_msg(commit_msg_file, type, scope, tags, jiras)
except Exception as e:
print("get exception while prepare commit msg: %s" % e)
traceback.print_exc()
def auto_commit_msg_enabled():
if len(sys.argv) >= 3 and sys.argv[2] != "template":
# NOTE(weiw): it's maybe cherry pick or amend or something
return False
bashCommand = "git config --get zstack.autoCommitMsg"
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
output = output.decode()
if error != None:
print("get error while running git config --get zstack.autoCommitMsg: %s" % error)
return False
elif "false" in output.lower():
return False
return True
def write_commit_msg(commit_msg_filepath, type, scope, tags, jiras):
template = '''# Possible types: fix/feature/test/refactor/chore
# Possible tags: (not support yet)
# Possible jira-footers: Resolves/Related
# Please describe the commit as detailed as possible!
# 1. Why is this change necessary?
# 2. How does it address the problem?
# 3. Are there any side effects?\n
'''
with open(commit_msg_filepath, 'r+') as msg:
in_usable_content = False
useable_contents = []
for line in msg.readlines():
if line.startswith("Resolves/Related: ZSTAC"):
in_usable_content = True
continue
if line.startswith("# ------------------------ >8 ------------------------"):
in_usable_content = True
# NOTE(weiw): do not continue, it's usable!
if in_usable_content is False:
continue
useable_contents.append(line)
real_commit_msg = []
real_commit_msg.append("<%s>[%s]: <description>\n\n" % (type, scope))
real_commit_msg.append(template)
if len(tags) > 0:
real_commit_msg.append("%s\n" % "\n".join(tags))
real_commit_msg.append("\n")
if jiras:
for jira in jiras:
real_commit_msg.append("Resolves: %s\n" % jira.upper())
else:
real_commit_msg.append("Resolves: ZSTAC-XXXX\n")
real_commit_msg.append("\nChange-Id: %s\n" % get_change_id())
with open(commit_msg_filepath, 'w') as msg:
real_commit_msg.extend(useable_contents)
msg.writelines(real_commit_msg)
def process_metadata(commit_msg_filepath):
# @return:
# changed_folders: list of changed first level folder,
# if root path of code repo, then return root.
# eg. ["root", "conf", "network", "root"]
# changed_paths: dict of paths of changed files with its changed type,
# eg. {".gitmessage":"new file", "conf/web.xml":"modified"}
# !! changed type not support yet !!
changed_folders = []
changed_paths = {}
with open(commit_msg_filepath, 'r+') as msg:
content = msg.readlines()
for no, line in enumerate(content):
line = line.strip()
if not line.startswith("diff --git a/"):
continue
path = line.split(" ")[2][2:]
changed_folders.append(get_top_folder_from_path(path))
changed_paths[path] = 'new file' if content[no+1].startswith('new file') else 'modified'
if changed_folders != []:
return changed_folders, changed_paths
bashCommand = "git diff HEAD"
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
content = output.decode()
if error != None:
raise Exception(error)
for no, line in enumerate(content.splitlines()):
line = line.strip()
if not line.startswith("diff --git a/"):
continue
path = line.split(" ")[2][2:]
changed_folders.append(get_top_folder_from_path(path))
changed_paths[path] = 'new file' if content[no+1].startswith('new file') else 'modified'
return changed_folders, changed_paths
def get_top_folder_from_path(filepath):
if "/" not in filepath and "\\" not in filepath:
return "root"
elif "/" in filepath:
return filepath.split("/")[0]
else:
return filepath.split("\\")[0]
def get_scope(changed_folders, changed_paths):
folder_counter = Counter(changed_folders)
most_common = folder_counter.most_common(1)[0][0]
if most_common not in ["plugin"]:
return most_common
if most_common in ["plugin"]:
modules = []
for p in changed_paths.keys():
if "plugin/" in p:
word_after_plugin = p.split("plugin/")[-1].split("/")[0]
if "_test" in word_after_plugin:
word_after_plugin = word_after_plugin.replace("_test", "")
if "." in word_after_plugin:
# eg. zstack-vyos/plugin/pmid.go
modules.append(word_after_plugin.split(".")[0])
else:
# shouldn't be here
modules.append(word_after_plugin.split("/")[0])
elif "/" in p:
modules.append(get_top_folder_from_path(p))
else:
modules.append("root")
module_counter = Counter(modules)
return module_counter.most_common(1)[0][0]
return most_common
def get_type(changed_folders, changed_paths):
new_file = 0
modified = 0
doc = 0
for p, t in changed_paths.items():
if t == "new file":
new_file += 1
else:
modified += 1
if "Doc_zh_cn" in p or p.endswith(".md") or p.startswith("doc/"):
doc += 1
if doc == len(changed_paths):
return "doc"
if new_file >= modified:
return "feature"
else:
return "fix"
def get_tags(changed_folders, changed_paths):
tags = set()
return tags
def get_jiras():
jiras = []
jira_patterns = [r"\bZSTAC-\d+\b", r"\bZSTACK-\d+\b", r"\bMINI-\d+\b",
r"\bZOPS-\d+\b", r"\bZHCI-\d+\b"]
bashCommand = "git rev-parse --abbrev-ref HEAD"
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
output = output.decode()
if error != None:
print("get error while reading current branch: %s" % error)
return jiras
for pattern in jira_patterns:
searchObj = re.search(pattern, output, re.I)
if searchObj:
jiras.append(searchObj.group())
return jiras
def get_change_id():
letters = string.ascii_lowercase
data = ''.join(random.choice(letters) for i in range(20)).encode()
return("I{}".format(binascii.hexlify(data).decode('iso8859-1')))
def get_git_root_path():
bashCommand = "git rev-parse --show-toplevel"
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
output = output.decode()
if error != None:
raise Exception(error)
return output
if __name__ == "__main__":
main()
#case "$2,$3" in
# merge,)
# /usr/bin/perl -i.bak -ne 's/^/# /, s/^# #/#/ if /^Conflicts/ .. /#/; print' "$1" ;;
#
## ,|template,)
## /usr/bin/perl -i.bak -pe '
## print "\n" . `git diff --cached --name-status -r`
## if /^#/ && $first++ == 0' "$1" ;;
#
# *) ;;
#esac
# SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p')
# grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1"
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/zstackio/zstack-vyos.git
git@gitee.com:zstackio/zstack-vyos.git
zstackio
zstack-vyos
zstack-vyos
master

搜索帮助