Skip to content
quarry Artifact [b887eec1c7]
Login

Artifact [b887eec1c7]

Artifact b887eec1c722d2c3819f5815c5f1730fe7dda4fa74f1e77e1b72137e9cac6616:


package api

import (
	"context"
	"fmt"
	"log"
	"sort"
	"strings"

	"craftdesign.group/quarry/internal/oltp"
	"craftdesign.group/quarry/internal/ops"
)

// CheckRulesStore is a repository's required-checks rules (RFC 0009),
// read and written: the store behind the settings page's rule rows.
// *oltp.DB satisfies it.
type CheckRulesStore interface {
	CheckRules(repo string) ([]oltp.CheckRule, error)
	SetCheckRule(repo, branch string, checks []string) error
}

type checkRulesIn struct {
	Repo string `json:"repo" validate:"required,max=64"`
}

type checkRuleRow struct {
	Branch string   `json:"branch"`
	Checks []string `json:"checks"`
}

type checkRulesOut struct {
	Rules []checkRuleRow `json:"rules"`
}

type checkRuleSetIn struct {
	Repo   string   `json:"repo" validate:"required,max=64"`
	Branch string   `json:"branch" validate:"required,max=200"`
	Checks []string `json:"checks" validate:"max=100"`
}

func (d Deps) checkRuleList(repo string) (checkRulesOut, error) {
	rules, err := d.CheckRules.CheckRules(repo)
	if err != nil {
		return checkRulesOut{}, err
	}
	out := checkRulesOut{Rules: []checkRuleRow{}}
	for _, c := range rules {
		out.Rules = append(out.Rules, checkRuleRow{Branch: c.Branch, Checks: c.Checks})
	}
	return out, nil
}

func registerRequiredChecks(r *ops.Registry, d Deps) error {
	noStore := fmt.Errorf("no required-checks store is configured here: %w", ops.ErrNotFound)
	if err := ops.Register(r, ops.Op[checkRulesIn, checkRulesOut]{
		Name: "ci.checks.list",
		Caps: "a",
		Doc: "List the repository's required-checks rules: for each branch name or glob, the check names a " +
			"landing onto it needs green on its merge (RFC 0009). Whoever may open the repository's settings may read them.",
		Kind:  ops.Query,
		Auth:  ops.Token,
		Route: "GET /api/v1/r/{repo}/ci/required-checks",
		Run: func(ctx context.Context, in checkRulesIn) (checkRulesOut, error) {
			if d.CheckRules == nil {
				return checkRulesOut{}, noStore
			}
			if _, err := d.repoFor(ctx, in.Repo); err != nil {
				return checkRulesOut{}, err
			}
			if err := d.refuseWithout(ctx, in.Repo, "a", false); err != nil {
				return checkRulesOut{}, err
			}
			return d.checkRuleList(in.Repo)
		},
	}); err != nil {
		return err
	}
	return ops.Register(r, ops.Op[checkRuleSetIn, checkRulesOut]{
		Name: "ci.checks.set",
		Ask:  "Set the required checks on {branch} of {repo}",
		Caps: "a",
		Doc: "Set the checks a landing onto a branch needs green on its merge, as the settings page does: " +
			"branch is a name or a glob, checks the check names; an empty list removes the rule. A name that is " +
			"only another name for a branch is refused, since check-ins on it resolve to the other and the rule could never fire. " +
			"Returns the repository's rules. An agent does not set one, since it decides what may land on a branch: it is refused, " +
			"and may ask the person who answers for it with `Quarry-Ask`, who then sets it as themselves. Recorded in the settings log.",
		Kind:  ops.Command,
		Auth:  ops.Token,
		Route: "POST /api/v1/r/{repo}/ci/required-checks",
		Run: func(ctx context.Context, in checkRuleSetIn) (checkRulesOut, error) {
			if d.CheckRules == nil {
				return checkRulesOut{}, noStore
			}
			if who := ops.User(ctx); who != "" {
				if op := d.operatorOf(who); op != "" {
					return checkRulesOut{}, fmt.Errorf("%s is an agent, operated by %s, and an agent does not set what may land on a branch; ask %s: %w",
						who, op, op, ops.ErrForbidden)
				}
			}
			repo, err := d.repoFor(ctx, in.Repo)
			if err != nil {
				return checkRulesOut{}, err
			}
			if err := d.refuseWithout(ctx, in.Repo, "a", false); err != nil {
				return checkRulesOut{}, err
			}
			branch := strings.TrimSpace(in.Branch)
			if branch == "" {
				return checkRulesOut{}, fmt.Errorf("a rule names a branch or a glob: %w", ops.ErrInvalid)
			}
			names := strings.Fields(strings.Join(in.Checks, " "))
			if len(names) > 0 && repo.Index != nil {
				if alias, is, err := repo.Index.AliasOf(branch); err == nil && is && alias != "" {
					return checkRulesOut{}, fmt.Errorf("%s is another name for %s here: check-ins on it resolve to %s, so a rule naming %s could never fire. Set it on %s instead: %w",
						branch, alias, alias, branch, alias, ops.ErrInvalid)
				}
			}
			was, err := d.CheckRules.CheckRules(in.Repo)
			if err != nil {
				return checkRulesOut{}, err
			}
			before := ""
			for _, c := range was {
				if c.Branch == branch {
					before = strings.Join(c.Checks, " ")
				}
			}
			if err := d.CheckRules.SetCheckRule(in.Repo, branch, names); err != nil {
				return checkRulesOut{}, err
			}
			d.logCheckRule(ctx, in.Repo, branch, before, names)
			return d.checkRuleList(in.Repo)
		},
	})
}

// logCheckRule records a changed rule in the settings log, in the
// branch-keyed field protection uses. A failure to write the row is
// logged, not returned: the rule is already set.
func (d Deps) logCheckRule(ctx context.Context, repo, branch, was string, names []string) {
	if d.SettingLog == nil {
		return
	}
	set := append([]string(nil), names...)
	sort.Strings(set)
	now := strings.Join(set, " ")
	if was == now {
		return
	}
	if was == "" {
		was = "(no required checks)"
	}
	if now == "" {
		now = "(no required checks)"
	}
	if ask, ok := signOffAskOf(ctx); ok {
		now = fmt.Sprintf("%s (asked by %s, request %s)", now, ask.agent, ask.id)
	}
	if err := d.SettingLog.LogSetting(repo, ops.User(ctx), ops.Via(ctx), "checks:"+branch, was, now); err != nil {
		log.Printf("settings log: required checks on %s: %v", repo, err)
	}
}