util

package
v2.19.0 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: Apache-2.0 Imports: 33 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MeetURL        = "https://meet.livekit.io/custom"
	ConsoleURLPath = "/projects/%s/agents/console/?"
)

Variables

View Source
var (

	// Theme holds the huh form styles for the active color theme. Pass it to a form
	// with FormTheme(); read it directly for individual styles.
	Theme *huh.Styles

	Fg              color.Color
	FormBaseStyle   lipgloss.Style
	FormHeaderStyle lipgloss.Style
)

Active theme state. Populated by applyTheme; switched once at startup via SetTheme. These are package-level so existing call sites (util.Theme, util.Accented, util.Fg, …) keep working; they are read at render time, which always happens after the theme is selected.

View Source
var (
	OpenFlag = &cli.StringFlag{
		Name:  "open",
		Usage: fmt.Sprintf("Open relevant `APP` in browser, supported options: %v", options),
		Validator: func(input string) error {
			if !slices.Contains(options, input) {
				return fmt.Errorf("invalid open target: %s, supported options: %v", input, options)
			}
			return nil
		},
	}
)

ValidThemes lists the selectable theme names, for validation and help text.

Functions

func Accent added in v2.16.5

func Accent() color.Color

func Accented added in v2.4.5

func Accented(text string) string

Accented renders text in the active theme's title style (brand color under livekit).

func Brand added in v2.16.5

func Brand() color.Color

Semantic color accessors. They read the active palette at call time, so they reflect the selected theme even when used to build styles lazily.

func Confirm added in v2.16.5

func Confirm() *huh.Confirm

Confirm is a yes/no prompt styled by the active theme. It uses huh's built-in confirm field, which supports y/n quick entry (Accept: y/Y, Reject: n/N) and renders both choices as side-by-side buttons.

func CopyFile

func CopyFile(src, dest string) error

Safely copy a file across filesystems, preserving permissions

func CreateTable

func CreateTable() *table.Table

func Dash added in v2.18.7

func Dash(s string) string

Dash returns s, or "-" when s is empty or only whitespace. It is the value counterpart of DashString (which takes a *string).

func DashInt32 added in v2.18.7

func DashInt32(v *int32) string

DashInt32 renders an optional int32 for a table cell (0 when nil).

func DashString added in v2.18.7

func DashString(s *string) string

DashString renders an optional string for a table cell, using a dash when it is nil or empty.

func Deref added in v2.18.7

func Deref[T any](p *T) T

Deref returns the pointed-to value, or the zero value when nil.

func DerefEnum added in v2.18.7

func DerefEnum[T ~string](p *T) string

DerefEnum renders an optional generated string-enum for a table cell, using a dash when nil or empty.

func DetectBackground added in v2.18.7

func DetectBackground()

DetectBackground resolves the terminal background now, so no later render has to. The query puts stdin in raw mode and waits for the terminal to answer, which must not happen once a Bubble Tea program or a huh form owns the input; running it before any command does keeps it out of their way. It's a no-op on a non-interactive terminal.

func Dimmed added in v2.4.5

func Dimmed(text string) string

Dimmed renders text in the active theme's muted/description style.

func EllipsizeTo

func EllipsizeTo(str string, maxLength int) string

func Err added in v2.18.3

func Err(text string) string

Warn renders text in the active theme's Error style

func Error added in v2.16.5

func Error() color.Color

func ExpandTemplate added in v2.4.13

func ExpandTemplate(template string) string

func ExtractSubdomain added in v2.4.6

func ExtractSubdomain(url string) string

func FileExists added in v2.5.0

func FileExists(dir fs.FS, filename string) bool

func FormTheme added in v2.18.7

func FormTheme() huh.Theme

FormTheme adapts the active theme to huh v2's Theme interface, which asks for a func(isDark bool) *Styles. Our styles already resolve light/dark per color (see adaptive), so the flag is ignored.

func FormatBytes added in v2.18.7

func FormatBytes(value json.RawMessage) string

FormatBytes renders a raw JSON byte count as a human-readable size (SI units), passing through non-numeric values unchanged.

func FormatRFC3339 added in v2.18.7

func FormatRFC3339(t time.Time, zero string) string

FormatRFC3339 renders t in RFC 3339, or the zero placeholder when t is the zero time.

func FormatTime added in v2.18.7

func FormatTime(t *time.Time) string

FormatTime renders an optional timestamp in local time, using a dash for a missing or zero value.

func GitCurrentBranch added in v2.18.0

func GitCurrentBranch(ctx context.Context, dir string) (string, error)

GitCurrentBranch returns the name of the currently checked-out branch. It returns an empty string (and no error) when HEAD is detached, since there is no meaningful branch to report.

func GitHeadCommit added in v2.18.0

func GitHeadCommit(ctx context.Context, dir string) (string, error)

GitHeadCommit returns the abbreviated SHA of the current HEAD commit. Git picks the shortest prefix that is unambiguous within the repository (min 7 chars, growing as needed), so the value uniquely identifies the commit in this repo. It errors when dir is not a git repository or has no commits yet.

