Check committed Go formatting
This commit is contained in:
@@ -2,8 +2,10 @@
|
||||
package validation
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"go/format"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
@@ -16,6 +18,7 @@ type Settings struct {
|
||||
Race bool
|
||||
FullVet bool
|
||||
CompileTargets []Target
|
||||
GoFormat bool
|
||||
}
|
||||
|
||||
// Target selects one package-compilation target.
|
||||
@@ -88,5 +91,55 @@ func Run(ctx context.Context, request Request) error {
|
||||
}
|
||||
}
|
||||
}
|
||||
if request.Settings.GoFormat {
|
||||
tree, err := request.ReadCandidateTree(ctx)
|
||||
if err != nil {
|
||||
return &Failure{Check: GoFormat, Cause: err}
|
||||
}
|
||||
if err := checkGoFormat(ctx, tree); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkGoFormat(ctx context.Context, tree *CandidateTree) error {
|
||||
var findings []Finding
|
||||
for _, entry := range tree.Entries() {
|
||||
if entry.Type != "blob" || (entry.Mode != "100644" && entry.Mode != "100755") || !strings.HasSuffix(entry.Path, ".go") {
|
||||
continue
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return &Failure{Check: GoFormat, Cause: err}
|
||||
}
|
||||
contents, err := tree.ReadFile(ctx, entry.Path)
|
||||
if err != nil {
|
||||
return &Failure{
|
||||
Check: GoFormat,
|
||||
Findings: []Finding{{
|
||||
Path: entry.Path,
|
||||
Message: "unable to inspect committed Go source",
|
||||
}},
|
||||
Cause: fmt.Errorf("inspect committed Go file %q: %w", entry.Path, err),
|
||||
}
|
||||
}
|
||||
formatted, err := format.Source(contents)
|
||||
if err != nil {
|
||||
return &Failure{
|
||||
Check: GoFormat,
|
||||
Findings: []Finding{{
|
||||
Path: entry.Path,
|
||||
Message: "committed Go source cannot be formatted",
|
||||
}},
|
||||
Cause: fmt.Errorf("format committed Go file %q: %w", entry.Path, err),
|
||||
}
|
||||
}
|
||||
if !bytes.Equal(contents, formatted) {
|
||||
findings = append(findings, Finding{Path: entry.Path, Message: "file is not gofmt-formatted"})
|
||||
}
|
||||
}
|
||||
if len(findings) != 0 {
|
||||
return &Failure{Check: GoFormat, Findings: findings}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user