github.com/jdhenke/godel@v0.0.0-20161213181855-abeb3861bf0d/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": `gofiles=$(git diff --cached --name-only --diff-filter=ACM | grep '\.go$')
    29  [ -z "$gofiles" ] && exit 0
    30  
    31  unformatted=$(./godelw format -l runAll $gofiles)
    32  exitCode=$?
    33  [[ $exitCode -ne 0 ]] && exit $exitCode
    34  [ -z "$unformatted" ] && exit 0
    35  
    36  # Unformatted files exist -- print and exit
    37  echo "Unformatted files exist -- run ./godelw format to format these files:"
    38  for file in $unformatted; do
    39  	echo "  $file"
    40  done
    41  
    42  exit 1
    43  `,
    44  }
    45  
    46  func InstallGitHooks(rootDir string) error {
    47  	gitDir := path.Join(rootDir, ".git")
    48  	if err := layout.VerifyDirExists(gitDir); err != nil {
    49  		return fmt.Errorf(".git directory does not exist at %v", gitDir)
    50  	}
    51  
    52  	for hook, contents := range hooks {
    53  		hookPath := path.Join(gitDir, "hooks", hook)
    54  		if err := ioutil.WriteFile(hookPath, []byte(contents), 0755); err != nil {
    55  			return errors.Wrapf(err, "Failed to write %s hook to %s", hook, hookPath)
    56  		}
    57  	}
    58  
    59  	return nil
    60  }