rules

package
v0.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 15 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package rules reads a repository's vx.toml: what text merges cannot see.

[[unique]]      files matching glob may not share a key, e.g. two
                migrations with the same number; or, with content
                (and scope), lines inside them may not share a value,
                e.g. two fields numbered 12 in one proto message
[[generated]]   files matching glob are generated by command: vx never
                text-merges them and tells people to regenerate
[checks]        required = commands vx land should run (--run)
[[policy]]      how changes to some paths land: fast (default), gated
                (required checks run by vx and passing) or human (a
                person approves first)
[files]         large = the size above which vx status and vx land warn
                about a new file (default 1 MiB)
[[check]]       what must be proven before a change lands or ships:
                a command vx runs, or a check an agent, CI or a person
                reports (see checks.go)

The package is pure: it reads trees and blobs through a blob.Store, so the server (land, ship, rebase) and the CLI (vx sync, vx land) apply the same rules to the same trees.

Index

Constants

View Source
const (
	ResultPass    = "pass"
	ResultFail    = "fail"
	ResultNeutral = "neutral"
)

Result states of a check on one tree, as pipelines see them.

View Source
const (
	StatePassed  = "passed"  // a passing result
	StateFailed  = "failed"  // a failing result
	StateNeutral = "neutral" // a neutral result: done, neither pass nor fail
	StateReady   = "ready"   // every check it runs after is done; waits for its result
	StateWaiting = "waiting" // some check it runs after has no result yet
	StateSkipped = "skipped" // a check it runs after failed or was skipped: it will not run on this tree
	StateNotHere = "not needed"
)

Pipeline states of a check on one tree.

View Source
const (
	RebaseAuto   = "auto"   // rebase when it replays cleanly, else say which files conflict
	RebaseNotify = "notify" // only say that the effort is behind, and whether it would conflict
	RebaseOff    = "off"    // do nothing
)

[automation] rebase values.

View Source
const DefaultLargeFile = 1 << 20

DefaultLargeFile is the [files] large default: 1 MiB.

View Source
const File = "vx.toml"

File is where a repository keeps its rules: the root of the tree.

View Source
const PolicyReviewCheck = "review"

PolicyReviewCheck is the name of the check a human [[policy]] stands for: a person approves the change through the review flow.

View Source
const WarningRule engine.WarningKind = "rule"

WarningRule marks a warning about a vx.toml rule.

Variables

Modes lists the modes in vx.toml spelling, least strict first.

Functions

func Check

func Check(ctx context.Context, s blob.Store, r Rules, base, tree hash.Hash) ([]engine.Warning, error)

Check reports [unique] violations in tree as warnings of kind WarningRule, limited to keys used by a file that is new or changed between base and tree, so a clash that predates the change is not repeated on every land. base may be zero: every file counts as new. Content rules (see content.go) report values used more often in tree than in base, with Decl = "SCOPE VALUE" (or "VALUE" outside scopes).

Each warning has Name = the rule name, Decl = the shared key, Files = the full paths of every file using it (sorted), Path = the first of them that changed, and a Detail for people:

migration 008 is used by 008_effort_rebases.sql and 008_orgs.sql (rule migration in vx.toml)

func ContentKeys added in v0.5.0

func ContentKeys(content, scope *regexp.Regexp, data []byte) map[string][]int

ContentKeys returns the values content matches in data, each prefixed with its scope ("LandResponse 12"; without scope, or outside every scope, just "12"), with the 1-based lines they are on. scope may be nil.

func Files

func Files(ctx context.Context, s blob.Store, tree hash.Hash, g Glob) ([]string, error)

Files lists the files of tree that match g, sorted. Only the glob's literal directory is read.

func FormatTimeout added in v0.7.0

func FormatTimeout(d time.Duration) string

FormatTimeout writes a timeout as vx.toml would ("30m", "1h30m", "90s").

func KeyOf

func KeyOf(key *regexp.Regexp, path string) (string, bool)

KeyOf returns the first group of key matched against the base name of path.

func MatchGlob

func MatchGlob(pattern, path string) bool

MatchGlob reports whether path matches pattern; an invalid pattern matches nothing.

func MergeOptions

func MergeOptions(ctx context.Context, s blob.Store, trees ...hash.Hash) []engine.MergeOption

MergeOptions are the engine options of a merge whose sides are trees: the [[generated]] rules of every one of them, so a generated file is never text-merged whichever side declared it. A vx.toml that does not parse adds nothing (the land reports it).

func MissingChecks

func MissingChecks(r Rules, ran []string) []string

