github.com/XiaoMi/Gaea@v1.2.5/misc/git/hooks/gofmt (about) 1 #!/bin/bash 2 # Copyright 2017 Google Inc. 3 # 4 # Licensed under the Apache License, Version 2.0 (the "License"); 5 # you may not use this file except in compliance with the License. 6 # You may obtain a copy of the License at 7 # 8 # http://www.apache.org/licenses/LICENSE-2.0 9 # 10 # Unless required by applicable law or agreed to in writing, software 11 # distributed under the License is distributed on an "AS IS" BASIS, 12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 # See the License for the specific language governing permissions and 14 # limitations under the License. 15 16 # git gofmt pre-commit hook 17 # 18 # To use, store as .git/hooks/pre-commit inside your repository and make sure 19 # it has execute permissions. 20 # 21 # This script does not handle file names that contain spaces. 22 gofiles=$(git diff --cached --name-only --diff-filter=d | grep '.go$') 23 24 [ -z "$gofiles" ] && exit 0 25 unformatted=$(gofmt -s -l $gofiles 2>&1) 26 [ -z "$unformatted" ] && exit 0 27 28 # Some files are not gofmt'd. Print command to fix them and fail. 29 30 # Deduplicate files first in case a file has multiple errors. 31 files=$( 32 # Split the "gofmt" output on newlines only. 33 OLDIFS=$IFS 34 IFS=' 35 ' 36 for line in $unformatted; do 37 # Strip everything after the first ':', including it. 38 # Example output for $line: 39 # go/vt/vttablet/tabletserver/txserializer/tx_serializer_test.go:241:60: expected ';', found 'IDENT' wg 40 echo ${line/:*/} 41 done | 42 # Remove duplicates. 43 sort -u 44 IFS=$OLDIFS 45 ) 46 47 echo >&2 48 echo >&2 "Go files must be formatted with gofmt. Please run:" 49 echo >&2 50 echo >&2 -n " gofmt -s -w" 51 52 for f in $files; do 53 # Print " \" after the "gofmt" above and each filename (except for the last one). 54 echo >&2 " \\" 55 echo >&2 -n " $PWD/$f" 56 done 57 echo >&2 58 59 echo >&2 60 echo >&2 "If gofmt fails and outputs errors, you have to fix them manually." 61 echo >&2 62 63 exit 1