Documentation
¶
Overview ¶
Entity provisioning (admin.go) holds idempotent create helpers for ConfigHub control-plane objects — Spaces, Triggers, Filters, and stored Invocations — plus wiring a Space's Triggers to a shared Filter. Each Ensure* helper creates the entity with allow-exists semantics, so it is safe to run repeatedly (the "install once per org" pattern), and returns the created or existing entity.
The helpers take the generated entity structs directly (goclientnew.Trigger, etc.) rather than re-describing them; fields the caller leaves unset (such as DisplayName) are defaulted by the server. Function arguments on Triggers and Invocations are built with Arguments.
Client construction (client.go) builds an authenticated ConfigHub API client for Go tools and `cub` plugins. It turns resolved credentials — a server URL plus a bearer token (or a full AuthSession for Basic auth) — into a ready *goclientnew.ClientWithResponses, and provides a server-verifying auth check.
Two credential sources are supported:
- Plugin environment: the CUB_SERVER / CUB_TOKEN / CUB_SPACE variables that `cub` passes to plugins. Use NewClientFromEnvironment.
- Local config: the active context of a Store (the ~/.confighub session a user creates with `cub auth login`). Use NewClientFromConfig.
ResolveClient tries the environment first and falls back to local config, so the same binary works both as a `cub` plugin and as a standalone CLI without code changes.
Config loading (config.go) is a kubeconfig-style loader for ConfigHub CLI configuration. It reads the on-disk format that `cub` writes — a config file (`~/.confighub/config.yaml`) holding named contexts, plus per-context token files (`~/.confighub/tokens/<name>.json`) — and resolves the active context and its credentials for use by other Go tools and `cub` plugins.
It is the analog of client-go's clientcmd: a reusable way to obtain "client info" (server URL, organization, default space, access token) without shelling out to `cub`. It has no dependency on cobra and holds no global state; construct a Store with LoadConfig and call methods on it.
This is the read/resolve half of `cub`'s ContextManager. Write operations (creating, renaming, and deleting contexts; persisting tokens) live with the `cub` CLI, which owns the login flow that produces them.
Config writing (config_write.go) is the mutation half of the kubeconfig-style Store: creating, renaming, and deleting contexts, persisting the config and token files, and first-run initialization. It complements the read/resolve methods in config.go. Friendly context-name generation is intentionally left to the caller (the cub CLI); Store.CreateContext takes an explicit name.
Mutations (mutate.go) are a dry-run/commit harness for ConfigHub data changes. It encodes one policy consistently:
- An empty Change.Description means dry-run: the server previews the change and writes nothing.
- A non-empty Description means commit: the change is written and the description is recorded with it.
It wraps the org-level function-invocation and bulk-patch endpoints and returns a structured Result (per-unit success, error, mutation diffs, and function outputs) instead of leaving callers to parse a CLI's text output.
Function arguments use the canonical api.FunctionArgument / api.FunctionInvocation types from core/function/api (with Evaluator constants api.EvaluatorTemplate / api.EvaluatorCEL); Arguments converts them to the generated client's form.
Queries (query.go) are typed, org-level read helpers over the ConfigHub API.
Two deliberate choices keep callers consistent:
- Org-level endpoints only. Reads always use the cross-space "ListAll*" endpoints (and ListSpaces, which is already org-scoped), scoped with a Where clause. There is no per-space-vs-"*" branching to get wrong.
- No globals. Every call takes an explicit Client and filter.
The generated list endpoints return "Extended" envelopes — e.g. ListAllUnits returns []ExtendedUnit, where the core record is in the .Unit field and related entities (.Space, .Target, …) are populated only when requested via ListOpts.Include.
Index ¶
- Constants
- Variables
- func Apply(ctx context.Context, client *goclientnew.ClientWithResponses, ...) ([]ApplyResult, *Inventory, error)
- func Arguments(args []api.FunctionArgument) []goclientnew.FunctionArgument
- func BuildWhereFilterFromImportFilters(filters []goclientnew.ImportFilter) (string, error)
- func DefaultConfigPath() (string, error)
- func EnsureFilter(ctx context.Context, c *Client, filter goclientnew.Filter) (*goclientnew.Filter, error)
- func EnsureInvocation(ctx context.Context, c *Client, invocation goclientnew.Invocation) (*goclientnew.Invocation, error)
- func EnsureSpace(ctx context.Context, c *Client, space goclientnew.Space) (*goclientnew.Space, error)
- func EnsureTrigger(ctx context.Context, c *Client, trigger goclientnew.Trigger) (*goclientnew.Trigger, error)
- func GetEntityBySlug(ctx context.Context, client *goclientnew.ClientWithResponses, ...) (interface{}, error)
- func GetRevisionByNum(ctx context.Context, client *goclientnew.ClientWithResponses, ...) (*goclientnew.ExtendedRevision, error)
- func GetSpaceDetailURL(serverURL, spaceID string) string
- func GetSpaceListURL(serverURL string) string
- func GetTargetListURL(serverURL string) string
- func GetUnitDetailURL(serverURL, spaceID, unitID string) string
- func GetUnitEditURL(serverURL, spaceID, unitID string) string
- func GetUnitListURL(serverURL string) string
- func GetUnitRevisionsURL(serverURL, spaceID, unitID string) string
- func GetWorkerListURL(serverURL string) string
- func InterpretErrorGeneric(err error, resp interface{}) error
- func IsAPIError(err error, resp APIResponse) bool
- func IsNotFoundError(err error) bool
- func ListAttributes(ctx context.Context, c *Client, where Where, opts ListOpts) ([]*goclientnew.ExtendedAttribute, error)
- func ListBridgeWorkers(ctx context.Context, c *Client, where Where, opts ListOpts, ...) ([]*goclientnew.ExtendedBridgeWorker, error)
- func ListChangeSets(ctx context.Context, c *Client, where Where, opts ListOpts) ([]*goclientnew.ExtendedChangeSet, error)
- func ListEntitiesForImport(ctx context.Context, client *goclientnew.ClientWithResponses, spaceID string, ...) ([]interface{}, error)
- func ListFilters(ctx context.Context, c *Client, where Where, opts ListOpts, ...) ([]*goclientnew.ExtendedFilter, error)
- func ListInvocations(ctx context.Context, c *Client, where Where, opts ListOpts) ([]*goclientnew.ExtendedInvocation, error)
- func ListLinks(ctx context.Context, c *Client, where Where, opts ListOpts) ([]*goclientnew.ExtendedLink, error)
- func ListSpaces(ctx context.Context, c *Client, where Where, opts ListOpts, ...) ([]*goclientnew.ExtendedSpace, error)
- func ListTags(ctx context.Context, c *Client, where Where, opts ListOpts) ([]*goclientnew.ExtendedTag, error)
- func ListTargets(ctx context.Context, c *Client, where Where, opts ListOpts) ([]*goclientnew.ExtendedTarget, error)
- func ListTriggers(ctx context.Context, c *Client, where Where, opts ListOpts) ([]*goclientnew.ExtendedTrigger, error)
- func ListUnits(ctx context.Context, c *Client, where Where, opts ListOpts, ...) ([]*goclientnew.ExtendedUnit, error)
- func ListViews(ctx context.Context, c *Client, where Where, opts ListOpts) ([]*goclientnew.ExtendedView, error)
- func MarshalYAMLWithoutReadonlyFields(entityType string, entity interface{}, spaceSlug string) ([]byte, error)
- func ParseBoolOption(options *goclientnew.ImportOptions, key string, defaultValue bool) bool
- func ParseStringOption(options *goclientnew.ImportOptions, key string, defaultValue string) string
- func Refresh(ctx context.Context, client *goclientnew.ClientWithResponses, ...) ([]ApplyResult, *Inventory, []byte, error)
- func ResolveFilter(ctx context.Context, c *Client, spaceID goclientnew.UUID, slug string) (*goclientnew.Filter, error)
- func ResolveInvocation(ctx context.Context, c *Client, spaceID goclientnew.UUID, slug string) (*goclientnew.Invocation, error)
- func ResolveSpace(ctx context.Context, c *Client, slug string) (*goclientnew.Space, error)
- func SelectFields(value string) string
- func SetSpaceTriggerFilter(ctx context.Context, c *Client, space *goclientnew.Space, ...) error
- func SpaceSlugByID(ctx context.Context, c *Client) (map[goclientnew.UUID]string, error)
- type APIResponse
- type ApplyResult
- type AuthSession
- type Change
- type Client
- func NewClient(opts ClientOptions) (*Client, error)
- func NewClientFromConfig(ctx context.Context, store *Store, opts ClientOptions) (*Client, error)
- func NewClientFromEnvironment(ctx context.Context, opts ClientOptions) (*Client, error)
- func ResolveClient(ctx context.Context, opts ClientOptions) (*Client, error)
- type ClientOptions
- type Config
- type Context
- type Coordinate
- type Environment
- type Inventory
- type InventoryResource
- type ListOpts
- type Metadata
- type Result
- func InvokeFunction(ctx context.Context, c *Client, fn api.FunctionInvocation, sel Selector, ...) (*Result, error)
- func InvokeStoredInvocation(ctx context.Context, c *Client, invocationID goclientnew.UUID, ...) (*Result, error)
- func UpgradeUnits(ctx context.Context, c *Client, where string, ch Change) (*Result, error)
- type Selector
- type Settings
- type Store
- func (s *Store) ActiveContext() (*Context, error)
- func (s *Store) ConfigPath() string
- func (s *Store) Context(name string) (*Context, error)
- func (s *Store) Contexts() []*Context
- func (s *Store) CreateContext(name, serverURL, organization, defaultSpace string) (*Context, error)
- func (s *Store) CurrentContextName() string
- func (s *Store) DeleteContext(name string) error
- func (s *Store) DeleteTokenData(ctx *Context) error
- func (s *Store) FindContextByCoordinate(coordinate Coordinate) (*Context, error)
- func (s *Store) GetAllContextNames() []string
- func (s *Store) RenameContext(oldName, newName string) error
- func (s *Store) SaveConfig() error
- func (s *Store) SaveTokenData(ctx *Context, token *TokenData) error
- func (s *Store) SetCurrentContext(name string) error
- func (s *Store) TokenData(ctx *Context) (*TokenData, error)
- func (s *Store) TokenPath(tokenFile string) string
- func (s *Store) Use(name string) error
- type TokenData
- type UnitOutcome
- type User
- type Where
Constants ¶
const ( EntityTypeSpace = "Space" EntityTypeFilter = "Filter" EntityTypeView = "View" EntityTypeInvocation = "Invocation" EntityTypeTrigger = "Trigger" EntityTypeTag = "Tag" EntityTypeChangeSet = "ChangeSet" EntityTypeTarget = "Target" EntityTypeBridgeWorker = "BridgeWorker" EntityTypeUnit = "Unit" EntityTypeLink = "Link" EntityTypeSet = "Set" EntityTypeAttribute = "Attribute" // Pseudo-EntityType EntityTypeInventory = "Inventory" )
Entity types
const ( // ConfigAPIVersion and ConfigKind identify the config file format. They // match the values `cub` writes. ConfigAPIVersion = "v1" ConfigKind = "Config" // ConfigHubDir is the per-user ConfigHub directory under $HOME. ConfigHubDir = ".confighub" // ConfigFileName is the default config file name within ConfigHubDir. ConfigFileName = "config.yaml" )
const ( AuthTypeBasic = "Basic" AuthTypeJWT = "JWT" )
const DefaultServerURL = "https://hub.confighub.com"
DefaultServerURL is the ConfigHub server used for a context when none is given.
const DefaultToolchainType = "Kubernetes/YAML"
DefaultToolchainType is used when a Selector leaves ToolchainType empty.
const DefaultUserAgent = "cub-sdk"
DefaultUserAgent is sent when ClientOptions.UserAgent is empty.
Variables ¶
var ErrEntityNotFound = errors.New("entity not found")
ErrEntityNotFound is used to mark entities that are not found during refresh
Functions ¶
func Apply ¶
func Apply( ctx context.Context, client *goclientnew.ClientWithResponses, data, lastAppliedData []byte, oldInventory *Inventory, defaultSpaceSlug string, unitSlug, spaceID string, ) ([]ApplyResult, *Inventory, error)
Apply processes the configuration data and returns the results and updated inventory. If unitSlug and spaceID are non-empty, each applied entity is annotated with the managing Unit's slug and SpaceID (confighub.com/UnitSlug, confighub.com/SpaceID), analogous to k8skit.EnsureConfigHubContextOnData for the Kubernetes bridge.
func Arguments ¶ added in v0.1.86
func Arguments(args []api.FunctionArgument) []goclientnew.FunctionArgument
Arguments converts canonical function arguments into the generated FunctionArgument list, mirroring how the cub CLI builds them (positional vs named, optional evaluator, scalar value).
func BuildWhereFilterFromImportFilters ¶
func BuildWhereFilterFromImportFilters(filters []goclientnew.ImportFilter) (string, error)
BuildWhereFilterFromImportFilters constructs a where filter string from ImportFilters
func DefaultConfigPath ¶ added in v0.1.86
DefaultConfigPath returns the config file path to use when none is given: $CUB_CONFIG if set, otherwise $HOME/.confighub/config.yaml.
func EnsureFilter ¶ added in v0.1.86
func EnsureFilter(ctx context.Context, c *Client, filter goclientnew.Filter) (*goclientnew.Filter, error)
EnsureFilter idempotently creates a Filter in filter.SpaceID.
func EnsureInvocation ¶ added in v0.1.86
func EnsureInvocation(ctx context.Context, c *Client, invocation goclientnew.Invocation) (*goclientnew.Invocation, error)
EnsureInvocation idempotently creates a stored Invocation in invocation.SpaceID.
func EnsureSpace ¶ added in v0.1.86
func EnsureSpace(ctx context.Context, c *Client, space goclientnew.Space) (*goclientnew.Space, error)
EnsureSpace idempotently creates a Space and returns it (the existing Space if it already exists).
func EnsureTrigger ¶ added in v0.1.86
func EnsureTrigger(ctx context.Context, c *Client, trigger goclientnew.Trigger) (*goclientnew.Trigger, error)
EnsureTrigger idempotently creates a Trigger in trigger.SpaceID.
func GetEntityBySlug ¶
func GetEntityBySlug(ctx context.Context, client *goclientnew.ClientWithResponses, entityType, slug, spaceID string) (interface{}, error)
GetEntityBySlug fetches an entity by its slug, similar to the old apiGet* functions but using direct client library calls without global variable dependencies
func GetRevisionByNum ¶
func GetRevisionByNum(ctx context.Context, client *goclientnew.ClientWithResponses, spaceID, unitID string, revisionNum int64) (*goclientnew.ExtendedRevision, error)
GetRevisionByNum fetches a revision by its RevisionNum for a specific unit
func GetSpaceDetailURL ¶
GetSpaceDetailURL returns the web UI URL for a specific space detail page
func GetSpaceListURL ¶
GetSpaceListURL returns the web UI URL for the spaces list page
func GetTargetListURL ¶
GetTargetListURL returns the web UI URL for the targets list page
func GetUnitDetailURL ¶
GetUnitDetailURL returns the web UI URL for a specific unit detail page
func GetUnitEditURL ¶
GetUnitEditURL returns the web UI URL for unit edit view Tab 1 is the edit tab in the unit detail page
func GetUnitListURL ¶
GetUnitListURL returns the web UI URL for the units list page Note: Space context is handled by the UI session
func GetUnitRevisionsURL ¶
GetUnitRevisionsURL returns the web UI URL for unit revisions view Tab 2 is the revisions tab in the unit detail page
func GetWorkerListURL ¶
GetWorkerListURL returns the web UI URL for the bridge workers list page
func InterpretErrorGeneric ¶
InterpretErrorGeneric checks the response for any errors and returns an error if found. If we found no non-nil JSON4xx or JSON5xx, presumably it is a 2xx success or client initiated termination.
func IsAPIError ¶
func IsAPIError(err error, resp APIResponse) bool
func IsNotFoundError ¶
IsNotFoundError returns true if the error represents a 404 Not Found response or a "not found" error from a slug lookup.
func ListAttributes ¶ added in v0.1.86
func ListAttributes(ctx context.Context, c *Client, where Where, opts ListOpts) ([]*goclientnew.ExtendedAttribute, error)
ListAttributes returns attributes across the organization matching where.
func ListBridgeWorkers ¶ added in v0.1.86
func ListBridgeWorkers(ctx context.Context, c *Client, where Where, opts ListOpts, with ...func(*goclientnew.ListAllBridgeWorkersParams)) ([]*goclientnew.ExtendedBridgeWorker, error)
ListBridgeWorkers returns bridge workers across the organization matching where. Bridge-worker-specific options (Summary) are set via the with mutators, which run after the common where/opts are applied.
func ListChangeSets ¶ added in v0.1.86
func ListChangeSets(ctx context.Context, c *Client, where Where, opts ListOpts) ([]*goclientnew.ExtendedChangeSet, error)
ListChangeSets returns change sets across the organization matching where.
func ListEntitiesForImport ¶
func ListEntitiesForImport(ctx context.Context, client *goclientnew.ClientWithResponses, spaceID string, entityType string, whereFilter string) ([]interface{}, error)
ListEntitiesForImport fetches entities of a specific type using the provided where filter. It returns the entities as a slice of interfaces that can be processed further.
func ListFilters ¶ added in v0.1.86
func ListFilters(ctx context.Context, c *Client, where Where, opts ListOpts, with ...func(*goclientnew.ListAllFiltersParams)) ([]*goclientnew.ExtendedFilter, error)
ListFilters returns filters across the organization matching where. Filter- specific options (Entity/Id) are set via the with mutators, which run after the common where/opts are applied.
func ListInvocations ¶ added in v0.1.86
func ListInvocations(ctx context.Context, c *Client, where Where, opts ListOpts) ([]*goclientnew.ExtendedInvocation, error)
ListInvocations returns stored invocations across the organization matching where.
func ListLinks ¶ added in v0.1.86
func ListLinks(ctx context.Context, c *Client, where Where, opts ListOpts) ([]*goclientnew.ExtendedLink, error)
ListLinks returns links across the organization matching where. Links have no per-space "ListAll" endpoint; the org-level search endpoint is used.
func ListSpaces ¶ added in v0.1.86
func ListSpaces(ctx context.Context, c *Client, where Where, opts ListOpts, with ...func(*goclientnew.ListSpacesParams)) ([]*goclientnew.ExtendedSpace, error)
ListSpaces returns spaces across the organization matching where. ListSpaces is already org-scoped, so there is no "ListAll" variant. Space-specific options (Summary) are set via the with mutators, which run after the common where/opts are applied.
func ListTags ¶ added in v0.1.86
func ListTags(ctx context.Context, c *Client, where Where, opts ListOpts) ([]*goclientnew.ExtendedTag, error)
ListTags returns tags across the organization matching where.
func ListTargets ¶ added in v0.1.86
func ListTargets(ctx context.Context, c *Client, where Where, opts ListOpts) ([]*goclientnew.ExtendedTarget, error)
ListTargets returns targets across the organization matching where.
func ListTriggers ¶ added in v0.1.86
func ListTriggers(ctx context.Context, c *Client, where Where, opts ListOpts) ([]*goclientnew.ExtendedTrigger, error)
ListTriggers returns triggers across the organization matching where.
func ListUnits ¶ added in v0.1.86
func ListUnits(ctx context.Context, c *Client, where Where, opts ListOpts, with ...func(*goclientnew.ListAllUnitsParams)) ([]*goclientnew.ExtendedUnit, error)
ListUnits returns units across the organization matching where, using the org-level ListAllUnits endpoint. Results are ExtendedUnit envelopes; the core record is in each element's .Unit field. Unit-specific options (ResourceType, WhereData, WhereTrigger, TriggerFilter, TriggersPassed, View) are set via the with mutators, which run after the common where/opts are applied.
func ListViews ¶ added in v0.1.86
func ListViews(ctx context.Context, c *Client, where Where, opts ListOpts) ([]*goclientnew.ExtendedView, error)
ListViews returns views across the organization matching where.
func MarshalYAMLWithoutReadonlyFields ¶
func MarshalYAMLWithoutReadonlyFields(entityType string, entity interface{}, spaceSlug string) ([]byte, error)
MarshalYAMLWithoutReadonlyFields marshals an entity to YAML while excluding readonly fields. It uses the Patch types which contain only the mutable fields that should be included in LiveState. It also removes null fields, the Version field, and adds SpaceSlug for space-resident entities.
func ParseBoolOption ¶
func ParseBoolOption(options *goclientnew.ImportOptions, key string, defaultValue bool) bool
ParseBoolOption extracts a boolean option from the options map
func ParseStringOption ¶
func ParseStringOption(options *goclientnew.ImportOptions, key string, defaultValue string) string
ParseStringOption extracts a string option from the options map
func Refresh ¶
func Refresh( ctx context.Context, client *goclientnew.ClientWithResponses, currentData []byte, oldInventory *Inventory, defaultSpaceSlug string, liveRevisionNum int64, spaceID, unitID string, ) ([]ApplyResult, *Inventory, []byte, error)
Refresh gets the current state of entities in the inventory and updates the config data, inventory, and live state. It returns the same ApplyResult structure as Apply, along with updated inventory and refreshed config data.
func ResolveFilter ¶ added in v0.1.86
func ResolveFilter(ctx context.Context, c *Client, spaceID goclientnew.UUID, slug string) (*goclientnew.Filter, error)
ResolveFilter finds a single Filter by slug within a space.
func ResolveInvocation ¶ added in v0.1.86
func ResolveInvocation(ctx context.Context, c *Client, spaceID goclientnew.UUID, slug string) (*goclientnew.Invocation, error)
ResolveInvocation finds a single stored Invocation by slug within a space.
func ResolveSpace ¶ added in v0.1.86
ResolveSpace looks up a single space by slug and returns its core record. It errors if no space (or more than one) matches.
func SelectFields ¶ added in v0.1.86
SelectFields normalizes a select value for use in ListOpts.Select: the "*" wildcard (meaning "all fields") becomes "", which the API treats the same way and which the list helpers omit from the request. Callers translating a CLI --select value should pass it through this.
func SetSpaceTriggerFilter ¶ added in v0.1.86
func SetSpaceTriggerFilter(ctx context.Context, c *Client, space *goclientnew.Space, filterID goclientnew.UUID) error
SetSpaceTriggerFilter points a Space's Triggers at a shared Filter: it sets the Space's TriggerFilterID to filterID and clears its WhereTrigger. space should be a full Space record (e.g. from ResolveSpace).
func SpaceSlugByID ¶ added in v0.1.86
SpaceSlugByID returns a map from space UUID to slug for the whole organization, for resolving the SpaceID fields on units and other entities.
Types ¶
type APIResponse ¶
type APIResponse interface {
StatusCode() int
}
type ApplyResult ¶
type ApplyResult struct {
EntityType string
EntityName string
EntityID string
SpaceSlug string
Action string // "created", "updated", "deleted", "failed"
Error error
Entity interface{} // Store the created/updated entity for display
}
func Destroy ¶
func Destroy(ctx context.Context, client *goclientnew.ClientWithResponses, inventory *Inventory, defaultSpaceSlug string) []ApplyResult
type AuthSession ¶
type AuthSession struct {
User User `json:"user"`
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token,omitempty"`
OrganizationID string `json:"organization_id"`
AuthType string `json:"auth_type"`
// Note: This field is not part of the API. We just use it to pass the password to setAuthHeaderToken.
BasicAuthPassword string `json:"basic_auth_password,omitempty"`
}
func PerformWorkerAuth ¶
func PerformWorkerAuth(serverURL, workerID, workerSecret string) (*AuthSession, error)
type Change ¶ added in v0.1.86
type Change struct {
// Description is recorded with the change on commit. Empty means dry-run.
Description string
}
Change describes whether a mutation is a dry-run preview or a commit. The zero value is a dry-run.
type Client ¶ added in v0.1.86
type Client struct {
API *goclientnew.ClientWithResponses
Server string // server URL without the "/api" suffix
Space string // default space slug, if known
}
Client wraps the generated API client together with the resolved server URL and default space, so tools don't have to thread them separately.
func NewClient ¶ added in v0.1.86
func NewClient(opts ClientOptions) (*Client, error)
NewClient constructs a Client from explicit options. It returns an error if ServerURL is empty.
func NewClientFromConfig ¶ added in v0.1.86
NewClientFromConfig builds a Client from a Store's active context, loading the bearer token from the context's token file. The context's default space becomes the client's default space unless opts.Space is already set.
func NewClientFromEnvironment ¶ added in v0.1.86
func NewClientFromEnvironment(ctx context.Context, opts ClientOptions) (*Client, error)
NewClientFromEnvironment builds a Client from the CUB_SERVER / CUB_TOKEN / CUB_SPACE variables (plugin mode). Fields set on opts (UserAgent, Debug, HTTPClient) are honored; opts.ServerURL/Token/Space are overridden by the environment. It returns an error when the environment lacks credentials.
func ResolveClient ¶ added in v0.1.86
func ResolveClient(ctx context.Context, opts ClientOptions) (*Client, error)
ResolveClient builds a Client using whichever credential source is available, preferring the plugin environment (CUB_SERVER/CUB_TOKEN) and falling back to the local ~/.confighub config (honoring CUB_CONFIG / CUB_CONTEXT). This is the one-call entry point for tools that should work both as a `cub` plugin and as a standalone CLI.
func (*Client) VerifyAuth ¶ added in v0.1.86
func (c *Client) VerifyAuth(ctx context.Context) (*goclientnew.OrganizationMember, error)
VerifyAuth round-trips GET /me to confirm the credentials are accepted by the server. It is the direct-API equivalent of `cub auth status`: unlike a local token check, it proves the server honors the token right now. On success it returns the authenticated organization member.
type ClientOptions ¶ added in v0.1.86
type ClientOptions struct {
ServerURL string
Token string
Session *AuthSession
// Space is the default space slug, when known (e.g. from CUB_SPACE or the
// active context's settings). It is carried on the returned Client for
// callers' convenience and does not affect requests.
Space string
UserAgent string
Debug bool // dump requests and responses to stdout
HTTPClient *http.Client // base client; defaults to a client using http.DefaultTransport
}
ClientOptions configures client construction. ServerURL is required; the rest are optional. Provide either Token (bearer) or Session (which additionally supports Basic auth); Session takes precedence when both are set.
type Config ¶ added in v0.1.86
type Config struct {
APIVersion string `yaml:"apiVersion" json:"apiVersion"`
Kind string `yaml:"kind" json:"kind"`
CurrentContext string `yaml:"currentContext,omitempty" json:"currentContext,omitempty"`
Contexts []*Context `yaml:"contexts" json:"contexts"`
}
Config is the root of the config file: a kubeconfig-like document with a list of named contexts and a pointer to the current one.
type Context ¶ added in v0.1.86
type Context struct {
Name string `yaml:"name" json:"name"`
Coordinate Coordinate `yaml:"coordinate" json:"coordinate"`
Settings Settings `yaml:"settings" json:"settings"`
Metadata Metadata `yaml:"metadata" json:"metadata"`
}
Context is a named configuration: a coordinate identifying the server, a few settings, and metadata including which token file holds its credentials.
type Coordinate ¶ added in v0.1.86
type Coordinate struct {
ServerURL string `yaml:"serverURL" json:"serverURL"`
OrganizationID string `yaml:"organizationID" json:"organizationID"`
User string `yaml:"user" json:"user"`
}
Coordinate uniquely identifies a context: server URL, organization, and user.
func (Coordinate) Equals ¶ added in v0.1.86
func (c Coordinate) Equals(other Coordinate) bool
Equals reports whether two coordinates identify the same context.
type Environment ¶ added in v0.1.86
type Environment struct {
Server string `env:"CUB_SERVER"`
Token string `env:"CUB_TOKEN"`
Space string `env:"CUB_SPACE"`
Config string `env:"CUB_CONFIG"`
Context string `env:"CUB_CONTEXT"`
}
Environment holds the credentials `cub` passes to plugins via environment variables (see core/plugin and cub's plugin execution). It is populated with go-envconfig.
func LoadEnvironment ¶ added in v0.1.86
func LoadEnvironment(ctx context.Context) (Environment, error)
LoadEnvironment reads the CUB_* variables from the process environment.
func (Environment) HasCredentials ¶ added in v0.1.86
func (e Environment) HasCredentials() bool
HasCredentials reports whether the environment carries enough to build a client directly (server URL and token), i.e. the binary is running as a `cub` plugin.
type Inventory ¶
type Inventory struct {
EntityType string `yaml:"EntityType"`
Resources []InventoryResource `yaml:"Resources"`
}
type InventoryResource ¶
type ListOpts ¶ added in v0.1.86
type ListOpts struct {
// Select is a comma-separated, PascalCase list of fields to return.
Select string
// Include expands related entities into the Extended envelope (e.g.
// "SpaceID,TargetID" to populate .Space and .Target on a unit).
Include string
// Filter names a stored Filter to apply, as "space/filter" or "filter".
Filter string
// Contains is a free-text search.
Contains string
}
ListOpts carries the query parameters common to every list helper. Zero values are omitted from the request. Entity-specific parameters are set via each helper's mutator functions.
type Metadata ¶ added in v0.1.86
type Metadata struct {
TokenFile string `yaml:"tokenFile" json:"tokenFile"`
OrganizationName string `yaml:"organizationName,omitempty" json:"organizationName,omitempty"`
Created time.Time `yaml:"created,omitempty" json:"created,omitempty"`
LastUsed time.Time `yaml:"lastUsed,omitempty" json:"lastUsed,omitempty"`
Description string `yaml:"description,omitempty" json:"description,omitempty"`
}
Metadata holds optional, non-identifying context data.
type Result ¶ added in v0.1.86
type Result struct {
DryRun bool
Outcomes []UnitOutcome
}
Result aggregates the per-unit outcomes of a mutation.
func InvokeFunction ¶ added in v0.1.86
func InvokeFunction(ctx context.Context, c *Client, fn api.FunctionInvocation, sel Selector, ch Change) (*Result, error)
InvokeFunction runs an ad-hoc function over the units matching sel, as a dry-run preview or a commit per ch. It also serves read-only functions (e.g. get-resources): inspect UnitOutcome.Outputs on the result.
func InvokeStoredInvocation ¶ added in v0.1.86
func InvokeStoredInvocation(ctx context.Context, c *Client, invocationID goclientnew.UUID, params map[string]any, sel Selector, ch Change) (*Result, error)
InvokeStoredInvocation runs a parameterized stored Invocation (by ID) over the units matching sel, as a dry-run preview or a commit per ch.
func UpgradeUnits ¶ added in v0.1.86
UpgradeUnits performs a bulk "--upgrade" patch over the units matching where: each unit is reconciled with its upstream. It is a dry-run preview or a commit per ch.
func (*Result) Failed ¶ added in v0.1.86
func (r *Result) Failed() []UnitOutcome
Failed returns the outcomes that did not succeed.
type Selector ¶ added in v0.1.86
type Selector struct {
Where string // unit filter, e.g. "Slug = 'checkout'" or "SpaceID = '...'"
WhereData string // filter on config data
WhereResource string // filter on resources within the config data
ResourceType string // e.g. "apps/v1/Deployment"
ToolchainType string // defaults to DefaultToolchainType
ExecutorSpace string // optional space whose worker/context executes functions
}
Selector scopes a mutation to a set of units using the org-level endpoints. Where is required for org-wide invocation and bulk patch.
type Settings ¶ added in v0.1.86
type Settings struct {
DefaultSpace string `yaml:"defaultSpace" json:"defaultSpace"`
}
Settings holds per-context preferences.
type Store ¶ added in v0.1.86
type Store struct {
// contains filtered or unexported fields
}
Store loads and resolves ConfigHub CLI configuration from a config file plus a sibling token directory. Use [Load] to construct one. Methods are safe for concurrent use.
Unlike `cub`'s ContextManager, a Store is read-only and never panics: a missing config file yields an empty but usable Store (no contexts), and resolving the active context returns an error rather than panicking when none is set.
func LoadConfig ¶ added in v0.1.86
LoadConfig reads the config at path and returns a Store. If path is empty, DefaultConfigPath is used. The token directory is the sibling "tokens" directory next to the config file.
A missing config file is not an error: the returned Store has no contexts. This lets callers fall back to other credential sources (e.g. plugin environment variables) without special-casing a first run.
func LoadOrInit ¶ added in v0.1.86
LoadOrInit loads the config at path, or — when no config file exists yet — creates a fresh one with a single default context named defaultContextName (server and space defaulted), makes it current, and persists it. It is the first-run initialization a CLI runs on startup. If path is empty, DefaultConfigPath is used.
func (*Store) ActiveContext ¶ added in v0.1.86
ActiveContext returns the context to use: the [Use] override if set, otherwise the current context from the config file. It returns an error when no context is configured.
func (*Store) ConfigPath ¶ added in v0.1.86
ConfigPath returns the absolute path of the loaded config file.
func (*Store) CreateContext ¶ added in v0.1.86
CreateContext adds a new context with the given (required, valid, unique) name. serverURL, organization, and defaultSpace fall back to defaults when empty. The first context created becomes the current one. It mutates the in-memory config only; call Store.SaveConfig to persist.
func (*Store) CurrentContextName ¶ added in v0.1.86
CurrentContextName returns the name of the current context as recorded in the config file (ignoring any in-memory override). It is empty when no context is configured.
func (*Store) DeleteContext ¶ added in v0.1.86
DeleteContext removes a context (and its token file) and persists the config. The last remaining context cannot be deleted; deleting the current context switches to another.
func (*Store) DeleteTokenData ¶ added in v0.1.86
DeleteTokenData removes a context's token file (a missing file is not an error).
func (*Store) FindContextByCoordinate ¶ added in v0.1.86
func (s *Store) FindContextByCoordinate(coordinate Coordinate) (*Context, error)
FindContextByCoordinate returns the context whose coordinate matches.
func (*Store) GetAllContextNames ¶ added in v0.1.86
GetAllContextNames returns the names of all configured contexts.
func (*Store) RenameContext ¶ added in v0.1.86
RenameContext renames a context, moving its token file and updating the current context if it was the one renamed. It mutates in-memory config (and the token file on disk) only; call Store.SaveConfig to persist the config.
func (*Store) SaveConfig ¶ added in v0.1.86
SaveConfig writes the configuration to the config file (creating the config directory if needed).
func (*Store) SaveTokenData ¶ added in v0.1.86
SaveTokenData writes a context's credentials to its token file (creating the token directory with secure permissions if needed).
func (*Store) SetCurrentContext ¶ added in v0.1.86
SetCurrentContext makes name the current context and stamps its LastUsed. It mutates in-memory config only; call Store.SaveConfig to persist.
func (*Store) TokenData ¶ added in v0.1.86
TokenData loads the credentials for a context from its token file.
type TokenData ¶ added in v0.1.86
type TokenData struct {
AccessToken string `json:"accessToken"`
RefreshToken string `json:"refreshToken,omitempty"`
}
TokenData is the contents of a token file.
type UnitOutcome ¶ added in v0.1.86
type UnitOutcome struct {
UnitID string
SpaceID string
SpaceSlug string
UnitSlug string
Success bool
Error string
HasMutations bool
// Mutations carries the (old -> new) diffs for rendering, when present.
Mutations *goclientnew.ResourceMutationList
// Outputs holds function output types mapped to embedded-JSON output data
// (e.g. the result of a read-only function like get-resources).
Outputs map[string]string
}
UnitOutcome is the per-unit result of a mutation or function invocation.
type User ¶
type User struct {
ID string `json:"id"`
Email string `json:"email"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
ProfilePictureURL string `json:"profile_picture_url"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
ExternalID string `json:"external_id,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
}
type Where ¶ added in v0.1.86
type Where struct {
// contains filtered or unexported fields
}
Where builds a SQL-inspired filter expression by AND-ing clauses, matching the syntax the ConfigHub API accepts for its "where" parameters. The zero value is an empty (match-all) filter. Where is immutable; each method returns a new value.
func NewWhere ¶ added in v0.1.86
NewWhere starts a filter from a raw clause. An empty clause yields an empty filter.
func (Where) And ¶ added in v0.1.86
And appends a raw clause, AND-ed with the existing ones. An empty clause is ignored, so And is safe to call with optional predicates.
func (Where) In ¶ added in v0.1.86
func (w Where) In(field string, ids []goclientnew.UUID) Where
In appends a `<field> IN ('a','b',…)` predicate over UUIDs. Calling In with no ids is a no-op (it returns the filter unchanged); callers that need "match nothing" semantics for an empty set should short-circuit before querying.