Skip to content
Merged
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions cmd/archfit/init_owner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -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 == "<your-github-login>"]; 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())
}
})
}
}
9 changes: 9 additions & 0 deletions cmd/archfit/init_v3.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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)
Expand Down
15 changes: 14 additions & 1 deletion cmd/archfit/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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, &notSent) {
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 {
Expand Down
33 changes: 26 additions & 7 deletions cmd/archfit/request_send_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
Expand All @@ -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"
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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")
}
Expand Down
50 changes: 43 additions & 7 deletions cmd/archfit/setup_command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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" {
Expand All @@ -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())
}
}
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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"):
Expand All @@ -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())
}
}
})
}
Expand Down Expand Up @@ -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())
}
}
Expand Down
8 changes: 5 additions & 3 deletions cmd/archfit/setup_files.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) }
Expand Down
6 changes: 5 additions & 1 deletion cmd/archfit/setup_wiring.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion cmd/archfit/setup_workflow_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
}
Expand Down
1 change: 1 addition & 0 deletions cmd/archfit/testdata/init/fresh.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
1 change: 1 addition & 0 deletions docs/ci.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading