git-pre-commit-hook/check_gofmt.go

53 lines
1.2 KiB
Go

package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"os"
"os/exec"
"strings"
"github.com/logrusorgru/aurora"
)
// goFmt checks for bad formatting. It uses the "goimports" command. As of
// 2020-02, the command "goimports ." recurses and ignores module boundaries and
// non-go directories. It can therefore be run from the root of the git repo.
func goFmt() error {
// execute goimports
wbuf := bytes.NewBuffer(nil)
cmd := exec.Command("goimports", "-l", ".")
cmd.Stdout = wbuf
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
// non-zero return code = program error (not bad formatting)
return fmt.Errorf("%s: %v", aurora.Blue("goimports -l"), aurora.Red(err))
}
// iterate over list of changed files, may be empty
var (
scanner = bufio.NewScanner(wbuf)
werr strings.Builder
ok = true
)
fmt.Fprintln(&werr, aurora.Red("The following files need reformatting:"))
for scanner.Scan() {
// ignore generated .pb.go files
if strings.HasSuffix(scanner.Text(), ".pb.go") {
continue
}
ok = false
werr.WriteByte('\t')
werr.WriteString(scanner.Text())
werr.WriteByte('\n')
}
if ok {
return nil
}
return errors.New(werr.String())
}