Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 65 additions & 1 deletion cmd/archfit/request_send_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ func TestRequestSendsFromCLI(t *testing.T) {
t.Error("missing credential")
}
if r.Method == http.MethodGet {
_, _ = fmt.Fprint(w, tc.pulls)
answerLookup(w, r, tc.pulls)
return
}
posts++
Expand Down Expand Up @@ -149,3 +149,67 @@ func TestRequestSendsFromCLI(t *testing.T) {
type requestTransport func(*http.Request) (*http.Response, error)

func (f requestTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }

// answerLookup answers the pull request lookup with pulls. The branch is not
// on GitHub, so a branch lookup is 404.
func answerLookup(w http.ResponseWriter, r *http.Request, pulls string) {
if strings.Contains(r.URL.Path, "/branches/") {
w.WriteHeader(http.StatusNotFound)
return
}
_, _ = fmt.Fprint(w, pulls)
}

// TestRequestFindsThePullRequestWithoutATrackingRef: a single-branch clone
// pushed with -u records the upstream but keeps no remote-tracking ref. The
// request still reaches the branch's pull request when its head is HEAD (N3).
func TestRequestFindsThePullRequestWithoutATrackingRef(t *testing.T) {
const token = "cli-secret-token"
const receipt = "https://github.com/acme/shop/pull/431#issuecomment-7"
t.Setenv("GH_TOKEN", token)
t.Setenv("GITHUB_TOKEN", "")
dir := fixtureRepo(t, fixtureFiles(), map[string]string{tcNetem: tcImportsUtil})
gitFixture(t, dir, "remote", "add", "origin", "https://github.com/acme/shop.git")
branch := strings.TrimSpace(gitOutput(t, dir, "symbolic-ref", "--short", "HEAD"))
gitFixture(t, dir, "config", "branch."+branch+".remote", "origin")
gitFixture(t, dir, "config", "branch."+branch+".merge", "refs/heads/"+branch)
head := strings.TrimSpace(gitOutput(t, dir, "rev-parse", "HEAD"))
runCLI(t, fixtureDate, cmdCheck, "-C", dir)
var posted []string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
if r.URL.Path != "/repos/acme/shop/pulls" || r.URL.Query().Get("head") != "acme:"+branch {
t.Errorf("lookup %s", r.URL)
}
_, _ = fmt.Fprintf(w, `[{"number":431,"head":{"sha":%q}}]`, head)
return
}
posted = append(posted, r.URL.Path)
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(map[string]any{"number": 431, "id": 7, "html_url": receipt})
}))
defer server.Close()
target, err := url.Parse(server.URL)
if err != nil {
t.Fatal(err)
}
transport := http.DefaultTransport.(*http.Transport).Clone()
defer transport.CloseIdleConnections()
client := &http.Client{Transport: requestTransport(func(r *http.Request) (*http.Response, error) {
r = r.Clone(r.Context())
r.URL.Scheme, r.URL.Host = target.Scheme, target.Host
return transport.RoundTrip(r)
})}
processRunner := toolrun.New()
runner := &toolrun.RunnerMock{RunFunc: func(ctx context.Context, cmd toolrun.ToolCmd) (toolrun.Output, error) {
if cmd.Name == "gh" {
return toolrun.Output{ExitCode: 1}, nil
}
return processRunner.Run(ctx, cmd)
}}
var stdout, stderr bytes.Buffer
code := runDeps([]string{cmdRequest, "-C", dir, "-m", whyGraph}, &appDeps{Runner: runner, Stdout: &stdout, Stderr: &stderr, requestClient: client, now: day(fixtureDate)})
if code != 0 || stdout.String() != receipt+"\n" || stderr.Len() != 0 || len(posted) != 1 || posted[0] != "/repos/acme/shop/issues/431/comments" {
t.Fatalf("exit %d, posted %v, stdout %q, stderr %q", code, posted, stdout.String(), stderr.String())
}
}
2 changes: 1 addition & 1 deletion cmd/archfit/setup_wiring.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func setupDependencies(deps *appDeps, dir string, noHooks bool) (setup.Dependenc
PolicyPath: defaultConfigPath, WorkflowsDir: workflowsDir,
Policy: files.ValidPolicy, UsesAction: setupUsesAction,
}
gh := setupGH{setupgit.GitHub{Root: co.root, Runner: local.Runner, BodyPath: setup.BodyPath}}
gh := setupGH{setupgit.GitHub{Root: co.root, Runner: local.Runner, BodyPath: setup.BodyPath, AppSlug: setup.AppSlug()}}
return setup.Dependencies{
Files: files, Git: git, GitHub: gh, Version: version,
ActionRef: actionRef, ActionRefNote: actionRefNote,
Expand Down
10 changes: 7 additions & 3 deletions cmd/archfit/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ import (
"fmt"

"github.com/coupling-dev/archfit/internal/application/request"
"github.com/coupling-dev/archfit/internal/application/setup"
requestsend "github.com/coupling-dev/archfit/internal/history/github"
)

type StatusCmd struct {
Dir string `short:"C" name:"directory" help:"Run in DIR instead of the current directory." placeholder:"DIR"`
}

func (c *StatusCmd) Run(deps *appDeps) {
func (c *StatusCmd) Run(deps *appDeps) error {
ctx := deps.runContext()
in := request.StatusInput{}
co, err := openCheckout(ctx, deps, dirOr(c.Dir))
Expand All @@ -22,9 +23,12 @@ func (c *StatusCmd) Run(deps *appDeps) {
in.Fresh = true
in.Verdict = last.Check.Status
}
in.StoryText, _ = requestsend.StoryText(ctx, co.root, co.runner)
in.StoryText, _ = requestsend.StoryText(ctx, co.root, co.runner, setup.AppSlug())
}
for _, line := range request.Status(in) {
_, _ = fmt.Fprintln(deps.Stdout, line)
if _, err := fmt.Fprintln(deps.Stdout, line); err != nil {
return err
}
}
return nil
}
62 changes: 62 additions & 0 deletions cmd/archfit/status_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package main

import (
"reflect"
"strings"
"testing"

"github.com/alecthomas/kong"
)

// TestStatusRunsThroughTheCLI: status runs through the real entry point (N2).
func TestStatusRunsThroughTheCLI(t *testing.T) {
t.Parallel()
code, stdout, stderr := runArchfit(t, "status", "-C", t.TempDir())
if code != 0 || stderr != "" || stdout != "✓ change ○ check\nnext: run archfit check\n" {
t.Fatalf("exit %d, stdout %q, stderr %q", code, stdout, stderr)
}
}

// TestEveryCommandRunReturnsError: kong checks a Run method only when it calls
// it, so a Run that returns no error crashes the command at run time. Running
// every command for real would push, post or install; the signature check
// stands in for that, and --help proves each command parses.
func TestEveryCommandRunReturnsError(t *testing.T) {
t.Parallel()
parser, err := kong.New(&cli{}, kong.Name("archfit"))
if err != nil {
t.Fatal(err)
}
errorType := reflect.TypeFor[error]()
var leaves int
var walk func(n *kong.Node, path []string)
walk = func(n *kong.Node, path []string) {
for _, child := range n.Children {
if child.Type != kong.CommandNode {
continue
}
args := append(append([]string{}, path...), child.Name)
if !child.Leaf() {
walk(child, args)
continue
}
leaves++
target := child.Target
if target.Kind() != reflect.Pointer {
target = target.Addr()
}
run := target.MethodByName("Run")
if !run.IsValid() || run.Type().NumOut() != 1 || run.Type().Out(0) != errorType {
t.Errorf("%s: Run must return exactly error, got %v", strings.Join(args, " "), run)
}
code, stdout, stderr := runArchfit(t, append(args, flagHelp)...)
if code != 0 || stderr != "" || stdout == "" {
t.Errorf("%s --help: exit %d, stderr %q", strings.Join(args, " "), code, stderr)
}
}
}
walk(parser.Model.Node, nil)
if leaves < 10 {
t.Fatalf("walked %d commands; the walk missed the command tree", leaves)
}
}
6 changes: 4 additions & 2 deletions docs/agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,10 @@ results need one:

- A `fail` whose `next:` is `archfit request`: the policy does not allow the
change. Only an owner can change that.
- An `unknown` whose cause is `policy`: the policy differs from the target
branch. An owner approves a policy change.
- An `unknown` whose cause is `policy` and whose `why:` is `only owners change
the policy`: the branch changed the policy. An owner approves a policy change.
When the record says the policy changed on the target branch instead, merge
the target branch and run the check again.

An `unknown` whose `next:` names a tool or a `git fetch` is yours to clear.

Expand Down
1 change: 1 addition & 0 deletions docs/ci.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ Run [`archfit setup`](commands.md#setup) to write this workflow. Setup substitut
`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.
A candidate build can also name another App, such as a staging App, in its install link. `archfit setup` and `archfit status` then read the `archfit/gate` check of that App only. A build whose install link names no App reads no check.
Setup does not replace an existing workflow. The Action checks out the repository itself.

```yaml
Expand Down
2 changes: 1 addition & 1 deletion docs/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ 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 <why> [--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 <push remote> HEAD`.
With a GitHub remote, `archfit request` posts `/archfit request <why> [--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 names no pull request: the error says so. When Git keeps no remote-tracking ref for the branch, as in a clone made with `--single-branch`, the request looks for the pull request by the branch's name on the push remote. It posts only when that pull request's head is the current commit; otherwise it names both commits and sends nothing, with `next: git push <push remote> HEAD:refs/heads/<branch>`. When the branch is not on GitHub at all, the error says the branch has no upstream branch, with `next: git push -u <push remote> 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: `no open pull request for <owner>:<branch>` and `next: open a pull request first`.

Expand Down
8 changes: 7 additions & 1 deletion docs/results.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,13 @@ $ archfit check
archfit: unknown, no verdict
```

This branch changed `.archfit.yaml`, so `next` restores the file. When the branch's file is still the one at the merge base and an owner changed the policy on the target branch, `next` is `git merge origin/main, then run archfit check again`.
This branch changed `.archfit.yaml`, so `next` restores the file. When the branch's file is still the one at the merge base, an owner changed the policy on the target branch, and the record says so:

```text
.archfit.yaml: policy: changed on origin/main since this branch started
why: the check uses the policy on origin/main
next: git merge origin/main, then run archfit check again
```

- `next` is `fix the code`, a command to run, `wait for an owner: #n`, or a short instruction such as `git fetch --unshallow`. A note in parentheses can follow it.
- An error with no file, such as an expired exception, names `.archfit.yaml` and no line.
Expand Down
10 changes: 9 additions & 1 deletion docs/troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,15 @@ The keys are a top-level `coupling` or `ai`, a `type` in a rule, and `scip` or `

## Policy differs from the target

A code change cannot judge itself under a policy it changes. Open a separate policy pull request for an owner, and restore the file on your branch: the record names the command. When an owner changed the policy on the target branch after you made your branch, the record says so with its `next` line: merge the target branch into your branch (`git merge origin/main`) and run `archfit check` again.
A code change cannot judge itself under a policy it changes. Open a separate policy pull request for an owner, and restore the file on your branch: the record names the command. When an owner changed the policy on the target branch after you made your branch, the record says so:

```text
.archfit.yaml: policy: changed on origin/main since this branch started
why: the check uses the policy on origin/main
next: git merge origin/main, then run archfit check again
```

Merge the target branch into your branch and run `archfit check` again.

An owner can preview a candidate with `archfit check --policy candidate.yaml`. A preview gives no verdict and saves no output for `archfit request`.

Expand Down
17 changes: 11 additions & 6 deletions internal/application/changecheck/changecheck.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ type Outcome struct {
const (
whyCompare = "the check compares the change with the merge base of its target branch"
whyDiffers = "only owners change the policy"
whyMoved = "the check uses the policy on %s"
whyInvalid = "the check cannot judge with a policy that is not valid"
whyTree = "the policy does not fit the files of the tree"
whyTargetBad = "the policy on %s is not valid"
Expand All @@ -195,6 +196,7 @@ const (
whatNoBase = "HEAD and %s have no merge base in this clone"
whatNoParent = "HEAD is the tip of %s and its parent is not in this clone"
whatDiffers = "differs from %s"
whatMoved = "changed on %s since this branch started"
whatNoPolicy = "no policy file"
nextBaseFlag = "pass --base <target branch>"
nextFetch = "git fetch"
Expand Down Expand Up @@ -479,18 +481,21 @@ func (s Service) compare(ctx context.Context, r *run, ref, commit string) (compa
case t.Err != nil:
r.stopLines(t.Err, fmt.Sprintf(whyTargetBad, ref), result.NextRestore, fmt.Sprintf(nextAskOwner, ref))
case r.differs:
next := fmt.Sprintf(nextRestore, ref)
moved, err := s.targetMoved(ctx, r, commit)
if err != nil {
return false, err
}
// A branch that edited the file must restore it; a branch the target
// moved past only needs the target's policy, so it is not told that
// only owners change the policy.
why := reason{
path: PolicyPath, cause: result.CausePolicy, what: fmt.Sprintf(whatDiffers, ref), why: whyDiffers,
kind: result.NextRestore, next: fmt.Sprintf(nextRestore, ref),
}
if moved {
next = fmt.Sprintf(nextMerge, ref)
why.what, why.why, why.next = fmt.Sprintf(whatMoved, ref), fmt.Sprintf(whyMoved, ref), fmt.Sprintf(nextMerge, ref)
}
r.stop(reason{
path: PolicyPath, cause: result.CausePolicy, what: fmt.Sprintf(whatDiffers, ref), why: whyDiffers,
kind: result.NextRestore, next: next,
})
r.stop(why)
}
return true, nil
}
Expand Down
12 changes: 8 additions & 4 deletions internal/application/changecheck/changecheck_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -543,7 +543,7 @@ func TestCheck(t *testing.T) {
name: "a policy the target changed after the merge base names the merge",
setup: func(w *world) { w.policies.target[mainSHA] = file(policyYAML + "# owner\n") },
want: want{
record: ".archfit.yaml: policy: differs from origin/main\n why: only owners change the policy\n" +
record: ".archfit.yaml: policy: changed on origin/main since this branch started\n why: the check uses the policy on origin/main\n" +
" next: git merge origin/main, then run archfit check again\n" + noVerdict,
target: mainRef, differs: true, base: baseSHA, stored: true,
},
Expand All @@ -556,7 +556,7 @@ func TestCheck(t *testing.T) {
w.policies.target[mainSHA] = file(policyYAML + "# owner\n")
},
want: want{
record: ".archfit.yaml: policy: differs from origin/main\n why: only owners change the policy\n" +
record: ".archfit.yaml: policy: changed on origin/main since this branch started\n why: the check uses the policy on origin/main\n" +
" next: git merge origin/main, then run archfit check again\n" + noVerdict,
target: mainRef, differs: true, base: headSHA, stored: true,
},
Expand All @@ -568,7 +568,7 @@ func TestCheck(t *testing.T) {
delete(w.policies.target, baseSHA)
},
want: want{
record: ".archfit.yaml: policy: differs from origin/main\n why: only owners change the policy\n" +
record: ".archfit.yaml: policy: changed on origin/main since this branch started\n why: the check uses the policy on origin/main\n" +
" next: git merge origin/main, then run archfit check again\n" + noVerdict,
target: mainRef, differs: true, base: baseSHA, stored: true,
},
Expand Down Expand Up @@ -715,7 +715,11 @@ func TestCheck(t *testing.T) {
w := newWorld()
tt.setup(w)
out := w.check(t, tt.opts)
if got := render(t, out.Result); got != tt.want.record {
got := render(t, out.Result)
if words := testutil.StoryNotUsedIn(got); tt.want.differs && len(words) > 0 {
t.Errorf("the policy record uses %v:\n%s", words, got)
}
if got != tt.want.record {
t.Errorf("record:\n--- got\n%s--- want\n%s", got, tt.want.record)
}
for _, note := range out.Notes {
Expand Down
17 changes: 17 additions & 0 deletions internal/application/setup/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,23 @@ var (
InstallURL = "https://github.com/apps/archfit-review/installations/new"
)

const appsPrefix = "https://github.com/apps/"

// AppSlug is the App whose archfit/gate check this build trusts: the slug in
// InstallURL, so a candidate build that installs another App also reads its
// check. An InstallURL with no slug trusts no App: falling back to the
// production App would read a check the build does not send users to.
func AppSlug() string { return appSlug(InstallURL) }

func appSlug(installURL string) string {
rest, ok := strings.CutPrefix(installURL, appsPrefix)
slug, _, _ := strings.Cut(rest, "/")
if !ok {
return ""
}
return slug
}

// Files reads and writes onboarding files in the current checkout.
type Files interface {
SafePaths() (string, error)
Expand Down
18 changes: 18 additions & 0 deletions internal/application/setup/setup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,3 +139,21 @@ func TestShellQuote(t *testing.T) {
t.Fatalf("unsafe quoting: %q", got)
}
}

func TestAppSlugComesFromTheInstallURL(t *testing.T) {
for _, tc := range []struct{ url, want string }{
{"https://github.com/apps/archfit-review/installations/new", "archfit-review"},
{"https://github.com/apps/archfit-review-staging/installations/new", "archfit-review-staging"},
{"https://github.com/apps/archfit-review-staging", "archfit-review-staging"},
{"https://github.com/apps//installations/new", ""},
{"https://example.com/apps/x/installations/new", ""},
{"", ""},
} {
if got := appSlug(tc.url); got != tc.want {
t.Errorf("appSlug(%q) = %q, want %q", tc.url, got, tc.want)
}
}
if AppSlug() != "archfit-review" {
t.Errorf("default build trusts %q", AppSlug())
}
}
Loading