MissingChecks returns the required checks of r that are not in ran (commands vx ran, compared after trimming spaces), in vx.toml order.

func NotVerified

func NotVerified(command string) string

NotVerified describes a required check vx did not run:

required check `go vet ./...` (vx.toml) was not run by vx

func ParseSize added in v0.7.0

func ParseSize(v any) (int64, error)

ParseSize reads a size such as "1 MiB", "500KB", "2MB" or a number of bytes (1048576). KB, MB and GB are powers of 1000; KiB, MiB and GiB of 1024.

func PipelineReady added in v0.7.0

func PipelineReady(steps []Step, results map[string]string, applies func(name string) bool) []string

PipelineReady lists the checks of steps that may run now on a tree: those without a result whose every after is done (see Pipeline). On a new tree, without results, these are the checks that run after nothing (or only after checks that do not apply).

func PipelineSkipped added in v0.7.0

func PipelineSkipped(steps []Step, results map[string]string, applies func(name string) bool) map[string]string

PipelineSkipped lists the checks of steps that will not run on a tree because a check they run after failed, with the reason.

func ResolveInputs added in v0.7.0

func ResolveInputs(s Step, outputs map[string]Output) (values map[string]string, missing []string)

ResolveInputs gives the values of a step's inputs that name earlier checks' outputs, keyed by the input as written ("build.preview_url"), from outputs (check name -> its result's outputs on this tree). Inputs vx provides itself are left to the caller. missing lists the inputs whose check has no such field or artifact.

func ShellQuote added in v0.4.0

func ShellQuote(s string) string

ShellQuote quotes s as one sh word, in single quotes.

func ValidateChecks added in v0.7.0

func ValidateChecks(defs ...[]CheckDef) error

ValidateChecks checks a set of checks that apply together, for example a repository's [[check]] tables and its organization's rules: names are unique, and after and inputs pass ValidatePipeline (every after names a check of the set). The problems name the check and its origin.

Types

type Approver added in v0.4.0

type Approver struct {
	Kind string // "user" or "team"
	Name string // a handle, or ORG/TEAM
}

Approver is a parsed approvers entry.

func ParseApprover added in v0.4.0

func ParseApprover(s string) (Approver, error)

ParseApprover parses "user:HANDLE" or "team:ORG/TEAM".

type Blocks added in v0.7.0

type Blocks string

Blocks is what a check without a passing result stops.

const (
	BlocksLand    Blocks = "land"
	BlocksShip    Blocks = "ship"
	BlocksNothing Blocks = "nothing"
)

What a check blocks.

type CheckDef added in v0.7.0

type CheckDef struct {
	Name     string   `json:"name"`
	When     When     `json:"when"`
	Paths    []string `json:"paths,omitempty"`  // globs; empty: every change
	Runner   string   `json:"runner,omitempty"` // "agent:KIND", "ci", "human"; empty for run checks
	Reporter Reporter `json:"reporter"`
	// AllowSamePerson lets another agent of the author's person count as
	// independent (allow_same_person = true; the company allows it).
	AllowSamePerson bool     `json:"allow_same_person,omitempty"`
	Inputs          []string `json:"inputs,omitempty"`
	Outputs         Outputs  `json:"outputs,omitempty"`
	After           []string `json:"after,omitempty"`
	Blocks          Blocks   `json:"blocks"`
	// Timeout bounds a run by a runner; zero: no limit set.
	Timeout time.Duration `json:"timeout,omitempty"`
	// Run is the command of a run check: the landing agent runs it (vx
	// land --run) and vx records the output.
	Run    string `json:"run,omitempty"`
	Origin Origin `json:"origin,omitempty"`
	// Line is the line of the table in vx.toml; 0 when not known.
	Line int `json:"line,omitempty"`
}

CheckDef is one check: a [[check]] table, an organization rule, or a check made from the older [checks] required and [[policy]] tables. Its JSON form is how organization rules are stored.

func ParseChecks added in v0.7.0

func ParseChecks(data []byte) ([]CheckDef, error)

ParseChecks parses TOML that holds only [[check]] tables, with the same rules as vx.toml (organization rules use it). Unknown keys are errors here: an organization's rules are written for this server.

func (CheckDef) Applies added in v0.7.0

func (d CheckDef) Applies(paths []string) bool

Applies reports whether a change of paths needs the check: always without Paths, else when one of them matches a glob.

func (CheckDef) ArtifactAllowed added in v0.7.0

func (d CheckDef) ArtifactAllowed(name string) bool

ArtifactAllowed reports whether an artifact called name may be attached to a result of the check.

func (CheckDef) Describe added in v0.7.0

func (d CheckDef) Describe() string

Describe names the check for people: `check "unit" (vx.toml line 12)`, `required check "go vet ./..." (vx.toml [checks])`.

func (CheckDef) IsRun added in v0.7.0

func (d CheckDef) IsRun() bool

IsRun reports whether the check is a command vx runs and records.

type Decision added in v0.4.0

type Decision struct {
	Mode Mode // ModeFast when no policy matches
	// Paths are the changed files under the policies of Mode, sorted: the
	// files that make this land gated or human.
	Paths []string
	// Require are the checks of every matching gated or human policy, in
	// vx.toml order without repeats.
	Require []string
	// Approvers has one list per matching human policy that names
	// approvers: a person approves only when they are in every list.
	Approvers [][]string
	// Policies describe the policies of Mode that matched (Policy.Describe).
	Policies []string
}

Decision is the policy that applies to a land: the strictest of the policies whose paths match a file the land changes.

func Combine added in v0.4.0

func Combine(ds ...Decision) Decision

Combine returns the strictest of decisions, for example the policies of the effort head's vx.toml and of the snapshot's: a change can make its own policy stricter but never weaker. The checks of every gated or human decision add up; the paths, approvers and policies are those of the strictest mode.

func (Decision) LandCommand added in v0.4.0

func (d Decision) LandCommand() string

LandCommand is the vx land that runs every check of d, quoted for sh:

vx land --run 'go vet ./...' --run 'go test ./...'

func (Decision) Missing added in v0.4.0

func (d Decision) Missing(passed, failed []string) []MissingCheck

Missing returns the checks of d that did not run by vx and pass: passed are the commands vx ran that passed (compared after trimming spaces), failed those it ran that failed. Each entry says which.

type Error

type Error struct {
	Problems []Problem
}

Error lists everything wrong in a vx.toml.

func (*Error) Error

func (e *Error) Error() string

type Generated

type Generated struct {
	Glob    string
	Command string
}

Generated says files matching Glob are generated by Command: vx never text-merges them and tells people to regenerate instead.

type Glob

type Glob struct {
	// contains filtered or unexported fields
}

Glob matches slash-separated repository paths. A "*" matches any run of characters within one path segment, "?" one character within a segment, and a "**" segment any number of segments (zero or more):

internal/store/migrations/*.sql   files directly in that directory
gen/**                            every file under gen/
**/*_string.go                    a file of that name at any depth
api/**/types.go                   api/types.go, api/v1/types.go, ...

Paths have no leading slash. Character classes and braces are not supported, so a glob means the same thing to everyone reading vx.toml.

func CompileGlob

func CompileGlob(pattern string) (Glob, error)

CompileGlob checks a glob and prepares it for matching. Errors say what is wrong and how to write it instead.

func (Glob) Dir

func (g Glob) Dir() string

Dir is the literal directory every matching path lives under, "" for the repository root: the part of the tree a scan has to read.

func (Glob) Match

func (g Glob) Match(path string) bool

Match reports whether path matches the glob.

func (Glob) String

func (g Glob) String() string

String returns the glob as written.

type InputRef added in v0.7.0

type InputRef struct {
	Raw string
	// Check is the earlier check whose output this is; empty for an input
	// vx provides (diff, changed_files, ...).
	Check string
	// Field is the data field of Check's result (build.preview_url).
	Field string
	// Artifact is the artifact name of Check's result
	// (build.artifact:app.zip).
	Artifact string
}

InputRef is one entry of a check's inputs.

func ParseInput added in v0.7.0

func ParseInput(s string) (InputRef, error)

ParseInput reads one inputs entry: NAME (provided by vx), CHECK.FIELD (a data field of CHECK's result) or CHECK.artifact:NAME (an artifact of CHECK's result).

func (InputRef) IsOutput added in v0.7.0

func (r InputRef) IsOutput() bool

IsOutput reports whether the input is an earlier check's output.

type MissingCheck added in v0.4.0

type MissingCheck struct {
	Command string
	Failed  bool // vx ran it and it failed; otherwise vx did not run it
}

MissingCheck is a required check a gated land lacks.

type Mode added in v0.4.0

type Mode string

Mode is how a landing policy lands changes to its paths.

const (
	// ModeFast lands at once and checks afterwards: what vx always did.
	ModeFast Mode = "fast"
	// ModeGated lands only when every required check ran by vx (vx land
	// --run) and passed in this land, on exactly what lands.
	ModeGated Mode = "gated"
	// ModeHuman is gated, and then a person approves before the change
	// lands: until then it waits as a pending review and the effort head
	// does not move.
	ModeHuman Mode = "human"
)

Landing modes, from the least to the most strict.

func (Mode) Stricter added in v0.4.0

func (m Mode) Stricter(o Mode) bool

Stricter reports whether m is stricter than o.

type Origin added in v0.7.0

type Origin string

Origin says where a check definition comes from.

const (
	OriginCheck    Origin = "check"    // a [[check]] table of vx.toml
	OriginRequired Origin = "required" // [checks] required, as a run check
	OriginPolicy   Origin = "policy"   // a gated or human [[policy]]
	OriginOrg      Origin = "org"      // an organization rule (set by org admins)
)

Origins.

type Output added in v0.7.0

type Output struct {
	Data      map[string]string // data fields
	Artifacts map[string]string // artifact file name -> where to get it (a URL or a blob reference)
}

Output is one named output of a check's result, for the inputs of the checks after it.

type Outputs added in v0.7.0

type Outputs struct {
	Required  []string `json:"required,omitempty"`
	Artifacts []string `json:"artifacts,omitempty"`
}

Outputs are what a check's report produces: Required names a passing report must include (an artifact name, the data file's name, or a top-level key of its data), Artifacts the globs artifact names must match (empty: any name).

