利用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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章