func GitWorkingTreeHash added in v2.18.0

func GitWorkingTreeHash(ctx context.Context, dir string) (string, error)

GitWorkingTreeHash returns an abbreviated, content-addressable SHA that uniquely identifies the exact current state of the working tree — including staged, unstaged, and untracked (but not ignored) files. This is useful for distinguishing dirty deploys that share the same HEAD commit. The snapshot is built in a throwaway index, so the user's staging area and working tree are left untouched. Two identical working trees produce the same hash. Like GitHeadCommit, the returned SHA is abbreviated to the shortest prefix that is unambiguous within the repository.

func HasUncommittedChanges added in v2.18.0

func HasUncommittedChanges(ctx context.Context, dir string) (bool, error)

HasUncommittedChanges reports whether the working tree at dir has staged or unstaged changes, or untracked files (i.e. `git status` is not clean).

func HashString

func HashString(str string) (string, error)
func Hyperlink(url, label string) string

Hyperlink wraps label in an OSC 8 terminal hyperlink pointing at url. Terminals that support OSC 8 render label as a clickable link; others ignore the escape and show label unchanged. Gate calls on an interactive terminal (see Printer.Interactive) so the escape never leaks into piped/redirected output.

func IsGitRepository added in v2.18.0

func IsGitRepository(ctx context.Context, dir string) bool

IsGitRepository reports whether dir is inside a git working tree. It returns false (rather than an error) when git is not installed or dir is not tracked, so callers can treat "no git" as a soft, non-fatal condition.

func MapStrings

func MapStrings(strs []string, fn func(string) string) []string

func MoveDir

func MoveDir(src, dest string) error

Safely move a directory across filesystems, preserving permissions

func OpenInConsole added in v2.16.1

func OpenInConsole(dashboardURL, projectId string, params *ConsoleURLParams) error

func OpenInMeet added in v2.4.13

func OpenInMeet(livekitURL, token string) error

func PrintJSON

func PrintJSON(obj any)

func PrintJSONTo added in v2.15.1

func PrintJSONTo(w io.Writer, obj any) error

func RawJSONToString added in v2.18.7

func RawJSONToString(value json.RawMessage) string

RawJSONToString renders a raw JSON scalar (number or string) for display, using a dash for an absent value.

func RenderList added in v2.18.7

func RenderList[T any](p *Printer, asJSON bool, list []T, empty string, headers []string, row func(T) []string) error

RenderList prints a list of items either as JSON (asJSON) or as a table whose rows are produced by row(). When the list is empty it prints the empty message as a status line. It is generic so callers render the source types directly without an intermediate view model.

func RenderOne added in v2.18.7

func RenderOne[T any](p *Printer, asJSON bool, item T, headers []string, row func(T) []string) error

RenderOne prints a single item as JSON (asJSON) or a one-row table.

func RenderPage added in v2.18.7

func RenderPage[T any](p *Printer, asJSON bool, list []T, nextCursor, empty string, headers []string, row func(T) []string) error

RenderPage prints one page of a cursor-paginated listing. As JSON it emits {items, nextCursor} so a caller can iterate; as a table it prints the rows and, when nextCursor is non-empty, a hint to re-run with --cursor.

func Result added in v2.18.7

func Result(a ...any)

Result writes primary output to the default Printer (stdout, always printed).

func Resultf added in v2.18.7

func Resultf(format string, a ...any)

Resultf is Printf-style Result on the default Printer.

func SetDefault added in v2.18.7

func SetDefault(p *Printer)

SetDefault registers the process-wide Printer.

func SetTheme added in v2.16.5

func SetTheme(name string) error

SetTheme selects the active theme by name. An empty name resolves to the default. It returns an error for any other unrecognized name (used to validate `lk set-theme`).

func Slugify added in v2.18.7

func Slugify(s string) string

Slugify converts s into a lowercase, URL-safe alias: runs of characters that aren't ASCII letters or digits collapse to a single hyphen, and leading and trailing hyphens are trimmed. Input with no usable characters yields "".

func Status added in v2.18.7

func Status(a ...any)

Status writes an informational breadcrumb to the default Printer (stderr, suppressed by --quiet).

func Statusf added in v2.18.7

func Statusf(format string, a ...any)

Statusf is Printf-style Status on the default Printer.

func Success added in v2.16.5

func Success() color.Color

func ToUnixPath added in v2.5.2

func ToUnixPath(p string) string

Converts a path (possibly Windows-style) to a Unix-style path.

func URLSafeName

func URLSafeName(projectURL string) (string, error)

func UseTempPath

func UseTempPath(permanentPath string) (string, func() error, func() error)

Provides a temporary path, a function to relocate it to a permanent path, and a function to clean up the temporary path that should always be deferred in the case of a failure to relocate.

func Warn added in v2.18.3

func Warn(text string) string

Warn renders text in the active theme's Warning style

