command

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 32 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 command is the command layer of the CLI, and the DSL of its local commands. A group's gen/cli.go makes one cobra command for each method and registers it here: Attach puts the commands of the endpoint groups and the behaviors under osapi client, and AttachLocal puts the commands of the local groups under osapi. A local group, which Define makes, runs in the CLI and calls no API: Run checks its input and calls its handler. The layer that sends an endpoint command's request gives the answer to Output, as Run gives a local method's output, and Output prints it: as JSON for --json, or from the method's output type, by the output style of the CLI. No command writes its own output.

Index

Constants

View Source
const (
	// RenderHidden leaves the field out of the output. --json has it.
	RenderHidden = "-"
	// RenderBytes prints a number of bytes as a size, such as 3.4 GB.
	RenderBytes = "bytes"
	// RenderAge prints the time since a time, or a number of seconds, such
	// as 3s.
	RenderAge = "age"
	// RenderTime prints a time in the one time format of the CLI.
	RenderTime = "time"
	// RenderDuration prints a duration: a Go duration, as a string or as a
	// number of nanoseconds.
	RenderDuration = "duration"
	// RenderDurationMs prints an integer of milliseconds as a duration.
	RenderDurationMs = "duration=ms"
	// RenderStatus prints a status word in its color.
	RenderStatus = "status"
	// RenderBody makes the field the whole output, as it is: a document,
	// such as the text of a skill. The other fields are only in --json.
	RenderBody = "body"
	// RenderShort is the prefix of short=N, which prints the first N
	// characters, with ... after them.
	RenderShort = "short="
)

The values of the render tag of an output field.

View Source
const (
	KindDefinition = "definition"
	KindOption     = "option"
	KindMethod     = "method"
	KindRefine     = "refine"
	KindTag        = "tag"
	KindOutput     = "output"
	KindWiring     = "wiring"
	KindDeps       = "deps"
	KindCheck      = "check"
	KindGenerated  = "generated"
)

The kinds of term in Spec, in the order that a group is written.

View Source
const (
	RuleName     = "name"
	RuleMethods  = "methods"
	RuleUnique   = "unique"
	RuleVerb     = "verb"
	RuleRoot     = "root"
	RuleHelp     = "help"
	RuleFlag     = "flag"
	RuleDoc      = "doc"
	RuleValidate = "validate"
	RuleFails    = "fails"
	RuleHandler  = "handler"
	RuleTag      = "tag"
	RuleSays     = "says"
	RuleSubDoc   = "subdoc"
	RulePrints   = "prints"
	// RuleSecret: a secret.Value input field is not tagged telemetry:"attr".
	RuleSecret = "secret"
)

The rules Validate checks, by the name a Problem reports.

View Source
const SecretHelp = " (a secret: secret://<vault>/<key>, or - to read it from standard input)"

SecretHelp is what the help of a secret flag adds: the forms it takes.

View Source
const SecretsHelp = " (secrets: NAME=secret://<vault>/<key>)"

SecretsHelp is what the help of a flag of a map of secrets adds.

View Source
const Stdin = "-"

Stdin is the value of a secret flag that reads its value from standard input.

View Source
const SubKey = "osapi.endpoint.sub"

SubKey is the annotation of a generated command that goes under a command of its own: the Sub segment of its method, such as trace in osapi client telemetry trace get.

View Source
const TableBlocks = "blocks"

TableBlocks is the table tag of a list whose items print as blocks of paragraphs: a list of long text, such as the terms of a DSL, which the cells of a table would cut.

View Source
const TableSections = "sections"

TableSections is the table tag of a list whose items print as sections: each item's first field is its heading, and the rest prints under it as an object does, with each list in it as a table or blocks.

Variables

View Source
var Absent any = absent{}

Absent is the Want of a Field that must not be in the output, such as the value of a secret, which a read never shows.

View Source
var Actions = map[string]bool{
	"admit": true, "reject": true, "revoke": true, "drain": true, "undrain": true, "retry": true,
	"export": true, "exec": true, "shell": true, "start": true, "stop": true,
	"restart": true, "enable": true, "disable": true, "install": true,
	"uninstall": true, "upload": true, "deploy": true, "undeploy": true,
	"pull": true, "signal": true, "reboot": true, "shutdown": true, "ping": true,
	"status": true, "fingerprint": true, "liveness": true, "ready": true,
	"generate": true, "validate": true, "setup": true, "rotate": true,
	"reveal": true,
}

Actions are the commands that do something a CRUD verb does not say. Add one here only for a real action, never for a noun: list the noun's items with list under it instead, such as agent facts list.

View Source
var Checks = guide.Checks{
	{
		Rule:     RuleName,
		Requires: "The group, each word of Under, each method and each Sub have a name of lowercase letters and digits, starting with a letter.",
		Fix:      "Name the group for what its commands are about, such as token, and each method for what it does, such as generate.",
	},
	{
		Rule:     RuleMethods,
		Requires: "The group has at least one method.",
		Fix:      "Add a method with command.Method, with its input and output types and its name.",
	},
	{
		Rule:     RuleUnique,
		Requires: "No two methods of a group have one name.",
		Fix:      "Give each method its own name.",
	},
	{
		Rule:     RuleVerb,
		Requires: "The last word of each command is a verb (list, get, create, update, delete) or an action in command.Actions, as TestCommandShape holds each command to.",
		Fix:      "Name the method for a verb, and put a noun before it with .Sub, such as key fingerprint. Add a word to command.Actions only for a real action, never for a noun.",
	},
	{
		Rule:     RuleRoot,
		Requires: "A command goes where it runs and what it touches. Its first word is one of command.RootGroups: controller, agent or nats for the process or the files of that component on this host, config for the config that each component reads, dsl for the definitions of osapi, skill for the skills in the binary, sdk for the Go SDK in the binary, and client for a call to the API. A local group calls no API, so it is never under client. Only start and version are commands of the root itself.",
		Fix:      "Put the group Under the command.Parent of the component whose process or files it works on, or of dsl for a command for authors. Add a word to command.RootGroups only as a decision of the owner, recorded in the specs cli.md.",
	},
	{
		Rule:     RuleHelp,
		Requires: "Each method has a Short, and a method with input has an Example. Each flag that an Example names is a flag of the command: a field of its input, a key that its Flag names, or --json, --debug or --osapi-file.",
		Fix:      "Add .Short(\"<what it does>\") and .Example(\"--flag value\") to the method, and spell each flag of an example as the command has it.",
	},
	{
		Rule:     RuleFlag,
		Requires: "Each value is a flag: the input is a struct, each field has a json name that is its flag with _ as -, no flag or in tag, and a type a flag holds (string, bool, int, []string, map[string]string, []byte, secret.Value, map[string]secret.Value, or a named string type of a closed set, such as command.Parent). A command takes no positional argument.",
		Fix:      "Make the input a struct, tag each field json:\"name\", drop the flag and in tags, and use one of the flag types.",
	},
	{
		Rule:     RuleSecret,
		Requires: "No secret.Value input field is tagged telemetry:\"attr\": a span is no place for a secret. A secret flag takes a reference, secret://<vault>/<key>, or - to read the value from standard input, and the command resolves a reference itself.",
		Fix:      "Remove telemetry:\"attr\" from the secret field.",
	},
	{
		Rule:     RuleDoc,
		Requires: "Each input field has a doc tag: the help of its flag.",
		Fix:      "Add doc:\"...\" to the field: a capital letter first and no period at the end.",
	},
	{
		Rule:     RuleValidate,
		Requires: "Each input field has a validate tag: its rules, or omitempty for an optional field with none. Run checks the value against it before the handler runs, and a value that breaks it is a usage error.",
		Fix:      rule.Fix,
	},
	{
		Rule:     RuleFails,
		Requires: "Each rule of an input field has a .Fails input that breaks it, which the command refuses with a usage error, required included. A min of 1 on a string that is required or optional needs none: its only bad value is empty.",
		Fix:      rule.FailsFix,
	},
	{
		Rule:     RuleSubDoc,
		Requires: "Each Sub segment that makes a command of its own, such as method in osapi dsl behavior method get, has a SubDoc: the one line of help of that command.",
		Fix:      "Add command.SubDoc(\"segment\", \"...\") to Define, with what the segment's commands do, such as Show one method of a behavior in full.",
	},
	{
		Rule:     RuleHandler,
		Requires: "The group Uses a type, and each method has a handler, func(context.Context, D, In) (Out, error), with D that type and In and Out the method's types.",
		Fix:      "Add command.Uses[Deps]() to Define, and .Handle(fn) to each method, with the signature that the message names.",
	},
	{
		Rule:     RuleTag,
		Requires: "Each tag key of an output field is one of command.KnownTags. Each render tag is one the output knows: -, bytes, age, time, duration, duration=ms, status or short=N with N above 0. An empty tag is on a list, and a title tag is on the blank field _ of the output type.",
		Fix:      "Use a render value that osapi dsl command spec get lists, put empty on a list field, and put title on a field _ struct{} of the output type.",
	},
	{
		Rule:     RuleSays,
		Requires: "A method that answers with no body says what occurred: its name has a past tense, such as admitted for admit, or .Says gives the text.",
		Fix:      "Add .Says(\"<state>\") to the method, such as .Says(\"draining\") for drain.",
	},
	{
		Rule:     RulePrints,
		Requires: "Each method that prints a body, and is not a process, has an Example that Prints gives its output: a value of the method's output type, which its docs page shows as the CLI prints it. Each process has an Example that Logs gives the lines it writes when it starts, which its docs page shows as its log handler writes them. Prints and Logs follow the Example that they show.",
		Fix:      "Add .Prints(sample) after the Example that it shows, with sample a value of the method's output type, in samples.go of the group. For a process, add .Logs(lines...) after its Example, with the lines in samples.go of the group.",
	},
}

Checks are the rules Validate applies. osapi dsl command validate --help prints each one, and each problem carries the fix of its rule, so an author or an agent can read the rules before breaking one. The tests trigger each rule, and fail on a rule without a check.

View Source
var KnownTags = []string{
	"before", "default", "doc", "empty", "example", "flag", "in", "json", "label",
	"mapstructure", "none", "param", "pattern", "prefix", "render",
	"short", "table", "telemetry", "template", "title", "validate", "yaml",
}

KnownTags are the struct tag keys that a field of an input or an output of a command, a behavior or an endpoint can carry: the DSLs, the validator, the output's renderer and the settings loader read them. A key outside the list is a typo: Go reads a tag only by its exact key, so the field gets nothing from it.

View Source
var RootGroups = []RootGroup{
	{Name: "start", Purpose: "Start each component of osapi on this host", Leaf: true},
	{Name: "version", Purpose: "Show the version of this binary", Leaf: true},
	{
		Name:    "controller",
		Purpose: "Run the controller on this host, and work on its key, its tokens and its roles",
	},
	{Name: "agent", Purpose: "Run the agent on this host, and work on its key"},
	{
		Name:    "nats",
		Purpose: "Run the embedded NATS server on this host, or prepare a NATS server",
	},
	{
		Name:    "pki",
		Purpose: "List and rotate the keys and the TLS certificates of osapi on this host",
	},
	{Name: "config", Purpose: "List, get and validate the config that each component reads"},
	{
		Name:    "skill",
		Purpose: "Show the agent skills in this binary, and install them into a repository",
	},
	{
		Name:    "sdk",
		Purpose: "List, describe and check the Go SDK in this binary: its types and its services",
	},
	{Name: "dsl", Purpose: "Describe, check and document the definitions of osapi, for authors"},
	{Name: "client", Purpose: "Call the API of the controller"},
}

RootGroups are the words directly under osapi, a closed list. A command goes where it runs and what it touches: client for a call to the API, controller, agent or nats for the process or the files of that component on this host, config for the config that each component reads, dsl for the definitions of osapi, skill for the skills in the binary, and sdk for the Go SDK in the binary. Only start and version act on the whole binary or host. TestCommandShape fails on any other word. A new word is a decision of the owner, recorded in the specs cli.md.

View Source
var ShutdownTimeout = 10 * time.Second

ShutdownTimeout is how long a process's components have to stop, after its context ends.

View Source
var Spec = guide.Spec{
	Kinds: []guide.Kind{
		{Kind: KindDefinition, Title: "Definition"},
		{Kind: KindOption, Title: "Options of Define"},
		{Kind: KindMethod, Title: "Methods"},
		{Kind: KindRefine, Title: "Refinements of a method"},
		{Kind: KindTag, Title: "Tags on input fields"},
		{Kind: KindOutput, Title: "Output, from the output type"},
		{Kind: KindDeps, Title: "What a Deps takes"},
		{Kind: KindWiring, Title: "Wiring"},
		{Kind: KindCheck, Title: "What holds a group to its rules"},
		{Kind: KindGenerated, Title: "Generated, never edited"},
	},
	Terms: []guide.Term{
		{
			Kind: KindDefinition,
			Name: `Register(Define(name, doc, options...))`,
			Does: "Declares a group of local commands and adds it to the registry. A local command runs in the CLI process and calls no API, such as osapi controller token generate. Its command is osapi <name>, and doc is its help.",
			When: "One time, in <group>.go under internal/cli/commands/<group>: var Group = command.Register(command.Define(...)). Add its import to internal/cli/commands/all. A command that calls the API is an endpoint or a behavior, not a local command.",
		},

		{
			Kind: KindOption,
			Name: "Uses[Deps]()",
			Does: "Names the struct of what the group's methods use, such as the config, the file system or the signing of tokens. The CLI gives one with Provide when a command runs, and a test gives one with fakes.",
			When: "In each group. Keep it to interfaces, so a test can fake each one. An empty struct needs no wiring.",
		},
		{
			Kind: KindOption,
			Name: `Long("text")`,
			Does: "Is the rest of the help of the group's command, after its one line. A method's .Long is the help of its own command.",
			When: "When the group's command needs more than its one line, such as what each of its commands reads.",
		},
		{
			Kind: KindOption,
			Name: `Fail()`,
			Does: "Is the error a handler returns with its output when the output says what failed, such as the problems of a config: return out, command.Fail(). The output prints as it does on success, then the command exits 1 with no message of its own.",
			When: "For a check whose answer is the report, such as config validate, so a script or CI fails on it. For any other failure, return the error itself.",
		},
		{
			Kind: KindOption,
			Name: `Config("prefix", T{...})`,
			Does: "Declares that the group owns the section prefix of osapi's config, such as controller, with a value of the section's type whose fields are the defaults of its keys. Each field becomes a key of osapi config list, with its environment variable and its default from here, as a behavior's settings come from behavior.Config.",
			When: "For a process group, such as controller start, which owns the section that its process reads. A default lives here, never in a central file; a key with no default is a choice of the operator and says why with a choice tag.",
		},
		{
			Kind: KindOption,
			Name: `Flat()`,
			Does: "Makes the group add no word of its own: each method is a command under the group's parent, the root or the words of Under. A command directly under the root is a leaf of command.RootGroups, such as version; any other has a verb or an action. The group's name stays its identity, for dsl command get --name and its package.",
			When: "For a command that stands alone, such as osapi version, or that goes under a parent that holds other things, such as osapi controller start. Not for a family of commands under one noun, such as token.",
		},
		{
			Kind: KindOption,
			Name: `SubDoc("segment", "short")`,
			Does: "Is the one line of help of the command that a Sub segment makes, such as roles in osapi controller role list. validate fails a Sub segment that makes a command and has none.",
			When: "For each Sub segment of the group whose word is not the method's.",
		},
		{
			Kind: KindOption,
			Name: `Under(Parent, ...)`,
			Does: "Puts the group's command under the command of the words, such as ParentController for osapi dsl endpoint. Use a Parent constant: validate refuses a word outside KnownParents, because Attach makes a word that has no command, so a misspelled word was a new command with no error. Attach uses a hand-written command that cmd/commands.go names.",
			When: "When the commands belong to a command that is there already, such as controller. Without it, the group is under the root.",
		},

		{
			Kind: KindMethod,
			Name: `Process("name")`,
			Does: "A command, osapi <group> <name>, that runs a process until the command's context ends, such as osapi nats start. It has no input and no output type; .Setup sets what it runs, and .Logs gives its page the lines that it writes when it starts. The context is the one the root makes and cancels on SIGINT or SIGTERM.",
			When: "For a command that starts a component and runs until a signal. Its name is an action, such as start.",
		},
		{
			Kind: KindMethod,
			Name: `.Setup(fn)`,
			Does: "Is func(ctx context.Context, d D) (command.Running, error): it makes the process's components with ctx, the command's context, so a signal stops a setup that waits. Running is the components, each with Start() and Stop(ctx), and a Cleanup. command.Serve starts them, waits until ctx ends, stops them together, then runs Cleanup; the stop and the cleanup get context.WithoutCancel(ctx), which keeps its values, with command.ShutdownTimeout, 10 seconds. An error is the command's error, and it exits 1.",
			When: "On each Process, in place of .Handle. Make each component in Setup and start nothing: Serve starts them.",
		},
		{
			Kind: KindMethod,
			Name: `Then(running, fn)`,
			Does: "Is running with fn after its Cleanup, such as the stop of a tracer, which flushes what the components recorded as they stopped.",
			When: "In a Setup that wraps the components of another, such as osapi start, which runs the NATS server, the controller and the agent under one tracer.",
		},
		{
			Kind: KindMethod,
			Name: `.Flag("key", ...)`,
			Does: "Adds a flag to a process for each config key, such as agent.max_jobs: --agent-max-jobs, the key with its dots and underscores as dashes, as OSAPI_AGENT_MAX_JOBS is its environment variable. The flag has the key's type, default and doc, from the config, and sets the key over the environment and the file.",
			When: "On a Process, for each key a person sets when they start it. A Method's flags are its input, so it has no Flag.",
		},
		{
			Kind: KindMethod,
			Name: `Method[In, Out]("name")`,
			Does: "A command, osapi <group> <name>, that takes In and prints Out. Each field of In is a flag. Out prints as JSON with --json, and from its type without it, by the output style of the CLI.",
			When: "For each command of the group. Its name is the command's last word: a verb (list, get, create, update, delete) or an action in command.Actions, never a noun.",
		},

		{
			Kind: KindRefine,
			Name: ".Handle(fn)",
			Does: "Sets the function that runs the command: func(ctx context.Context, d Deps, in In) (Out, error). The generated command reads the flags into In, checks it against its validate tags, and calls it. An error from it prints, and the command exits 1.",
			When: "On each method. Validate checks the signature.",
		},
		{
			Kind: KindRefine,
			Name: `.Short("text")`,
			Does: "Sets the command's one line of help. It starts with a capital letter and has no period at the end; a test of every command holds this.",
			When: "On each method.",
		},
		{
			Kind: KindRefine,
			Name: `.Long("text")`,
			Does: "Sets the rest of the command's help, in sentences.",
			When: "When a person needs more than the one line, such as what the command reads.",
		},
		{
			Kind: KindRefine,
			Name: `.Example("--flag value", "doc")`,
			Does: "Adds an example of the command: the flags after osapi <group> <method>, and, when given, what it shows, as a # line above it. The help and the CLI page show each one.",
			When: "At least one for each method with input: the call a person makes most.",
		},
		{
			Kind: KindRefine,
			Name: `.Prints(sample)`,
			Does: "Gives the last Example its output: a value of the method's output type, which the CLI page shows as the CLI prints it, and as JSON for --json. The page of a method with no output shows its one line for each example, from the example's flags, with no Prints.",
			When: "After the Example that it shows, on each method that prints a body and is not a process: validate fails one with no Prints. Put the sample in samples.go of the group, with each time in UTC.",
		},
		{
			Kind: KindRefine,
			Name: `.Check("words", "flags", path, want, ...)`,
			Does: "Gives the last Example a read that shows its result: the command words after the binary, its flags, and pairs of a path in its --json output and the value that the path must have. A path is JSON names joined with a dot, and a segment [name=value] selects an element of a list. command.Absent is a field that must not be there, and command.OneOf a field that may have any of its values. {out.<path>} is a field of the example's own --json output. The integration suite runs the read after the example, again for up to 30 seconds until it matches.",
			When: "After each Example of a write: the integration gate fails a write example with no Check, CheckFails or NoCheck.",
		},
		{
			Kind: KindRefine,
			Name: `.CheckFails("words", "flags", "text")`,
			Does: "Gives the last Example a read that must fail with text in its error, such as not found: the example removed the thing that the read names.",
			When: "After each Example of a delete or a revoke.",
		},
		{
			Kind: KindRefine,
			Name: `.NoCheck("why")`,
			Does: "Says why no read shows the result of the method's examples. The integration gate takes it in place of a Check, and requires a reason of 40 characters or more.",
			When: "Only on a write whose result no osapi command reads back, such as the streams that nats setup makes.",
		},
		{
			Kind: KindRefine,
			Name: `.Logs(lines...)`,
			Does: "Gives the last Example of a process the lines that it writes when it starts, each a command.LogLine: a level, a message and its attributes. The CLI page shows them as the log handler of the CLI writes them in a terminal, in color, and as JSON for --json.",
			When: "After the Example of each process: validate fails a process with no Logs, and Logs on a method. Put the lines in samples.go of the group, copied from a real start at the info level.",
		},
		{
			Kind: KindRefine,
			Name: `.Sub("segment")`,
			Does: "Puts the command under a command of its own in the group: osapi <group> <segment> <method>, such as controller role list. The method's identity is its segment and its name, so a group can have get and spec get.",
			When: "When the command is about a noun of the group: the noun is the Sub, and the method is the verb.",
		},
		{
			Kind: KindRefine,
			Name: `.Says("state")`,
			Does: "Sets what the one line of a method with no output says, after the key of the input: a state, such as draining. Without it, the line says the past tense of the method, such as admitted for admit. An endpoint method has the same refinement.",
			When: "On a method with no output whose result is a state, not the past tense of its name. validate fails a method with no output, no past tense and no Says.",
		},
		{
			Kind: KindRefine,
			Name: `.Fails("doc", in)`,
			Does: "Declares an input that the command refuses with a usage error, exit code 2: the method's input, with the other fields valid and one rule broken. TestRefusals in internal/cli/commands/all runs each one.",
			When: "For each rule of each input field, required included, as validate requires.",
		},

		{
			Kind: KindTag,
			Name: `json:"name"`,
			Does: "Names the field, its flag (with _ as -) and its key in the JSON of the output.",
			When: "On each field.",
		},
		{
			Kind: KindTag,
			Name: "secret.Value",
			Does: "Not a tag: the type of an input field that holds a secret, from internal/secret; map[string]secret.Value is a map of them. Its flag takes a reference, secret://<vault>/<key>, or - to read the value from standard input; a map flag takes NAME=secret://<vault>/<key>. The command refuses a literal value, which the shell history keeps. Its String, Format, MarshalJSON and LogValue give the reference or [redacted]; Reveal gives the value. Run refuses a reference until the config has a vault. The secret rule refuses one with telemetry:\"attr\".",
			When: "On each input that holds a password, a key or a token. Not a string: a string whose name is on the audit denylist fails TestSecretsAreTyped.",
		},
		{
			Kind: KindTag,
			Name: `doc:"..."`,
			Does: "Is the help of the field's flag. A rule of oneof adds its values in brackets.",
			When: "On each input field: a capital letter first and no period at the end.",
		},
		{
			Kind: KindTag,
			Name: `short:"r"`,
			Does: "Gives the field's flag a one-letter shorthand, such as -r.",
			When: "When the CLI uses that shorthand for the flag elsewhere.",
		},
		{
			Kind: KindTag,
			Name: `default:"value"`,
			Does: "Gives the field's flag its value when the caller gives none. A field with a default is never a required flag.",
			When: "For an option with a value that most calls use.",
		},
		{
			Kind: KindTag,
			Name: rule.TagName,
			Does: "The rules of the value, which Run checks before the handler runs: a value that breaks one is a usage error that names the flag, and the command exits 2. required makes the flag required. The rules are those of internal/validation, which endpoints and behaviors use; dive applies the rules after it to each value of a []string. A custom rule, such as permission, is declared with rule.Declare.",
			When: rule.TagWhen,
		},
		{
			Kind: KindTag,
			Name: "the type of a field",
			Does: "Is the kind of its flag: a string, a bool, an int, a []string (a flag given once for each value, or with commas), a map[string]string (key=value pairs) or a []byte (the path of a local file, whose content the field gets).",
			When: "Pick the type of the value a person types.",
		},

		{
			Kind: KindOutput,
			Name: "Render(p, group, out)",
			Does: "Prints the output of a method through a Printer, as the CLI prints it. The terminal and the pages of the docs site both use it, so a page written from a command's output shows what the command shows.",
			When: "To write an output somewhere other than the terminal, such as a page of the reference.",
		},
		{
			Kind: KindOutput,
			Name: "a list: Items []T, with TotalItems or not, or []T",
			Does: "Prints a heading with the count, such as Files (6):, then a table with one column for each field of T. A list with fewer items than TotalItems counts as (3 of 120). An empty list prints its heading with (0), then None. and the hint of its empty tag.",
			When: "For each method that returns a list. Name the fields Items and TotalItems, and add no other field.",
		},
		{
			Kind: KindOutput,
			Name: "one object",
			Does: "Prints a heading, then an aligned key-value block, one pair for each field. An object in it is a section under the block, with its label as the heading. A list in it is a table under the block, with its count. An object with one field that is an object or a list is an envelope: the value of the field prints, and the envelope does not.",
			When: "For each method that returns one thing.",
		},
		{
			Kind: KindOutput,
			Name: "no output",
			Does: "A method whose output type has no field, such as struct{}, or whose answer has no body (204), prints one line: the key of the input and what occurred, such as m-1 admitted. With --json, it prints nothing.",
			When: "For a write with nothing to return. The text is the past tense of the method, or what .Says gives.",
		},
		{
			Kind: KindOutput,
			Name: "the rules with no options",
			Does: "The columns and the keys have the order of the fields. A field with omitempty or omitzero and no value is not shown. A bool is yes or no. A float32 or float64 has two decimals, such as 0.00. A []string is its values, joined with commas. A time.Time is in the one time format of the CLI. A label is the json name in sentence case, with an initialism such as ID in capitals: machine_id is Machine ID. A column header is the label in capitals. A table leaves out a column that has no value in any row. In a table cell, an object is its values, with a space between them, such as Ubuntu 24.04. A list of objects is the first field of each, with commas, such as HighLoad, DiskPressure. The heading is the name of the group in sentence case, with s for a list.",
			When: "To change the order of the output, change the order of the fields.",
		},
		{
			Kind: KindOutput,
			Name: `render:"-|bytes|age|time|duration|duration=ms|status|short=N|body"`,
			Does: "Changes how a field prints: - leaves it out (--json has it), bytes is a size such as 3.4 GB, age is the time since a time or a number of seconds, time is a time as text in the one time format, duration is a Go duration, duration=ms is an integer of milliseconds as a duration, status is a status word in its color, short=N is the first N characters with ... after them, in a table only: a key-value block shows all of the value, and body makes the field the whole output, as it is, such as the text of a document; the other fields are only in --json.",
			When: "On an output field whose raw value a person cannot read at a glance. validate fails a value that is not one of these.",
		},
		{
			Kind: KindOutput,
			Name: `label:"..."`,
			Does: "Gives the field a different label, and the column the same text in capitals.",
			When: "When the json name does not say what the value is to a person, such as Last seen for registered_at.",
		},
		{
			Kind: KindOutput,
			Name: `none:"..."`,
			Does: "Is the text of a field with no value: absent, null, empty or a zero time. A field with omitempty and a none tag is shown, with the text. A table keeps a column with a none tag, because no cell of it is empty.",
			When: "When no value means something, such as never for a time or (deleted) for a hash.",
		},
		{
			Kind: KindOutput,
			Name: `empty:"..."`,
			Does: "On a list field: the hint that an empty list prints after None., such as Upload one with osapi client file upload.",
			When: "On each list that a person can add to, to tell what to do next.",
		},
		{
			Kind: KindOutput,
			Name: `prefix:"..."`,
			Does: "Is text in front of each value of the field, such as @fact. in front of a fact key.",
			When: "When a person types the value with the prefix.",
		},
		{
			Kind: KindOutput,
			Name: `table:"-"`,
			Does: "Leaves the field out of a table. The key-value block of a get shows it.",
			When: "On a field that a list does not need and a get does, such as a reason or a time of each change.",
		},
		{
			Kind: KindOutput,
			Name: `title:"..."`,
			Does: "On the field _ struct{} of the output type: a different heading. The blank field is not in the JSON or the spec.",
			When: "When the name of the group is not what the output is, such as Stale deployments in the file group.",
		},

		{
			Kind: KindDeps,
			Name: "avfs.VFS",
			Does: "The filesystem, for a command that reads or writes files on the machine where it runs, such as a key or the config. cmd/commands.go gives the real one. A test gives memfs.New(), an in-memory filesystem, and reads what the command wrote from it.",
			When: "For each file that a command reads or writes. Never the os package, which a test cannot replace.",
		},
		{
			Kind: KindDeps,
			Name: "fs.FS",
			Does: "A read-only tree of files, such as the skills and templates that the binary embeds. A test gives fstest.MapFS with the files that it needs.",
			When: "For files that the binary carries, not files on the host.",
		},
		{
			Kind: KindDeps,
			Name: "config.Config, string",
			Does: "The config that osapi read, and plain values such as the path of the config file, a directory or the version. A test gives the value.",
			When: "For what the command reads and does not change. A value is not a service, so it needs no interface.",
		},
		{
			Kind: KindDeps,
			Name: "*slog.Logger",
			Does: "The logger of the process. A test gives slog.New(slog.DiscardHandler).",
			When: "For a process, such as osapi agent start, that logs while it runs. A command that prints its result returns it as its output instead.",
		},
		{
			Kind: KindDeps,
			Name: "*slog.LevelVar",
			Does: "The level of the logger of the process, which the process can change while it runs. The root gives the one that its logger logs at; a test gives new(slog.LevelVar), or nil.",
			When: "For a process whose level can change at run time, such as osapi agent start, which takes the log level of the controller's config of the agent.",
		},
		{
			Kind: KindDeps,
			Name: "func(...)",
			Does: "A function that the CLI gives, such as Behaviors, Validate or NewAgent: it reads the registry of this binary, or makes a part of the process. A test gives a function that returns what the case needs.",
			When: "For one call, or a constructor. When a test must check the calls that a part gets, make the part an interface, as Agent is, and return it from the function.",
		},
		{
			Kind: KindDeps,
			Name: "an interface of the group, in deps.go",
			Does: "A service with methods, such as Tokens, or a part that a constructor returns, such as Agent, Controller and Server. The tests give the mockgen mock from the group's mocks/, from go generate ./internal/cli/commands/<group>/mocks.",
			When: "For a service whose calls a test asserts. Never write a fake by hand: a fake does not fail on a call that the test did not expect.",
		},
		{
			Kind: KindDeps,
			Name: "*cobra.Command",
			Does: "The root command of the CLI, for a group that reads the tree of commands, such as docs and dsl command.",
			When: "Only to read the commands of this binary.",
		},
		{
			Kind: KindDeps,
			Name: "another group's Deps",
			Does: "The Deps of a different group, for a command that runs that group's work, as osapi start runs the NATS server, the controller and the agent.",
			When: "For a command that is several other commands at one time. Each part keeps its own Deps.",
		},
		{
			Kind: KindWiring,
			Name: "Provide[Deps](Group, fn)",
			Does: "Gives the group's methods their Deps: fn makes them when a command runs, after osapi read its config. A command of a group whose Deps has a field, and that has no Provide, fails.",
			When: "In cmd/commands.go, one time for each group whose Deps has a field, with the real config, file system or client.",
		},

		{
			Kind: KindCheck,
			Name: "Root(word) and RootGroups",
			Does: "Where a command goes. The words under osapi are a closed list, each with its purpose: controller, agent or nats for the process or the files of that component on this host, config for the config that each component reads, dsl for the definitions of osapi, skill for the skills in the binary, sdk for the Go SDK in the binary, and client for a call to the API. Only start and version are commands of the root. A local group calls no API, so it is never under client. Under client, the words follow the API path. dsl command validate refuses a group whose first word is not one of them, under the rule root, and TestCommandShape fails on any other word under osapi.",
			When: "Before you name a group: put it Under the component whose process or files it works on, or Under dsl for a command for authors. A new word under osapi is a decision of the owner.",
		},
		{
			Kind: KindWiring,
			Name: "DescribeRoot(root)",
			Does: "Gives each command under the root the purpose of its word in RootGroups as its help. Thus osapi --help and the CLI page of the docs site list each word with its purpose from one list.",
			When: "Once, in cmd/root.go, after each group is attached. Write a purpose in RootGroups, not in a Short of a root command.",
		},
		{
			Kind: KindCheck,
			Name: "Flaggable(type)",
			Does: "Whether a flag holds a value of the type: string, bool, int, []string, map[string]string, []byte, a file, secret.Value, map[string]secret.Value, or a named string type of a closed set, such as Parent, which the command converts from its string flag. The command generator builds a flag of each, and dsl behavior validate asks it of each CLI behavior's input, so the two agree.",
			When: "Give an input field one of those types.",
		},
		{
			Kind: KindCheck,
			Name: "NamedString(type)",
			Does: "Whether the type is a named type of a closed set: a type of its own whose kind is string, such as Parent, and not secret.Value. A flag of it is a string flag, and the command generator converts the flag's value to the type.",
			When: "Give an input field the named type of a closed set, and keep its oneof rule, which checks the value.",
		},
		{
			Kind: KindCheck,
			Name: "TagProblems(type)",
			Does: "Each output tag, such as render, that the output does not know, in the type and the types it holds: the check that dsl command validate makes of a registered command. dsl behavior validate asks it of each behavior's output, so its author sees the problem in the validator they run.",
			When: "Use a render value that dsl command spec get lists.",
		},
		{
			Kind: KindCheck,
			Name: "osapi dsl command validate",
			Does: "Checks every local group against the rules of a definition, and the output of every group: each output tag is one the output knows, and each method with no output says what occurred. Each problem names the rule and ends with its fix. validate --help lists each rule. go generate fails on a local group that breaks one.",
			When: "After each change to a group.",
		},
		{
			Kind: KindCheck,
			Name: "TestRefusals",
			Does: "Runs each input that a method's Fails declares through Run, as the generated command does, and expects a usage error.",
			When: "It is in internal/cli/commands/all, and covers each group with no change.",
		},
		{
			Kind: KindCheck,
			Name: "TestCommandShape",
			Does: "Holds each command under osapi client, and each command of a local group, to <resource> <verb>, with the verbs and actions of command.Verbs and command.Actions.",
			When: "It is in cmd/help_style_test.go. A new action goes in command.Actions; a noun does not.",
		},
		{
			Kind: KindCheck,
			Name: "go generate ./internal/cli/commands/all",
			Does: "Writes, for each local group, the cobra commands in gen/cli.go, and internal/cli/commands/all/gen, which registers every group's commands. cmd attaches them under the root.",
			When: "After each change to a group. go-generate-check fails when a gen/ file is stale. Never edit a gen/ file.",
		},
		{
			Kind: KindCheck,
			Name: "osapi dsl command create --name <group> --description \"...\" --under <word>",
			Does: "Writes a new group under internal/cli/commands/<group>, Under the word of the root that --under names (agent, controller, dsl or nats): a list and a get, an empty Deps, its types and the tests of its methods, and adds its import to internal/cli/commands/all. It builds, validates and passes its tests; command-scaffold-check in just test holds it to that.",
			When: "To start a new group. Then run go generate ./internal/cli/commands/all and just cli-docs-generate, and change it.",
		},
		{
			Kind: KindCheck,
			Name: "osapi dsl command get --name <group>",
			Does: "Describes a group, local, endpoint or behavior: each command and its one line of help. A local group's commands also have their flags and the inputs they refuse.",
			When: "To see a group's commands, and the flags and refusals of a local group.",
		},
		{
			Kind: KindCheck,
			Name: "osapi dsl command list",
			Does: "Lists each command of the binary, and the layer that made it: command, endpoint, behavior, or hand-written.",
			When: "To see what a definition makes, and what is still written by hand in cmd/.",
		},

		{
			Kind: KindGenerated,
			Name: "internal/cli/commands/<group>/gen/",
			Does: "The cobra commands of the group, from go generate ./internal/cli/commands/all.",
			When: "Change the definition, then generate. A generated file that is wrong is fixed in the definition or in internal/cli/command/gen.",
		},
		{
			Kind: KindGenerated,
			Name: "internal/cli/commands/<group>/mocks/",
			Does: "The doubles of the group's Deps, from go generate ./internal/cli/commands/<group>/mocks.",
			When: "Run it again after deps.go changes.",
		},
		{
			Kind: KindGenerated,
			Name: "internal/cli/commands/all/gen/",
			Does: "The import of each group's gen package, so the CLI registers its commands, from go generate ./internal/cli/commands/all.",
			When: "Change the definition, then generate.",
		},
		{
			Kind: KindGenerated,
			Name: "docs/docs/sidebar/usage/cli/",
			Does: "The CLI pages, from just cli-docs-generate. The page of a local command comes from .Short, .Long, .Example, .Prints, .Logs and each input field's doc.",
			When: "Change the definition, then generate. Do not write a CLI page by hand.",
		},
	},
}