type PipelineProblem added in v0.7.0

type PipelineProblem struct {
	Check string // the check the problem is on
	Msg   string
}

PipelineProblem is one thing wrong with the after and inputs of a set of checks.

func ValidatePipeline added in v0.7.0

func ValidatePipeline(steps []Step, known func(name string) bool) []PipelineProblem

ValidatePipeline checks the after and inputs of steps: no check runs after itself or after a check that (through others) runs after it, and an input CHECK.FIELD names a check this one runs after, directly or through others. Names in after that are not in steps are problems unless known says they exist elsewhere (organization checks, for a vx.toml); known may be nil.

func (PipelineProblem) String added in v0.7.0

func (p PipelineProblem) String() string

type Policy added in v0.4.0

type Policy struct {
	Paths []string // globs
	Mode  Mode
	// Require are the checks a gated or human land needs, run by vx and
	// passing: the policy's own require, or [checks] required when the
	// policy does not set it.
	Require []string
	// Approvers limit who approves a human land: "user:HANDLE" or
	// "team:ORG/TEAM". Empty: anyone with write on the repository.
	Approvers []string
	Line      int // line of the [[policy]] header in vx.toml; 0 when not known
}

Policy is one [[policy]] of vx.toml: how changes to Paths land.

func (Policy) Describe added in v0.4.0