func Warnf added in v2.18.7

func Warnf(format string, a ...any)

Warnf writes a warning to the default Printer (stderr, never suppressed).

func Warning added in v2.16.5

func Warning() color.Color

func WrapToLines

func WrapToLines(input string, maxLineLength int) []string

func WrapWith

func WrapWith(wrap string) func(string) string

Types

type ConsoleURLParams added in v2.16.1

type ConsoleURLParams struct {
	AgentName    string            `url:"agentName,omitempty"`
	Deployment   string            `url:"deployment,omitempty"`
	JobMetadata  string            `url:"jobMetadata,omitempty"`
	RoomName     string            `url:"roomName,omitempty"`
	RoomMetadata string            `url:"roomMetadata,omitempty"`
	Identity     string            `url:"identity,omitempty"`
	Metadata     string            `url:"metadata,omitempty"`
	Attributes   map[string]string `url:"attributes,omitempty"`
	Hidden       bool              `url:"hidden,omitempty"`
	AutoStart    bool              `url:"autoStart,omitempty"`
}

type OpenTarget added in v2.4.13

type OpenTarget string
const (
	OpenTargetMeet    OpenTarget = "meet"
	OpenTargetConsole OpenTarget = "console"
)

type Printer added in v2.16.5

type Printer struct {
	Out   io.Writer // primary output: data the user might pipe or redirect
	Err   io.Writer // status, warnings, diagnostics
	Quiet bool      // suppresses Status (warnings and errors still print)
	// contains filtered or unexported fields
}

Printer is a single sink for human-facing CLI output. One instance per process is initialized from the root command and reused everywhere, so all status, warning, and result lines share consistent streams and gating.

var Default *Printer

Default is the process-wide Printer, set once from the root command via SetDefault. It lets lower-level packages that can't reach the command's Printer (config, agentfs, …) route output through the same streams and gating using the package-level Status/Statusf/Warnf/Result helpers below. It is nil until SetDefault runs; every helper (and every Printer method) is nil-safe, so pre-init or in tests they are no-ops.

func NewPrinter added in v2.16.5

func NewPrinter(out, err io.Writer, quiet bool) *Printer

NewPrinter builds a Printer targeting the given writers. Pass nil to default to os.Stdout / os.Stderr; this is the path tests use with bytes.Buffer.

func (*Printer) Await added in v2.16.5

func (p *Printer) Await(title string, ctx context.Context, action func(ctx context.Context) error) error

Await runs action while showing a spinner, then returns the action's error.

The spinner is decoration: it only animates when the Printer targets an interactive terminal and is not in quiet mode. Otherwise Await emits the title once as a plain status line (itself suppressed by --quiet) and runs the action without animation, so redirected/piped/CI output stays free of escape sequences and --quiet stays silent.

func (*Printer) Interactive added in v2.18.0

func (p *Printer) Interactive() bool

Interactive reports whether status output is going to a real terminal, so callers can gate terminal-only escapes (e.g. OSC 8 hyperlinks) and avoid leaking them into piped or redirected output.

func (*Printer) Result added in v2.16.5

func (p *Printer) Result(a ...any)

Result writes the command's primary output to stdout. Always printed.

func (*Printer) ResultWriter added in v2.16.5

func (p *Printer) ResultWriter() io.Writer

ResultWriter is the streaming counterpart of Result: always printed.

func (*Printer) Resultf added in v2.16.5

func (p *Printer) Resultf(format string, a ...any)

Resultf is Printf-style Result.

func (*Printer) Status added in v2.16.5

func (p *Printer) Status(a ...any)

Status writes an informational breadcrumb to stderr ("Using project [X]", "Cloning template…"). Suppressed by --quiet. A trailing newline is appended.

func (*Printer) StatusWriter added in v2.16.5

func (p *Printer) StatusWriter() io.Writer

StatusWriter is the streaming counterpart of Status: io.Discard under --quiet.

func (*Printer) Statusf added in v2.16.5

func (p *Printer) Statusf(format string, a ...any)

Statusf is Printf-style Status.

func (*Printer) WarnWriter added in v2.16.5

func (p *Printer) WarnWriter() io.Writer

WarnWriter is the streaming counterpart of Warnf: never silenced.

func (*Printer) Warnf added in v2.16.5

func (p *Printer) Warnf(format string, a ...any)

Warnf writes a warning to stderr. NOT suppressed by --quiet — warnings are always worth surfacing.

type ThemeName added in v2.16.5

type ThemeName string

ThemeName identifies a color theme. The active theme is selected once at startup (see SetTheme) from the value persisted in the CLI config.

const (
	// ThemeDefault uses only ANSI palette colors, so it adapts to the user's terminal
	// color scheme. This is the original look.
	ThemeDefault ThemeName = "default"
	// ThemeLiveKit uses the LiveKit brand palette (truecolor hex with light/dark variants).
	ThemeLiveKit ThemeName = "livekit"
)

Jump to

Keyboard shortcuts

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