diff --git a/README.md b/README.md index c42a5910..cc99ae23 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,8 @@ archfit init # write .archfit.yaml from the code; today's errors become exce archfit check # the change: pass, fail, or unknown ``` +This is the local-only path. For checks on GitHub pull requests, run `archfit setup` instead: it writes the policy and the workflow and opens the setup pull request. See [Try it on your pull request](docs/try-it-on-your-pull-request.md). + Read the policy `init` writes, then open a pull request with it. [Getting started](docs/getting-started.md) has the other ways to install (`go install` needs Go 1.27 or newer), the tools each language needs, the agent hooks, and CI. ## What archfit is and is not diff --git a/cmd/archfit/init_owner_test.go b/cmd/archfit/init_owner_test.go index f9076ac9..bb40e5c4 100644 --- a/cmd/archfit/init_owner_test.go +++ b/cmd/archfit/init_owner_test.go @@ -10,6 +10,7 @@ import ( "time" "github.com/coupling-dev/archfit/internal/config/policyfile" + "github.com/coupling-dev/archfit/internal/testutil" "github.com/coupling-dev/archfit/internal/toolrun" ) @@ -50,6 +51,14 @@ func TestInitOwners(t *testing.T) { if code != 0 || len(policy.Owners) != 1 || policy.Owners[0] != tc.owner || !strings.Contains(out.String(), tc.next) || !strings.Contains(out.String(), tc.notice) { t.Fatalf("exit %d policy %s output %s stderr %s", code, data, out.String(), errout.String()) } + notes := strings.Count(out.String(), "Owners approve requests: name an owner who does not write most of the changes") + if wantNotes := map[bool]int{true: 0, false: 1}[tc.owner == ""]; notes != wantNotes || + (notes == 1 && !strings.Contains(out.String(), "owner: "+tc.owner+". Owners approve requests")) { + t.Errorf("sole owner note %d times, want %d:\n%s", notes, wantNotes, out.String()) + } + if words := testutil.StoryNotUsedIn(out.String()); len(words) > 0 { + t.Errorf("init vocabulary %v in:\n%s", words, out.String()) + } }) } } diff --git a/cmd/archfit/init_v3.go b/cmd/archfit/init_v3.go index 5dda3199..d1218c07 100644 --- a/cmd/archfit/init_v3.go +++ b/cmd/archfit/init_v3.go @@ -111,6 +111,9 @@ func runInit(ctx context.Context, deps *appDeps, co checkout, noHooks, forSetup if !forSetup { writeOwnerDecisions(&b, draft.File) } + if owners := draft.File.Owners; len(owners) == 1 && owners[0] != identity.PlaceholderOwner { + b.WriteString(soleOwnerNote(owners[0]) + "\n") + } if draft.File.Owners[0] == identity.PlaceholderOwner { b.WriteString("no person is named as an owner yet\n") if forSetup { @@ -125,6 +128,12 @@ func runInit(ctx context.Context, deps *appDeps, co checkout, noHooks, forSetup return b.String(), nil } +// soleOwnerNote says once what the one owner init named does: an owner who +// writes most changes would approve their own requests. +func soleOwnerNote(login string) string { + return "owner: " + login + ". Owners approve requests: name an owner who does not write most of the changes" +} + // initFresh writes the first policy of a repository. func (co checkout) initFresh(ctx context.Context, b *strings.Builder) (policy3.Result, error) { owner, verified := identity.OwnerIdentity(ctx, co.root, co.runner) diff --git a/cmd/archfit/request.go b/cmd/archfit/request.go index 1fbdb6f2..373c2944 100644 --- a/cmd/archfit/request.go +++ b/cmd/archfit/request.go @@ -77,7 +77,7 @@ func (c *RequestCmd) Run(deps *appDeps) error { } out, err := svc.Ask(ctx, request.Input{Reason: c.Message, Expires: c.Expires}) if err != nil { - return noVerdict(err) + return noVerdict(withReply(err, out.Request)) } if out.URL != "" { _, err := fmt.Fprintln(deps.Stdout, out.URL) @@ -96,6 +96,19 @@ func (c *RequestCmd) Run(deps *appDeps) error { return exitWith(exitUnknown) } +// withReply adds the pull request comment that asks the same thing when +// nothing reached GitHub. Only a request from check output has one: the App +// reads the check of the pull request it is posted on. An unknown outcome +// gets none, so a request is not asked twice. +func withReply(err error, r request.Request) error { + var notSent interface{ NothingSent() } + if r.Base == "" || !errors.As(err, ¬Sent) { + return err + } + line := strings.TrimSuffix(requestsend.Line(requestsend.Input{Reason: r.Reason, Expires: r.Expires}), "\n") + return fmt.Errorf("%w\nor reply on the pull request: %s", err, line) +} + // writeRequest prints a request no App sent: the errors it asks about, the // reason and the date asked for, then the next step last. func writeRequest(w io.Writer, r request.Request, protected bool, today time.Time) error { diff --git a/cmd/archfit/request_send_test.go b/cmd/archfit/request_send_test.go index 3e5b2aea..656cb466 100644 --- a/cmd/archfit/request_send_test.go +++ b/cmd/archfit/request_send_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "net/http" "net/http/httptest" @@ -13,9 +14,12 @@ import ( "strings" "testing" + "github.com/coupling-dev/archfit/internal/testutil" "github.com/coupling-dev/archfit/internal/toolrun" ) +const onePullJSON = "[{\"number\":431}]" + func TestRequestSendsFromCLI(t *testing.T) { const token = "cli-secret-token" const receipt = "https://github.com/acme/shop/issues/431" @@ -29,14 +33,19 @@ func TestRequestSendsFromCLI(t *testing.T) { code int next string posts int + offline bool + reply bool }{ - {"pull comment", []string{cmdCheck}, true, "[{\"number\":431}]", 201, false, 0, "", 1}, - {"can issue", []string{cmdCan, pkgTC, pkgUtil}, false, "[]", 201, false, 0, "", 1}, - {"check no upstream", []string{cmdCheck}, false, "[]", 0, false, 2, "open a pull request first", 0}, - {"check no pull", []string{cmdCheck}, true, "[]", 0, false, 2, "open a pull request first", 0}, - {"ambiguous", []string{cmdCheck}, true, "[{\"number\":431},{\"number\":432}]", 0, false, 2, "#431, #432", 0}, - {"API failure", []string{cmdCheck}, true, "[{\"number\":431}]", 403, false, 2, "HTTP 403", 1}, - {"no credentials", []string{cmdCheck}, true, "[]", 0, true, 2, "next: gh auth login", 0}, + {"pull comment", []string{cmdCheck}, true, onePullJSON, 201, false, 0, "", 1, false, false}, + {"can issue", []string{cmdCan, pkgTC, pkgUtil}, false, "[]", 201, false, 0, "", 1, false, false}, + {"check no upstream", []string{cmdCheck}, false, "[]", 0, false, 2, "this branch has no upstream branch, so archfit cannot find its pull request; nothing sent\nnext: git push -u origin HEAD", 0, false, true}, + {"check no pull", []string{cmdCheck}, true, "[]", 0, false, 2, "open a pull request first", 0, false, true}, + {"ambiguous", []string{cmdCheck}, true, "[{\"number\":431},{\"number\":432}]", 0, false, 2, "#431, #432", 0, false, true}, + {"API failure", []string{cmdCheck}, true, onePullJSON, 403, false, 2, "HTTP 403", 1, false, true}, + {"API failure, outcome unknown", []string{cmdCheck}, true, onePullJSON, 500, false, 2, "outcome unknown", 1, false, false}, + {"no credentials", []string{cmdCheck}, true, "[]", 0, true, 2, "next: gh auth login", 0, false, true}, + {"can, no credentials", []string{cmdCan, pkgTC, pkgUtil}, false, "[]", 0, true, 2, "next: gh auth login", 0, false, false}, + {"GitHub unreachable", []string{cmdCheck}, true, "[]", 0, false, 2, "could not reach GitHub: tls: failed to verify certificate: x509: OSStatus -26276; nothing sent", 0, true, true}, } { t.Run(tc.name, func(t *testing.T) { t.Setenv("GH_TOKEN", token) @@ -90,6 +99,9 @@ func TestRequestSendsFromCLI(t *testing.T) { transport := http.DefaultTransport.(*http.Transport).Clone() defer transport.CloseIdleConnections() client := &http.Client{Transport: requestTransport(func(r *http.Request) (*http.Response, error) { + if tc.offline { + return nil, errors.New("tls: failed to verify certificate: x509: OSStatus -26276") + } r = r.Clone(r.Context()) r.URL.Scheme, r.URL.Host = target.Scheme, target.Host return transport.RoundTrip(r) @@ -113,6 +125,13 @@ func TestRequestSendsFromCLI(t *testing.T) { } else if stdout.Len() != 0 || !strings.Contains(stderr.String(), tc.next) { t.Errorf("stdout=%q stderr=%q; want next %q", stdout.String(), stderr.String(), tc.next) } + reply := "\nor reply on the pull request: /archfit request " + whyGraph + "\n" + if strings.Contains(stderr.String(), reply) != tc.reply { + t.Errorf("reply line shown %t, want %t; stderr=%s", !tc.reply, tc.reply, stderr.String()) + } + if words := testutil.StoryNotUsedIn(stderr.String()); len(words) > 0 { + t.Errorf("request vocabulary %v in:\n%s", words, stderr.String()) + } if strings.Contains(stdout.String()+stderr.String(), token) { t.Error("credential in command output") } diff --git a/cmd/archfit/setup_command_test.go b/cmd/archfit/setup_command_test.go index 48743693..6888f765 100644 --- a/cmd/archfit/setup_command_test.go +++ b/cmd/archfit/setup_command_test.go @@ -11,6 +11,7 @@ import ( "strings" "testing" + "github.com/coupling-dev/archfit/internal/application/setup" "github.com/coupling-dev/archfit/internal/testutil" "github.com/coupling-dev/archfit/internal/toolrun" ) @@ -60,12 +61,38 @@ func TestSetupWrongBranchStopsWithoutWriting(t *testing.T) { } } +// TestSetupDetectsMergedWithoutGitHub: after the setup pull request is +// merged, setup reports the checks that run, also when the setup branch +// is still there (B3) and when the policy makes the check required. func TestSetupDetectsMergedWithoutGitHub(t *testing.T) { + for _, tc := range []struct { + name string + setupBranch, required bool + state, next string + }{ + {"advisory", false, false, "advisory checks on", "open the setup page: " + setup.AppURL}, + {"setup branch left behind", true, false, "advisory checks on", "open the setup page: " + setup.AppURL}, + {"required", true, true, "required checks on", "check that a branch ruleset requires archfit/gate: https://github.com/o/r/settings/rules"}, + } { + t.Run(tc.name, func(t *testing.T) { + setupMergedRepo(t, tc.setupBranch, tc.required, tc.state, tc.next) + }) + } +} + +func setupMergedRepo(t *testing.T, setupBranch, required bool, state, next string) { + t.Helper() files := fixtureFiles() files[".github/workflows/test.yaml"] = "jobs:\n archfit:\n steps:\n - uses: coupling-dev/archfit-action@v1\n" + if required { + files[defaultConfigPath] = strings.Replace(fixturePolicy, "version: 1\n", "version: 1\ngate: required\n", 1) + } dir := fixtureRepo(t, files, nil) gitFixture(t, dir, "remote", "add", "origin", "https://github.com/o/r.git") gitFixture(t, dir, "switch", "main") + if setupBranch { + gitFixture(t, dir, "branch", "archfit/setup", "main") + } runner := toolrun.New() mock := &toolrun.RunnerMock{RunFunc: func(ctx context.Context, cmd toolrun.ToolCmd) (toolrun.Output, error) { if cmd.Name == "gh" { @@ -88,7 +115,7 @@ func TestSetupDetectsMergedWithoutGitHub(t *testing.T) { if words := testutil.StoryNotUsedIn(stdout.String()); len(words) > 0 { t.Errorf("setup vocabulary %v in:\n%s", words, stdout.String()) } - if code != 0 || !strings.Contains(stdout.String(), "state: done") || !strings.Contains(stdout.String(), "advisory:") || strings.Contains(stdout.String(), "next:") { + if code != 0 || !strings.Contains(stdout.String(), "state: "+state+"\n") || !strings.Contains(stdout.String(), "next: "+next+"\n") { t.Fatalf("exit %d, stdout %q, stderr %q", code, stdout.String(), stderr.String()) } } @@ -136,12 +163,17 @@ func TestSetupCommitPersistsAfterCommandReturns(t *testing.T) { func TestSetupResumesPublishedBranchWithoutMutations(t *testing.T) { //nolint:gocyclo // process stub covers each external command const signedIn = "repo, workflow" + // What gh 2.105 prints when a TLS-intercepting proxy breaks its call (B6). + const unreachable = "github.com\n X Failed to log in to github.com account someone (keyring)\n" + + " - The token in keyring is invalid.\n" + + ` - Error: Get "https://api.github.com/": tls: failed to verify certificate: x509: OSStatus -26276` + "\n" for _, tc := range []struct { - name, auth, prs, checks, state, next string + name, auth, authErr, prs, checks, state, next string }{ - {"no gh", "", "", "", "setup pull request not opened; gh is not signed in", "open the pull request:"}, - {"no app check", signedIn, `[{"number":7,"state":"OPEN","url":"https://github.com/o/r/pull/7","headRefOid":"abc"}]`, `{"check_runs":[]}`, "waiting for the App", "install the App:"}, - {"app check", signedIn, `[{"number":7,"state":"OPEN","url":"https://github.com/o/r/pull/7","headRefOid":"abc"}]`, `{"check_runs":[{"app":{"slug":"archfit-review"},"status":"completed","conclusion":"neutral","html_url":"https://github.com/o/r/check","output":{"title":"merge to start"}}]}`, "waiting for the merge", "merge #7:"}, + {"no gh", "", "You are not logged into any GitHub hosts. To log in, run: gh auth login\n", "", "", "setup pull request not opened; gh is not signed in", "open the pull request:"}, + {"gh cannot reach GitHub", "", unreachable, "", "", "setup pull request not opened; could not reach GitHub", "open the pull request:"}, + {"no app check", signedIn, "", `[{"number":7,"state":"OPEN","url":"https://github.com/o/r/pull/7","headRefOid":"abc"}]`, `{"check_runs":[]}`, "waiting for the App", "install the App:"}, + {"app check", signedIn, "", `[{"number":7,"state":"OPEN","url":"https://github.com/o/r/pull/7","headRefOid":"abc"}]`, `{"check_runs":[{"app":{"slug":"archfit-review"},"status":"completed","conclusion":"neutral","html_url":"https://github.com/o/r/check","output":{"title":"merge to start"}}]}`, "waiting for the merge", "merge #7:"}, } { t.Run(tc.name, func(t *testing.T) { files := fixtureFiles() @@ -172,7 +204,7 @@ func TestSetupResumesPublishedBranchWithoutMutations(t *testing.T) { //nolint:go t.Fatalf("unexpected write: %s", args) case cmd.Name == "gh" && strings.HasPrefix(args, "auth status"): if tc.auth == "" { - return toolrun.Output{ExitCode: 1}, nil + return toolrun.Output{ExitCode: 1, Stderr: []byte(tc.authErr)}, nil } return toolrun.Output{Stderr: []byte("- Token scopes: 'repo', 'workflow'\n")}, nil case cmd.Name == "gh" && strings.HasPrefix(args, "pr list"): @@ -198,6 +230,10 @@ func TestSetupResumesPublishedBranchWithoutMutations(t *testing.T) { //nolint:go if code != wantCode || !strings.Contains(stdout.String(), "state: "+tc.state) || !strings.Contains(stdout.String(), "next: "+tc.next) { t.Fatalf("exit %d stdout %s stderr %s", code, stdout.String(), stderr.String()) } + if tc.authErr == unreachable && (!strings.Contains(stdout.String(), "could not reach GitHub: tls: failed to verify certificate: x509: OSStatus -26276\n") || + strings.Contains(stdout.String(), "not signed in") || strings.Contains(stdout.String(), "api.github.com")) { + t.Fatalf("unreachable GitHub reported as:\n%s", stdout.String()) + } } }) } @@ -449,7 +485,7 @@ func TestSetupNoHooksIgnoresPrivateHarnessAfterMerge(t *testing.T) { }} var stdout, stderr bytes.Buffer code := runDeps([]string{setupCommand, setupNoHooks, "-C", dir}, &appDeps{Runner: mock, Stdout: &stdout, Stderr: &stderr}) - if code != 0 || !strings.Contains(stdout.String(), "state: done") { + if code != 0 || !strings.Contains(stdout.String(), "state: advisory checks on") { t.Fatalf("exit %d stdout %s stderr %s", code, stdout.String(), stderr.String()) } } diff --git a/cmd/archfit/setup_files.go b/cmd/archfit/setup_files.go index 32b97a06..b220f1b7 100644 --- a/cmd/archfit/setup_files.go +++ b/cmd/archfit/setup_files.go @@ -155,9 +155,11 @@ jobs: `, strings.ReplaceAll(branch, "'", "''"), actionRepo, sha, tag, setup.AppURL) } -func (f setupFiles) ValidPolicy(data []byte) bool { - _, err := policyfile.Decode(data) - return err == nil +// ValidPolicy reports whether data is a version 1 policy and whether it makes +// the check required. +func (f setupFiles) ValidPolicy(data []byte) (valid, required bool) { + policy, err := policyfile.Decode(data) + return err == nil, err == nil && policy.Gate == policyfile.GateRequired } func (f setupFiles) PinNote() string { return doctorPin(f.co.root, version) } diff --git a/cmd/archfit/setup_wiring.go b/cmd/archfit/setup_wiring.go index d81eb912..033fd897 100644 --- a/cmd/archfit/setup_wiring.go +++ b/cmd/archfit/setup_wiring.go @@ -36,7 +36,7 @@ func setupDependencies(deps *appDeps, dir string, noHooks bool) (setup.Dependenc git := setupgit.Git{ Root: co.root, Runner: local.Runner, ActionRepository: actionRepo, PolicyPath: defaultConfigPath, WorkflowsDir: workflowsDir, - Version1: files.ValidPolicy, UsesAction: setupUsesAction, + Policy: files.ValidPolicy, UsesAction: setupUsesAction, } gh := setupGH{setupgit.GitHub{Root: co.root, Runner: local.Runner, BodyPath: setup.BodyPath}} return setup.Dependencies{ @@ -105,6 +105,10 @@ func (g setupGH) Create(ctx context.Context, repo, base, branch string) (setup.P return setup.PullRequest(p), err } +func (g setupGH) Auth(ctx context.Context) setup.Login { + return setup.Login(g.GitHub.Auth(ctx)) +} + func (g setupGH) Check(ctx context.Context, repo, head string) (setup.AppCheck, error) { c, err := g.GitHub.Check(ctx, repo, head) return setup.AppCheck(c), err diff --git a/cmd/archfit/setup_workflow_test.go b/cmd/archfit/setup_workflow_test.go index 44368802..b2adf2ef 100644 --- a/cmd/archfit/setup_workflow_test.go +++ b/cmd/archfit/setup_workflow_test.go @@ -124,7 +124,7 @@ func TestSetupIgnoresUncommittedAlternateWorkflow(t *testing.T) { func TestSetupRejectsInvalidMergedPolicy(t *testing.T) { f := setupFiles{} - if f.ValidPolicy([]byte("version: 1\ninvalid_key: true\n")) { + if valid, _ := f.ValidPolicy([]byte("version: 1\ninvalid_key: true\n")); valid { t.Fatal("invalid version 1 policy accepted") } } diff --git a/cmd/archfit/testdata/init/fresh.txt b/cmd/archfit/testdata/init/fresh.txt index b0e26801..90eb8626 100644 --- a/cmd/archfit/testdata/init/fresh.txt +++ b/cmd/archfit/testdata/init/fresh.txt @@ -9,4 +9,5 @@ for the owner to decide: module pkg_runtime: volatility not set; taken as high module pkg_tc: volatility not set; taken as high module pkg_util: volatility not set; taken as high +owner: alice. Owners approve requests: name an owner who does not write most of the changes next: read .archfit.yaml, then open a pull request with it diff --git a/docs/ci.md b/docs/ci.md index 57bef694..2fb00ea5 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -12,6 +12,7 @@ The Go coverage example describes version 2 (Archfit 3). Use the current text-re Run [`archfit setup`](commands.md#setup) to write this workflow. Setup substitutes your default branch for `main` and the commit SHA of the Action tag that matches the installed Archfit release. For an annotated tag, it uses the commit the tag points to. Development builds cannot pin an Action release. +A candidate build, made for testing before a release, pins an Action commit and marks it `# candidate` instead of a tag. Setup does not replace an existing workflow. The Action checks out the repository itself. ```yaml diff --git a/docs/commands.md b/docs/commands.md index 5010cd87..9cf91c48 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -135,9 +135,16 @@ Only an error whose `next` is `archfit request` joins the request: an error of a A use past the surface asks one question: should its package be part of the surface? The printed request shows it on a `question:` line; the App asks the owner to declare the package `public` or `model`, or to reject the request. -With a GitHub remote, `archfit request` posts `/archfit request [--expires DATE]` as a comment on the one open pull request for the current branch. The target repository is `origin`, or a configured GitHub `upstream` for a fork. The head uses the push remote's owner, falling back to the `origin` owner. Several matching pull requests means nothing is sent: the error names their numbers. A detached HEAD or a branch without an upstream has no matching pull request. +With a GitHub remote, `archfit request` posts `/archfit request [--expires DATE]` as a comment on the one open pull request for the current branch. The target repository is `origin`, or a configured GitHub `upstream` for a fork. The head uses the push remote's owner, falling back to the `origin` owner. Several matching pull requests means nothing is sent: the error names their numbers. A detached HEAD or a branch without an upstream names no pull request: the error says which, and for a branch without an upstream `next: git push -u HEAD`. -Without a pull request, only a request from `archfit can` opens an issue. Its body holds the request line and the `can` record; the App marks the numbers "as reported" until a pull request confirms them. With `check` output, nothing is opened: `next: open a pull request first`. +Without a pull request, only a request from `archfit can` opens an issue. Its body holds the request line and the `can` record; the App marks the numbers "as reported" until a pull request confirms them. With `check` output, nothing is opened: `no open pull request for :` and `next: open a pull request first`. + +When a network error stops the lookup, the error is `could not reach GitHub: ; nothing sent`. The cause never includes a URL or a token. When nothing reached GitHub for a request from `check` output, the last line is the comment that asks the same thing, to post on the pull request yourself: + +```text +archfit: send the request: could not reach GitHub: tls: failed to verify certificate: x509: OSStatus -26276; nothing sent +or reply on the pull request: /archfit request netem needs the shared retry helper +``` Credentials are tried in order: `GH_TOKEN`, `GITHUB_TOKEN`, then `gh auth token`. No credentials means exit `2` and `next: gh auth login`. Tokens are never printed. Success exits `0` and prints the comment or issue URL. API errors exit `2` without printing a successful request or changing the last result. HTTP calls time out after 30 seconds. A POST is never retried; when the send outcome is unknown (for example, a lost connection after sending), check GitHub before trying again. @@ -177,7 +184,7 @@ next: ask an owner (open a pull request first if there is none) | The repository has | `archfit init` | | --- | --- | -| No `.archfit.yaml` | Writes a version 1 policy from the code: a module for each directory of code cut to two levels, such as `pkg/chaos` (for Python, below `src/`), with `paths` and `public` (the packages other modules use today); `depends_on` as the dependencies that exist; `tests` and `generated`; `owners` from the local GitHub identity; an `only` rule for network, process, or database code that only some modules use; and an exception for each error that exists today, so the first `check` passes when the evidence is complete. | +| No `.archfit.yaml` | Writes a version 1 policy from the code: a module for each directory of code cut to two levels, such as `pkg/chaos` (for Python, below `src/`), with `paths` and `public` (the packages other modules use today); `depends_on` as the dependencies that exist; `tests` and `generated`; `owners` from the local GitHub identity (when that is the only owner, init and setup say once that owners approve requests, so the owner should not write most of the changes); an `only` rule for network, process, or database code that only some modules use; and an exception for each error that exists today, so the first `check` passes when the evidence is complete. | | Any other `.archfit.yaml`, such as version 2 (Archfit 3) | Fails with the version error and changes nothing. Remove the file, then run `archfit init`. | | A version 1 `.archfit.yaml` | Leaves it as it is. | @@ -217,7 +224,7 @@ The list identifies exceptions, modules with no public part declared, and module Run `archfit setup` from the default branch of a checkout with a GitHub `origin`. Run `archfit setup` again when the output asks you to continue. -After setup creates `archfit/setup`, continue on that branch. +After setup creates `archfit/setup`, continue on that branch until the setup pull request is merged. Use `--no-hooks` to skip Claude Code and Codex hooks, or `-C DIR` to select a checkout. | State | What setup does | What to do next | @@ -225,10 +232,11 @@ Use `--no-hooks` to skip Claude Code and Codex hooks, or `-C DIR` to select a ch | No policy | Writes a policy and the agent instructions. | Read `.archfit.yaml`, then run `archfit setup` again. | | No workflow | Keeps the policy and writes a [pinned workflow](ci.md#the-workflow-archfit-setup-writes). | Follow the next step after the push. | | Stopped before the push | The HTTPS push uses a `gh` login with known classic scopes, without `workflow`. | Run `gh auth refresh -s workflow`, then run setup again. | -| Pull request not opened | Prints a compare link and saves the body to `.archfit-cache/setup-pull-request.md`. | Open the pull request on GitHub with the saved body. | +| Pull request not opened | Prints a compare link and saves the body to `.archfit-cache/setup-pull-request.md`. The state says why: `gh is not signed in`, or `could not reach GitHub` with its cause. | Open the pull request on GitHub with the saved body. | | Pull request open, no App check | Prints the App install link. Setup does not re-run the workflow. | Install the App. Use the printed re-run link if the check does not start. | | App check present | Prints the status of `archfit/gate`. | Review and merge the setup pull request. | -| Done | The default branch has the policy and an Archfit workflow. | Checks are advisory. Setup prints no `next:` line. | +| Advisory checks on | The default branch has the policy and an Archfit workflow. | Open the setup page: an owner approves the first policy there, then makes the check required. | +| Required checks on | The same, and the policy has `gate: required`. | Check that a branch ruleset requires `archfit/gate`: without it, a fail does not block a merge. | After writing a new policy, setup shows how it would judge up to 30 recent first-parent changes. It also includes the counts in the first setup pull request body. Replay uses the local remote-tracking default branch, does not fetch PR labels or start CI, and stops after 60 seconds. If the local ref is unavailable, run `archfit replay` later. @@ -240,6 +248,8 @@ Review the pull request before merging. SSH pushes use the SSH key and do not require the `gh` `workflow` scope. When `gh` does not report classic scopes, setup attempts the push and reports a permission error if Git rejects it. Without a signed-in `gh`, setup still pushes via Git. It cannot see the pull request or App check. +When `gh` cannot reach GitHub (for example, a network or TLS error, or no answer within 30 seconds), setup says `could not reach GitHub` with the cause, not that `gh` is not signed in. The cause never includes the request URL or a response body; an HTTP answer other than 401 shows only its status. +After the merge, setup reads the default branch first, so a leftover `archfit/setup` branch does not stop it. A later run does not push an unchanged branch. If Git refuses to update the workflow, fix your Git credentials. When setup can detect a merged policy and workflow, it works without `gh`. diff --git a/docs/getting-started.md b/docs/getting-started.md index 7efe33cb..998affbd 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -1,8 +1,11 @@ # Getting started -This guide installs archfit, sets up a repository with `archfit init`, and shows the daily loop: `rules`, `can`, `check`, and `request`. For full tool requirements, see [Language support](languages.md). +This guide installs archfit, sets up a repository, and shows the daily loop: `rules`, `can`, `check`, and `request`. For full tool requirements, see [Language support](languages.md). -For advisory checks on GitHub, follow [Try it on your pull request](try-it-on-your-pull-request.md). This guide also covers the local-only workflow. +There are two ways to set up a repository: + +- **Checks on GitHub pull requests:** run `archfit setup` and follow [Try it on your pull request](try-it-on-your-pull-request.md). Setup writes the policy, the workflow and the setup pull request. +- **Local only:** run `archfit init`, as below. It writes the policy and no workflow; you can run `archfit setup` later. ## Install archfit @@ -15,10 +18,10 @@ brew install coupling-dev/tap/archfit Or install with Go 1.27 or newer: ```sh -go install github.com/coupling-dev/archfit/cmd/archfit@v0.9.0 +go install github.com/coupling-dev/archfit/cmd/archfit@latest ``` -The Homebrew formula and the release binary need no Go toolchain. You can also download a release binary from the [release page](https://github.com/coupling-dev/archfit/releases). Check the file against `SHA256SUMS` before you install it. +Each command installs the latest release. Setup pins the Action release that matches the archfit you installed, so install the release you want before you run `archfit setup`. The Homebrew formula and the release binary need no Go toolchain. You can also download a release binary from the [release page](https://github.com/coupling-dev/archfit/releases). Check the file against `SHA256SUMS` before you install it. ## Check the tools @@ -32,15 +35,15 @@ This command reports tools for the languages it finds, in two groups: needed for `doctor` compares the local engine with the version comment on the workflow pin. It also reports missing or inactive hooks. See [Hooks](agents.md#hooks). -## Set up the repository +## Set up the repository locally -From your repository, run: +For checks on GitHub pull requests, run `archfit setup` instead: see [Try it on your pull request](try-it-on-your-pull-request.md). For the local-only path, run from your repository: ```sh archfit init ``` -`init` writes the policy, `.archfit.yaml`, from the code: the modules, the part of each module that other modules use today (`public`), the dependencies between modules that exist (`depends_on`), the test and generated paths, and the authenticated GitHub user as owner, or an unverified login from a GitHub noreply author email. If neither identity is available, replace the placeholder with your GitHub login. Each error that exists today becomes an exception dated 90 days from the run, so the first check passes when the evidence is complete. The final list names these decisions for the owner. `init` also writes five lines for agents between markers in `AGENTS.md`. +`init` writes the policy, `.archfit.yaml`, from the code: the modules, the part of each module that other modules use today (`public`), the dependencies between modules that exist (`depends_on`), the test and generated paths, and the authenticated GitHub user as owner, or an unverified login from a GitHub noreply author email. If neither identity is available, replace the placeholder with your GitHub login. Owners approve requests, so name an owner who does not write most of the changes: `init` and `setup` say so when they name you as the only owner. Each error that exists today becomes an exception dated 90 days from the run, so the first check passes when the evidence is complete. The final list names these decisions for the owner. `init` also writes five lines for agents between markers in `AGENTS.md`. ```text $ archfit init @@ -49,8 +52,13 @@ wrote AGENTS.md: the instruction block for agents installed hooks: .claude/settings.json installed hooks: .codex/hooks.json codex runs these hooks only after you trust them: start codex and approve the hooks -exceptions for the owner to review: +for the owner to decide: exception: duplication pkg_tc -> pkg_util until 2027-02-08 + module pkg_chaos: volatility not set; taken as high + module pkg_runtime: volatility not set; taken as high + module pkg_tc: volatility not set; taken as high + module pkg_util: volatility not set; taken as high +owner: alice. Owners approve requests: name an owner who does not write most of the changes next: read .archfit.yaml, then open a pull request with it ``` @@ -125,7 +133,7 @@ Fail the job on any exit code except `0`. See [CI](ci.md) for the workflow. The release image runs archfit with a bundled toolchain: ```sh -docker run --rm -v "$(pwd):/src" ghcr.io/coupling-dev/archfit:v0.9.0 \ +docker run --rm -v "$(pwd):/src" ghcr.io/coupling-dev/archfit:latest \ check ``` diff --git a/docs/plans/20261122-archfit-onboarding-texts.md b/docs/plans/20261122-archfit-onboarding-texts.md index 089c74a0..723efaff 100644 --- a/docs/plans/20261122-archfit-onboarding-texts.md +++ b/docs/plans/20261122-archfit-onboarding-texts.md @@ -147,6 +147,18 @@ the App, once the pull request is open: Exit `0`. The last line is information. The second run cannot tell the pull request from the App check, so it says so (see 2.6). +When `gh` is signed in but cannot reach GitHub (gh's `auth status` then says the token is invalid and gives an `Error:` +line), setup does not say that gh is not signed in. Before the body line it prints the cause from gh's error, without +the request URL or a response body (an HTTP answer shows only its status), and the state names it: + +```text +could not reach GitHub: tls: failed to verify certificate: x509: OSStatus -26276 +pull request: open it, or check on GitHub; gh cannot show it +pull request body: .archfit-cache/setup-pull-request.md +state: setup pull request not opened; could not reach GitHub +next: open the pull request: https://github.com///compare/main...archfit/setup?expand=1 +``` + ### 2.6 Setup pull request open, App not installed Second run, or a run after 2.5: @@ -182,13 +194,23 @@ Exit `0`. ### 2.8 Merged: advisory ```text -setup pull request #12 is merged -advisory: checks report on each pull request and do not block a merge (changed; see 6.1) -setup page: -state: done +advisory: checks report on each pull request and do not block a merge +state: advisory checks on +next: open the setup page: +an owner approves the first policy there, then makes the check required ``` -No `next:` line. Exit `0`. +Exit `0`. Setup reads the merge before the setup branch, so a leftover `archfit/setup` branch does not stop it. Setup +cannot tell whether the first policy is approved, so its one action is to open the setup page, which can. + +When the merged policy has `gate: required`: + +```text +required: a fail blocks a merge when a branch ruleset requires archfit/gate +setup page: +state: required checks on +next: check that a branch ruleset requires archfit/gate: https://github.com///settings/rules +``` ### 2.9 Stop states (exit 2) diff --git a/docs/try-it-on-your-pull-request.md b/docs/try-it-on-your-pull-request.md index e3605b72..59bc3d02 100644 --- a/docs/try-it-on-your-pull-request.md +++ b/docs/try-it-on-your-pull-request.md @@ -13,7 +13,16 @@ In [Pumba](https://github.com/alexei-led/pumba), a change added a dependency and On Linux without Homebrew, download the binary for your architecture from the [releases page](https://github.com/coupling-dev/archfit/releases), verify it against `SHA256SUMS`, and put it on your `PATH`. 2. From the default branch of a checkout with a GitHub `origin`, run `archfit setup`. Read the policy and follow each `next:` line, running `archfit setup` again when asked. Setup writes the workflow and opens a setup pull request, or prints a compare link to open one yourself. 3. Install the App for the repository from the link printed by setup. If the check does not start, use the printed re-run link. -4. Review and merge the setup pull request. Run `archfit setup` again to see the advisory state and setup page. +4. Review and merge the setup pull request. Run `archfit setup` again on the default branch: + + ```text + advisory: checks report on each pull request and do not block a merge + state: advisory checks on + next: open the setup page: https://app.coupling.dev + an owner approves the first policy there, then makes the check required + ``` + + An owner approves the first policy on the setup page before anyone can answer a request. When the policy has `gate: required`, setup says `required checks on` and asks you to check that a branch ruleset requires `archfit/gate`: only the ruleset makes a fail block a merge. No sign-in or passkey is required for initial advisory checks. See the [setup command reference](commands.md#setup) for its states and recovery steps. diff --git a/internal/application/request/request.go b/internal/application/request/request.go index 0a588f4b..16806e64 100644 --- a/internal/application/request/request.go +++ b/internal/application/request/request.go @@ -220,7 +220,9 @@ func (s Service) Ask(ctx context.Context, in Input) (Outcome, error) { } sent, err := s.Sender.Send(ctx, req) if err != nil { - return Outcome{}, fmt.Errorf("send the request: %w", err) + // The request comes back with the error, so the caller can show + // another way to post it. + return Outcome{Request: req}, fmt.Errorf("send the request: %w", err) } return Outcome{Request: req, Number: sent.Number, URL: sent.URL}, nil } diff --git a/internal/application/setup/run_test.go b/internal/application/setup/run_test.go index d1634d13..60739ed4 100644 --- a/internal/application/setup/run_test.go +++ b/internal/application/setup/run_test.go @@ -26,17 +26,19 @@ func TestSetupResumesAcrossExternalSteps(t *testing.T) { for _, tc := range []struct { name string ready, scope bool + unreachable string createErr error wantState State wantActions []string }{ - {"signed in", true, true, nil, Unpublished, []string{workflowAction, checkAction, switchAction, commitAction, pushAction, writeBodyAction, createAction}}, - {"no gh", false, false, nil, ManualPR, []string{workflowAction, checkAction, switchAction, commitAction, pushAction, writeBodyAction}}, - {"missing scope", true, false, nil, NeedsScope, []string{workflowAction, checkAction, switchAction, commitAction}}, - {"cannot create pull request", true, true, errors.New("no access"), ComparePR, []string{workflowAction, checkAction, switchAction, commitAction, pushAction, writeBodyAction, createAction}}, + {"signed in", true, true, "", nil, Unpublished, []string{workflowAction, checkAction, switchAction, commitAction, pushAction, writeBodyAction, createAction}}, + {"no gh", false, false, "", nil, ManualPR, []string{workflowAction, checkAction, switchAction, commitAction, pushAction, writeBodyAction}}, + {"gh cannot reach GitHub", false, false, tlsFailure, nil, OfflinePR, []string{workflowAction, checkAction, switchAction, commitAction, pushAction, writeBodyAction}}, + {"missing scope", true, false, "", nil, NeedsScope, []string{workflowAction, checkAction, switchAction, commitAction}}, + {"cannot create pull request", true, true, "", errors.New("no access"), ComparePR, []string{workflowAction, checkAction, switchAction, commitAction, pushAction, writeBodyAction, createAction}}, } { t.Run(tc.name, func(t *testing.T) { - f := setupFixture{branch: fixtureBranch, ready: tc.ready, scope: tc.scope, createErr: tc.createErr} + f := setupFixture{branch: fixtureBranch, ready: tc.ready, scope: tc.scope, unreachable: tc.unreachable, createErr: tc.createErr} deps := f.deps(t) init := Run(t.Context(), deps) assertOutcome(t, init, NoPolicy, 0, "archfit setup", "for the owner to decide:") @@ -45,6 +47,9 @@ func TestSetupResumesAcrossExternalSteps(t *testing.T) { second := Run(t.Context(), deps) assertOutcome(t, second, tc.wantState, 0, Next(second.Progress), "kept .archfit.yaml", "check: fail against origin/main") assertActions(t, f.actions, tc.wantActions...) + if tc.wantState == OfflinePR { + assertOutcome(t, second, OfflinePR, 0, Next(second.Progress), "could not reach GitHub: "+tlsFailure, "gh cannot show it") + } if tc.wantState == NeedsScope { assertOutcome(t, second, NeedsScope, 0, refreshNext) f.scope = true @@ -59,8 +64,8 @@ func TestSetupResumesAcrossExternalSteps(t *testing.T) { case ComparePR: assertOutcome(t, third, Unpublished, 0, Next(third.Progress)) assertActions(t, f.actions, createAction) - case ManualPR: - assertOutcome(t, third, ManualPR, 0, Next(third.Progress)) + case ManualPR, OfflinePR: + assertOutcome(t, third, tc.wantState, 0, Next(third.Progress)) assertActions(t, f.actions) if !strings.Contains(f.body, InstallURL) || strings.Contains(f.body, "suggested_target_id") { t.Errorf("body should contain the plain install link: %s", f.body) @@ -88,15 +93,48 @@ func TestSetupResumesAcrossExternalSteps(t *testing.T) { } f.merged, f.ready = true, false merged := Run(t.Context(), deps) - assertOutcome(t, merged, Merged, 0, "", "advisory:", "setup page:") + assertOutcome(t, merged, Advisory, 0, "open the setup page: "+AppURL, "advisory:") assertActions(t, f.actions) mergedAgain := Run(t.Context(), deps) - assertOutcome(t, mergedAgain, Merged, 0, "", "advisory:", "setup page:") + assertOutcome(t, mergedAgain, Advisory, 0, "open the setup page: "+AppURL, "advisory:") + assertActions(t, f.actions) + }) + } +} + +const tlsFailure = "tls: failed to verify certificate: x509: OSStatus -26276" + +// TestSetupAfterTheMerge: the setup branch stays behind after its pull +// request is merged; setup reports the checks that run, not the branch. +func TestSetupAfterTheMerge(t *testing.T) { + for _, tc := range []struct { + name, branch string + required bool + want State + next, line string + }{ + {"advisory on the default branch", fixtureBranch, false, Advisory, "open the setup page: " + AppURL, "advisory: checks report on each pull request and do not block a merge"}, + {"advisory on the setup branch", Branch, false, Advisory, "open the setup page: " + AppURL, "advisory:"}, + {"required", fixtureBranch, true, Required, "check that a branch ruleset requires archfit/gate: https://github.com/o/r/settings/rules", "required: a fail blocks a merge when a branch ruleset requires archfit/gate"}, + } { + t.Run(tc.name, func(t *testing.T) { + f := setupFixture{branch: tc.branch, policy: true, workflow: true, merged: true, required: tc.required, setupBranch: true} + out := Run(t.Context(), f.deps(t)) + assertOutcome(t, out, tc.want, 0, tc.next, tc.line) assertActions(t, f.actions) }) } } +// TestSetupBranchBeforeTheMerge: before the merge, the work is on the setup +// branch, so setup on the default branch sends the user there. +func TestSetupBranchBeforeTheMerge(t *testing.T) { + f := setupFixture{branch: fixtureBranch, policy: true, workflow: true, setupBranch: true} + out := Run(t.Context(), f.deps(t)) + assertOutcome(t, out, Blocked, 2, "git switch archfit/setup, then archfit setup", "the setup branch already exists") + assertActions(t, f.actions) +} + func TestSetupStopsWithoutPublishing(t *testing.T) { for _, tc := range []struct { name string @@ -157,6 +195,8 @@ func assertActions(t *testing.T, got []string, want ...string) { type setupFixture struct { branch, body string policy, workflow, pending, merged, ahead, noAuthor, ready, scope, pushed bool + required, setupBranch bool + unreachable string createErr, policyErr, workflowErr, pushSafetyErr, pushErr, remoteErr error pr PullRequest check AppCheck @@ -209,13 +249,17 @@ func (f *setupFixture) Paths() []string { return []string{".archfit.ya type fixtureGit struct{ *setupFixture } -func (g fixtureGit) Repository(context.Context) (string, error) { return "o/r", nil } -func (g fixtureGit) Default(context.Context) (string, string, error) { return fixtureBranch, "", nil } -func (g fixtureGit) SetupBranchExists(context.Context, string) (bool, error) { return false, nil } -func (g fixtureGit) Branch(context.Context) (string, error) { return g.branch, nil } -func (g fixtureGit) Fetch(context.Context, string) error { return nil } -func (g fixtureGit) Aligned(context.Context, string) (bool, error) { return !g.ahead, nil } -func (g fixtureGit) Merged(context.Context, string) (bool, error) { return g.merged, nil } +func (g fixtureGit) Repository(context.Context) (string, error) { return "o/r", nil } +func (g fixtureGit) Default(context.Context) (string, string, error) { return fixtureBranch, "", nil } +func (g fixtureGit) SetupBranchExists(context.Context, string) (bool, error) { + return g.setupBranch, nil +} +func (g fixtureGit) Branch(context.Context) (string, error) { return g.branch, nil } +func (g fixtureGit) Fetch(context.Context, string) error { return nil } +func (g fixtureGit) Aligned(context.Context, string) (bool, error) { return !g.ahead, nil } +func (g fixtureGit) Merged(context.Context, string) (bool, bool, error) { + return g.merged, g.required, nil +} func (g fixtureGit) Pending(_ context.Context, paths []string) ([]string, error) { if g.pending { return paths, nil @@ -259,7 +303,9 @@ func (g fixtureGit) Push(context.Context, string) error { type fixtureGH struct{ *setupFixture } -func (h fixtureGH) Auth(context.Context) (bool, bool) { return h.ready, h.scope } +func (h fixtureGH) Auth(context.Context) Login { + return Login{Ready: h.ready, Workflow: h.scope, Unreachable: h.unreachable} +} func (h fixtureGH) PullRequest(context.Context, string, string, string) (PullRequest, error) { return h.pr, nil } diff --git a/internal/application/setup/setup.go b/internal/application/setup/setup.go index 4d3c0965..ba87885b 100644 --- a/internal/application/setup/setup.go +++ b/internal/application/setup/setup.go @@ -55,7 +55,7 @@ type Git interface { SetupBranchExists(context.Context, string) (bool, error) Fetch(context.Context, string) error Aligned(context.Context, string) (bool, error) - Merged(context.Context, string) (bool, error) + Merged(context.Context, string) (merged, required bool, err error) Pending(context.Context, []string) ([]string, error) Pin(context.Context, string) (string, error) Identity(context.Context) (string, error) @@ -78,9 +78,17 @@ type AppCheck struct { Status, Conclusion, HTMLURL, Title string } +// Login is what gh reports about its GitHub login. Unreachable holds gh's +// error when it could not ask GitHub; Ready is then false, but the login may +// be fine, so setup does not say that gh is not signed in. +type Login struct { + Ready, Workflow bool + Unreachable string +} + // GitHub reads and opens pull requests and inspects the App check. type GitHub interface { - Auth(context.Context) (ready, workflowScope bool) + Auth(context.Context) Login PullRequest(context.Context, string, string, string) (PullRequest, error) Create(context.Context, string, string, string) (PullRequest, error) Check(context.Context, string, string) (AppCheck, error) @@ -126,12 +134,14 @@ type State string // States reported by setup, including states that require a person. const ( Blocked State = "stopped" - Merged State = "done" + Advisory State = "advisory checks on" + Required State = "required checks on" NoPolicy State = "no workflow yet" NoWorkflow State = "policy, no workflow" Unpublished State = "setup pull request open; the App is not installed" ComparePR State = "setup pull request not opened" ManualPR State = "setup pull request not opened; gh is not signed in" + OfflinePR State = "setup pull request not opened; could not reach GitHub" NeedsScope State = "stopped before the push" NoCheck State = "waiting for the App" CheckPresent State = "waiting for the merge" @@ -167,13 +177,17 @@ func Next(p Progress) string { return refreshNext case NoWorkflow, Unpublished, NoCheck: return "install the App: " + link - case ManualPR, ComparePR: + case ManualPR, OfflinePR, ComparePR: return fmt.Sprintf("open the pull request: https://github.com/%s/compare/%s...%s?expand=1", p.Repo, url.PathEscape(p.Default), Branch) case CheckPresent: return fmt.Sprintf("merge #%d: %s", p.PR.Number, p.PR.URL) case Closed: return fmt.Sprintf("pull request #%d was closed; reopen it, or delete the branch archfit/setup, then archfit setup", p.PR.Number) + case Advisory: + return "open the setup page: " + AppURL + case Required: + return fmt.Sprintf("check that a branch ruleset requires archfit/gate: https://github.com/%s/settings/rules", p.Repo) default: return "" } @@ -244,8 +258,9 @@ func Body(version, link string, replay *ReplaySummary, decisions []string) strin // Detection is the state and branch metadata read before setup advances. type Detection struct { Progress - branch string - pushed, ready, scope bool + branch string + pushed bool + login Login } // Detect reads the checkout and the remote default branch before any setup writes. @@ -269,17 +284,6 @@ func Detect(ctx context.Context, d Dependencies, out *Outcome) (Detection, bool) out.stop(errors.New("start from the default branch or archfit/setup"), "git switch "+ShellQuote(s.Default)+", then archfit setup") return s, false } - if s.branch == s.Default { - exists, err := d.Git.SetupBranchExists(ctx, Branch) - if err != nil { - out.stop(err, "check the setup branch on origin, then archfit setup") - return s, false - } - if exists { - out.stop(errors.New("the setup branch already exists"), "git switch archfit/setup, then archfit setup") - return s, false - } - } if next, err := d.Files.SafePaths(); err != nil { out.stop(err, next) return s, false @@ -302,13 +306,30 @@ func Detect(ctx context.Context, d Dependencies, out *Outcome) (Detection, bool) out.stop(errors.New("local "+s.Default+" does not match origin/"+s.Default), "sync "+ShellQuote(s.Default)+" with "+ShellQuote("origin/"+s.Default)+", then archfit setup") return s, false } - if merged, err := d.Git.Merged(ctx, s.Default); err != nil { + // A merged setup leaves its branch behind, so the merge is read first. + merged, required, err := d.Git.Merged(ctx, s.Default) + if err != nil { out.stop(err, "check "+ShellQuote("origin/"+s.Default)+", then archfit setup") return s, false - } else if merged { - s.State = Merged + } + if merged { + s.State = Advisory + if required { + s.State = Required + } return s, true } + if s.branch == s.Default { + exists, err := d.Git.SetupBranchExists(ctx, Branch) + if err != nil { + out.stop(err, "check the setup branch on origin, then archfit setup") + return s, false + } + if exists { + out.stop(errors.New("the setup branch already exists"), "git switch archfit/setup, then archfit setup") + return s, false + } + } switch { case !policy: s.State = NoPolicy @@ -336,8 +357,11 @@ func Run(ctx context.Context, d Dependencies) Outcome { } out.Progress = s.Progress switch s.State { - case Merged: + case Advisory: out.add("advisory: checks report on each pull request and do not block a merge") + out.After = append(out.After, "an owner approves the first policy there, then makes the check required") + case Required: + out.add("required: a fail blocks a merge when a branch ruleset requires archfit/gate") out.add("setup page: %s", AppURL) case NoPolicy: lines, err := d.Init(ctx) @@ -414,7 +438,7 @@ func publish(ctx context.Context, d Dependencies, s Detection, out *Outcome) { out.stop(errors.New("no setup files are available to commit"), "review the setup files, then archfit setup") return } - s.ready, s.scope = d.GitHub.Auth(ctx) + s.login = d.GitHub.Auth(ctx) if !s.pushed { https, err := d.Git.PushSafety(ctx, s.Default, d.Files.Paths()) if err != nil { @@ -434,7 +458,7 @@ func publish(ctx context.Context, d Dependencies, s Detection, out *Outcome) { out.stop(err, next) return } - if s.ready && https && !s.scope { + if s.login.Ready && https && !s.login.Workflow { out.State = NeedsScope out.add("the gh login has no workflow scope, so GitHub would refuse the workflow file") return @@ -512,7 +536,8 @@ func decisionLines(d Dependencies) ([]string, error) { func publishPR(ctx context.Context, d Dependencies, s Detection, out *Outcome) { out.InstallURL = InstallURL - if s.ready { + switch { + case s.login.Ready: pr, err := d.GitHub.PullRequest(ctx, s.Repo, s.Default, Branch) if err != nil { out.stop(err, "fix the pull request lookup, then archfit setup") @@ -529,7 +554,11 @@ func publishPR(ctx context.Context, d Dependencies, s Detection, out *Outcome) { if d.GitHub.IsFork(ctx, s.Repo) { out.add("warning: fork pull requests do not receive an id-token") } - } else { + case s.login.Unreachable != "": + // Not knowing is not the same as no pull request: say both. + out.add("could not reach GitHub: %s", s.login.Unreachable) + out.add("pull request: open it, or check on GitHub; gh cannot show it") + default: out.add("pull request: open it, or check on GitHub; gh cannot show it") } decisions, err := decisionLines(d) @@ -541,7 +570,8 @@ func publishPR(ctx context.Context, d Dependencies, s Detection, out *Outcome) { out.stop(err, "fix the pull request body file") return } - if s.ready { + switch { + case s.login.Ready: pr, err := d.GitHub.Create(ctx, s.Repo, s.Default, Branch) if err == nil { out.add("opened setup pull request #%d: %s", pr.Number, pr.URL) @@ -549,7 +579,9 @@ func publishPR(ctx context.Context, d Dependencies, s Detection, out *Outcome) { } out.add("could not open the pull request: %v", err) out.State = ComparePR - } else { + case s.login.Unreachable != "": + out.State = OfflinePR + default: out.State = ManualPR } out.add("pull request body: %s", BodyPath) diff --git a/internal/application/setup/setup_test.go b/internal/application/setup/setup_test.go index d308039b..256ea30c 100644 --- a/internal/application/setup/setup_test.go +++ b/internal/application/setup/setup_test.go @@ -19,10 +19,12 @@ func TestNext(t *testing.T) { {Unpublished, "install the App: " + InstallURL}, {NeedsScope, "gh auth refresh -s workflow"}, {ManualPR, "open the pull request: https://github.com/o/r/compare/release%2Fmain...archfit/setup?expand=1"}, + {OfflinePR, "open the pull request: https://github.com/o/r/compare/release%2Fmain...archfit/setup?expand=1"}, {NoCheck, "install the App: " + InstallURL}, {CheckPresent, "merge #7: https://github.com/o/r/pull/7"}, {Closed, "pull request #7 was closed; reopen it, or delete the branch archfit/setup, then archfit setup"}, - {Merged, ""}, + {Advisory, "open the setup page: " + AppURL}, + {Required, "check that a branch ruleset requires archfit/gate: https://github.com/o/r/settings/rules"}, {Blocked, ""}, } { t.Run(string(tc.state), func(t *testing.T) { @@ -34,6 +36,17 @@ func TestNext(t *testing.T) { } } +// TestNextUsesTheInjectedAppURL: a candidate build sets AppURL with -X, and +// the setup page it names must be that App, not the production one. +func TestNextUsesTheInjectedAppURL(t *testing.T) { + old := AppURL + AppURL = "https://candidate.example.test" + t.Cleanup(func() { AppURL = old }) + if got := Next(Progress{State: Advisory}); got != "open the setup page: https://candidate.example.test" { + t.Errorf("next: %q", got) + } +} + func TestTag(t *testing.T) { const release = "v0.10.0" for version, want := range map[string]string{ diff --git a/internal/history/github/git_test.go b/internal/history/github/git_test.go index 6da92d4f..90a49625 100644 --- a/internal/history/github/git_test.go +++ b/internal/history/github/git_test.go @@ -2,6 +2,7 @@ package requestsend import ( "context" + "errors" "testing" "github.com/coupling-dev/archfit/internal/toolrun" @@ -28,13 +29,13 @@ func TestRoutingWithRealGit(t *testing.T) { git("config", "branch.feature.pushRemote", "fork") git("config", "push.default", "current") s := New(dir, runner) - repo, head, err := s.repository(t.Context()) - if err != nil || repo != testRepo || head != forkHead { - t.Fatalf("repo=%q head=%q err=%v", repo, head, err) + repo, head, noHead, err := s.repository(t.Context()) + if err != nil || repo != testRepo || head != forkHead || noHead != nil { + t.Fatalf("repo=%q head=%q noHead=%v err=%v", repo, head, noHead, err) } git("checkout", "--detach", "-q") - repo, head, err = s.repository(t.Context()) - if err != nil || repo != testRepo || head != "" { - t.Fatalf("detached: repo=%q head=%q err=%v", repo, head, err) + repo, head, noHead, err = s.repository(t.Context()) + if err != nil || repo != testRepo || head != "" || !errors.Is(noHead, errDetached) { + t.Fatalf("detached: repo=%q head=%q noHead=%v err=%v", repo, head, noHead, err) } } diff --git a/internal/history/github/regression_test.go b/internal/history/github/regression_test.go index ba829261..588a8a3d 100644 --- a/internal/history/github/regression_test.go +++ b/internal/history/github/regression_test.go @@ -26,7 +26,7 @@ func TestEffectivePushURLAndTrackingBranch(t *testing.T) { }, "acme:feature/part"}, } { t.Run(tc.name, func(t *testing.T) { - _, head, err := New(".", gitRunner(t, tc.override)).repository(t.Context()) + _, head, _, err := New(".", gitRunner(t, tc.override)).repository(t.Context()) if err != nil || head != tc.want { t.Fatalf("head=%q err=%v, want %q", head, err, tc.want) } diff --git a/internal/history/github/sender.go b/internal/history/github/sender.go index 51ab301e..0b8d31f9 100644 --- a/internal/history/github/sender.go +++ b/internal/history/github/sender.go @@ -10,6 +10,7 @@ import ( "net/http" "net/url" "os" + "regexp" "strconv" "strings" "time" @@ -37,7 +38,7 @@ func New(dir string, runner toolrun.Runner) *Sender { // Send finds exactly one open pull request and posts one comment. Without a // pull request, only a can answer may open an issue. POST is never retried. func (s *Sender) Send(ctx context.Context, r Input) (Outcome, error) { - repo, head, err := s.repository(ctx) + repo, head, noHead, err := s.repository(ctx) if err != nil { return Outcome{}, err } @@ -45,7 +46,7 @@ func (s *Sender) Send(ctx context.Context, r Input) (Outcome, error) { return Outcome{}, nil } if head == "" && r.Can == nil { - return Outcome{}, openPull() + return Outcome{}, noHead } token, err := s.credentials(ctx) if err != nil { @@ -62,20 +63,20 @@ func (s *Sender) Send(ctx context.Context, r Input) (Outcome, error) { return Outcome{}, err } if pulls == nil { - return Outcome{}, errors.New("GitHub lookup returned no list; nothing sent") + return Outcome{}, notSent("GitHub lookup returned no list; nothing sent") } if len(pulls) > 1 || more { numbers := make([]string, 0, len(pulls)) for _, p := range pulls { numbers = append(numbers, "#"+strconv.Itoa(p.Number)) } - return Outcome{}, fmt.Errorf("several open pull requests match: %s; nothing sent", strings.Join(numbers, ", ")) + return Outcome{}, notSent(fmt.Sprintf("several open pull requests match: %s; nothing sent", strings.Join(numbers, ", "))) } } var payload any if len(pulls) == 1 { if pulls[0].Number < 1 { - return Outcome{}, errors.New("GitHub returned an invalid pull request; nothing sent") + return Outcome{}, notSent("GitHub returned an invalid pull request; nothing sent") } path += "/issues/" + strconv.Itoa(pulls[0].Number) + "/comments" payload = struct { @@ -83,7 +84,7 @@ func (s *Sender) Send(ctx context.Context, r Input) (Outcome, error) { }{Line(r)} } else { if r.Can == nil { - return Outcome{}, openPull() + return Outcome{}, notSent("no open pull request for " + head + "; nothing sent\nnext: open a pull request first") } path += "/issues" payload = struct { @@ -114,8 +115,45 @@ func (s *Sender) Send(ctx context.Context, r Input) (Outcome, error) { return Outcome{Number: number, URL: sent.URL}, nil } -func openPull() error { - return errors.New("no open pull request for this branch; nothing sent\nnext: open a pull request first") +// NothingSent marks an error after which nothing reached GitHub, so the +// request may be posted another way without a duplicate. +type nothingSent string + +func (e nothingSent) Error() string { return string(e) } + +// NothingSent marks the error. +func (nothingSent) NothingSent() {} + +func notSent(message string) error { return nothingSent(message) } + +// Why the current checkout names no pull request head. +var ( + errDetached = notSent("HEAD is not on a branch, so archfit cannot find its pull request; nothing sent\nnext: switch to the branch of the pull request") + remoteName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`) +) + +// noUpstream names the push remote in the command only when the name is safe +// to paste into a shell. +func noUpstream(remote string) error { + next := "push the branch with -u to its remote" + if remoteName.MatchString(remote) { + next = "git push -u " + remote + " HEAD" + } + return notSent("this branch has no upstream branch, so archfit cannot find its pull request; nothing sent\nnext: " + next) +} + +// transportCause is the first line of the network error under err, never the +// URL or a response, and nothing that contains the token. +func transportCause(err error, token string) string { + var u *url.Error + if !errors.As(err, &u) { + return "" + } + cause, _, _ := strings.Cut(u.Err.Error(), "\n") + if cause == "" || strings.Contains(cause, token) { + return "" + } + return ": " + cause } // credentials never returns the output or error of gh: either can contain a @@ -132,17 +170,18 @@ func (s *Sender) credentials(ctx context.Context) (string, error) { return token, nil } } - return "", errors.New("no GitHub credentials; nothing sent\nnext: gh auth login") + return "", notSent("no GitHub credentials; nothing sent\nnext: gh auth login") } -// call deliberately omits response bodies, URLs and transport errors from -// diagnostics: an upstream or proxy error may echo the Authorization header. +// call deliberately omits response bodies and URLs from diagnostics: an +// upstream or proxy error may echo the Authorization header. A transport +// error shows only its cause, and none that contains the token. func (s *Sender) call(ctx context.Context, token, method, path string, payload, result any) (bool, error) { var body io.Reader if payload != nil { data, err := json.Marshal(payload) if err != nil { - return false, errors.New("cannot encode the request; nothing sent") + return false, notSent("cannot encode the request; nothing sent") } // A reader rather than a bytes.Reader leaves GetBody nil: no automatic // replay of a POST by net/http. @@ -150,7 +189,7 @@ func (s *Sender) call(ctx context.Context, token, method, path string, payload, } req, err := http.NewRequestWithContext(ctx, method, "https://api.github.com"+path, body) if err != nil { - return false, errors.New("cannot build GitHub request; nothing sent") + return false, notSent("cannot build GitHub request; nothing sent") } req.Header.Set("Authorization", "Bearer "+token) req.Header.Set("Accept", "application/vnd.github+json") @@ -171,7 +210,7 @@ func (s *Sender) call(ctx context.Context, token, method, path string, payload, if method == http.MethodPost { return false, errors.New("GitHub send failed; outcome unknown: check GitHub before trying again (not retried)") } - return false, errors.New("GitHub lookup failed; nothing sent") + return false, notSent("could not reach GitHub" + transportCause(err, token) + "; nothing sent") } defer func() { _ = response.Body.Close() }() want := http.StatusOK @@ -179,11 +218,10 @@ func (s *Sender) call(ctx context.Context, token, method, path string, payload, want = http.StatusCreated } if response.StatusCode != want { - suffix := "; nothing sent" if method == http.MethodPost && (response.StatusCode < 400 || response.StatusCode >= 500) { - suffix = "; outcome unknown: check GitHub before trying again (not retried)" + return false, fmt.Errorf("GitHub returned HTTP %d; outcome unknown: check GitHub before trying again (not retried)", response.StatusCode) } - return false, fmt.Errorf("GitHub returned HTTP %d%s", response.StatusCode, suffix) + return false, notSent(fmt.Sprintf("GitHub returned HTTP %d; nothing sent", response.StatusCode)) } dec := json.NewDecoder(io.LimitReader(response.Body, 1<<20)) err = dec.Decode(result) @@ -197,7 +235,7 @@ func (s *Sender) call(ctx context.Context, token, method, path string, payload, if method == http.MethodPost { return false, errors.New("GitHub receipt unreadable; outcome unknown: check GitHub before trying again") } - return false, errors.New("GitHub lookup unreadable; nothing sent") + return false, notSent("GitHub lookup unreadable; nothing sent") } return strings.Contains(response.Header.Get("Link"), `rel="next"`), nil } @@ -206,68 +244,72 @@ func (s *Sender) call(ctx context.Context, token, method, path string, payload, func (s *Sender) git(ctx context.Context, args ...string) (string, int, error) { out, err := s.runner.Run(ctx, toolrun.ToolCmd{Name: "git", Args: args, WorkDir: s.dir, Timeout: timeout}) if err != nil { - return "", 0, errors.New("cannot read GitHub repository from git; nothing sent") + return "", 0, notSent("cannot read GitHub repository from git; nothing sent") } return strings.TrimSpace(string(out.Stdout)), out.ExitCode, nil } -func (s *Sender) repository(ctx context.Context) (string, string, error) { +// repository returns the target repository and the pull request head. When +// the checkout names no head, noHead says why; a can answer still opens an +// issue then. +func (s *Sender) repository(ctx context.Context) (repo, head string, noHead, err error) { origin, code, err := s.git(ctx, "config", "--get", "remote.origin.url") if err != nil { - return "", "", err + return "", "", nil, err } if code != 0 && code != 1 { - return "", "", errors.New("cannot read origin; nothing sent") + return "", "", nil, notSent("cannot read origin; nothing sent") } - repo := githubRepository(origin) + repo = githubRepository(origin) if repo == "" { - return "", "", nil + return "", "", nil, nil } target, _, err := s.git(ctx, "config", "--get", "remote.upstream.url") if err != nil { - return "", "", err + return "", "", nil, err } if upstream := githubRepository(target); upstream != "" { repo = upstream } branch, code, err := s.git(ctx, "symbolic-ref", "--quiet", "--short", "HEAD") if err != nil { - return "", "", err + return "", "", nil, err } if code == 1 { - return repo, "", nil - } // Detached HEAD. + return repo, "", errDetached, nil + } if code != 0 { - return "", "", errors.New("cannot read current branch; nothing sent") + return "", "", nil, notSent("cannot read current branch; nothing sent") } upstream, code, err := s.git(ctx, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}") if err != nil { - return "", "", err - } - if code != 0 { - return repo, "", nil + return "", "", nil, err } + hasUpstream := code == 0 pushRemote, _, err := s.git(ctx, "for-each-ref", "--format=%(push:remotename)", "refs/heads/"+branch) if err != nil { - return "", "", err + return "", "", nil, err } if pushRemote == "" { pushRemote = "origin" } + if !hasUpstream { + return repo, "", noUpstream(pushRemote), nil + } remote, code, err := s.git(ctx, "remote", "get-url", "--push", pushRemote) if err != nil { - return "", "", err + return "", "", nil, err } pushRepo := githubRepository(remote) if code != 0 || pushRepo == "" { - return "", "", errors.New("cannot identify the GitHub push destination; nothing sent") + return "", "", nil, notSent("cannot identify the GitHub push destination; nothing sent") } _, remoteBranch, ok := strings.Cut(upstream, "/") if !ok || remoteBranch == "" { - return "", "", errors.New("cannot identify the upstream branch; nothing sent") + return "", "", nil, notSent("cannot identify the upstream branch; nothing sent") } owner, _, _ := strings.Cut(pushRepo, "/") - return repo, owner + ":" + remoteBranch, nil + return repo, owner + ":" + remoteBranch, nil, nil } // githubRepository accepts GitHub HTTPS, SSH and scp-style clone URLs. Reject diff --git a/internal/history/github/sender_test.go b/internal/history/github/sender_test.go index 1ece8ada..5d6237c2 100644 --- a/internal/history/github/sender_test.go +++ b/internal/history/github/sender_test.go @@ -19,15 +19,17 @@ import ( ) const ( - testReason = "why" - testRepo = "acme/shop" - unknownOutcome = "outcome unknown" - secondCredential = "second" - thirdCredential = "third" - forkHead = "worker:feature" - originCommand = "git config --get remote.origin.url" - pushURLCommand = "git remote get-url --push origin" - upstreamCommand = "git rev-parse --abbrev-ref --symbolic-full-name @{upstream}" + testReason = "why" + testRepo = "acme/shop" + unknownOutcome = "outcome unknown" + secondCredential = "second" + thirdCredential = "third" + forkHead = "worker:feature" + originCommand = "git config --get remote.origin.url" + pushURLCommand = "git remote get-url --push origin" + upstreamCommand = "git rev-parse --abbrev-ref --symbolic-full-name @{upstream}" + branchCommand = "git symbolic-ref --quiet --short HEAD" + pushRemoteCommand = "git for-each-ref --format=%(push:remotename) refs/heads/feature" ) const testToken = "secret-test-token" @@ -46,7 +48,7 @@ func TestSendPaths(t *testing.T) { {"check comment", false, onePull, "/repos/acme/shop/issues/431/comments", commentURL, ""}, {"can comment", true, onePull, "/repos/acme/shop/issues/431/comments", commentURL, ""}, {"can issue", true, "[]", "/repos/acme/shop/issues", issueURL, ""}, - {"check without pull", false, "[]", "", "", "next: open a pull request first"}, + {"check without pull", false, "[]", "", "", "no open pull request for acme:feature; nothing sent\nnext: open a pull request first"}, {"ambiguous", false, "[{\"number\":431},{\"number\":432}]", "", "", "#431, #432"}, } { t.Run(tc.name, func(t *testing.T) { @@ -135,6 +137,11 @@ func TestAPIFailuresNeverRetryOrLeak(t *testing.T) { if err == nil || !strings.Contains(err.Error(), tc.want) || strings.Contains(err.Error(), testToken) || got != (Outcome{}) || posts != tc.posts { t.Fatalf("delivery=%+v err=%v posts=%d", got, err, posts) } + // An unknown outcome may have reached GitHub: it must not invite + // the same request a second way. + if marked := nothingSentMarked(err); marked != (tc.want != unknownOutcome) { + t.Errorf("nothing-sent mark %t on %q", marked, err) + } }) } } @@ -156,11 +163,16 @@ func TestSendOutcomeUnknownAfterConnectionLost(t *testing.T) { _ = conn.Close() }) got, err := s.Send(t.Context(), Input{Reason: testReason}) - if err == nil || !strings.Contains(err.Error(), unknownOutcome) || got != (Outcome{}) || posts.Load() != 1 { + if err == nil || !strings.Contains(err.Error(), unknownOutcome) || nothingSentMarked(err) || got != (Outcome{}) || posts.Load() != 1 { t.Fatalf("delivery=%+v err=%v posts=%d", got, err, posts.Load()) } } +func nothingSentMarked(err error) bool { + var marked interface{ NothingSent() } + return errors.As(err, &marked) +} + func TestNoCredentialsSendsNothing(t *testing.T) { t.Setenv("GH_TOKEN", "") t.Setenv("GITHUB_TOKEN", "") @@ -208,21 +220,21 @@ func TestRepositoryRouting(t *testing.T) { }{ {"origin", nil, testRepo, "acme:feature"}, {"fork push", map[string]toolrun.Output{ - "git for-each-ref --format=%(push:remotename) refs/heads/feature": {Stdout: []byte("fork\n")}, - "git remote get-url --push fork": {Stdout: []byte("git@github.com:worker/shop.git\n")}, + pushRemoteCommand: {Stdout: []byte("fork\n")}, + "git remote get-url --push fork": {Stdout: []byte("git@github.com:worker/shop.git\n")}, }, testRepo, forkHead}, {"origin fork upstream", map[string]toolrun.Output{ originCommand: {Stdout: []byte("https://github.com/worker/shop.git")}, "git config --get remote.upstream.url": {Stdout: []byte("https://github.com/acme/shop.git")}, }, testRepo, forkHead}, {"no upstream", map[string]toolrun.Output{upstreamCommand: {ExitCode: 128}}, testRepo, ""}, - {"detached", map[string]toolrun.Output{"git symbolic-ref --quiet --short HEAD": {ExitCode: 1}}, testRepo, ""}, + {"detached", map[string]toolrun.Output{branchCommand: {ExitCode: 1}}, testRepo, ""}, {"non GitHub", map[string]toolrun.Output{originCommand: {Stdout: []byte("git@gitlab.com:acme/shop.git")}}, "", ""}, {"no origin", map[string]toolrun.Output{originCommand: {ExitCode: 1}}, "", ""}, } { t.Run(tc.name, func(t *testing.T) { s := New(".", gitRunner(t, tc.override)) - repo, head, err := s.repository(t.Context()) + repo, head, _, err := s.repository(t.Context()) if err != nil || repo != tc.repo || head != tc.head { t.Fatalf("repo=%q head=%q err=%v", repo, head, err) } @@ -230,11 +242,54 @@ func TestRepositoryRouting(t *testing.T) { } } -func TestNoUpstreamDoesNotLookupOrSendCheck(t *testing.T) { - s := New(".", gitRunner(t, map[string]toolrun.Output{upstreamCommand: {ExitCode: 128}})) - got, err := s.Send(t.Context(), Input{Reason: testReason}) - if err == nil || !strings.Contains(err.Error(), "open a pull request first") || got != (Outcome{}) { - t.Fatalf("delivery=%+v err=%v", got, err) +// TestNoHeadSaysWhy: a branch pushed without -u has a pull request that +// archfit cannot find; it must not claim there is none (B6). +func TestNoHeadSaysWhy(t *testing.T) { + for _, tc := range []struct { + name string + override map[string]toolrun.Output + want string + }{ + {"no upstream", map[string]toolrun.Output{upstreamCommand: {ExitCode: 128}}, + "this branch has no upstream branch, so archfit cannot find its pull request; nothing sent\nnext: git push -u origin HEAD"}, + {"no upstream, fork push remote", map[string]toolrun.Output{upstreamCommand: {ExitCode: 128}, pushRemoteCommand: {Stdout: []byte("fork\n")}}, + "this branch has no upstream branch, so archfit cannot find its pull request; nothing sent\nnext: git push -u fork HEAD"}, + {"no upstream, unsafe remote name", map[string]toolrun.Output{upstreamCommand: {ExitCode: 128}, pushRemoteCommand: {Stdout: []byte("$(touch x)\n")}}, + "this branch has no upstream branch, so archfit cannot find its pull request; nothing sent\nnext: push the branch with -u to its remote"}, + {"detached", map[string]toolrun.Output{branchCommand: {ExitCode: 1}}, + "HEAD is not on a branch, so archfit cannot find its pull request; nothing sent\nnext: switch to the branch of the pull request"}, + } { + t.Run(tc.name, func(t *testing.T) { + s := New(".", gitRunner(t, tc.override)) + got, err := s.Send(t.Context(), Input{Reason: testReason}) + var marked interface{ NothingSent() } + if err == nil || err.Error() != tc.want || !errors.As(err, &marked) || got != (Outcome{}) { + t.Fatalf("delivery=%+v err=%v", got, err) + } + }) + } +} + +// TestUnreachableGitHubNamesTheCause: a lookup that never reaches GitHub +// says so with the network error, never the URL or the token (B6). +func TestUnreachableGitHubNamesTheCause(t *testing.T) { + for _, tc := range []struct{ name, cause, want string }{ + {"tls", "tls: failed to verify certificate: x509: OSStatus -26276", + "could not reach GitHub: tls: failed to verify certificate: x509: OSStatus -26276; nothing sent"}, + {"token in the cause", "proxy said Bearer " + testToken, "could not reach GitHub; nothing sent"}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("GH_TOKEN", testToken) + s := New(".", gitRunner(t, nil)) + s.Client = &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) { + return nil, errors.New(tc.cause) + })} + got, err := s.Send(t.Context(), Input{Reason: testReason}) + var marked interface{ NothingSent() } + if err == nil || err.Error() != tc.want || !errors.As(err, &marked) || got != (Outcome{}) { + t.Fatalf("delivery=%+v err=%v", got, err) + } + }) } } @@ -340,11 +395,11 @@ func fakeSender(t *testing.T, override map[string]toolrun.Output, handler http.H func gitRunner(t *testing.T, override map[string]toolrun.Output) *toolrun.RunnerMock { t.Helper() commands := map[string]toolrun.Output{ - originCommand: {Stdout: []byte("https://github.com/acme/shop.git\n")}, - "git config --get remote.upstream.url": {ExitCode: 1}, - "git symbolic-ref --quiet --short HEAD": {Stdout: []byte("feature\n")}, - upstreamCommand: {Stdout: []byte("origin/feature\n")}, - "git for-each-ref --format=%(push:remotename) refs/heads/feature": {}, + originCommand: {Stdout: []byte("https://github.com/acme/shop.git\n")}, + "git config --get remote.upstream.url": {ExitCode: 1}, + branchCommand: {Stdout: []byte("feature\n")}, + upstreamCommand: {Stdout: []byte("origin/feature\n")}, + pushRemoteCommand: {}, } for key, value := range override { commands[key] = value diff --git a/internal/history/setupgit/git.go b/internal/history/setupgit/git.go index 11c066ee..af5c00b3 100644 --- a/internal/history/setupgit/git.go +++ b/internal/history/setupgit/git.go @@ -50,12 +50,15 @@ func nonInteractive(cmd toolrun.ToolCmd) toolrun.ToolCmd { // Git supplies Git operations scoped to the checkout. type Git struct { - Root string - Runner toolrun.Runner - ActionRepository string - PolicyPath string - WorkflowsDir string - Version1, UsesAction func([]byte) bool + Root string + Runner toolrun.Runner + ActionRepository string + PolicyPath string + WorkflowsDir string + // Policy reports whether data is a version 1 policy, and whether that + // policy makes the check required. + Policy func([]byte) (valid, required bool) + UsesAction func([]byte) bool } // Repository verifies that the origin fetch and push URLs identify one repository. @@ -157,20 +160,25 @@ func (g Git) Aligned(ctx context.Context, branch string) (bool, error) { } } -// Merged detects an onboarded default branch without relying on pull request history. -func (g Git) Merged(ctx context.Context, branch string) (bool, error) { +// Merged detects an onboarded default branch without relying on pull request +// history, and reports whether its policy makes the check required. +func (g Git) Merged(ctx context.Context, branch string) (merged, required bool, err error) { ref := OriginRef(branch) names, err := g.run(ctx, "ls-tree", "-z", "-r", "--name-only", ref, "--", g.PolicyPath, g.WorkflowsDir) if err != nil { - return false, err + return false, false, err } files := strings.Split(names, "\x00") if !slices.Contains(files, g.PolicyPath) { - return false, nil + return false, false, nil } policy, err := g.run(ctx, "show", ref+":"+g.PolicyPath) - if err != nil || !g.Version1([]byte(policy)) { - return false, err + if err != nil { + return false, false, err + } + valid, required := g.Policy([]byte(policy)) + if !valid { + return false, false, nil } for _, file := range files { if ext := path.Ext(file); path.Dir(file) != g.WorkflowsDir || (ext != ".yaml" && ext != ".yml") { @@ -178,13 +186,13 @@ func (g Git) Merged(ctx context.Context, branch string) (bool, error) { } data, err := g.run(ctx, "show", ref+":"+file) if err != nil { - return false, err + return false, false, err } if g.UsesAction([]byte(data)) { - return true, nil + return true, required, nil } } - return false, nil + return false, false, nil } // Pending lists modified or untracked setup paths, preserving the input order. diff --git a/internal/history/setupgit/github.go b/internal/history/setupgit/github.go index 619ab8c4..fcc5ff4b 100644 --- a/internal/history/setupgit/github.go +++ b/internal/history/setupgit/github.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" urlpkg "net/url" + "regexp" "strconv" "strings" @@ -30,26 +31,94 @@ type AppCheck struct { Status, Conclusion, HTMLURL, Title string } +// Login is what gh reports about its login. Unreachable holds gh's error when +// it could not ask GitHub. +type Login struct { + Ready, Workflow bool + Unreachable string +} + // Auth reports whether the active login works and whether a known scope permits workflows. // Missing scope information is not evidence of a missing permission. -func (g GitHub) Auth(ctx context.Context) (bool, bool) { +// +// gh reports a network failure as an invalid token, followed by an "Error:" +// line with the cause. Only "not logged into any" hosts and an HTTP 401 mean +// the login itself is missing or refused; any other failure is reported as +// unreachable with its cause, so the user does not sign in again for a +// network fault. +func (g GitHub) Auth(ctx context.Context) Login { out, err := g.command(ctx, "auth", "status", "--hostname", "github.com", "--active") - if err != nil || out.ExitCode != 0 { - return false, false + if errors.Is(err, context.DeadlineExceeded) { + return Login{Unreachable: fmt.Sprintf("gh did not answer within %s", gitTimeout)} + } + if err != nil { + return Login{} + } + if out.ExitCode != 0 { + return Login{Unreachable: unreachable(string(out.Stdout) + "\n" + string(out.Stderr))} } for _, data := range [][]byte{out.Stdout, out.Stderr} { for line := range strings.SplitSeq(string(data), "\n") { - if scopes, ok := strings.CutPrefix(strings.TrimSpace(strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(line), "-"))), "Token scopes:"); ok { + if scopes, ok := strings.CutPrefix(statusLine(line), "Token scopes:"); ok { for scope := range strings.SplitSeq(scopes, ",") { if strings.Trim(strings.TrimSpace(scope), "'\"") == "workflow" { - return true, true + return Login{Ready: true, Workflow: true} } } - return true, false + return Login{Ready: true} } } } - return true, true + return Login{Ready: true, Workflow: true} +} + +// unreachable returns the cause of a failed auth status that was not about +// the login, and "" when gh is not signed in, GitHub refused the token, or gh +// gave no cause. +func unreachable(output string) string { + if strings.Contains(output, "not logged into any") { + return "" + } + for line := range strings.SplitSeq(output, "\n") { + if detail, ok := strings.CutPrefix(statusLine(line), "Error:"); ok { + return errorCause(strings.TrimSpace(detail)) + } + } + return "" +} + +var ( + // requestPrefix is the method and URL that Go puts before a transport error. + requestPrefix = regexp.MustCompile(`^[A-Za-z]+ "[^"]*": `) + // httpAnswer matches gh's two forms of an HTTP error: the scope check's + // "non-200 OK status code: 403 Forbidden body: ..." and the API + // client's "HTTP 403: ()". + httpAnswer = regexp.MustCompile(`^(?:non-200 OK status code: |HTTP )([0-9]{3})\b`) +) + +// errorCause keeps what gh's error says went wrong, never the request URL or +// a response message: a proxy may echo request headers into either. An HTTP +// answer keeps only its status, and a 401 is a refused login, not a cause. +func errorCause(detail string) string { + cause := ghDetail(detail) + if cause == "GitHub answered HTTP 401" { + return "" + } + return cause +} + +// ghDetail is one line of gh's error without the request URL or the text of +// an HTTP answer. +func ghDetail(detail string) string { + if m := httpAnswer.FindStringSubmatch(detail); m != nil { + return "GitHub answered HTTP " + m[1] + } + return requestPrefix.ReplaceAllString(detail, "") +} + +// statusLine trims the indentation and list marker of a gh auth status line. +func statusLine(line string) string { + return strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(line), "-")) } // PullRequest finds an open setup pull request from the same repository. @@ -192,7 +261,7 @@ func (g GitHub) run(ctx context.Context, args ...string) (string, error) { } if out.ExitCode != 0 { detail, _, _ := strings.Cut(strings.TrimSpace(string(out.Stderr)), "\n") - return "", fmt.Errorf("gh %s exited %d: %s", args[0], out.ExitCode, detail) + return "", fmt.Errorf("gh %s exited %d: %s", args[0], out.ExitCode, ghDetail(detail)) } return string(out.Stdout), nil } diff --git a/internal/history/setupgit/setupgit_test.go b/internal/history/setupgit/setupgit_test.go index f0d230d7..8e67ffa0 100644 --- a/internal/history/setupgit/setupgit_test.go +++ b/internal/history/setupgit/setupgit_test.go @@ -58,21 +58,54 @@ func TestPinUsesOnlyExactRefs(t *testing.T) { } func TestAuthChecksWorkflowScope(t *testing.T) { + // The failure texts are what gh 2.105 prints. + const failed = "github.com\n X Failed to log in to github.com account someone (keyring)\n - Active account: true\n" + + " - The token in keyring is invalid.\n - To re-authenticate, run: gh auth login -h github.com\n" + const tls = "tls: failed to verify certificate: x509: OSStatus -26276" for _, tc := range []struct { - name, output string - exit int - ready, workflow bool + name, output string + exit int + want Login }{ - {"valid", " - Token scopes: 'repo', 'workflow'\n", 0, true, true}, - {"unknown scopes", " - Token: fine-grained\n", 0, true, true}, - {"missing", " - Token scopes: 'repo', 'not-workflow'\n", 0, true, false}, - {"account not signed in", " - Token scopes: 'workflow'\n", 1, false, false}, + {"valid", " - Token scopes: 'repo', 'workflow'\n", 0, Login{Ready: true, Workflow: true}}, + {"unknown scopes", " - Token: fine-grained\n", 0, Login{Ready: true, Workflow: true}}, + {"missing", " - Token scopes: 'repo', 'not-workflow'\n", 0, Login{Ready: true}}, + {"account not signed in", " - Token scopes: 'workflow'\n", 1, Login{}}, + {"no login", "You are not logged into any GitHub hosts. To log in, run: gh auth login\n", 1, Login{}}, + {"token refused", failed + ` - Error: non-200 OK status code: 401 Unauthorized body: "{}"` + "\n", 1, Login{}}, + {"network failure", failed + ` - Error: Get "https://api.github.com/": ` + tls + "\n", 1, Login{Unreachable: tls}}, + {"port with 401 in it", failed + ` - Error: Get "https://api.github.com/": proxyconnect tcp: dial tcp 127.0.0.1:4010: connect: connection refused` + "\n", 1, + Login{Unreachable: "proxyconnect tcp: dial tcp 127.0.0.1:4010: connect: connection refused"}}, + {"token refused, API client form", failed + " - Error: HTTP 401: Bad credentials (https://api.github.com/)\n", 1, Login{}}, + {"GitHub answered, API client form", failed + " - Error: HTTP 403: Resource protected by IP allow list (https://api.github.com/)\n", 1, + Login{Unreachable: "GitHub answered HTTP 403"}}, + {"GitHub answered", failed + ` - Error: non-200 OK status code: 403 Forbidden body: "{\"message\":\"echo Bearer secret\"}"` + "\n", 1, + Login{Unreachable: "GitHub answered HTTP 403"}}, } { t.Run(tc.name, func(t *testing.T) { gh := mockGH(t, "auth status --hostname github.com --active", "", tc.output, tc.exit) - ready, workflow := gh.Auth(t.Context()) - if ready != tc.ready || workflow != tc.workflow { - t.Errorf("got %t, %t; want %t, %t", ready, workflow, tc.ready, tc.workflow) + if got := gh.Auth(t.Context()); got != tc.want { + t.Errorf("got %+v; want %+v", got, tc.want) + } + }) + } +} + +func TestAuthWithoutAnAnswer(t *testing.T) { + for _, tc := range []struct { + name string + err error + want Login + }{ + {"no gh", errors.New(`exec: "gh": executable file not found in $PATH`), Login{}}, + {"gh hangs", context.DeadlineExceeded, Login{Unreachable: "gh did not answer within 30s"}}, + } { + t.Run(tc.name, func(t *testing.T) { + gh := GitHub{Runner: &toolrun.RunnerMock{RunFunc: func(context.Context, toolrun.ToolCmd) (toolrun.Output, error) { + return toolrun.Output{}, tc.err + }}} + if got := gh.Auth(t.Context()); got != tc.want { + t.Errorf("got %+v; want %+v", got, tc.want) } }) } @@ -91,6 +124,19 @@ func TestPullRequestChoosesOpenSameRepository(t *testing.T) { } } +func TestPullRequestLookupErrorOmitsTheURL(t *testing.T) { + for _, tc := range []struct{ stderr, want string }{ + {`Post "https://api.github.com/graphql": tls: failed to verify certificate`, "gh pr exited 1: tls: failed to verify certificate"}, + {"HTTP 502: Bad gateway from proxy echo (https://api.github.com/graphql)", "gh pr exited 1: GitHub answered HTTP 502"}, + } { + gh := mockGH(t, "pr list --repo o/r --head archfit/setup --base main --state all --json number,state,url,headRefOid,isCrossRepository", "", tc.stderr+"\n", 1) + _, err := gh.PullRequest(t.Context(), repo, "main", "archfit/setup") + if err == nil || err.Error() != tc.want { + t.Errorf("error %v, want %q", err, tc.want) + } + } +} + func TestAppCheckIgnoresOtherApps(t *testing.T) { for _, tc := range []struct { name, second string @@ -260,8 +306,11 @@ func TestMergedReadsDefaultBranchContent(t *testing.T) { g := Git{ Root: root, Runner: toolrun.New(), PolicyPath: ".archfit.yaml", WorkflowsDir: ".github/workflows", - Version1: func(data []byte) bool { return strings.TrimSpace(string(data)) == "version: 1" }, - UsesAction: func(data []byte) bool { return strings.Contains(string(data), "coupling-dev/archfit-action@") }, + Policy: func(data []byte) (bool, bool) { + version, rest, _ := strings.Cut(string(data), "\n") + return version == "version: 1", rest == "gate: required" + }, + UsesAction: func(data []byte) bool { return strings.Contains(string(data), "coupling-dev/archfit-action@") }, } run := func(args ...string) { t.Helper() @@ -285,11 +334,11 @@ func TestMergedReadsDefaultBranchContent(t *testing.T) { run("config", "commit.gpgsign", "false") run("commit", "--allow-empty", "-m", "initial") run("update-ref", "refs/remotes/origin/main", "HEAD") - assertMerged := func(want bool) { + assertMerged := func(want bool, wantRequired ...bool) { t.Helper() - got, err := g.Merged(t.Context(), "main") - if err != nil || got != want { - t.Fatalf("merged %t, error %v; want %t", got, err, want) + got, required, err := g.Merged(t.Context(), "main") + if err != nil || got != want || required != (len(wantRequired) > 0 && wantRequired[0]) { + t.Fatalf("merged %t, required %t, error %v; want %t, %v", got, required, err, want, wantRequired) } } assertMerged(false) @@ -300,6 +349,11 @@ func TestMergedReadsDefaultBranchContent(t *testing.T) { assertMerged(false) run("update-ref", "refs/remotes/origin/main", "HEAD") assertMerged(true) + write(".archfit.yaml", "version: 1\ngate: required\n") + run("add", "-A") + run("commit", "-m", "required") + run("update-ref", "refs/remotes/origin/main", "HEAD") + assertMerged(true, true) write(".archfit.yaml", "version: 2\n") run("add", "-A") run("commit", "-m", "invalid policy")