Spec is every term of the command DSL. osapi dsl command spec get prints it, so an author, or an agent, learns the DSL from the binary that it builds. A test fails on an exported option, method or refinement of this package without an entry.

View Source
var Verbs = map[string]bool{
	"list":   true,
	"get":    true,
	"create": true,
	"update": true,
	"delete": true,
}

Verbs are the verbs of a resource: each command is <resource> <verb>, and a last word that is not one of these is an action in Actions.

Functions

func AddCommands

func AddCommands(
	g Group,
	cmds ...*cobra.Command,
)

AddCommands adds a group's generated commands. Each gen/cli.go calls it from init.

func Attach

func Attach(
	parent *cobra.Command,
	d Deps,
	groups ...*cobra.Command,
) error

Attach adds every registered group's commands under parent, osapi client, and keeps d for the commands to call through. A group goes under the commands of its command path: next node sysctl is under next, then node, which Attach adds when parent does not have them. A group or a command that is among groups, by name, is that one, so the generated commands join a hand-written command of the same name, such as agent with key and status. A local group is not attached here: AttachLocal puts it under the root.

func AttachLocal

func AttachLocal(
	root *cobra.Command,
	d Deps,
	groups ...*cobra.Command,
) error

AttachLocal adds the commands of every registered local group under root, osapi, as Attach does for the groups under osapi client: a group goes under the commands that Under names, such as controller.