func (p Policy) Describe() string

Describe names the policy for people:

[[policy]] paths = ["internal/store/migrations/**"] (vx.toml line 12)

func (Policy) Matches added in v0.4.0

func (p Policy) Matches(path string) bool

Matches reports whether path is under one of the policy's globs.

type Problem

type Problem struct {
	Line int // 1-based; 0 when the line is not known
	Msg  string
}

Problem is one thing wrong in vx.toml.

func (Problem) String

func (p Problem) String() string

type Reporter added in v0.7.0

type Reporter string

Reporter says whose result counts for a check. The rules of each are in the service (Service.reporterCounts).

const (
	ReporterSelf        Reporter = "self"        // anyone with write, the author included
	ReporterIndependent Reporter = "independent" // not the author, nor another agent of the author's person
	ReporterCI          Reporter = "ci"          // a CI service token
	ReporterHuman       Reporter = "human"       // a person, never an agent
)

Reporters.

type Rules

type Rules struct {
	Unique         []Unique
	Generated      []Generated
	RequiredChecks []string
	// Rebase is [automation] rebase: what vx does with an open effort when
	// its base branch moves. Empty means RebaseAuto.
	Rebase   string
	Policies []Policy
	// Checks are the [[check]] tables, in vx.toml order (Effective adds
	// the older [checks] required and [[policy]] tables as checks).
	Checks []CheckDef
	Source string // e.g. "vx.toml at 3f2a1c9d0e7b"; empty: none
	// LargeFile is [files] large in bytes: vx status and vx land warn
	// about new files above it. 0 means DefaultLargeFile.
	LargeFile int64
	// Ignored says what of vx.toml this vx does not know (keys or tables
	// of a newer vx) and so left out: a rule with an unknown key is
	// ignored as a whole. "vx.toml line 15: rule [[unique]] "proto-field"
	// uses key "scope", which this vx does not know; ...".
	Ignored []string
}

Rules are a repository's vx.toml.

func At

func At(ctx context.Context, s blob.Store, tree hash.Hash) (Rules, error)

