Repository navigation
fix(ci): lint complete pull request diffs #1852
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
skevetter
wants to merge
2
commits into
main
Choose a base branch
from
fix/ci-complete-pr-lint
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,297 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "bufio" | ||
| "crypto/sha256" | ||
| "encoding/json" | ||
| "errors" | ||
| "fmt" | ||
| "io" | ||
| "os" | ||
| "os/exec" | ||
| "path/filepath" | ||
| "regexp" | ||
| "strings" | ||
| "unicode" | ||
| "unicode/utf8" | ||
| ) | ||
|
|
||
| var ( | ||
| lintCommitID = regexp.MustCompile(`^[0-9a-fA-F]{40}$`) | ||
| lintSafePath = regexp.MustCompile( | ||
| `^(?:/[A-Za-z0-9_.-][A-Za-z0-9_./-]*|[A-Za-z]:/[A-Za-z0-9_./-]*)$`, | ||
| ) | ||
| ) | ||
|
|
||
| type lintPatchRef struct { | ||
| SHA string `json:"sha"` | ||
| } | ||
|
|
||
| type lintPatchPullRequest struct { | ||
| Base lintPatchRef `json:"base"` | ||
| Head lintPatchRef `json:"head"` | ||
| } | ||
|
|
||
| type lintPatchEvent struct { | ||
| PullRequest *lintPatchPullRequest `json:"pull_request"` | ||
| } | ||
|
|
||
| type lintPatchInput struct { | ||
| repo string | ||
| eventPath string | ||
| runnerTemp string | ||
| } | ||
|
|
||
| type lintPatchResult struct { | ||
| base, head, checkout, mergeBase, path, digest string | ||
| } | ||
|
|
||
| func lintPatchCLI(args []string, stdout, stderr io.Writer) int { | ||
| if len(args) != 0 { | ||
| _, _ = fmt.Fprintln(stderr, "lint-patch: unexpected arguments") | ||
| return 2 | ||
| } | ||
| temp := os.Getenv("RUNNER_TEMP") | ||
| if !filepath.IsAbs(temp) || filepath.Clean(temp) != temp || | ||
| !lintSafePath.MatchString(filepath.ToSlash(temp)) { | ||
| _, _ = fmt.Fprintln(stderr, "lint-patch: RUNNER_TEMP must be a safe absolute directory") | ||
| return 1 | ||
| } | ||
| repo, err := os.Getwd() | ||
| if err != nil { | ||
| _, _ = fmt.Fprintln(stderr, "lint-patch: cannot determine checkout directory") | ||
| return 1 | ||
| } | ||
| result, err := generateLintPatch(lintPatchInput{ | ||
| repo: repo, eventPath: os.Getenv("GITHUB_EVENT_PATH"), | ||
| runnerTemp: temp, | ||
| }) | ||
| if err != nil { | ||
| _, _ = fmt.Fprintf(stderr, "lint-patch: %v\n", err) | ||
| return 1 | ||
| } | ||
| _, _ = fmt.Fprintf( | ||
| stderr, | ||
| "lint-patch: base=%s head=%s checkout=%s merge_base=%s patch_sha256=%s\n", | ||
| result.base, | ||
| result.head, | ||
| result.checkout, | ||
| result.mergeBase, | ||
| result.digest, | ||
| ) | ||
| if _, err := fmt.Fprintf( | ||
| stdout, | ||
| "args=--new-from-patch=%s --new=false --new-from-rev= --new-from-merge-base=\n", | ||
| result.path, | ||
| ); err != nil { | ||
| _, _ = fmt.Fprintln(stderr, "lint-patch: cannot write action output") | ||
| return 1 | ||
| } | ||
| return 0 | ||
| } | ||
|
|
||
| func generateLintPatch(input lintPatchInput) (lintPatchResult, error) { | ||
| var result lintPatchResult | ||
| base, head, err := readLintPatchEvent(input.eventPath) | ||
| if err != nil { | ||
| return result, err | ||
| } | ||
| result.base, result.head = base, head | ||
| checkout, err := validateLintCheckout(input.repo, head) | ||
| if err != nil { | ||
| return result, err | ||
| } | ||
| result.checkout = checkout | ||
| mergeBase, err := uniqueLintMergeBase(input.repo, base, head) | ||
| if err != nil { | ||
| return result, err | ||
| } | ||
| result.mergeBase = mergeBase | ||
| path, digest, err := writeLintPatch(input.repo, input.runnerTemp, mergeBase, head) | ||
| if err != nil { | ||
| return result, err | ||
| } | ||
| current, err := validateLintCheckout(input.repo, head) | ||
| if err != nil || current != checkout { | ||
| return result, errors.New("checkout changed while generating pull request patch") | ||
| } | ||
| result.path, result.digest = path, digest | ||
| return result, nil | ||
| } | ||
|
|
||
| func readLintPatchEvent(path string) (string, string, error) { | ||
| if path == "" { | ||
| return "", "", errors.New("missing pull request event path") | ||
| } | ||
| file, err := os.Open(path) | ||
| if err != nil { | ||
| return "", "", errors.New("cannot open pull request event") | ||
| } | ||
| defer func() { _ = file.Close() }() | ||
| var event lintPatchEvent | ||
| decoder := json.NewDecoder(file) | ||
| if err := decoder.Decode(&event); err != nil || event.PullRequest == nil { | ||
| return "", "", errors.New("invalid pull request event") | ||
| } | ||
| if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) { | ||
| return "", "", errors.New("invalid pull request event") | ||
| } | ||
| base := event.PullRequest.Base.SHA | ||
| head := event.PullRequest.Head.SHA | ||
| if !lintCommitID.MatchString(base) || !lintCommitID.MatchString(head) { | ||
| return "", "", errors.New("pull request base and head must be full SHA1 hashes") | ||
| } | ||
| return strings.ToLower(base), strings.ToLower(head), nil | ||
| } | ||
|
|
||
| func validateLintCheckout(repo, head string) (string, error) { | ||
| prefix, err := lintGitOutput(repo, "rev-parse", "--show-prefix") | ||
| if err != nil || prefix != "" { | ||
| return "", errors.New("checkout must be the repository root") | ||
| } | ||
| checkout, err := lintGitOutput(repo, "rev-parse", "--verify", "HEAD^{commit}") | ||
| if err != nil || checkout != head { | ||
| return "", errors.New("checkout does not match pull request head") | ||
| } | ||
| return checkout, nil | ||
| } | ||
|
|
||
| func uniqueLintMergeBase(repo, base, head string) (string, error) { | ||
| output, err := lintGitOutput(repo, "merge-base", "--all", base, head) | ||
| if err != nil { | ||
| return "", errors.New("cannot compute pull request merge base") | ||
| } | ||
| parts := strings.Fields(output) | ||
| if len(parts) != 1 || !lintCommitID.MatchString(parts[0]) { | ||
| return "", errors.New("pull request must have exactly one merge base") | ||
|
skevetter marked this conversation as resolved.
Resolved
|
||
| } | ||
| return parts[0], nil | ||
| } | ||
|
|
||
| func lintGitOutput(repo string, args ...string) (string, error) { | ||
| cmd := exec.Command("git", args...) | ||
| cmd.Dir = repo | ||
| output, err := cmd.Output() | ||
| if err != nil { | ||
| return "", err | ||
| } | ||
| return strings.TrimSpace(string(output)), nil | ||
| } | ||
|
|
||
| func writeLintPatch(repo, temp, mergeBase, head string) (string, string, error) { | ||
| if err := validateLintPatchPaths(repo, mergeBase, head); err != nil { | ||
| return "", "", err | ||
| } | ||
| file, path, err := openLintPatch(temp) | ||
| if err != nil { | ||
| return "", "", err | ||
| } | ||
| hash := sha256.New() | ||
| cmd := exec.Command( | ||
| "git", | ||
| "--no-pager", | ||
| "-c", | ||
| "core.quotePath=false", | ||
| "diff", | ||
| "--no-ext-diff", | ||
| "--no-textconv", | ||
| "--no-color", | ||
| "--no-relative", | ||
| "--src-prefix=a/", | ||
| "--dst-prefix=b/", | ||
| "--find-renames", | ||
| "-l0", | ||
| "--unified=3", | ||
| mergeBase, | ||
| head, | ||
| "--", | ||
| ) | ||
| cmd.Dir = repo | ||
| cmd.Stdout = io.MultiWriter(file, hash) | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
| runErr := cmd.Run() | ||
| info, statErr := file.Stat() | ||
| closeErr := file.Close() | ||
| if runErr != nil || statErr != nil || closeErr != nil { | ||
| return "", "", errors.New("cannot generate complete pull request patch") | ||
| } | ||
| if info.Size() == 0 { | ||
| return "", "", errors.New("pull request patch is empty") | ||
| } | ||
| return path, fmt.Sprintf("%x", hash.Sum(nil)), nil | ||
| } | ||
|
|
||
| func openLintPatch(temp string) (*os.File, string, error) { | ||
| if !filepath.IsAbs(temp) || filepath.Clean(temp) != temp || | ||
| strings.HasPrefix(filepath.ToSlash(temp), "//") { | ||
| return nil, "", errors.New("RUNNER_TEMP must be a safe absolute directory") | ||
| } | ||
| dir, err := os.MkdirTemp(temp, "devsy-lint-patch-") | ||
| if err != nil { | ||
| return nil, "", errors.New("cannot create private patch directory") | ||
| } | ||
| path := filepath.Join(dir, "pull-request.patch") | ||
| file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) | ||
| if err != nil { | ||
| return nil, "", errors.New("cannot create patch file") | ||
| } | ||
| return file, filepath.ToSlash(path), nil | ||
| } | ||
|
|
||
| func validateLintPatchPaths(repo, mergeBase, head string) error { | ||
| cmd := exec.Command( | ||
| "git", "--no-pager", "-c", "core.quotePath=false", "diff", | ||
| "--no-ext-diff", "--no-textconv", "--no-color", "--no-relative", | ||
| "--find-renames", "-l0", "--name-only", "-z", "--diff-filter=d", | ||
| mergeBase, head, "--", | ||
| ) | ||
| cmd.Dir = repo | ||
| pipe, err := cmd.StdoutPipe() | ||
| if err != nil { | ||
| return errors.New("cannot open pull request path list") | ||
| } | ||
| if err := cmd.Start(); err != nil { | ||
| return errors.New("cannot start pull request path list") | ||
| } | ||
| pathErr := checkLintPatchPaths(pipe) | ||
| if pathErr != nil { | ||
| _ = pipe.Close() | ||
| _ = cmd.Process.Kill() | ||
| } | ||
| waitErr := cmd.Wait() | ||
| if pathErr != nil { | ||
| return pathErr | ||
| } | ||
| if waitErr != nil { | ||
| return errors.New("cannot validate pull request Go paths for lint") | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| func checkLintPatchPaths(src io.Reader) error { | ||
| reader := bufio.NewReader(src) | ||
| for { | ||
| path, err := reader.ReadString(0) | ||
| if errors.Is(err, io.EOF) && path == "" { | ||
| return nil | ||
| } | ||
| if err != nil || !strings.HasSuffix(path, "\x00") { | ||
| return errors.New("invalid pull request path list") | ||
| } | ||
| path = strings.TrimSuffix(path, "\x00") | ||
| if strings.HasSuffix(path, ".go") && !lintRepresentableGoPath(path) { | ||
| return errors.New("pull request Go path cannot be represented in lint patch") | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func lintRepresentableGoPath(path string) bool { | ||
| if !utf8.ValidString(path) || strings.ContainsAny(path, " \"\\") { | ||
| return false | ||
| } | ||
| for _, char := range path { | ||
| if unicode.IsControl(char) { | ||
| return false | ||
| } | ||
| } | ||
| return true | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.