func Check

func Check(
	ctx context.Context,
	in any,
) error

Check validates in against the validate tags of its fields, as Run does before the handler runs. A value that breaks a rule is a *UsageError that names the flag of its field.

func Derive

func Derive(
	p Printer,
	g Group,
	m Command,
	in any,
	answer []byte,
) error

Derive prints answer, the JSON that method m of g answered, through p as the CLI prints it from the output type. in is the method's input, for the one line of an answer with no body.

func DescribeRoot

func DescribeRoot(
	root *cobra.Command,
)

DescribeRoot gives each command directly under root the purpose of its word in RootGroups as its help, so that osapi --help and the CLI page of the docs site list each word with its purpose from one list.

func Done

func Done(
	g Group,
	m Command,
	flags string,
) (any, []byte, bool)

Done is what method m of g prints for an example with flags, when m answers with no body: the input that the flags give, for the one line that Derive prints, and the JSON that --json prints. ok is false for a method that answers with a body, whose example needs a sample output.

func ExampleFlagProblems

func ExampleFlagProblems(
	examples []Example,
	flags map[string]bool,
) []string

ExampleFlagProblems are the flags that examples name and that are not in flags or the flags of each command. A misspelled flag made a docs page show a command that fails. The command DSL and the endpoint DSL both check their examples with it.

func Fail

func Fail() error

Fail is the error a handler returns with its output when the output says what failed, so that a script or CI fails on it: return out, command.Fail(). The output prints as it does on success, then the command exits 1.

func FlagName

func FlagName(
	f reflect.StructField,
) string

FlagName is the flag of an input field: its json name, with _ as -.

func Flaggable

func Flaggable(
	t reflect.Type,
) bool

Flaggable reports whether a flag can hold a value of type t: the types that the command generator builds a flag for, and a named type of a closed set, such as Parent, which is a string flag that the command converts, and a list of one, such as []types.Role. The behavior DSL asks it, so the two cannot disagree.

func GlobalFlag

func GlobalFlag(
	name string,
) bool

GlobalFlag reports whether name, without its dashes, is a flag that the root command adds to each command, such as json.

func GroupByArea

func GroupByArea(
	cmd *cobra.Command,
)

GroupByArea puts each command under cmd that Attach made for a group in a cobra command group of the group's area, so the help of cmd lists them under the label of each area, in the order of area.All: osapi client node --help lists dns and interface under Networking. A command of no area stays under Additional Commands. Call it after Attach.

func InputFlags

func InputFlags(
	in reflect.Type,
) map[string]bool

InputFlags are the flags of the command of a method whose input is in, as the command generator declares them: each field's flag tag, else its FlagName, and its short tag. A field tagged in:"body" that is a struct gives a flag for each of its fields. The keys are the names without the dashes.

func NamedString

func NamedString(
	t reflect.Type,
) bool

NamedString reports whether t is a named type of a closed set: a type of its own whose kind is string, such as Parent. A secret is not one: a flag reads it as a reference.

func Now

func Now() time.Time

Now is the time that an age is from: the clock, or the fixed time that SetNow gives, so a docs page that shows an age is the same on each run.

func Output

func Output(
	group Group,
	method string,
	in any,
	answer []byte,
)

Output prints the answer of method of group, to the input in. With --json it prints the body as it came, or, for a method that answered with no body, its key and what it did. Without it, a group that a GroupPrinter prints, such as a behavior, prints its way, and each other method prints from its output type.

func PrintsGroups

func PrintsGroups(
	p GroupPrinter,
)

PrintsGroups adds p, which prints a kind of group. The behavior runtime adds the result table of each behavior.

func Provide

func Provide[D any](
	g *LocalGroup,
	fn func() D,
)

Provide gives the group's methods their deps: fn makes them when a command runs, after the config is read. D must be the type the group Uses; any other is a mistake in the code, so it panics. A group whose Deps has no field needs none.

func ReadFile

func ReadFile(
	path string,
) ([]byte, bool)

ReadFile is the content of the local file at path, for a flag of a []byte field. A file that it cannot read is reported, and ok is false.

func Render

func Render(
	p Printer,
	name string,
	out any,
) error

Render prints out, the output of a method of the group name, through p as the CLI prints it: thus a page of the docs site that a markdown printer writes from a command's output shows the same thing as the command.

func RenderTags

func RenderTags() []string

RenderTags are the render tags of an output field, as the CLI and the UI read them. short= takes a number after it, such as short=12.

func Report

func Report(
	err error,
)

Report reports a failed call of the running command, through the Error that Attach got.

func Run

func Run(
	cmd *cobra.Command,
	g *LocalGroup,
	method string,
	in any,
) error

Run runs method of g with in, the input that the command's flags made: it checks in against its validate tags, calls the method's handler with the deps that Provide gave, and gives the output to Output, which prints it. An input that breaks a rule is a *UsageError, and the handler does not run. The generated command of each local method calls it.

func Scaffold

func Scaffold(
	root string,
	group string,
	doc string,
	under Parent,
) ([]string, error)

Scaffold writes a new local group's layout under internal/cli/commands/<name>/ in the osapi checkout at root, Under the word of the root that under names, such as controller, and registers it in internal/cli/commands/all. It returns the files written, relative to root, the registration last. Everything is rendered and checked before anything is written, so a taken name or a root that is not a checkout writes nothing.

func Secret

func Secret(
	cmd *cobra.Command,
	name string,
	flag string,
) (secret.Value, bool)

Secret is the value of the secret flag name, as the command sends it: a reference as it is, or the value that standard input gives for -, with no line break at its end. A literal value is refused, and so is a value from standard input that is empty. A refusal is reported, and ok is false.

func Secrets

func Secrets(
	_ *cobra.Command,
	name string,
	flags map[string]string,
) (map[string]secret.Value, bool)

Secrets are the values of the flag name of a map of secrets, each NAME=secret://<vault>/<key>. A literal value is refused, as for Secret, and standard input gives one value only, so - is refused too. A refusal is reported, and ok is false.

func Serve

func Serve(
	cmd *cobra.Command,
	g *LocalGroup,
	method string,
) error

Serve runs the process method of g. The context is the command's: one context, which the root makes and cancels on SIGINT or SIGTERM. Setup gets it, so a signal stops a setup that waits. Serve starts each component, waits until the context ends, then stops the components together, and then runs the cleanup. The stop and the cleanup get the context without its cancel, which keeps its values, with ShutdownTimeout. An error of Setup is the command's error. The generated command of each process calls it.

func SetNow

func SetNow(
	t time.Time,
)

SetNow fixes the time that an age is from to t, or gives the clock back with the zero time. The generator of the docs pages fixes it.

func SetTraceID

func SetTraceID(
	id string,
)

SetTraceID keeps the trace of the call the running command made, for TraceID. The layer that sends the call sets it before Output.

func Strings

func Strings[T ~string](
	values []string,
) []T

Strings is values as a list of T, for a flag of a []T field whose T is a named string type, such as []types.Role.

func TagKeys

func TagKeys(
	tag reflect.StructTag,
) []string

TagKeys are the keys of tag, in order, by the convention that reflect.StructTag.Get reads: key:"value" pairs separated by spaces.

func TagProblems

func TagProblems(
	t reflect.Type,
) []string

TagProblems is each tag of output type t, and of the types it holds, that the output does not know: the check that ValidateOutput makes on a registered command, for a validator that has the type before a command.

func TraceID

func TraceID() string

TraceID is the trace of the call that the running command made, from the controller's traceresponse header, for a printer that prints it, as each behavior's result table does. It is "" when the answer had none.

func WithCheck

func WithCheck(
	examples []Example,
	c ReadBack,
) bool

WithCheck adds c to the last of examples, and reports false when there is no example for it to check: the Check of a method came before its Example, which validate refuses.

Types

type Choice

type Choice []any

Choice is the Want of a Field that may have any of its values, as OneOf makes it.

func OneOf

func OneOf(
	values ...any,
) Choice

OneOf is the Want of a Field that may have any of values, for a state that moves on its own, such as Draining, which becomes Cordoned when the agent's last job ends.

type Column

type Column struct {
	// JSON is the field's json name, its key in the answer.
	JSON string
	// Label is the json name in sentence case, or the label tag.
	Label string
	// Header is the label in capitals.
	Header string
	// Render is the field's render tag, or "".
	Render string
	// None is the text for a field with no value, from the none tag.
	None string
	// Empty is the hint after None. for an empty list, from the empty tag.
	Empty string
	// Prefix is the text in front of each value, from the prefix tag.
	Prefix string
	// OmitEmpty is true for a field whose json tag has omitempty or
	// omitzero: with no value, it is not shown.
	OmitEmpty bool
	// NoTable is true for a field tagged table:"-": a table leaves it out,
	// and a key-value block shows it.
	NoTable bool
	// Blocks is true for a list tagged table:"blocks": each item prints as
	// a block of paragraphs, not as a row, for a list of long text.
	Blocks bool
	// Sections is true for a list tagged table:"sections": each item prints
	// as a section, headed by its first field, such as a kind of a DSL and
	// its terms, since a table cannot show the list each item holds.
	Sections bool
	// NoLabel is true for a field tagged label:"-": in a block, its text
	// is a paragraph with no label.
	NoLabel bool
	// Type is the field's type.
	Type reflect.Type
}

Column is one field of an output type: a column of a table, or a pair of a key-value block.

func Columns

func Columns(
	out reflect.Type,
) []Column

Columns are the fields of out that the output shows, in the order of the fields: each exported field with a json name, of out or of its element for a list, except a field tagged render:"-".

func (Column) Format

func (c Column) Format(
	p Printer,
	v any,
) string

Format is the text of v, the value of the column's field in the answer as JSON decodes it, by its render tag and its type, for a table: short=N cuts it.

func (Column) FormatKV

func (c Column) FormatKV(
	p Printer,
	v any,
) string

FormatKV is the text of v for a key-value block: as Format, except that short=N does not cut it, because a block has the room for all of it.

type Command

type Command interface {
	// MethodName is the method's name in its group.
	MethodName() string
	// Input is the type of the method's input: a flag for each field.
	Input() reflect.Type
	// CommandName is the command's name.
	CommandName() string
	// SubPath is the command the command goes under in its group, or "".
	SubPath() string
	// CommandShort is the command's one line of help.
	CommandShort() string
	// CommandLong is the rest of the command's help, or "".
	CommandLong() string
	// Examples are the command's examples.
	Examples() []Example
	// PageNotes is the Notes section of the command's page, or "".
	PageNotes() string
	// PageResult is the Result section of the command's page, or "".
	PageResult() string
	// Output is the type of the method's output, which the output prints
	// from.
	Output() reflect.Type
	// KeyField is the json name of the input field that names what the
	// command acts on, such as machine_id, or "".
	KeyField() string
	// Saying is what the one line of a method with no body says, which Says
	// set, or "" for the past tense of the method.
	Saying() string
}

Command is one method of a group: one command.

type Component

type Component interface {
	// Start starts the component, and does not block.
	Start()
	// Stop stops the component, in the time that ctx gives.
	Stop(ctx context.Context)
}

Component is a part of a process, such as the NATS server or the agent.

type Deps

type Deps struct {
	// JSON reports whether --json was given.
	JSON func() bool
	// Error reports a failed call.
	Error func(err error)
	// PrintJSON prints an answer as it came, for --json.
	PrintJSON func(body []byte)
	// Print is what the output of a method prints through: the CLI's
	// headings, blocks, tables and formats.
	Print Printer
}

Deps is what the commands need from the CLI.

type Example

type Example struct {
	Flags string
	Doc   string
	// Output is what the API answers for the example, a value of the
	// method's output type, which Prints sets. The docs page of the command
	// shows it as the CLI prints it. Nil shows no output.
	Output any
	// Logs are the lines that a process writes when it starts, which Logs
	// sets. The docs page of the command shows them as its log handler
	// writes them.
	Logs []LogLine
	// Checks are the reads that show what the example changed, which Check
	// and CheckFails add. The integration suite runs each after the example
	// and asserts its fields.
	Checks []ReadBack
}

Example is an example of a CLI command: its flags, and what it shows, which the help writes as a # line above it.

type FailedError

type FailedError struct{}

FailedError is the error of a method whose output says what failed, such as the problems of a config: Run prints the output, then the command exits 1 with no message of its own. Fail returns it.

func (FailedError) Error

func (FailedError) Error() string

type Field

type Field struct {
	Path string
	Want any
}

Field is one field of a ReadBack: the path of the field in the --json output, and the value that it must have.

A path is the JSON names of the fields, joined with a dot, such as labels.group. A segment [name=value] selects the first element of a list whose field name has value, such as items.[id=1a2b3c4d].revoked. Want is compared as JSON: 4 matches 4 and "4" does not. Absent is a field, or a selected element, that is not there, and OneOf is a field that may have any of its values.

func Fields

func Fields(
	pathsAndWants ...any,
) []Field

Fields pairs paths and wants, such as Fields("max_jobs", 4, "log_level", "debug"). It panics on an odd count or a path that is not a string: a definition is wrong, and the gate's tests catch it.

type Group

type Group interface {
	// GroupName is the group's command.
	GroupName() string
	// GroupDoc says what the group is, in one line: its command's help.
	GroupDoc() string
	// GroupNotes is the Notes section of the page of the group's command,
	// or "".
	GroupNotes() string
	// GroupLong is the rest of the help of the group's command, or "".
	GroupLong() string
	// SubDoc is the one line of help of the command that a Sub segment
	// makes, such as trace, or "".
	SubDoc(segment string) string
	// CommandPath is the words of the group's command under osapi client,
	// such as next node sysctl.
	CommandPath() []string
	// Commands are the group's methods, in the order they were declared.
	Commands() []Command
	// CommandPermission is the permission the command of method m needs, or
	// "" for one that needs none.
	CommandPermission(m Command) types.Permission
}

Group is a group of commands, osapi client <group>, with one command for each of its methods. An endpoint group is one.

func Groups

func Groups() []Group

Groups are the registered groups: each endpoint group, behavior and local group whose commands AddCommands added, in the order they were added.

func Origin

func Origin(
	c *cobra.Command,
) (Group, bool)

Origin is the group whose definition made c, a command that Attach or AttachLocal added, and false for a command that a person wrote.

type GroupPrinter

type GroupPrinter func(g Group, method string, answer []byte) bool

GroupPrinter prints the answer of method of group g, and is true, or is false for a group that it does not print.

type LocalGroup

type LocalGroup struct {
	// Name is the group's command, the first word under its path.
	Name string
	// Doc says what the group is, in one line: its command's help.
	Doc string
	// Parents are the words of the command the group goes under, which
	// Under sets, such as controller. The root has none.
	Parents []Parent
	// Deps is the type Uses names: what the methods get from the CLI.
	Deps reflect.Type
	// Methods are the group's commands, in the order they were declared.
	Methods []*LocalMethod
	// Flat is true for a group that adds no word of its own, which Flat
	// sets: its commands are under its parent, such as osapi version.
	Flat bool
	// Long is the rest of the help of the group's command, which Long
	// sets.
	Long string
	// SubDocs are the one line of help of each command that a Sub makes,
	// such as roles in osapi controller role list, which SubDoc sets.
	SubDocs map[string]string

	// ConfigPrefix and ConfigDefaults are the section of the config that the
	// group owns, and its defaults, which Config sets.
	ConfigPrefix   string
	ConfigDefaults any
	// contains filtered or unexported fields
}

LocalGroup is a group of local commands: commands that run in the CLI process, with no API, such as osapi controller token generate. Define makes one; its gen/cli.go makes a cobra command for each method, and Run runs it.

func All

func All() []*LocalGroup

All is each registered local group, by command path.

func Define

func Define(
	name string,
	doc string,
	opts ...Option,
) *LocalGroup

Define builds a local group from its options. Validate checks the result.

func Lookup

func Lookup(
	path string,
) *LocalGroup

Lookup is the registered local group with the command path, such as token, or nil.

func Register

func Register(
	g *LocalGroup,
) *LocalGroup

Register adds g to the local groups the CLI has, and returns it. Two groups with one command path are a mistake in the code, so it panics.

func (*LocalGroup) CommandPath

func (g *LocalGroup) CommandPath() []string

CommandPath is the words of the group's command under the root: the words Under set, then its name.

func (*LocalGroup) CommandPermission

func (g *LocalGroup) CommandPermission(
	_ Command,
) types.Permission

CommandPermission is "": a local command calls no API, so it needs no permission.

func (*LocalGroup) Commands

func (g *LocalGroup) Commands() []Command

Commands are the group's methods.

func (*LocalGroup) GroupDoc

func (g *LocalGroup) GroupDoc() string

GroupDoc is the group's Doc.

func (*LocalGroup) GroupLong

func (g *LocalGroup) GroupLong() string

GroupLong is the help Long set, or "".

func (*LocalGroup) GroupName

func (g *LocalGroup) GroupName() string

GroupName is the group's Name.

func (*LocalGroup) GroupNotes

func (g *LocalGroup) GroupNotes() string

GroupNotes is "": a local group's page has no Notes section.

func (*LocalGroup) Method

func (g *LocalGroup) Method(
	name string,
) *LocalMethod

Method is the method of g with the name, its MethodName, such as get or spec get, or nil.

func (*LocalGroup) Path

func (g *LocalGroup) Path() string

Path is the group's words and its name, such as dsl endpoint, or version for a flat group at the root: the key that Register and Lookup use, and the name that a problem and dsl command get give it.

func (*LocalGroup) SubDoc

func (g *LocalGroup) SubDoc(
	segment string,
) string

SubDoc is the help SubDoc set for the segment, or "".

type LocalMethod

type LocalMethod struct {
	// Name is the method's name in its group, and the command's last word.
	Name string
	// In is the input type: each field is a flag.
	In reflect.Type
	// Out is the output type, which prints as JSON with --json.
	Out reflect.Type
	// contains filtered or unexported fields
}

LocalMethod is one local command. Method makes one; its methods set the rest and return it, so a definition chains them.

func Method

func Method[In, Out any](
	name string,
) *LocalMethod

Method is a local command named name that takes In, whose fields are its flags, and prints Out.

func Process

func Process(
	name string,
) *LocalMethod

Process is a local command named name that runs a process until the context ends, such as osapi nats start: it has no input and no output. Setup sets what it runs.

func (*LocalMethod) Check

func (m *LocalMethod) Check(
	command string,
	flags string,
	pathsAndWants ...any,
) *LocalMethod

Check gives the last Example a read that shows its result: the command words after the binary, such as pki key get, its flags, and the paths and wants of the fields of its --json output, as command.Fields pairs them. The integration suite runs it after the example. validate refuses a Check before an Example.

func (*LocalMethod) CheckFails

func (m *LocalMethod) CheckFails(
	command string,
	flags string,
	errorText string,
) *LocalMethod

CheckFails gives the last Example a read that fails with errorText, such as not found: the example removed the thing that the read names.

func (*LocalMethod) CommandLong

func (m *LocalMethod) CommandLong() string

CommandLong is the help Long set, or "".

func (*LocalMethod) CommandName

func (m *LocalMethod) CommandName() string

CommandName is the command's name, the method's.

func (*LocalMethod) CommandShort

func (m *LocalMethod) CommandShort() string

CommandShort is the one line Short set.

func (*LocalMethod) ConfigKeys

func (m *LocalMethod) ConfigKeys() []string

ConfigKeys are the config keys that Flag named.

func (*LocalMethod) Example

func (m *LocalMethod) Example(
	flags string,
	doc ...string,
) *LocalMethod

Example adds an example of the command: its flags, such as --name web, and, when doc is given, what it shows, as a # line above it.

func (*LocalMethod) Examples

func (m *LocalMethod) Examples() []Example

Examples are the examples Example added.

func (*LocalMethod) Fails

func (m *LocalMethod) Fails(
	doc string,
	input any,
) *LocalMethod

Fails declares an input that the command refuses with a usage error: the method's input with the other fields valid and one rule broken. Validate requires one for each rule of each input field, and a test runs each one.

func (*LocalMethod) Flag

func (m *LocalMethod) Flag(
	keys ...string,
) *LocalMethod

Flag adds a flag for each config key, such as agent.max_jobs, to a process: --agent-max-jobs, with the key's type, default and doc, which sets the key over the environment and the file.

func (*LocalMethod) Handle

func (m *LocalMethod) Handle(
	fn any,
) *LocalMethod

Handle sets the function that runs the command: func(ctx context.Context, d D, in In) (Out, error), with D the type the group Uses. Validate checks the signature; Run calls it.

func (*LocalMethod) Handler

func (m *LocalMethod) Handler() any

Handler is the function Handle set, or nil.

func (*LocalMethod) Input

func (m *LocalMethod) Input() reflect.Type

Input is the method's In.

func (*LocalMethod) IsProcess

func (m *LocalMethod) IsProcess() bool

IsProcess is true for a method that Process made.

func (*LocalMethod) KeyField

func (m *LocalMethod) KeyField() string

KeyField is "": a local command acts on no item of an API.

func (*LocalMethod) Logs

func (m *LocalMethod) Logs(
	lines ...LogLine,
) *LocalMethod

Logs gives the last Example the lines that a process writes when it starts, at the info level or above. The docs page of the command shows them as its log handler writes them in a terminal, and as JSON for --json. validate refuses Logs before an Example, Logs on a method that is not a process, and a process that no example Logs.

func (*LocalMethod) Long

func (m *LocalMethod) Long(
	text string,
) *LocalMethod

Long sets the rest of the command's help.

func (*LocalMethod) MethodName

func (m *LocalMethod) MethodName() string

MethodName is the method's identity in its group: its Sub and its Name, such as roles list, or its Name for a method with no Sub. Two methods of a group can have one Name under two Subs, such as get and spec get.

func (*LocalMethod) NoCheck

func (m *LocalMethod) NoCheck(
	why string,
) *LocalMethod

NoCheck says why no read shows the result of the method's examples, for a write whose result no command reads back. The integration gate requires a Check of each example of a write, or this.

func (*LocalMethod) Output

func (m *LocalMethod) Output() reflect.Type

Output is the method's Out, which its output prints from.

func (*LocalMethod) PageNotes

func (m *LocalMethod) PageNotes() string

PageNotes is "": a local command's page has no Notes section.

func (*LocalMethod) PageResult

func (m *LocalMethod) PageResult() string

PageResult is "": a local command's page has no Result section.

func (*LocalMethod) Prints

func (m *LocalMethod) Prints(
	out any,
) *LocalMethod

Prints gives the last Example its output: what the command prints, a value of the method's output type. The docs page of the command shows it as the CLI prints it, and as JSON for --json. validate refuses a value of another type, Prints before an Example, and a method with output that no example Prints.

func (*LocalMethod) Refusals

func (m *LocalMethod) Refusals() []Refusal

Refusals are the inputs Fails declared.

func (*LocalMethod) Saying

func (m *LocalMethod) Saying() string

Saying is the text Says set, or "".

func (*LocalMethod) Says

func (m *LocalMethod) Says(
	text string,
) *LocalMethod

Says is what the one line of a method with no output says, when it is a state and not the past tense of the method, such as draining for drain.

func (*LocalMethod) Setup

func (m *LocalMethod) Setup(
	fn any,
) *LocalMethod

Setup sets the function that makes a process's components: func(ctx context.Context, d D) (command.Running, error), with D the type the group Uses. Serve calls it with the context of the command, then runs what it returns until that context ends.

func (*LocalMethod) Short

func (m *LocalMethod) Short(
	text string,
) *LocalMethod

Short sets the command's one line of help.

func (*LocalMethod) Sub

func (m *LocalMethod) Sub(
	segment string,
) *LocalMethod

Sub puts the command under a command of its own in the group, such as roles in osapi controller role list.

func (*LocalMethod) SubPath

func (m *LocalMethod) SubPath() string

SubPath is the segment Sub set, or "".

func (*LocalMethod) Unchecked

func (m *LocalMethod) Unchecked() string

Unchecked is why no read shows the result of the method's examples, as NoCheck says it, or "".

type LogLine

type LogLine struct {
	Level slog.Level
	Msg   string
	Attrs []slog.Attr
}

LogLine is a line that a process writes to its log: its level, its message, and its attributes in order, such as component=nats.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option is a setting of a local group, or one of its methods.

func Config

func Config(
	prefix string,
	defaults any,
) Option

Config declares that the group owns the section prefix of osapi's config, such as controller, with defaults: a value of the section's type whose fields are its keys' defaults. Each field becomes a key of osapi config list, with its environment variable, and its default comes from here, as a behavior's settings come from behavior.Config. A process group, such as controller start, owns the section that its process reads.

func Flat

func Flat() Option

Flat makes the group add no word of its own: each method is a command under the group's parent, the root or the words of Under. osapi version is the method version of a flat group at the root; osapi controller start would be the method start of a flat group Under controller. A command directly under the root is a leaf of RootGroups, and any other has a verb or an action.

func Long

func Long(
	text string,
) Option

Long is the rest of the help of the group's command, after its one line, such as what each of its commands reads.

func SubDoc

func SubDoc(
	segment string,
	short string,
) Option

SubDoc is the one line of help of the command that the Sub segment makes, such as roles in osapi controller role list.

func Under

func Under(
	words ...Parent,
) Option

Under puts the group's command under the command of words, such as ParentController for osapi dsl endpoint. Without it, the group is under the root.

func Uses

func Uses[D any]() Option

Uses names D, the struct of what the group's methods use, such as the config or the signing of tokens. The CLI gives one D with Provide, and a test gives one with fakes. Each handler takes it as its second argument.

type Parent

type Parent string

Parent is a command that local groups go under, such as controller for osapi dsl endpoint. A misspelled parent made a new command at the root with no error, so validate refuses a word outside KnownParents.

const (
	ParentAgent      Parent = "agent"
	ParentController Parent = "controller"
	ParentDSL        Parent = "dsl"
	ParentNATS       Parent = "nats"
	ParentPKI        Parent = "pki"
)

The commands that local groups go under.

func KnownParents

func KnownParents() []Parent

KnownParents are the commands that a group can be Under. Add a constant here to make a new one.

func (Parent) Valid

func (p Parent) Valid() bool

Valid reports whether p is a command that a group can be Under.

func (Parent) Values

func (Parent) Values() []Parent

Values are the commands that a group can be Under, for the enum rule.

type Printer

type Printer interface {
	// Heading prints the heading of a block.
	Heading(title string)
	// KV adds labelled values to the key-value block under the heading.
	KV(pairs ...string)
	// Table prints a table under its heading.
	Table(t Table)
	// Verdict prints one line at the left margin, such as m-1 admitted.
	Verdict(text string)
	// Text prints text as it is, such as a document a field holds.
	Text(text string)
	// Block prints one item of a list tagged table:"blocks": its title on
	// a line, then each pair, a label and a text, as a wrapped paragraph.
	// A pair with no label is a paragraph alone.
	Block(title string, pairs ...string)
	// Status is a status word in its color.
	Status(word string) string
	// Bytes is a size, such as 3.4 GB.
	Bytes(n int64) string
	// Age is the time since something, such as 3s.
	Age(d time.Duration) string
	// Time is a time in the one time format of the CLI.
	Time(t time.Time) string
	// Duration is a duration rounded to a useful precision.
	Duration(d time.Duration) string
}

Printer is how the output of a method prints: the headings, blocks and tables of the CLI, and the formats of its values. The CLI gives the helpers of internal/cli, which has the one theme, through Deps.

type Problem

type Problem struct {
	// Group is the command path of the group it is about.
	Group string `json:"group"`
	// Method is the method it is about, or "" for the group.
	Method string `json:"method,omitempty"`
	// Rule is the name of the rule, from Checks.
	Rule string `json:"rule"`
	// Message says what is wrong.
	Message string `json:"message"`
	// Fix is how to fix it, from the check of Rule.
	Fix string `json:"fix" table:"-"`
}

Problem is a rule a definition breaks, and how to fix it.

func Validate

func Validate(
	g *LocalGroup,
) []Problem

Validate is each rule g breaks. A group with no problems makes commands that hold to the CLI's rules.

func ValidateOutput

func ValidateOutput() []Problem

ValidateOutput is each rule that the output of a registered group breaks: each group whose commands AddCommands added, endpoint, behavior and local. Each tag of an output type has a value that the output knows, and a method with no body says what occurred.

func (Problem) String

func (p Problem) String() string

type ReadBack

type ReadBack struct {
	// Command is the words of the read after the binary, such as client
	// agent config get.
	Command string
	// Flags are the read's flags, such as --hostname web-01.
	Flags string
	// Fields are the fields of the read's --json output to assert.
	Fields []Field
	// Fails is the text that the read's error contains, in place of
	// Fields: the example removed the thing that it reads.
	Fails string
}

ReadBack is a read that shows the result of an example: a command, its flags, and the fields of its --json output with the values that they must have, or the text of the error that the read must fail with, for a thing that the example removed.

The integration suite fills the flags and the values of a check as it fills the example's own: a name that the example uses, such as web-01 or app.conf, becomes the suite's. {out.<path>} is the field at path of the example's own --json output, such as {out.id} for the ID that a create answers.

type Refusal

type Refusal struct {
	// Doc says what is wrong with the input, such as "an unknown role".
	Doc string
	// Input is the method's input, with one rule broken.
	Input any
}

Refusal is an input that the command refuses with a usage error, as Fails declares it.

type RootGroup

type RootGroup struct {
	// Name is the word, such as controller.
	Name string
	// Purpose says what goes under the word, in one line: the help of its
	// command, and its row on the CLI page of the docs site.
	Purpose string
	// Leaf is true for a command of the root itself, with no words under
	// it, such as version.
	Leaf bool
}

RootGroup is a word directly under osapi, and what goes under it.

func Root

func Root(
	word string,
) (RootGroup, bool)

Root is the RootGroup of word, and false for a word that is not one.

type Running

type Running struct {
	Components []Component
	Cleanup    func(ctx context.Context)
}

Running is what a process's Setup made: the components that Serve starts and stops, and what it does after they stop, such as flush the traces.

func Then

func Then(
	r Running,
	fn func(ctx context.Context),
) Running

Then is r with fn after its cleanup, such as the stop of a tracer, which flushes what the components recorded as they stopped.

type Table

type Table struct {
	Title   string
	Headers []string
	Rows    [][]string
	Empty   string
}

Table is a table of the output: its heading with the count, the column headers, the rows, and the hint that an empty list prints after None.

type UsageError

type UsageError struct {
	// Msg says what is wrong, and names the flag.
	Msg string
}

UsageError is a command that was called wrong, such as a flag whose value breaks a rule of its field. The CLI prints it with a pointer to the help, and exits 2.

func (*UsageError) Error

func (e *UsageError) Error() string

Directories

Path Synopsis
gen
Package commandgen writes the cobra commands of a group of the command layer, gen/cli.go: one command for each method, with its help, its flags and its examples, for the local generator, the endpoint generator and the behavior generator alike.
Package commandgen writes the cobra commands of a group of the command layer, gen/cli.go: one command for each method, with its help, its flags and its examples, for the local generator, the endpoint generator and the behavior generator alike.
generate command
Command generate writes the files that come from the local groups: for each group, the cobra commands in gen/cli.go, and internal/cli/commands/all/gen, which registers every group's commands.
Command generate writes the files that come from the local groups: for each group, the cobra commands in gen/cli.go, and internal/cli/commands/all/gen, which registers every group's commands.
genfile
Package genfile writes generated files for the local, endpoint and behavior generators alike: it removes the files a run made before, writes each file under the repository's root, and groups a Go file's imports as the repository does.
Package genfile writes generated files for the local, endpoint and behavior generators alike: it removes the files a run made before, writes each file under the repository's root, and groups a Go file's imports as the repository does.
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.

Jump to

Keyboard shortcuts

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