At returns the rules in vx.toml at the root of tree. Without a vx.toml there are no rules and no error. Source says where they came from.

func Parse

func Parse(data []byte) (Rules, error)

Parse parses vx.toml. Syntax errors, unknown keys, invalid globs and regular expressions are errors (*Error) that say the line and what is wrong.

func (Rules) Check added in v0.7.0

func (r Rules) Check(name string) (CheckDef, bool)

Check returns the [[check]] called name.

func (Rules) Decide added in v0.4.0

func (r Rules) Decide(paths []string) Decision

Decide returns the policy for a land that changes paths.

func (Rules) Effective added in v0.7.0

func (r Rules) Effective() []CheckDef

Effective is every check of the rules: the [[check]] tables, then the older tables as checks so one list says what a change needs:

  • [checks] required: run checks named by their command that block nothing (vx land marks them not verified when vx did not run them), unless a [[check]] already runs the same command;
  • the checks a gated or human [[policy]] requires: run checks that block land for the policy's paths (Service.landPolicy enforces them, with its own messages);
  • a human [[policy]]: a check "review" a person reports by approving the change (vx review approve), blocking land for the policy's paths.

func (Rules) GeneratedMatcher

func (r Rules) GeneratedMatcher() func(path string) (command string, ok bool)

GeneratedMatcher compiles the [[generated]] globs once. The returned function reports whether path is generated and by which command (the first matching rule wins). Invalid globs match nothing.

func (Rules) IsEmpty

func (r Rules) IsEmpty() bool

IsEmpty reports whether there are no rules.

func (Rules) LargeFileLimit added in v0.7.0

func (r Rules) LargeFileLimit() int64

LargeFileLimit is [files] large, DefaultLargeFile when unset.

func (Rules) RebaseMode added in v0.4.0

func (r Rules) RebaseMode() string

RebaseMode is the [automation] rebase setting, RebaseAuto by default.

func (Rules) RunCheck added in v0.7.0

func (r Rules) RunCheck(command string) (CheckDef, bool)

RunCheck returns the [[check]] whose run command is command (after trimming spaces).

func (Rules) UniqueRule

func (r Rules) UniqueRule(name string) (Unique, bool)

UniqueRule returns the [unique] rule called name.

type Step added in v0.7.0

type Step struct {
	Name   string
	After  []string
	Inputs []string
}

Step is what a pipeline needs of a check: its name, the checks it runs after and its inputs.

func StepsOf added in v0.7.0

func StepsOf(defs []CheckDef) []Step

StepsOf is what pipelines need of checks (pipeline.go).

type StepState added in v0.7.0

type StepState struct {
	Name  string
	Depth int // 0 for a check that runs after nothing; else 1 + the deepest check it runs after
	// Parent is the check it is shown under (its deepest after), empty at
	// depth 0; After are all of them.
	Parent string
	After  []string
	State  string
	// Reason says why a check waits or was skipped, for people:
	//
	//	waits for unit
	//	skipped: unit failed
	//	skipped: build was skipped (unit failed)
	Reason string
	// contains filtered or unexported fields
}

StepState is one check's place in the pipeline of one tree.

func Pipeline added in v0.7.0

func Pipeline(steps []Step, results map[string]string, applies func(name string) bool) []StepState

Pipeline places every step on one tree: results maps a check name to its result there (pass, fail or neutral; missing: no result yet), applies reports whether a check applies to the change at all (nil: every one does). A check that does not apply counts as done for the checks that run after it. Neutral counts as done too: only a failure stops a pipeline.

The states come in dependency order (a check after every check it runs after, otherwise in the order of steps), each under its deepest parent, so printing them indented by Depth draws the pipeline. Names in after that are not steps are ignored (ValidatePipeline reports them); a cycle leaves its checks waiting.

type Unique

type Unique struct {
	Name    string
	Glob    string
	Key     string
	Content string // optional, instead of Key: a regular expression matched against each line
	Scope   string // optional, with Content: a regular expression whose first group names a scope
}

Unique says that files matching Glob may not share the first group of Key, matched against the file's base name (for example two migrations with the same number). With Content instead of Key, the rule looks inside the files: the first group of Content, matched against each line, may not be used twice, within each scope that Scope starts (see content.go).

func (Unique) IsContent added in v0.5.0

func (u Unique) IsContent() bool

IsContent reports whether the rule looks inside files rather than at their names.

type When added in v0.7.0

type When string

When is the stage at which a check is expected to run.

const (
	WhenLand   When = "land"   // before the change lands
	WhenShip   When = "ship"   // before the effort ships
	WhenManual When = "manual" // only when someone asks for it
)

Stages.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL