利用git 的钩子拦截有问题的代码

利用git 的钩子拦截有问题的代码
通过git 提供的钩子功能,保证有问题的代码绝对不会被提交

Git 提供多种钩子,在项目目录的.git/hooks 目录下面,名称格式一般是pre-xxx。一个正常的git 的hooks 下面有多个示例文件,名称格式为pre-xxx.sample。

在这里我们需要的是pre-commit。

修改他的内容为./gradlew assembleDebug

chmod 777 pre-commit

然后修改文件属性。由于mac 的安全机制,我们的shell 脚本不会被执行,需要去除相应的属性。
命令为
xattr -c pre-commit

然后提交代码测试吧

改进:
每次构建需要花费很多的时间,可选择的方案有:
通过gradle 构建时保存时间,如果当前修改的文件的时间大于gradlew 时间的话,需要重新来一次构建
如果当前修改文件的 时间小于gradle 上次的构建时间,不需要重新进行构建

# coding=utf-8
import os
import sys
import time

from git import Repo

path = "."
if len(sys.argv) > 1:
    path = sys.argv[1]
print(path)
last_time = 0
repo = Repo(path)
staged = repo.index.diff(None)
for s in staged:
    print(s.a_path)
    mTime = os.stat(os.path.join(path, s.a_path)).st_mtime
    if mTime > last_time:
        last_time = mTime
# headCommit = repo.head.commit
# print(headCommit)
# tree = headCommit.tree

# for t in tree:  # intuitive iteration of tree members
#     print(t.type)
#     if t.type == "tree":
#         if len(t.blobs) > 0:
#             mTime = os.stat(t.blobs[0].abspath).st_mtime
#     else:
#         mTime = os.stat(t.abspath).st_mtime
#     print(type(mTime))
#     if mTime > last_time:
#         last_time = mTime
print(last_time)
if last_time == 0:
    exit(0)
file_modify_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(last_time))
print("修改时间是: {0}".format(file_modify_time))
gradle_build_time_file = os.path.join(path, "build_gradle_time")
if not os.path.exists(gradle_build_time_file):
    print("没有时间文件")
    exit(1)
with open(gradle_build_time_file) as file_obj:
    content = file_obj.read()
    if int(content) > last_time:
        print("无需重新构建")
        exit(0)
    else:
        print("需要重新构建")
        exit(1)
task saveTime() {
    try(FileWriter writer = new FileWriter(new File(rootDir,"build_gradle_time"))) {
        writer.write((System.currentTimeMillis()/1000).toInteger().toString())
    }
}

preBuild.dependsOn(checkStrings, genTelemetry, genCora, saveTime)
#!/bin/sh
python main.py
echo $?
if (($? == 0));then
 exit 0
fi

./gradlew assembleDebug
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章