htcli

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2026 License: MIT Imports: 18 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 htcli is the machinery the generated commands and the hand-written ones share: the operation descriptor, the flag surface built from it, the request runner on top of the Go SDK, and the exit codes.

Index

Constants

View Source
const (
	FlagJSON           = "json"
	FlagSet            = "set"
	FlagQuery          = "query"
	FlagQueryFile      = "query-file"
	FlagIdempotencyKey = "idempotency-key"
)

Flag names the command layer owns. A generated parameter that would collide with one of these is renamed by the generator, so the two sets never overlap.

View Source
const (
	// ExitOK is a command that did what it was asked.
	ExitOK = 0
	// ExitError is a failure with no more specific code.
	ExitError = 1
	// ExitUsage is a malformed command line: an unknown flag, a missing
	// argument, a bad value.
	ExitUsage = 2
	// ExitAuth is a missing, rejected or under-scoped credential.
	ExitAuth = 3
	// ExitNotFound is an address that names nothing.
	ExitNotFound = 4
	// ExitInvalid is a request the API refused on its merits: a
	// validation problem, a conflict, a precondition.
	ExitInvalid = 5
	// ExitRateLimit is a throttle or an exhausted quota.
	ExitRateLimit = 6
	// ExitNetwork is a failure to reach the API, or a fault on its side.
	ExitNetwork = 7
)

Exit codes. A command that succeeded exits 0; everything else picks the code that says what kind of failure it was, so a script can branch without parsing the message.

View Source
const (
	EnvToken   = "HT_TOKEN"
	EnvBaseURL = "HT_BASE_URL"
	EnvProfile = "HT_PROFILE"
	EnvOutput  = "HT_OUTPUT"
)

Environment variables the global options fall back to.

Variables

This section is empty.

Functions

func AddGroups

func AddGroups(root *cobra.Command, opts *Options)

AddGroups builds a command for every registered group and operation and hangs them off root.

func BuildBody

func BuildBody(jsonSource string, sets []string, stdin io.Reader) ([]byte, error)

BuildBody assembles a request body from --json and --set.

--json supplies the document; each --set then writes one value into it at a dotted path, so a small change needs no file:

--set name=api --set settings.interval=5 --set tags.0=prod

A value is read as JSON when it parses as one (a number, true, false, null, an object, an array) and as a plain string otherwise. Wrapping it in quotes forces the string reading: --set name='"5"'.

func Count

func Count() int

Count reports how many operation commands are registered.

func ExitCode

func ExitCode(err error) int

ExitCode maps an error onto the exit-code table.

func GroupCommand

func GroupCommand(group Group, opts *Options) *cobra.Command

GroupCommand builds one group command with its operations under it.

func OperationCommand

func OperationCommand(op Operation, opts *Options) *cobra.Command

OperationCommand builds the command for one operation: its positional arguments from the path, its flags from the parameters and the body.

func PrintError

func PrintError(w io.Writer, err error, format output.Format)

PrintError writes a failure to w. An API failure is reported as the RFC 9457 problem it is: the machine code, the human detail, the offending members, and the request id to quote in a support request. Under --output json the whole problem document is printed instead, so a script can read it.

func ReadJSONSource

func ReadJSONSource(source string, stdin io.Reader) ([]byte, error)

ReadJSONSource reads one of the three spellings a JSON argument takes:

'{"name":"api"}'   inline
@body.json         a file
-                  standard input

func Register

func Register(op Operation)

Register declares one operation command.

func RegisterGroup

func RegisterGroup(g Group)

RegisterGroup declares a command group. The generated files call it from their init functions.

func Usagef

func Usagef(format string, args ...any) error

Usagef builds a UsageError.

Types

type Answer

type Answer struct {
	Status      int
	Header      http.Header
	Body        []byte
	ContentType string
}

Answer is a successful reply, read into memory.

func (*Answer) JSON

func (a *Answer) JSON() bool

JSON reports whether the answer carries a JSON document.

type Arg

type Arg struct {
	// Name is the wire name, e.g. "monitorId".
	Name string
	// Help is what the argument identifies.
	Help string
}

Arg is one path parameter, taken as a positional argument.

type Group

type Group struct {
	// Name is the group command, e.g. "status-pages".
	Name string
	// Tag is the tag it was built from, e.g. "StatusPages".
	Tag string
	// Short is the one-line group help.
	Short string
	// Aliases are alternative spellings of the group name.
	Aliases []string
}

Group is a command group, one per tag of the document.

func Groups

func Groups() []Group

Groups lists the registered groups in alphabetical order.

type Operation

type Operation struct {
	// Group is the command group, e.g. "monitors".
	Group string
	// Name is the command name inside the group, e.g. "bulk-create".
	Name string
	// ID is the operationId, so a command can be traced to the document.
	ID string
	// Method and Path address the operation.
	Method string
	Path   string
	// Summary is the one-line help.
	Summary string
	// Description is the long help.
	Description string
	// Args are the path parameters, in path order.
	Args []Arg
	// Params are the query and header parameters.
	Params []Param
	// Body reports that the operation takes a JSON request body.
	Body bool
	// BodyRequired reports that the body is not optional.
	BodyRequired bool
	// QueryPath is the POST <path>/q body-query twin, folded into this
	// command as --query and --query-file. Empty when there is none.
	QueryPath string
	// Paged reports a collection that --all may walk to exhaustion.
	Paged bool
	// Binary reports an answer that is not JSON (a report download).
	Binary bool
	// Deprecated carries the replacement when the operation is going away.
	Deprecated string
}

Operation is one API operation, as a command.

func OperationsOf

func OperationsOf(group string) []Operation

OperationsOf lists a group's operations in alphabetical order.

func (Operation) Use

func (op Operation) Use() string

Use is the cobra usage line: the command name followed by its positional arguments.

type Options

type Options struct {
	Profile   string
	Token     string
	BaseURL   string
	OutputFmt string
	Timeout   time.Duration
	NoRetry   bool
	Verbose   bool
	All       bool

	// Streams. Tests replace them; main leaves them at the process ones.
	Out io.Writer
	Err io.Writer
	In  io.Reader

	// UserAgent is appended to the SDK's own product token.
	UserAgent string

	// Started reports that a command body was reached. A failure raised
	// before that came from the command line, not from the API.
	Started bool
	// contains filtered or unexported fields
}

Options is the global flag set, plus everything a command needs to run: the resolved profile, the streams, and the SDK client built from them.

func (*Options) Bind

func (o *Options) Bind(fs *pflag.FlagSet)

Bind declares the global flags on fs.

func (*Options) Client

func (o *Options) Client() (*hosttracker.Client, error)

Client builds the SDK client the command runs on, once per command. Everything the CLI does on the wire goes through it, so auth, retries, idempotency keys and error mapping are the SDK's, not the CLI's.

func (*Options) Do

func (o *Options) Do(ctx context.Context, req Request) (*Answer, error)

Do sends one request through the SDK. Everything on the wire, the bearer token, the idempotency key, the retry ladder and the mapping of a >= 400 answer onto *hosttracker.Error, is the SDK's doing.

func (*Options) Emit

func (o *Options) Emit(answer *Answer) error

Emit prints one answer: the JSON document through the chosen format, a binary payload straight through, an empty answer not at all.

func (*Options) File

func (o *Options) File() *config.File

File is the loaded configuration document.

func (*Options) Format

func (o *Options) Format() output.Format

Format is the settled output format.

func (*Options) Printer

func (o *Options) Printer() output.Printer

Printer writes answers to the command's output stream.

func (*Options) ProfileName

func (o *Options) ProfileName() string

ProfileName is the profile the command is running under.

func (*Options) Resolve

func (o *Options) Resolve() error

Resolve loads the configuration file and settles every setting, in the order flag, environment, profile, default. It runs once per command.

func (*Options) ResolvedBaseURL

func (o *Options) ResolvedBaseURL() string

ResolvedBaseURL is the API root in force.

func (*Options) ResolvedProfile

func (o *Options) ResolvedProfile() config.Profile

ResolvedProfile is the profile's stored settings.

func (*Options) ResolvedToken

func (o *Options) ResolvedToken() string

ResolvedToken is the credential in force, from --token, the environment or the profile.

func (*Options) Streams

func (o *Options) Streams()

Streams fills in the process streams for anything left unset.

type Param

type Param struct {
	// Name is the wire name, e.g. "monitorId".
	Name string
	// Flag is the command-line spelling, e.g. "monitor-id".
	Flag string
	// In is "query" or "header".
	In string
	// Type is "string", "integer", "number", "boolean" or "array".
	Type string
	// Items is the element type when Type is "array".
	Items string
	// Enum lists the accepted values, when the parameter has a closed set.
	Enum []string
	// Explode reports the array serialisation the document asked for:
	// true repeats the key once per element, false joins the elements
	// with commas into a single key.
	Explode bool
	// Help is the one-line flag description.
	Help string
	// Required reports a parameter the API refuses the call without.
	Required bool
}

Param is one query or header parameter of an operation.

type Request

type Request struct {
	Method string
	Path   string
	Query  url.Values
	Header http.Header
	Body   []byte
}

Request is one call, as the CLI assembles it before handing it to the SDK.

type UsageError

type UsageError struct {
	Err error
}

UsageError marks a failure caused by the command line itself, so it exits 2 and the usage text is worth showing.

func (*UsageError) Error

func (e *UsageError) Error() string

Error implements error.

func (*UsageError) Unwrap

func (e *UsageError) Unwrap() error

Unwrap exposes the cause.

Jump to

Keyboard shortcuts

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