github.com/joshdk/godel@v0.0.0-20170529232908-862138a45aee/cmd/githooks/hooks.go (about) 1 // Copyright 2016 Palantir Technologies, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package githooks 16 17 import ( 18 "fmt" 19 "io/ioutil" 20 "path" 21 22 "github.com/pkg/errors" 23 24 "github.com/palantir/godel/layout" 25 ) 26 27 var hooks = map[string]string{ 28 "pre-commit": `#!/bin/bash 29 gofiles=$(git diff --cached --name-only --diff-filter=ACM | grep '\.go$') 30 [ -z "$gofiles" ] && exit 0 31 32 unformatted=$(./godelw format -l runAll $gofiles) 33 exitCode=$? 34 [ "$exitCode" -eq "0" ] && exit 0 35 36 if [ -n "$unformatted" ]; then 37 echo "Unformatted files exist -- run ./godelw format to format these files:" 38 for file in $unformatted; do 39 echo " $file" 40 done 41 fi 42 43 exit $exitCode 44 `, 45 } 46 47 func InstallGitHooks(rootDir string) error { 48 gitDir := path.Join(rootDir, ".git") 49 if err := layout.VerifyDirExists(gitDir); err != nil { 50 return fmt.Errorf(".git directory does not exist at %v", gitDir) 51 } 52 53 for hook, contents := range hooks { 54 hookPath := path.Join(gitDir, "hooks", hook) 55 if err := ioutil.WriteFile(hookPath, []byte(contents), 0755); err != nil { 56 return errors.Wrapf(err, "Failed to write %s hook to %s", hook, hookPath) 57 } 58 } 59 60 return nil 61 }