Xcode IDE中可以安裝Clang format外掛程式,格式化iOS代碼。可總是有人會忘,故再加上Git用戶端pre-commit hook一枚用於防呆,在執行git commit命令後檢查,檢查通過後正常完成commit:)
可是有些人懶得連hook都不配,所以再加上Jenkins驗證,竟然不改就想上庫。哼╭(╯^╰)╮,打回去重來~~~~
如下,Git hook採用全域hook的形式(當然你也可以自己每次複製後拷到單倉下用,如果你時間比較多的話:))
【使用前提】
本地需要安裝clang-format工具,.clangformat檔案已放好
【部署方法】
1,建立全域hook目錄(有了請執行第2步):
$mkdir -p~/.git_template/hooks/
2,將如下兩行拷貝到~/.gitconfig檔案的最後(有了請執行第3步):
$git config --global init.templatedir ~/.git_template
3,增加pre-commit指令碼,並添加可執行許可權。這個指令碼會檢查有沒有格式化,沒有做會幫他改了直接提交:
#!/bin/bash STYLE=$(git config --get hooks.clangformat.style) if [ -n "${STYLE}" ] ; then STYLEARG="-style=${STYLE}" else STYLEARG="" fi format_file() { file="${1}" if [ "${file##*.}" = "c" ] || [ "${file##*.}" = "m" ] || [ "${file##*.}" = "mm" ] || [ "${file##*.}" = "h" ]; then clang-format -i ${STYLEARG} ${1} git add ${1} fi } case "${1}" in --about ) echo "Runs clang-format on source files" ;; * ) for file in `git diff-index --cached --diff-filter=ACMR --name-only HEAD` ; do format_file "${file}" done ;; esac
4,配置Jenkins gerrit trigger,指令碼如下,沒有做格式化的禁止提交,但是不幫他改,只打負分:
#!/bin/shif [ -d "checkstyle_dir" ]; then rm -fr checkstyle_dir mkdir checkstyle_direlse mkdir checkstyle_dirfi# get json string:GERRIT_CHANGE_ID="$1"ssh -p 29418 jenkins@x.x.x.x gerrit query --files --current-patch-set $GERRIT_CHANGE_ID --format=json > checkstyle_dir/string.json# delete line 2 to the end (cat xx | wc -l)sed -i '' '2,$d' checkstyle_dir/string.json# read filelist by change-id:cat checkstyle_dir/string.json | jq '.currentPatchSet | .files | map(select(.type != "DELETED")) | .[] | .file' | sed 's/"//g' > checkstyle_dir/filelistwhile read ONE_LINEdo if [[ ${ONE_LINE} = "Libraries"* ]] || [[ ${ONE_LINE} = *".framework"* ]]; then echo "skip $ONE_LINE" elif [ "${ONE_LINE##*.}" = "c" ] || [ "${ONE_LINE##*.}" = "m" ] || [ "${ONE_LINE##*.}" = "mm" ] || [ "${ONE_LINE##*.}" = "h" ]; then #cp --parents $ONE_LINE checkstyle_dir cp $ONE_LINE checkstyle_dir fidone < checkstyle_dir/filelist# checkstylecp ~/.clang-format .RESULT=`ls checkstyle_dir/*.[chm] | xargs clang-format -style=file -output-replacements-xml | grep -c "<replacement "`if [ $RESULT -ne 0 ]; then echo "====================================================================================================" echo "Commit did not match clang-format, please use git commit --amend to modify and push to gerrit again!" echo "====================================================================================================" exit 1;fi
【使用方法】
1,部署前,已複製的倉,請手工拷貝到本地工程的hooks目錄中去:
$cp~/.git_template/hooks/pre-commit .git/hooks/.
2,部署後,新複製的倉,無需任何操作,可直接使用:)
【參考】
http://stackoverflow.com/questions/22866609/can-clang-format-tell-me-if-formatting-changes-are-necessary
https://github.com/andrewseidl/githook-clang-format/blob/master/clang-format.hook