| // Copyright 2022 Google LLC | |
| // | |
| // Use of this source code is governed by a BSD-style license that can be | |
| // found in the LICENSE file. | |
| // The presubmit binary runs many checks on the differences between the current commit and its | |
| // parent branch. This is usually origin/main. If there is a chain of CLs (i.e. branches), this | |
| // will only consider the diffs between the current commit and the parent branch. | |
| // If all presubmits pass, this binary will output nothing (by default) and have exit code 0. | |
| // If any presubmits fail, there will be errors logged to stdout and the exit code will be non-zero. | |
| // | |
| // This should be invoked from the root of the repo via Bazel like | |
| // | |
| // bazel run //cmd/presubmit | |
| // | |
| // See presubmit.sh for a helper that pipes in the correct value for repo_dir. | |
| package main | |
| import ( | |
| "bytes" | |
| "context" | |
| "encoding/json" | |
| "errors" | |
| "flag" | |
| "fmt" | |
| "go/build" | |
| "io" | |
| "os" | |
| "os/exec" | |
| "path/filepath" | |
| "regexp" | |
| "sort" | |
| "strconv" | |
| "strings" | |
| "go.skia.org/infra/bazel/external/buildifier" | |
| "go.skia.org/infra/bazel/external/rules_go" | |
| "go.skia.org/infra/go/copyright_headers" | |
| "go.skia.org/infra/go/deepequal" | |
| "go.skia.org/infra/go/util" | |
| ) | |
| const ( | |
| golangci = "github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.14.0" | |
| workflowCheck = "go.temporal.io/sdk/contrib/tools/workflowcheck@v0.4.0" | |
| betteralign = "github.com/dkorunic/betteralign/cmd/betteralign@v0.15.3" | |
| ) | |
| func main() { | |
| var ( | |
| // https://bazel.build/docs/user-manual#running-executables | |
| repoDir = flag.String("repo_dir", os.Getenv("BUILD_WORKSPACE_DIRECTORY"), "The root directory of the repo. Default set by BUILD_WORKSPACE_DIRECTORY env variable.") | |
| upstream = flag.String("upstream", "origin/main", "The upstream repo to diff against.") | |
| verbose = flag.Bool("verbose", false, "If extra logging is desired") | |
| upload = flag.Bool("upload", false, "If true, this will skip any checks that are not suitable for an upload check (may be the empty set).") | |
| commit = flag.Bool("commit", false, "If true, this will skip any checks that are not suitable for a commit check (may be the empty set).") | |
| ) | |
| flag.Parse() | |
| ctx := withOutputWriter(context.Background(), os.Stdout) | |
| ctx = withVerbose(ctx, *verbose) | |
| if *repoDir == "" { | |
| logf(ctx, "Must set --repo_dir\n") | |
| flag.PrintDefaults() | |
| os.Exit(1) | |
| } | |
| if *upload && *commit { | |
| logf(ctx, "Cannot set both --upload and --commit\n") | |
| flag.PrintDefaults() | |
| os.Exit(1) | |
| } | |
| if err := os.Chdir(*repoDir); err != nil { | |
| logf(ctx, "Could not cd to %s\n", *repoDir) | |
| os.Exit(1) | |
| } | |
| filesWithDiffs := findUncommittedChanges(ctx) | |
| if len(filesWithDiffs) > 0 { | |
| filesStr := strings.Join(filesWithDiffs, "\n") | |
| logf(ctx, "Found uncommitted changes in %d files. Aborting.\n:%s", len(filesWithDiffs), filesStr) | |
| os.Exit(1) | |
| } | |
| untrackedFiles := findUntrackedFiles(ctx) | |
| for _, uf := range untrackedFiles { | |
| if filepath.Base(uf) == "BUILD.bazel" { | |
| logf(ctx, "Found uncommitted BUILD.bazel files: %s. Please delete these or check them in. Aborting.\n", uf) | |
| os.Exit(1) | |
| } | |
| } | |
| branchBaseCommit := findBranchBase(ctx, *upstream) | |
| if branchBaseCommit == "" { | |
| // This either means the user hasn't committed their changes or is just on the main branch | |
| // somewhere. Either way, we don't want to run the presubmits. It could mutate those | |
| // un-committed changes or just be a no-op, since presumably code in the past passed the | |
| // presubmit checks. | |
| logf(ctx, "No commits since %s. Presubmit passes by default. Did you commit all new files?\n", *upstream) | |
| os.Exit(0) | |
| } | |
| if *verbose { | |
| logf(ctx, "Base commit is %s\n", branchBaseCommit) | |
| } | |
| changedFiles, deletedFiles := computeDiffFiles(ctx, branchBaseCommit) | |
| if *verbose { | |
| logf(ctx, "Changed files:\n%v\n", changedFiles) | |
| logf(ctx, "Deleted files:\n%s\n", deletedFiles) | |
| } | |
| // Run checks and keep track of errors. | |
| var failedChecks []string | |
| runCheck := func(name string, checkFn func() bool) { | |
| if *verbose { | |
| logf(ctx, "[presubmit] Running %s...\n", name) | |
| } | |
| ok := checkFn() | |
| if !ok { | |
| if *verbose { | |
| logf(ctx, "[presubmit] %s failed.\n", name) | |
| } | |
| failedChecks = append(failedChecks, name) | |
| } else if *verbose { | |
| logf(ctx, "[presubmit] %s passed.\n", name) | |
| } | |
| } | |
| if *commit { | |
| runCheck("GoGenerate", func() bool { return runGoGenerate(ctx, changedFiles, branchBaseCommit) }) | |
| changedFiles, _ = computeDiffFiles(ctx, branchBaseCommit) | |
| } | |
| runCheck("Buildifier", func() bool { return runBuildifier(ctx, changedFiles, branchBaseCommit) }) | |
| changedFiles, _ = computeDiffFiles(ctx, branchBaseCommit) | |
| runCheck("CopyrightHeaders", func() bool { return runCopyrightHeaders(ctx, changedFiles, *repoDir, branchBaseCommit) }) | |
| changedFiles, _ = computeDiffFiles(ctx, branchBaseCommit) | |
| runCheck("Goimports", func() bool { return runGoimports(ctx, changedFiles, *repoDir, branchBaseCommit) }) | |
| changedFiles, _ = computeDiffFiles(ctx, branchBaseCommit) | |
| runCheck("Gofmt", func() bool { return runGofmt(ctx, changedFiles, branchBaseCommit) }) | |
| changedFiles, _ = computeDiffFiles(ctx, branchBaseCommit) | |
| runCheck("GoVet", func() bool { return runGoVet(ctx, changedFiles, branchBaseCommit) }) | |
| runCheck("Errcheck", func() bool { return runErrcheck(ctx) }) | |
| if *commit { | |
| runCheck("NpmCi", func() bool { return runNpmCi(ctx) }) | |
| } | |
| runCheck("Prettier", func() bool { return runPrettier(ctx, changedFiles, *repoDir, branchBaseCommit) }) | |
| changedFiles, _ = computeDiffFiles(ctx, branchBaseCommit) | |
| runCheck("ESLint", func() bool { return runESLint(ctx, changedFiles, *repoDir, branchBaseCommit) }) | |
| changedFiles, _ = computeDiffFiles(ctx, branchBaseCommit) | |
| runCheck("Stylelint", func() bool { return runStylelint(ctx, changedFiles, *repoDir, branchBaseCommit) }) | |
| changedFiles, _ = computeDiffFiles(ctx, branchBaseCommit) | |
| runCheck("Gazelle", func() bool { return runGazelle(ctx, changedFiles, deletedFiles, branchBaseCommit) }) | |
| changedFiles, _ = computeDiffFiles(ctx, branchBaseCommit) | |
| runCheck("TODOHasOwner", func() bool { return checkTODOHasOwner(ctx, changedFiles) }) | |
| runCheck("StrayWhitespace", func() bool { return checkForStrayWhitespace(ctx, changedFiles) }) | |
| runCheck("PythonFilesHaveNoTabs", func() bool { return checkPythonFilesHaveNoTabs(ctx, changedFiles) }) | |
| runCheck("BannedGoAPIs", func() bool { return checkBannedGoAPIs(ctx, changedFiles) }) | |
| runCheck("JSDebugging", func() bool { return checkJSDebugging(ctx, changedFiles) }) | |
| runCheck("GolangCILintForPinpoint", func() bool { return runGolangCILintForPinpoint(ctx, changedFiles, branchBaseCommit) }) | |
| runCheck("BetterAlignForPinpoint", func() bool { return runBetterAlignForPinpoint(ctx, changedFiles) }) | |
| runCheck("IdempotentDDL", func() bool { return checkIdempotentDDL(ctx, changedFiles, *repoDir) }) | |
| runCheck("WorkflowCheck", func() bool { return runWorkflowCheck(ctx, changedFiles, *repoDir) }) | |
| if !*commit { | |
| runCheck("NonASCII", func() bool { return checkNonASCII(ctx, changedFiles) }) | |
| runCheck("Autoreview", func() bool { return runAutoreview(ctx, branchBaseCommit) }) | |
| } | |
| if len(failedChecks) > 0 { | |
| logf(ctx, "Presubmit errors detected! The following checks failed: %s\n", strings.Join(failedChecks, ", ")) | |
| os.Exit(1) | |
| } | |
| os.Exit(0) | |
| } | |
| const ( | |
| gitErrorMessage = `Error running git - is git on your path? | |
| If running with Bazel, you need to invoke this like: | |
| bazel run //cmd/presubmit --run_under="cd $PWD &&" | |
| ` | |
| refSeperator = "$|" // Some string we hope that no users start their branch names with | |
| ) | |
| func isCitcWorkspace() bool { | |
| _, err := os.Stat(".git") | |
| return os.IsNotExist(err) | |
| } | |
| // findUncommittedChanges returns a list of files that git says have changed (compared to HEAD). | |
| func findUncommittedChanges(ctx context.Context) []string { | |
| if isCitcWorkspace() { | |
| // In a CitC workspace, changes are tracked directly in the working copy commit (@), | |
| // so there are no "uncommitted" changes in the Git sense. | |
| return nil | |
| } | |
| // diff-index is one of the git "plumbing" commands and the output should be relatively stable. | |
| // https://mirrors.edge.kernel.org/pub/software/scm/git/docs/git.html#_low_level_commands_plumbing | |
| cmd := exec.CommandContext(ctx, "git", "diff-index", "HEAD") | |
| output, err := cmd.CombinedOutput() | |
| if err != nil { | |
| log(ctx, string(output)+"\n") | |
| log(ctx, err.Error()+"\n") | |
| panic(gitErrorMessage) | |
| } | |
| return extractFilesWithDiffs(string(output)) | |
| } | |
| var fileDiff = regexp.MustCompile(`^:.+\t(?P<file>[^\t]+)$`) | |
| func extractFilesWithDiffs(output string) []string { | |
| output = strings.TrimSpace(output) | |
| if output == "" { | |
| return nil | |
| } | |
| var files []string | |
| lines := strings.Split(output, "\n") | |
| for _, line := range lines { | |
| if match := fileDiff.FindStringSubmatch(line); len(match) > 0 { | |
| files = append(files, match[1]) | |
| } | |
| } | |
| return files | |
| } | |
| // findUntrackedFiles returns a list of files untracked and unignored by Git. | |
| func findUntrackedFiles(ctx context.Context) []string { | |
| if isCitcWorkspace() { | |
| // CitC automatically tracks files in the working copy commit, so we don't use this. | |
| return nil | |
| } | |
| // https://stackoverflow.com/a/2659808/1447621 | |
| // This will list all untracked, unignored files on their own lines | |
| cmd := exec.CommandContext(ctx, "git", "ls-files", "--others", "--exclude-standard") | |
| output, err := cmd.CombinedOutput() | |
| if err != nil { | |
| log(ctx, string(output)+"\n") | |
| log(ctx, err.Error()+"\n") | |
| panic(gitErrorMessage) | |
| } | |
| return strings.Split(string(output), "\n") | |
| } | |
| // findBranchBase returns the git commit of the parent branch. If there is a chain of CLs | |
| // (i.e. branches), this will return the parent branch's most recent commit. If we are on the | |
| // upstream branch, this will return empty string. Otherwise, it will return the commit on the | |
| // upstream branch where branching occurred. It shells out to git, which is presumed to be on | |
| // PATH in order to find this information. | |
| func findBranchBase(ctx context.Context, upstream string) string { | |
| if isCitcWorkspace() { | |
| // In a CitC/jj workspace, the current working commit is '@'. | |
| // Its parent is '@-', its grandparent is '@--', and so on. | |
| // A user can have multiple local commits (e.g., 'â—‹' nodes in `jj log`). | |
| // We want to find the first remote/immutable commit (e.g., 'â—†' node in `jj log`), | |
| // which represents the base of the local stack. | |
| // Run `git citc cli.log` to fetch the commit history. | |
| cmd := exec.CommandContext(ctx, "git", "citc", "cli.log", "-n", "100") | |
| output, err := cmd.CombinedOutput() | |
| if err != nil { | |
| log(ctx, string(output)+"\n") | |
| log(ctx, err.Error()+"\n") | |
| panic(gitErrorMessage) | |
| } | |
| return extractBranchBaseCitc(string(output), ctx) | |
| } | |
| // rev-list is one of the git "plumbing" commands and the output should be relatively stable. | |
| // https://mirrors.edge.kernel.org/pub/software/scm/git/docs/git.html#_low_level_commands_plumbing | |
| cmd := exec.CommandContext(ctx, "git", "rev-list", "HEAD", "^"+upstream, | |
| // %D means "ref names", which is the commit hash and any branch name associated with it | |
| // %P means the parent hash | |
| `--format=%D`+refSeperator+`%P`) | |
| output, err := cmd.CombinedOutput() | |
| if err != nil { | |
| log(ctx, string(output)+"\n") | |
| log(ctx, err.Error()+"\n") | |
| panic(gitErrorMessage) | |
| } | |
| return extractBranchBase(string(output)) | |
| } | |
| func extractBranchBaseCitc(output string, ctx context.Context) string { | |
| lines := strings.Split(strings.TrimSpace(output), "\n") | |
| // We count backwards through the parents. The working copy '@' is level 0. | |
| // Its parent '@-' is level 1, its grandparent '@--' is level 2, etc. | |
| // `jj log` outputs commits from top to bottom (newest to oldest). | |
| // We want to find the first commit marked with 'â—†' (immutable/remote base). | |
| level := -1 | |
| for _, line := range lines { | |
| // The first character usually denotes the type of commit node. | |
| // 'â—†' denotes an immutable commit (the base we want). | |
| // 'â—‹' denotes a local commit. | |
| // '@' denotes the working copy commit. | |
| if strings.HasPrefix(line, "@ ") { | |
| level++ | |
| } else if strings.HasPrefix(line, "â—‹ ") { | |
| level++ | |
| } else if strings.HasPrefix(line, "â—† ") { | |
| level++ | |
| // We found the immutable base. We return the relative jj notation for it. | |
| if level == 0 { | |
| return "@" // Should rarely happen, but means the working copy is the remote commit | |
| } | |
| base := "@" + strings.Repeat("-", level) | |
| if isVerbose(ctx) { | |
| logf(ctx, "[presubmit] CitC workspace detected. Found base commit at %s: %s\n", base, line) | |
| } | |
| return base | |
| } | |
| } | |
| // Fallback to immediate parent if we can't parse correctly. | |
| if isVerbose(ctx) { | |
| logf(ctx, "[presubmit] CitC workspace detected, but failed to parse base from log. Falling back to '@-'.\n") | |
| } | |
| return "@-" | |
| } | |
| type revEntry struct { | |
| commit string | |
| branch string | |
| parents []string | |
| // depth is a monotonically increasing number for each commit we see as we are going back | |
| // in time. | |
| depth int | |
| } | |
| // extractBranchBase looks for the most recent branch, as indicated by the "ref name". Failing to find | |
| // that, it will return the last parent commit, which will connect to the upstream branch. | |
| func extractBranchBase(output string) string { | |
| output = strings.TrimSpace(output) | |
| if output == "" { | |
| return "" | |
| } | |
| lines := strings.Split(output, "\n") | |
| // Create a graph of commits. The entries map holds onto all the nodes (using the commit as | |
| // a key). After we create the graph, we'll look for the key features. | |
| entries := map[string]*revEntry{} | |
| var currentEntry *revEntry | |
| depth := 0 | |
| for _, line := range lines { | |
| if strings.HasPrefix(line, "commit ") { | |
| c := strings.TrimPrefix(line, "commit ") | |
| entry := entries[c] | |
| if entry == nil { | |
| entry = &revEntry{commit: c, depth: depth} | |
| entries[c] = entry | |
| } else { | |
| entry.depth = depth | |
| } | |
| currentEntry = entry | |
| depth++ | |
| continue | |
| } | |
| parts := strings.Split(line, refSeperator) | |
| // First part is the possibly empty branch name | |
| currentEntry.branch = parts[0] | |
| // second part is the possibly multiple parents, separated by spaces | |
| parents := strings.Split(parts[1], " ") | |
| currentEntry.parents = parents | |
| for _, parent := range parents { | |
| // Associate the parents with the depth of the child they apply to. | |
| entries[parent] = &revEntry{commit: parent, depth: depth} | |
| } | |
| } | |
| // Go through the created graph and find commits of interest | |
| var shallowestCommitWithNoParents *revEntry | |
| var shallowestCommitWithBranch *revEntry | |
| for _, entry := range entries { | |
| if len(entry.parents) == 0 { | |
| if shallowestCommitWithNoParents == nil || shallowestCommitWithNoParents.depth > entry.depth { | |
| shallowestCommitWithNoParents = entry | |
| } | |
| } | |
| if entry.branch != "" && !strings.HasPrefix(entry.branch, "HEAD -> ") { | |
| if shallowestCommitWithBranch == nil || shallowestCommitWithBranch.depth > entry.depth { | |
| shallowestCommitWithBranch = entry | |
| } | |
| } | |
| } | |
| // If we found a branch that HEAD descends from, compare to the shallowest commit belonging | |
| // to that branch. | |
| if shallowestCommitWithBranch != nil { | |
| return shallowestCommitWithBranch.commit | |
| } | |
| // Otherwise, go with the shallowest commit that we didn't find parents for. These parent-less | |
| // commits correspond to commits on the main branch, and the shallowest one will be the newest. | |
| if shallowestCommitWithNoParents != nil { | |
| return shallowestCommitWithNoParents.commit | |
| } | |
| // This should not happen unless we are parsing things wrong. | |
| panic("Could not find a branch to compare to") | |
| } | |
| // computeDiffFiles returns a slice of changed (modified or added) files with the lines touched | |
| // and a slice of deleted files. It shells out to git, which is presumed to be on PATH in order | |
| // to find this information. | |
| func computeDiffFiles(ctx context.Context, branchBase string) ([]fileWithChanges, []string) { | |
| if isCitcWorkspace() { | |
| return computeDiffFilesCitc(ctx, branchBase) | |
| } | |
| // git diff-index is considered to be a "git plumbing" API, so its output should be pretty | |
| // stable across git version (unlike ordinary git diff, which can do things like show | |
| // tabs as multiple spaces). | |
| cmd := exec.CommandContext(ctx, "git", "diff-index", branchBase, | |
| // Don't show any surrounding context (i.e. lines which did not change) | |
| "--unified=0", | |
| "--patch-with-raw", | |
| "--no-color") | |
| output, err := cmd.CombinedOutput() | |
| if err != nil { | |
| log(ctx, string(output)+"\n") | |
| log(ctx, err.Error()+"\n") | |
| panic(gitErrorMessage) | |
| } | |
| return extractChangedAndDeletedFiles(string(output)) | |
| } | |
| func computeDiffFilesCitc(ctx context.Context, branchBase string) ([]fileWithChanges, []string) { | |
| if isVerbose(ctx) { | |
| logf(ctx, "[presubmit] Executing: git citc cli.diff %s @\n", branchBase) | |
| } | |
| cmd := exec.CommandContext(ctx, "git", "citc", "cli.diff", branchBase, "@") | |
| output, err := cmd.CombinedOutput() | |
| if err != nil { | |
| log(ctx, string(output)+"\n") | |
| log(ctx, err.Error()+"\n") | |
| panic(gitErrorMessage) | |
| } | |
| return extractChangedAndDeletedFilesCitc(string(output)) | |
| } | |
| var ( | |
| gitDiffLine = regexp.MustCompile(`^diff --git (?P<fileA>.*) (?P<fileB>.*)$`) | |
| lineAnchor = regexp.MustCompile(`^@@ -(?P<deleted>\d+)(?P<delLines>,\d+)? \+(?P<added>\d+)(?P<addLines>,\d+)? @@.*$`) | |
| ) | |
| const ( | |
| deletedFilePrefix = "deleted file mode" | |
| addedLinePrefix = "+" | |
| ) | |
| // fileWithChanges represents an added or modified files along with the lines changed (touched). | |
| // Lines that were deleted are not tracked. | |
| type fileWithChanges struct { | |
| fileName string | |
| touchedLines []lineOfCode | |
| } | |
| func (f fileWithChanges) String() string { | |
| rv := f.fileName + "\n" | |
| for _, line := range f.touchedLines { | |
| rv += " " + line.String() + "\n" | |
| } | |
| return rv | |
| } | |
| type lineOfCode struct { | |
| contents string | |
| num int | |
| } | |
| func (c lineOfCode) String() string { | |
| return fmt.Sprintf("% 4d:%s", c.num, c.contents) | |
| } | |
| // extractChangedAndDeletedFiles looks through the provided `git diff` output and finds the files | |
| // that were added or modified, as well as the new version of any lines touched. It also returns | |
| // a slice of deleted files. | |
| func extractChangedAndDeletedFiles(diffOutput string) ([]fileWithChanges, []string) { | |
| var changed []fileWithChanges | |
| var deleted []string | |
| lines := strings.Split(diffOutput, "\n") | |
| currFileDeleted := false | |
| lastLineIndex := -1 | |
| for i := 0; i < len(lines); i++ { | |
| line := lines[i] | |
| if match := gitDiffLine.FindStringSubmatch(line); len(match) > 0 { | |
| // A new file was changed, reset our counters, trackers, and add an entry for it. | |
| var newFile fileWithChanges | |
| newFile.fileName = strings.TrimPrefix(match[2], "b/") | |
| changed = append(changed, newFile) | |
| currFileDeleted = false | |
| lastLineIndex = -1 | |
| } | |
| if currFileDeleted || len(changed) == 0 { | |
| continue | |
| } | |
| currFile := &changed[len(changed)-1] | |
| if strings.HasPrefix(line, deletedFilePrefix) { | |
| deleted = append(deleted, currFile.fileName) | |
| changed = changed[:len(changed)-1] // trim off changed file | |
| currFileDeleted = true | |
| continue | |
| } | |
| if match := lineAnchor.FindStringSubmatch(line); len(match) > 0 { | |
| // The added group has the line number corresponding to the next line starting with a + | |
| var err error | |
| lastLineIndex, err = strconv.Atoi(match[3]) | |
| if err != nil { | |
| panic("Got an integer where none was expected: " + line + "\n" + err.Error()) | |
| } | |
| continue | |
| } | |
| if lastLineIndex < 0 { | |
| // Have not found a line index yet, ignore the lines like: | |
| // ++ b/PRESUBMIT.py | |
| continue | |
| } | |
| if strings.HasPrefix(line, addedLinePrefix) { | |
| currFile.touchedLines = append(currFile.touchedLines, lineOfCode{ | |
| contents: strings.TrimPrefix(line, addedLinePrefix), | |
| num: lastLineIndex, | |
| }) | |
| lastLineIndex++ | |
| } | |
| } | |
| return changed, deleted | |
| } | |
| func extractChangedAndDeletedFilesCitc(diffOutput string) ([]fileWithChanges, []string) { | |
| var changed []fileWithChanges | |
| var deleted []string | |
| lines := strings.Split(diffOutput, "\n") | |
| currFileDeleted := false | |
| lastLineIndex := -1 | |
| for i := 0; i < len(lines); i++ { | |
| line := lines[i] | |
| if strings.HasPrefix(line, "--- ") { | |
| if i+1 < len(lines) && strings.HasPrefix(lines[i+1], "+++ ") { | |
| minusLine := line | |
| plusLine := lines[i+1] | |
| i++ // skip +++ line | |
| currFileDeleted = false | |
| lastLineIndex = -1 | |
| if strings.HasPrefix(plusLine, "+++ /dev/null") { | |
| fileName := strings.TrimPrefix(minusLine, "--- ") | |
| if strings.HasPrefix(fileName, "a/") || strings.HasPrefix(fileName, "b/") { | |
| fileName = fileName[2:] | |
| } | |
| deleted = append(deleted, fileName) | |
| currFileDeleted = true | |
| } else { | |
| fileName := strings.TrimPrefix(plusLine, "+++ ") | |
| if strings.HasPrefix(fileName, "a/") || strings.HasPrefix(fileName, "b/") { | |
| fileName = fileName[2:] | |
| } | |
| var newFile fileWithChanges | |
| newFile.fileName = fileName | |
| changed = append(changed, newFile) | |
| } | |
| } | |
| continue | |
| } | |
| if currFileDeleted || len(changed) == 0 { | |
| continue | |
| } | |
| currFile := &changed[len(changed)-1] | |
| if match := lineAnchor.FindStringSubmatch(line); len(match) > 0 { | |
| var err error | |
| lastLineIndex, err = strconv.Atoi(match[3]) | |
| if err != nil { | |
| panic("Got an integer where none was expected: " + line + "\n" + err.Error()) | |
| } | |
| continue | |
| } | |
| if lastLineIndex < 0 { | |
| continue | |
| } | |
| if strings.HasPrefix(line, "+") { | |
| currFile.touchedLines = append(currFile.touchedLines, lineOfCode{ | |
| contents: strings.TrimPrefix(line, "+"), | |
| num: lastLineIndex, | |
| }) | |
| lastLineIndex++ | |
| } else if strings.HasPrefix(line, "-") || strings.HasPrefix(line, "\\") { | |
| // Do nothing for removed lines and "No newline at end of file" comments | |
| } else if strings.HasPrefix(line, " ") { | |
| // Context line | |
| lastLineIndex++ | |
| } | |
| } | |
| return changed, deleted | |
| } | |
| func runGolangCILintForPinpoint(ctx context.Context, files []fileWithChanges, branchBaseCommit string) bool { | |
| // Collect unique directories of the changed files. | |
| // We must pass directories to golangci-lint, not individual files. | |
| // Passing individual files breaks the Go package context and causes "undefined type" errors. | |
| dirsMap := make(map[string]bool) | |
| for _, f := range files { | |
| // Only run the linter for Go files inside the pinpoint directory. | |
| if filepath.Ext(f.fileName) == ".go" && strings.HasPrefix(f.fileName, "pinpoint/") { | |
| dirsMap["./"+filepath.Dir(f.fileName)] = true | |
| } | |
| } | |
| if len(dirsMap) == 0 { | |
| return true | |
| } | |
| var dirs []string | |
| for d := range dirsMap { | |
| dirs = append(dirs, d) | |
| } | |
| baseArgs := []string{ | |
| "run", | |
| "--config=mayberemote", | |
| "//:go", | |
| "--", | |
| "run", | |
| golangci, | |
| "run", | |
| "--new-from-rev", | |
| branchBaseCommit, | |
| "--whole-files", | |
| "--fix", | |
| } | |
| args := append(baseArgs, dirs...) | |
| cmd := exec.CommandContext(ctx, "bazelisk", args...) | |
| if output, err := cmd.CombinedOutput(); err != nil { | |
| log(ctx, string(output)) | |
| log(ctx, "golangci-lint failed!\n") | |
| return false | |
| } | |
| return true | |
| } | |
| func runBetterAlignForPinpoint(ctx context.Context, files []fileWithChanges) bool { | |
| // Collect unique directories of the changed files. | |
| // We must pass directories to betteralign, not individual files. | |
| dirsMap := make(map[string]bool) | |
| for _, f := range files { | |
| // Only run the linter for Go files inside the pinpoint directory. | |
| if filepath.Ext(f.fileName) == ".go" && strings.HasPrefix(f.fileName, "pinpoint/") { | |
| dirsMap["./"+filepath.Dir(f.fileName)] = true | |
| } | |
| } | |
| if len(dirsMap) == 0 { | |
| return true | |
| } | |
| var dirs []string | |
| for d := range dirsMap { | |
| dirs = append(dirs, d) | |
| } | |
| baseArgs := []string{ | |
| "run", | |
| "--config=mayberemote", | |
| "//:go", | |
| "--", | |
| "run", | |
| betteralign, | |
| "-apply", | |
| } | |
| args := append(baseArgs, dirs...) | |
| cmd := exec.CommandContext(ctx, "bazelisk", args...) | |
| if output, err := cmd.CombinedOutput(); err != nil { | |
| log(ctx, string(output)) | |
| log(ctx, "betteralign failed!\n") | |
| return false | |
| } | |
| return true | |
| } | |
| type workflowcheckIssue struct { | |
| Posn string `json:"posn"` | |
| Message string `json:"message"` | |
| } | |
| type workflowcheckResult struct { | |
| Issues []workflowcheckIssue `json:"workflowcheck"` | |
| } | |
| // workflowCheckFormatPosn takes a compiler-formatted position string and converts | |
| // the absolute path to a relative path from repoRoot, keeping line/col suffixes intact. | |
| func workflowCheckFormatPosn(posn, repoRoot string) string { | |
| relPosn, err := filepath.Rel(repoRoot, posn) | |
| if err != nil { | |
| return posn | |
| } | |
| return relPosn | |
| } | |
| // workflowCheckFormatMessage formats workflow check error messages for better readability. | |
| func workflowCheckFormatMessage(message string) string { | |
| return strings.ReplaceAll(message, " -> ", "\n-> ") | |
| } | |
| // runWorkflowCheck runs the official Temporal workflowcheck linter on workflow package directories. | |
| func runWorkflowCheck(ctx context.Context, changedFiles []fileWithChanges, repoRoot string) bool { | |
| var dirs []string | |
| for _, f := range changedFiles { | |
| ext := filepath.Ext(f.fileName) | |
| dir := "./" + filepath.Dir(f.fileName) | |
| if strings.ToLower(ext) == ".go" && !contains(dirs, dir) { | |
| // Skip directories where build constraints exclude all Go files on the current platform. | |
| var noGoErr *build.NoGoError | |
| if _, err := build.Default.ImportDir(filepath.Join(repoRoot, filepath.Dir(f.fileName)), 0); errors.As(err, &noGoErr) { | |
| continue | |
| } | |
| dirs = append(dirs, dir) | |
| } | |
| } | |
| if len(dirs) == 0 { | |
| return true | |
| } | |
| args := []string{ | |
| "run", | |
| "--config=mayberemote", | |
| "//:go", | |
| "--", | |
| "run", | |
| workflowCheck, | |
| "--config=workflowcheck.yaml", | |
| "--json", | |
| "--single-line", | |
| } | |
| args = append(args, dirs...) | |
| var stdoutBuf, stderrBuf bytes.Buffer | |
| if isVerbose(ctx) { | |
| logf(ctx, "[presubmit] Executing bazelisk %s\n", strings.Join(args, " ")) | |
| } | |
| cmd := exec.CommandContext(ctx, "bazelisk", args...) | |
| cmd.Stdout = &stdoutBuf | |
| cmd.Stderr = &stderrBuf | |
| if err := cmd.Run(); err != nil { | |
| log(ctx, stderrBuf.String()) | |
| logf(ctx, "\nworkflowcheck failed to run: %s\n", err) | |
| return false | |
| } | |
| stdoutBytes := stdoutBuf.Bytes() | |
| var results map[string]workflowcheckResult | |
| if unmarshalErr := json.Unmarshal(stdoutBytes, &results); unmarshalErr != nil { | |
| logf( | |
| ctx, | |
| "workflowcheck returned invalid JSON: %s\nOutput: %s\n", | |
| unmarshalErr, | |
| string(stdoutBytes), | |
| ) | |
| return false | |
| } | |
| var issues []string | |
| for _, pkgResult := range results { | |
| for _, issue := range pkgResult.Issues { | |
| relPosn := workflowCheckFormatPosn(issue.Posn, repoRoot) | |
| // Append only issues relevant for modified files. | |
| for _, f := range changedFiles { | |
| if strings.HasPrefix(relPosn, f.fileName) { | |
| message := workflowCheckFormatMessage(issue.Message) | |
| issues = append( | |
| issues, | |
| fmt.Sprintf("workflowcheck: %s: %s\n\n", relPosn, message), | |
| ) | |
| } | |
| } | |
| } | |
| } | |
| if len(issues) > 0 { | |
| log(ctx, strings.Join(issues, "")) | |
| logf(ctx, "workflowcheck: found %d determinism issues.\n", len(issues)) | |
| log(ctx, "Temporal workflows must be deterministic. Use //workflowcheck:ignore to ignore.\n") | |
| return false | |
| } | |
| return true | |
| } | |
| var todoWithoutOwner = regexp.MustCompile(`TODO[^(]`) | |
| // checkTODOHasOwner looks through all touched lines and returns false if any of them (not covered | |
| // by exceptions) have a TODO without an owner or a bug. | |
| // Based on https://chromium.googlesource.com/chromium/tools/depot_tools.git/+/19b3eb5adbe00e9da40375cb5dc47380a46f3041/presubmit_canned_checks.py#464 | |
| func checkTODOHasOwner(ctx context.Context, files []fileWithChanges) bool { | |
| ignoreFiles := []string{ | |
| // These files have TODO in their function names and test data. | |
| "cmd/presubmit/presubmit.go", "cmd/presubmit/presubmit_test.go", | |
| // Generated by proto compiler, ignore check. | |
| "pinpoint/webui/app/gateway/gateway.ts", | |
| } | |
| ok := true | |
| for _, f := range files { | |
| if contains(ignoreFiles, f.fileName) { | |
| continue | |
| } | |
| for _, line := range f.touchedLines { | |
| if todoWithoutOwner.MatchString(line.contents) || strings.HasSuffix(line.contents, "TODO") { | |
| logf(ctx, "%s:%d TODO without owner or bug\n", f.fileName, line.num) | |
| ok = false | |
| } | |
| } | |
| } | |
| return ok | |
| } | |
| var trailingWhitespace = regexp.MustCompile(`\s+$`) | |
| // checkForStrayWhitespace goes through all touched lines and returns false if any of them end with | |
| // a whitespace character (e.g. tabs, spaces). newlines should have been stripped out of | |
| // the content of a line earlier. | |
| // Based on https://chromium.googlesource.com/chromium/tools/depot_tools.git/+/19b3eb5adbe00e9da40375cb5dc47380a46f3041/presubmit_canned_checks.py#476 | |
| func checkForStrayWhitespace(ctx context.Context, files []fileWithChanges) bool { | |
| ok := true | |
| for _, f := range files { | |
| for _, line := range f.touchedLines { | |
| if trailingWhitespace.MatchString(line.contents) { | |
| logf(ctx, "%s:%d Trailing whitespace\n", f.fileName, line.num) | |
| ok = false | |
| } | |
| } | |
| } | |
| return ok | |
| } | |
| // checkPythonFilesHaveNoTabs goes through the touched lines of all Python files and returns false | |
| // if any of them have tabs anywhere. | |
| // Based on https://chromium.googlesource.com/chromium/tools/depot_tools.git/+/19b3eb5adbe00e9da40375cb5dc47380a46f3041/presubmit_canned_checks.py#441 | |
| func checkPythonFilesHaveNoTabs(ctx context.Context, files []fileWithChanges) bool { | |
| ok := true | |
| for _, f := range files { | |
| if filepath.Ext(f.fileName) != ".py" { | |
| continue | |
| } | |
| for _, line := range f.touchedLines { | |
| if strings.Contains(line.contents, "\t") { | |
| logf(ctx, "%s:%d Tab character not allowed\n", f.fileName, line.num) | |
| ok = false | |
| } | |
| } | |
| } | |
| return ok | |
| } | |
| type bannedGoAPI struct { | |
| regex *regexp.Regexp | |
| suggestion string | |
| exceptions []*regexp.Regexp | |
| } | |
| // checkBannedGoAPIs goes through all touched lines in go files and returns false if any of them | |
| // have APIs that we wish not to use. It logs suggested replacements in that case. | |
| func checkBannedGoAPIs(ctx context.Context, files []fileWithChanges) bool { | |
| bannedAPIs := []bannedGoAPI{ | |
| {regex: regexp.MustCompile(`reflect\.DeepEqual`), suggestion: "Equal in go.skia.org/infra/go/deepequal/assertdeep"}, | |
| {regex: regexp.MustCompile(`github\.com/golang/glog`), suggestion: "go.skia.org/infra/go/sklog"}, | |
| {regex: regexp.MustCompile(`github\.com/skia-dev/glog`), suggestion: "go.skia.org/infra/go/sklog"}, | |
| {regex: regexp.MustCompile(`http\.Get`), suggestion: "NewTimeoutClient in go.skia.org/infra/go/httputils"}, | |
| {regex: regexp.MustCompile(`http\.Head\(`), suggestion: "NewTimeoutClient in go.skia.org/infra/go/httputils", | |
| exceptions: []*regexp.Regexp{ | |
| // generated file we have no control over. | |
| regexp.MustCompile(`go/issuetracker/.*\.go`), | |
| }}, | |
| {regex: regexp.MustCompile(`http\.Post`), suggestion: "NewTimeoutClient in go.skia.org/infra/go/httputils"}, | |
| {regex: regexp.MustCompile(`http\.PostForm`), suggestion: "NewTimeoutClient in go.skia.org/infra/go/httputils"}, | |
| {regex: regexp.MustCompile(`os\.Interrupt`), suggestion: "AtExit in go.skia.org/go/cleanup"}, | |
| {regex: regexp.MustCompile(`signal\.Notify`), suggestion: "AtExit in go.skia.org/go/cleanup"}, | |
| {regex: regexp.MustCompile(`syscall\.SIGINT`), suggestion: "AtExit in go.skia.org/go/cleanup"}, | |
| {regex: regexp.MustCompile(`syscall\.SIGTERM`), suggestion: "AtExit in go.skia.org/go/cleanup"}, | |
| {regex: regexp.MustCompile(`syncmap\.Map`), suggestion: "sync.Map, added in go 1.9"}, | |
| {regex: regexp.MustCompile(`assert\s+"github\.com/stretchr/testify/require"`), suggestion: `non-aliased import; this can be confused with package "github.com/stretchr/testify/assert"`}, | |
| { | |
| regex: regexp.MustCompile(`"git"`), | |
| suggestion: `Executable in go.skia.org/infra/go/git`, | |
| exceptions: []*regexp.Regexp{ | |
| // These don't actually shell out to git; the tests look for "git" in the | |
| // command line and mock stdout accordingly. | |
| regexp.MustCompile(`autoroll/go/repo_manager/.*_test\.go`), | |
| // This doesn't shell out to git; it's referring to a CIPD package with | |
| // the same name. | |
| regexp.MustCompile(`infra/bots/gen_tasks\.go`), | |
| // This doesn't shell out to git; it retrieves the path to the Git binary | |
| // in the corresponding Bazel-downloaded CIPD packages. | |
| regexp.MustCompile(`bazel/external/cipd/git/git\.go`), | |
| // Our presubmits invoke git directly because git is a necessary | |
| // executable for all devs, and we do not want our presubmit code to | |
| // depend on the code it is checking. | |
| regexp.MustCompile(`cmd/presubmit/.*`), | |
| // This doesn't shell out to git. | |
| regexp.MustCompile(`go/depot_tools/deps_parser/.*\.go`), | |
| // This is the one place where we are allowed to shell out to git; all | |
| // others should go through here. | |
| regexp.MustCompile(`go/git/git_common/.*\.go`), | |
| // Just using the word "git" as a config value. | |
| regexp.MustCompile(`perf/go/config/.*\.go`), | |
| // Just using the word "git" as a directory name. | |
| regexp.MustCompile(`perf/go/git/providers/git_checkout/.*\.go`), | |
| // Not necessary on developer machines. | |
| regexp.MustCompile(`sk/go/try/try\.go`), | |
| }, | |
| }, | |
| } | |
| ok := true | |
| for _, f := range files { | |
| if filepath.Ext(f.fileName) != ".go" { | |
| continue | |
| } | |
| if f.fileName == "cmd/presubmit/presubmit_test.go" { | |
| // We don't want our own test cases to trigger any of these. | |
| continue | |
| } | |
| for _, line := range f.touchedLines { | |
| bannedAPILoop: | |
| for _, bannedAPI := range bannedAPIs { | |
| for _, exception := range bannedAPI.exceptions { | |
| if exception.MatchString(f.fileName) { | |
| continue bannedAPILoop | |
| } | |
| } | |
| if match := bannedAPI.regex.FindStringSubmatch(line.contents); len(match) > 0 { | |
| logf(ctx, "%s:%d Instead of %s, please use %s\n", f.fileName, line.num, match[0], bannedAPI.suggestion) | |
| ok = false | |
| } | |
| } | |
| } | |
| } | |
| return ok | |
| } | |
| // checkIdempotentDDL parses modified SQL migrations to ensure they are idempotent. | |
| // For example, it checks if CREATE TABLE uses IF NOT EXISTS (e.g. CREATE TABLE IF NOT EXISTS test (id INT);). | |
| func checkIdempotentDDL(ctx context.Context, files []fileWithChanges, repoDir string) bool { | |
| ok := true | |
| for _, f := range files { | |
| if !strings.HasPrefix(f.fileName, "perf/go/sql/expectedschema/migrations/") || !strings.HasSuffix(f.fileName, ".sql") { | |
| continue | |
| } | |
| content, err := os.ReadFile(filepath.Join(repoDir, f.fileName)) | |
| if err != nil { | |
| continue | |
| } | |
| statements := splitSQLStatements(string(content)) | |
| for _, stmt := range statements { | |
| stmt = strings.TrimSpace(stmt) | |
| if stmt == "" { | |
| continue | |
| } | |
| snippet := stmt | |
| if len(snippet) > 100 { | |
| snippet = snippet[:100] + "..." | |
| } | |
| // Normalize spaces and newlines for easier checking | |
| normalized := strings.Join(strings.Fields(stmt), " ") | |
| upperStmt := strings.ToUpper(normalized) | |
| if strings.HasPrefix(upperStmt, "CREATE TABLE") && !strings.HasPrefix(upperStmt, "CREATE TABLE IF NOT EXISTS") { | |
| logf(ctx, "%s: CREATE TABLE must use IF NOT EXISTS. Statement: %s\n", f.fileName, snippet) | |
| ok = false | |
| } | |
| if strings.HasPrefix(upperStmt, "ALTER TABLE") { | |
| if strings.Contains(upperStmt, " ADD ") { | |
| normalizedForAdd := strings.ReplaceAll(upperStmt, " ADD COLUMN ", " ADD ") | |
| addCount := strings.Count(normalizedForAdd, " ADD ") | |
| addConstraintCount := strings.Count(normalizedForAdd, " ADD CONSTRAINT ") | |
| addPolicyCount := strings.Count(normalizedForAdd, " ADD ROW DELETION POLICY ") | |
| if (addCount - addConstraintCount - addPolicyCount) != strings.Count(normalizedForAdd, " IF NOT EXISTS ") { | |
| logf(ctx, "%s: ALTER TABLE ADD [COLUMN] must use IF NOT EXISTS for every column. Statement: %s\n", f.fileName, snippet) | |
| ok = false | |
| } | |
| } | |
| if strings.Contains(upperStmt, " DROP ") { | |
| normalizedForDrop := strings.ReplaceAll(upperStmt, " DROP COLUMN ", " DROP ") | |
| dropCount := strings.Count(normalizedForDrop, " DROP ") | |
| dropConstraintCount := strings.Count(normalizedForDrop, " DROP CONSTRAINT ") | |
| dropPolicyCount := strings.Count(normalizedForDrop, " DROP ROW DELETION POLICY ") | |
| if (dropCount - dropConstraintCount - dropPolicyCount) != strings.Count(normalizedForDrop, " IF EXISTS ") { | |
| logf(ctx, "%s: ALTER TABLE DROP [COLUMN] must use IF EXISTS for every column. Statement: %s\n", f.fileName, snippet) | |
| ok = false | |
| } | |
| } | |
| } | |
| if (strings.HasPrefix(upperStmt, "CREATE INDEX") || strings.HasPrefix(upperStmt, "CREATE UNIQUE INDEX")) && !strings.Contains(upperStmt, "IF NOT EXISTS") { | |
| logf(ctx, "%s: CREATE INDEX must use IF NOT EXISTS. Statement: %s\n", f.fileName, snippet) | |
| ok = false | |
| } | |
| if strings.HasPrefix(upperStmt, "DROP TABLE") && !strings.HasPrefix(upperStmt, "DROP TABLE IF EXISTS") { | |
| logf(ctx, "%s: DROP TABLE must use IF EXISTS. Statement: %s\n", f.fileName, snippet) | |
| ok = false | |
| } | |
| if strings.HasPrefix(upperStmt, "DROP INDEX") && !strings.HasPrefix(upperStmt, "DROP INDEX IF EXISTS") { | |
| logf(ctx, "%s: DROP INDEX must use IF EXISTS. Statement: %s\n", f.fileName, snippet) | |
| ok = false | |
| } | |
| if strings.HasPrefix(upperStmt, "CREATE SEQUENCE") && !strings.HasPrefix(upperStmt, "CREATE SEQUENCE IF NOT EXISTS") { | |
| logf(ctx, "%s: CREATE SEQUENCE must use IF NOT EXISTS. Statement: %s\n", f.fileName, snippet) | |
| ok = false | |
| } | |
| if strings.HasPrefix(upperStmt, "DROP SEQUENCE") && !strings.HasPrefix(upperStmt, "DROP SEQUENCE IF EXISTS") { | |
| logf(ctx, "%s: DROP SEQUENCE must use IF EXISTS. Statement: %s\n", f.fileName, snippet) | |
| ok = false | |
| } | |
| } | |
| } | |
| return ok | |
| } | |
| // splitSQLStatements splits a SQL script into statements by semicolon, | |
| // correctly ignoring semicolons inside strings, identifiers, and comments. | |
| // TODO(msheshukov): Consider using a SQL parser which builds AST instead, like https://github.com/xwb1989/sqlparser | |
| func splitSQLStatements(content string) []string { | |
| var statements []string | |
| var currentStmt strings.Builder | |
| inSingleQuote := false | |
| inDoubleQuote := false | |
| inBacktick := false | |
| inSingleLineComment := false | |
| inMultiLineComment := false | |
| length := len(content) | |
| for i := 0; i < length; i++ { | |
| char := content[i] | |
| if inSingleLineComment { | |
| if char == '\n' { | |
| inSingleLineComment = false | |
| } | |
| continue | |
| } | |
| if inMultiLineComment { | |
| if char == '*' && i+1 < length && content[i+1] == '/' { | |
| inMultiLineComment = false | |
| i++ // skip '/' | |
| } | |
| continue | |
| } | |
| if inSingleQuote { | |
| if char == '\\' { | |
| if i+1 < length { | |
| i++ | |
| } | |
| } else if char == '\'' { | |
| inSingleQuote = false | |
| currentStmt.WriteByte(char) | |
| } | |
| continue | |
| } | |
| if inDoubleQuote { | |
| if char == '\\' { | |
| if i+1 < length { | |
| i++ | |
| } | |
| } else if char == '"' { | |
| inDoubleQuote = false | |
| currentStmt.WriteByte(char) | |
| } | |
| continue | |
| } | |
| if inBacktick { | |
| if char == '\\' { | |
| if i+1 < length { | |
| i++ | |
| } | |
| } else if char == '`' { | |
| inBacktick = false | |
| currentStmt.WriteByte(char) | |
| } | |
| continue | |
| } | |
| // Not in any string or comment | |
| if char == '-' && i+1 < length && content[i+1] == '-' { | |
| inSingleLineComment = true | |
| i++ // skip second '-' | |
| currentStmt.WriteByte(' ') // replace comment with space | |
| continue | |
| } | |
| if char == '/' && i+1 < length && content[i+1] == '*' { | |
| inMultiLineComment = true | |
| i++ // skip '*' | |
| currentStmt.WriteByte(' ') // replace comment with space | |
| continue | |
| } | |
| if char == '\'' { | |
| inSingleQuote = true | |
| currentStmt.WriteByte(char) | |
| continue | |
| } | |
| if char == '"' { | |
| inDoubleQuote = true | |
| currentStmt.WriteByte(char) | |
| continue | |
| } | |
| if char == '`' { | |
| inBacktick = true | |
| currentStmt.WriteByte(char) | |
| continue | |
| } | |
| if char == ';' { | |
| stmt := strings.TrimSpace(currentStmt.String()) | |
| if stmt != "" { | |
| statements = append(statements, stmt) | |
| } | |
| currentStmt.Reset() | |
| continue | |
| } | |
| currentStmt.WriteByte(char) | |
| } | |
| stmt := strings.TrimSpace(currentStmt.String()) | |
| if stmt != "" { | |
| statements = append(statements, stmt) | |
| } | |
| return statements | |
| } | |
| // checkJSDebugging goes through all touched lines and returns false if any TS or JS files contain | |
| // refinements of debugging that we don't want to check in. | |
| func checkJSDebugging(ctx context.Context, files []fileWithChanges) bool { | |
| debuggingCalls := []string{"debugger;", "it.only(", "describe.only("} | |
| targetFileExts := []string{".ts", ".js"} | |
| ok := true | |
| for _, f := range files { | |
| if !contains(targetFileExts, filepath.Ext(f.fileName)) { | |
| continue | |
| } | |
| for _, line := range f.touchedLines { | |
| for _, call := range debuggingCalls { | |
| if strings.Contains(line.contents, call) { | |
| logf(ctx, "%s:%d debugging code found (%s)\n", f.fileName, line.num, call) | |
| ok = false | |
| } | |
| } | |
| } | |
| } | |
| return ok | |
| } | |
| // checkNonASCII goes through all touched lines and returns false if any of them contain non-ASCII | |
| // characters (except for file formats that support things like UTF-8). | |
| func checkNonASCII(ctx context.Context, files []fileWithChanges) bool { | |
| // This list can grow if other file extensions are OK with non-ascii (UTF-8) characters | |
| ignoreFileExts := []string{".go"} | |
| ok := true | |
| for _, f := range files { | |
| if contains(ignoreFileExts, filepath.Ext(f.fileName)) { | |
| continue | |
| } | |
| for _, line := range f.touchedLines { | |
| // https://stackoverflow.com/a/53069799/1447621 | |
| for i := 0; i < len(line.contents); i++ { | |
| if line.contents[i] > '\u007F' { // unicode.MaxASCII | |
| // Report both line number and (1-indexed) byte offset | |
| logf(ctx, "%s:%d:%d Non ASCII character found\n", f.fileName, line.num, i+1) | |
| ok = false | |
| break | |
| } | |
| } | |
| } | |
| } | |
| return ok | |
| } | |
| // runCopyrightHeaders adds missing copyright headers to any changed golang files. It | |
| // returns false if adding headers fails or produces any diffs. | |
| func runCopyrightHeaders(ctx context.Context, files []fileWithChanges, workspaceRoot, branchBaseCommit string) bool { | |
| var goFiles []string | |
| for _, f := range files { | |
| if filepath.Ext(f.fileName) == ".go" { | |
| goFiles = append(goFiles, f.fileName) | |
| } | |
| } | |
| if len(goFiles) == 0 { | |
| return true | |
| } | |
| if _, err := copyright_headers.AddCopyrightHeadersToGoFiles(ctx, workspaceRoot, goFiles, false); err != nil { | |
| logf(ctx, "Failed to add copyright headers: %s\n", err) | |
| return false | |
| } | |
| changedFiles, _ := computeDiffFiles(ctx, branchBaseCommit) | |
| return checkUnchanged(ctx, "CopyrightHeaders", files, changedFiles) | |
| } | |
| // runBuildifier uses a provided buildifier path to reformat our BUILD.bazel and .bzl files as | |
| // well as check them for linting errors. If buildifier has no output and a non-zero exit code, | |
| // that is interpreted as "all good" and we return true. If there are issues, we print the | |
| // buildifier output (which has files and line numbers) and return false. | |
| func runBuildifier(ctx context.Context, files []fileWithChanges, branchBaseCommit string) bool { | |
| buildifierPath := buildifier.MustFind() | |
| args := []string{"-lint=warn", "-mode=fix"} | |
| foundAny := false | |
| // Note: This duplicates exlude_patterns in //BUILD.bazel, but because the | |
| // file list passed to buildifier overrides any exlude_patterns we need to | |
| // avoid including those files here. | |
| excludes := []string{ | |
| "bazel/rbe/generated/", | |
| } | |
| for _, f := range files { | |
| if util.HasPrefixAny(f.fileName, excludes) { | |
| continue | |
| } | |
| if filepath.Base(f.fileName) == "BUILD.bazel" || filepath.Ext(f.fileName) == ".bzl" { | |
| args = append(args, f.fileName) | |
| foundAny = true | |
| } | |
| } | |
| if !foundAny { | |
| return true | |
| } | |
| cmd := exec.CommandContext(ctx, buildifierPath, args...) | |
| output, err := cmd.CombinedOutput() | |
| if err != nil { | |
| log(ctx, string(output)) | |
| log(ctx, "Buildifier linting errors detected!\n") | |
| return false | |
| } | |
| changedFiles, _ := computeDiffFiles(ctx, branchBaseCommit) | |
| return checkUnchanged(ctx, "Buildifier", files, changedFiles) | |
| } | |
| // runGoimports runs goimports on any changed golang files. It returns false if goimports fails or | |
| // produces any diffs. | |
| func runGoimports(ctx context.Context, files []fileWithChanges, workspaceRoot, branchBaseCommit string) bool { | |
| // `goimports` shells out to `go`, so we need to ensure that `go` exists. | |
| goCmd := exec.CommandContext(ctx, "bazelisk", "run", "--config=mayberemote", "//:go", "--", "version") | |
| if output, err := goCmd.CombinedOutput(); err != nil { | |
| logf(ctx, "go failed with: %s", output) | |
| return false | |
| } | |
| // -w means "write", as in, modify the files that need formatting. | |
| goBin, err := rules_go.Find() | |
| if err != nil { | |
| logf(ctx, "Failed to find Go: %s", err.Error()) | |
| return false | |
| } | |
| bazelGoPath := filepath.Dir(goBin) | |
| runUnderCmd := fmt.Sprintf("cd %s && export PATH=\"%s:$PATH\" &&", workspaceRoot, bazelGoPath) | |
| args := []string{"run", "--config=mayberemote", "//:goimports", "--run_under=" + runUnderCmd, "--", "-w"} | |
| foundAny := false | |
| for _, f := range files { | |
| if filepath.Ext(f.fileName) == ".go" { | |
| args = append(args, f.fileName) | |
| foundAny = true | |
| } | |
| } | |
| if !foundAny { | |
| return true | |
| } | |
| cmd := exec.CommandContext(ctx, "bazelisk", args...) | |
| output, err := cmd.CombinedOutput() | |
| if err != nil { | |
| log(ctx, string(output)) | |
| log(ctx, "goimports failed!\n") | |
| return false | |
| } | |
| changedFiles, _ := computeDiffFiles(ctx, branchBaseCommit) | |
| return checkUnchanged(ctx, "Goimports", files, changedFiles) | |
| } | |
| // runNpmCi runs "npm ci" to ensure that the "node_modules" directory exists. | |
| func runNpmCi(ctx context.Context) bool { | |
| cmd := exec.CommandContext(ctx, "bazelisk", "run", "--config=mayberemote", "//:npm", "--", "ci") | |
| output, err := cmd.CombinedOutput() | |
| if err != nil { | |
| log(ctx, "Command \"npm ci\" failed. Output:\n") | |
| log(ctx, string(output)) | |
| return false | |
| } | |
| return true | |
| } | |
| // runESLint runs eslint on any changed files. It returns false if prettier | |
| // returns a non-zero error code. | |
| func runESLint(ctx context.Context, files []fileWithChanges, workspaceRoot, branchBaseCommit string) bool { | |
| ignoreFiles := []string{ | |
| // Generated by proto compiler, has different style rules. | |
| "pinpoint/webui/app/gateway/gateway.ts", | |
| } | |
| args := []string{"run", "--config=mayberemote", "//:npx", "--", "eslint", "--quiet"} | |
| numFiles := 0 | |
| for _, f := range files { | |
| if contains(ignoreFiles, f.fileName) { | |
| continue | |
| } | |
| if filepath.Ext(f.fileName) == ".ts" { | |
| args = append(args, f.fileName) | |
| numFiles++ | |
| } | |
| } | |
| if numFiles == 0 { | |
| return true | |
| } | |
| cmd := exec.CommandContext(ctx, "bazelisk", args...) | |
| output, err := cmd.CombinedOutput() | |
| if err != nil { | |
| log(ctx, string(output)) | |
| log(ctx, "eslint failed!\n") | |
| return false | |
| } | |
| return true | |
| } | |
| // runStylelint runs stylelint on any changed SCSS, CSS, or TS files. It returns | |
| // false if stylelint returns a non-zero error code. | |
| func runStylelint(ctx context.Context, files []fileWithChanges, workspaceRoot, branchBaseCommit string) bool { | |
| var allFiles []string | |
| var tsFiles []string | |
| for _, f := range files { | |
| ext := filepath.Ext(f.fileName) | |
| if ext == ".scss" || ext == ".css" || ext == ".ts" { | |
| allFiles = append(allFiles, f.fileName) | |
| if ext == ".ts" { | |
| tsFiles = append(tsFiles, f.fileName) | |
| } | |
| } | |
| } | |
| if len(allFiles) == 0 { | |
| return true | |
| } | |
| args := append([]string{"run", "--config=mayberemote", "//:npx", "--", "stylelint", "--quiet", "--fix"}, allFiles...) | |
| cmd := exec.CommandContext(ctx, "bazelisk", args...) | |
| output, err := cmd.CombinedOutput() | |
| if len(tsFiles) > 0 { | |
| // PostCSS-Lit AST serializer reconstructs TS template strings with class-relative indentation. | |
| // Immediately run Prettier on the touched TS files to normalize formatting back to Prettier rules. | |
| pArgs := append([]string{"run", "--config=mayberemote", "//:npx", "--", "prettier", "--write"}, tsFiles...) | |
| pCmd := exec.CommandContext(ctx, "bazelisk", pArgs...) | |
| pOutput, pErr := pCmd.CombinedOutput() | |
| if pErr != nil { | |
| log(ctx, string(pOutput)) | |
| log(ctx, "prettier failed!\n") | |
| return false | |
| } | |
| } | |
| if err != nil { | |
| log(ctx, string(output)) | |
| log(ctx, "stylelint failed!\n") | |
| return false | |
| } | |
| // Recalculate diffs and fail if stylelint modified anything | |
| changedFiles, _ := computeDiffFiles(ctx, branchBaseCommit) | |
| return checkUnchanged(ctx, "Stylelint", files, changedFiles) | |
| } | |
| func filterPnpmLock(files []fileWithChanges) []fileWithChanges { | |
| var out []fileWithChanges | |
| for _, f := range files { | |
| if filepath.Base(f.fileName) != "pnpm-lock.yaml" { | |
| out = append(out, f) | |
| } | |
| } | |
| return out | |
| } | |
| // runPrettier runs prettier --write on any changed files. It returns false if | |
| // prettier returns a non-zero error code. | |
| func runPrettier(ctx context.Context, files []fileWithChanges, workspaceRoot, branchBaseCommit string) bool { | |
| ignoreFiles := []string{ | |
| // Generated by proto compiler, has different formatting rules. | |
| "pinpoint/webui/app/gateway/gateway.ts", | |
| } | |
| args := []string{"run", "--config=mayberemote", "//:npx", "--", "prettier", "--write", "--ignore-unknown"} | |
| for _, f := range files { | |
| if contains(ignoreFiles, f.fileName) { | |
| logf(ctx, "Skipping Prettier for %s\n", f.fileName) | |
| continue | |
| } | |
| if filepath.Ext(f.fileName) == ".bazel" || filepath.Ext(f.fileName) == ".bzl" || filepath.Ext(f.fileName) == ".go" { | |
| logf(ctx, "Skipping Prettier for %s\n", f.fileName) | |
| continue | |
| } | |
| args = append(args, f.fileName) | |
| } | |
| cmd := exec.CommandContext(ctx, "bazelisk", args...) | |
| output, err := cmd.CombinedOutput() | |
| if err != nil { | |
| log(ctx, string(output)) | |
| log(ctx, "prettier failed!\n") | |
| return false | |
| } | |
| changedFiles, _ := computeDiffFiles(ctx, branchBaseCommit) | |
| // Ignore pnpm-lock.yaml changes as they are side effects of running npx | |
| files = filterPnpmLock(files) | |
| changedFiles = filterPnpmLock(changedFiles) | |
| return checkUnchanged(ctx, "Prettier", files, changedFiles) | |
| } | |
| // runGofmt runs gofmt on any changed golang files. It returns false if gofmt fails or | |
| // produces any diffs. | |
| func runGofmt(ctx context.Context, files []fileWithChanges, branchBaseCommit string) bool { | |
| // -s means "simplify" | |
| // -w means "write", as in, modify the files that need formatting. | |
| args := []string{"run", "--config=mayberemote", "//:gofmt", "--", "-s", "-w"} | |
| foundAny := false | |
| for _, f := range files { | |
| if filepath.Ext(f.fileName) == ".go" { | |
| args = append(args, f.fileName) | |
| foundAny = true | |
| } | |
| } | |
| if !foundAny { | |
| return true | |
| } | |
| cmd := exec.CommandContext(ctx, "bazelisk", args...) | |
| output, err := cmd.CombinedOutput() | |
| if err != nil { | |
| log(ctx, string(output)) | |
| log(ctx, "gofmt failed!\n") | |
| return false | |
| } | |
| changedFiles, _ := computeDiffFiles(ctx, branchBaseCommit) | |
| return checkUnchanged(ctx, "Gofmt", files, changedFiles) | |
| } | |
| // runGoVet runs `go vet` on all golang files. It returns false if go vet fails. | |
| func runGoVet(ctx context.Context, files []fileWithChanges, branchBaseCommit string) bool { | |
| args := []string{"run", "--config=mayberemote", "//:go", "--", "vet", "./..."} | |
| cmd := exec.CommandContext(ctx, "bazelisk", args...) | |
| output, err := cmd.CombinedOutput() | |
| if err != nil { | |
| log(ctx, string(output)) | |
| log(ctx, "go vet failed!\n") | |
| return false | |
| } | |
| return true | |
| } | |
| // runErrcheck runs `errcheck` on all golang files. It returns false if errcheck fails. | |
| func runErrcheck(ctx context.Context) bool { | |
| args := []string{"run", "--config=mayberemote", "//:errcheck", "--", "-ignore", ":Close", "go.skia.org/infra/..."} | |
| cmd := exec.CommandContext(ctx, "bazelisk", args...) | |
| output, err := cmd.CombinedOutput() | |
| if err != nil { | |
| log(ctx, string(output)) | |
| log(ctx, "errcheck failed!\n") | |
| return false | |
| } | |
| return true | |
| } | |
| // runGoGenerate runs `go generate ./...` and returns false if it fails or produces any diffs. | |
| func runGoGenerate(ctx context.Context, files []fileWithChanges, branchBaseCommit string) bool { | |
| args := []string{"run", "--config=mayberemote", "//:go", "--", "generate", "./..."} | |
| cmd := exec.CommandContext(ctx, "bazelisk", args...) | |
| output, err := cmd.CombinedOutput() | |
| if err != nil { | |
| log(ctx, string(output)) | |
| log(ctx, "go generate failed!\n") | |
| return false | |
| } | |
| changedFiles, _ := computeDiffFiles(ctx, branchBaseCommit) | |
| return checkUnchanged(ctx, "go generate", files, changedFiles) | |
| } | |
| // runAutoreview runs the AI-powered code review tool. It returns false if autoreview fails or finds a blocker. | |
| func runAutoreview(ctx context.Context, branchBaseCommit string) bool { | |
| value := os.Getenv("AI_PRESUBMIT_CHECK") | |
| if isTrue, err := strconv.ParseBool(value); err != nil || !isTrue { | |
| log(ctx, "Skip AI review.\n") | |
| return true | |
| } | |
| args := []string{ | |
| "run", | |
| "--config=mayberemote", | |
| "//cmd/autoreview", | |
| "--", | |
| "--base-commit=" + branchBaseCommit, | |
| "--show-lgtm=false", | |
| "--show-warnings=false", | |
| } | |
| cmd := exec.CommandContext(ctx, "bazelisk", args...) | |
| output, err := cmd.CombinedOutput() | |
| if err != nil { | |
| log(ctx, string(output)) | |
| log(ctx, "autoreview failed or found a blocker!\n") | |
| return false | |
| } | |
| return true | |
| } | |
| // runGazelle uses gazelle (and our custom gazelle plugin) to regenerate BUILD.bazel files for our | |
| // go files as well as our Typescript and SCSS rules. Gazelle is idempotent, so if a user has | |
| // already generated BUILD.bazel files, there should be no diffs. If the user forgot to do so, | |
| // there could be diffs or new files added. This function returns false if that is the case or true | |
| // if Gazelle made no modifications. | |
| func runGazelle(ctx context.Context, changedFiles []fileWithChanges, deletedFiles []string, branchBaseCommit string) bool { | |
| // If these change, we should regenerate everything (slower, but more sound) | |
| globalFilesToCheck := []string{"WORKSPACE", "WORKSPACE.bazel", "go.mod", "go.sum"} | |
| globalExtensionsToCheck := []string{".bzl"} | |
| // If these change, then we should only need to update their containing folders. | |
| localFilesToCheck := []string{"BUILD.bazel"} | |
| localExtensionsToCheck := []string{".go", ".ts", ".scss"} | |
| var foldersToCheck []string | |
| regenEverything := len(deletedFiles) > 0 | |
| if !regenEverything { | |
| for _, f := range changedFiles { | |
| if contains(globalFilesToCheck, filepath.Base(f.fileName)) || contains(globalExtensionsToCheck, filepath.Ext(f.fileName)) { | |
| regenEverything = true | |
| break | |
| } | |
| if contains(localFilesToCheck, filepath.Base(f.fileName)) || contains(localExtensionsToCheck, filepath.Ext(f.fileName)) { | |
| folder := filepath.Dir(f.fileName) | |
| if !contains(foldersToCheck, folder) { | |
| foldersToCheck = append(foldersToCheck, folder) | |
| } | |
| } | |
| } | |
| } | |
| // No need to run gazelle | |
| if !regenEverything && len(foldersToCheck) == 0 { | |
| return true | |
| } | |
| args := []string{"run", "--config=mayberemote", "//:gazelle", "--", "update"} | |
| if regenEverything { | |
| // Reminder: we have changed directory into the repo root | |
| args = append(args, "./") | |
| } else { | |
| args = append(args, foldersToCheck...) | |
| } | |
| cmd := exec.CommandContext(ctx, "bazelisk", args...) | |
| output, err := cmd.CombinedOutput() | |
| if err != nil { | |
| log(ctx, string(output)) | |
| log(ctx, "Could not regenerate BUILD.bazel changedFiles using gazelle!\n") | |
| return false | |
| } | |
| if newChangedFiles, _ := computeDiffFiles(ctx, branchBaseCommit); !deepequal.DeepEqual(changedFiles, newChangedFiles) { | |
| log(ctx, "Gazelle caused changes. Please inspect them (git diff) and commit if ok.\n") | |
| return false | |
| } | |
| for _, f := range findUntrackedFiles(ctx) { | |
| if filepath.Base(f) == "BUILD.bazel" { | |
| log(ctx, "Gazelle created new BUILD.bazel files. Please inspect these and check them in.\n") | |
| return false | |
| } | |
| } | |
| return true | |
| } | |
| // contains returns true if the given slice has the provided element in it. | |
| func contains[T string](a []T, s T) bool { | |
| for _, x := range a { | |
| if x == s { | |
| return true | |
| } | |
| } | |
| return false | |
| } | |
| // checkUnchanged verifies if the files before and after a tool runs are identical. | |
| // If there are differences, it logs the modified files with commit instructions and returns false. | |
| func checkUnchanged(ctx context.Context, toolName string, before, after []fileWithChanges) bool { | |
| if deepequal.DeepEqual(before, after) { | |
| return true | |
| } | |
| modified := modifiedFileNames(before, after) | |
| logf(ctx, "%s caused additional changes in: %s. Please inspect them (git diff) and commit if ok.\n", toolName, strings.Join(modified, ", ")) | |
| return false | |
| } | |
| // modifiedFileNames compares the fileWithChanges slices before and after a tool runs | |
| // and returns the names of the files that were modified or added by the tool. | |
| func modifiedFileNames(before, after []fileWithChanges) []string { | |
| beforeMap := make(map[string][]lineOfCode) | |
| for _, f := range before { | |
| beforeMap[f.fileName] = f.touchedLines | |
| } | |
| afterMap := make(map[string]bool) | |
| var modified []string | |
| for _, f := range after { | |
| afterMap[f.fileName] = true | |
| if oldLines, ok := beforeMap[f.fileName]; !ok || !deepequal.DeepEqual(oldLines, f.touchedLines) { | |
| modified = append(modified, f.fileName) | |
| } | |
| } | |
| for _, f := range before { | |
| if !afterMap[f.fileName] { | |
| modified = append(modified, f.fileName) | |
| } | |
| } | |
| sort.Strings(modified) | |
| return modified | |
| } | |
| type contextKeyType string | |
| const outputWriterKey contextKeyType = "outputWriter" | |
| const verboseKey contextKeyType = "verbose" | |
| // withVerbose sets the verbose flag in the context. | |
| func withVerbose(ctx context.Context, v bool) context.Context { | |
| return context.WithValue(ctx, verboseKey, v) | |
| } | |
| // isVerbose returns true if the verbose flag is set in the context. | |
| func isVerbose(ctx context.Context) bool { | |
| v, ok := ctx.Value(verboseKey).(bool) | |
| return ok && v | |
| } | |
| // withOutputWriter registers the given writer to the context. See also logf. | |
| func withOutputWriter(ctx context.Context, w io.Writer) context.Context { | |
| return context.WithValue(ctx, outputWriterKey, w) | |
| } | |
| // logf takes the writer on the context and writes the given format and arguments to it. This allows | |
| // unit tests to intercept logged output if necessary. It panics if a writer was not registered | |
| // using withOutputWriter. | |
| func logf(ctx context.Context, format string, args ...interface{}) { | |
| log(ctx, fmt.Sprintf(format, args...)) | |
| } | |
| // log takes the writer on the context and writes the string to it. This allows | |
| // unit tests to intercept logged output if necessary. It panics if a writer was | |
| // not registered using withOutputWriter. | |
| func log(ctx context.Context, msg string) { | |
| w, ok := ctx.Value(outputWriterKey).(io.Writer) | |
| if !ok { | |
| panic("Must set outputWriter on ctx") | |
| } | |
| _, err := fmt.Fprint(w, msg) | |
| if err != nil { | |
| panic("Error while logging " + err.Error()) | |
| } | |
| } |