azldev

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 18, 2026 License: MIT Imports: 36 Imported by: 0

Documentation

Overview

Package azldev implements the core of the azldev command-line tool.

Contents

To the executable, it provides:

  • The App type: implementation of the azldev command-line tool, usable by the executable.

To packages implementing commands, it provides:

  • The Env type: high-level environment and context for tool commands. Implements the opctx.Ctx interface for use with helper packages that do not take dependencies on this package (azldev).
  • RunFunc and RunFuncWithExtraArgs: helpers that *should* be used for azldev commands to implement cobra.Command.

The [core] package provides additional utilities for command implementations.

Background

The azldev command-line tool is focused on development-oriented operations for developing, building, analyzing, and maintaining the Azure Linux distro or its components. This package (azldev) is focused on providing common infrastructure to (1) simplify adding new commands, and (2) ensuring that commands are exposed to the user in a consistent and discoverable manner.

Core to usage of this tool is the notion of a "project". A project contains configuration, components, checkers, and other elements pertinent to building and maintaining components of the distro. A project is typically defined at the git repo-level, although it is possible to have multiple projects living in a single repo.

A file called `azldev.toml` defines a project. The directory containing that file is considered the project root. This configuration file may, in turn, include other config files. A full definition of the file format is outside the scope of this documentation.

Execution Flow

When this command-line tool is invoked, it uses the cobra package to construct a root cobra.Command containing global command-line options, and under which top-level tool commands will be registered.

The executable that wraps an App instance will statically register the top-level commands that will always be available through the tool. Command packages that include functionality only relevant in certain projects or configurations will register a post-initialization callback with the App. These callbacks will be invoked after configuration has been loaded and processed.

When the executable transfers control to App.Execute, the App instance will:

  • Inspect the command line for a core set of options that affect general tool execution. These include logging verbosity as well as options that influence how the project root and its configuration are found.
  • Initialize early logging, without any persistent log files.
  • Load and process project configuration. On error, execution will return to the executable wrapper.
  • Construct the singleton instance of Env that will be used for the duration of the tool's execution.
  • Re-initialize logging, if the configuration specified paths to log files.
  • Invoke any registered post-init callbacks.
  • Prune any intermediate sub-commands that have no leaf children.
  • Invoke the cobra.Command.Execute method to execute the command line.

Individual command packages implement instances of cobra.Command and use RunFunc or RunFuncWithExtraArgs to implement the cobra.Command's RunE callback function, providing to them an "inner" function that implements the core logic of the command.

The App threads through the Env instance to cobra.Command instances by associating it as the context.Context of the root-level cobra.Command. This allows RunFunc and RunFuncWithExtraArgs to extract the Env instance and pass it through to the inner command implementations.

These inner implementations are expected to return an `interface{}` and an `error`. Upon regaining control, RunFunc and RunFuncWithExtraArgs will format the returned `interface{}` value and display it to the user using the encoding format requested on the command-line (e.g., JSON, human-readable table, etc.).

Index

Constants

View Source
const (
	// CommandGroupMeta represents the command group for meta commands like help, completion, and version.
	CommandGroupMeta = "meta"
	// CommandGroupPrimary represents the command group for primary application commands.
	CommandGroupPrimary = "primary"
)
View Source
const CmdAnnotationMCPEnabled = "azldev.mcp.enabled"

CmdAnnotationMCPFuncType is the cobra.Command annotation key used to indicate that a command should be enabled in MCP server mode. The value associated with the key is ignored.

View Source
const (
	// CommandAnnotationRootOK is a [cobra.Command.Annotations] key used to indicate that a command
	// is allowed to be run as root.
	CommandAnnotationRootOK = "rootOK"
)

Variables

View Source
var ErrInvalidUsage = errors.New("invalid usage")

Error to return when a command is invoked with invalid usage.

Functions

func DefaultCmdFactory

func DefaultCmdFactory(dryRunInfo opctx.DryRunnable, eventListener opctx.EventListener) (opctx.CmdFactory, error)

DefaultCmdFactory returns a default opctx.CmdFactory that uses the exec.Cmd command execution facilities.

func DefaultFileSystemFactory

func DefaultFileSystemFactory() opctx.FileSystemFactory

DefaultFileSystemFactory returns a default opctx.FileSystemFactory that uses the OS file system.

func DefaultOSEnvFactory

func DefaultOSEnvFactory() opctx.OSEnvFactory

DefaultOSEnvFactory returns a default opctx.OSEnvFactory that uses the OS environment.

func ExportAsMCPTool

func ExportAsMCPTool(cmd *cobra.Command)

ExportAsMCPTool updates the provided command (and all descendant commands), opting it into being advertised as a tool in MCP server mode.

func NewAppDryRunnable

func NewAppDryRunnable(dryRun bool) *appDryRunnable

NewAppDryRunnable constructs a new [appDryRunnable] instance with the specified dry run mode.

func NewEventListener

func NewEventListener(eventLogger *slog.Logger) (*appEventListener, error)

NewEventListener creates a new event listener for the environment.

func RunFunc

func RunFunc(innerFunc CmdFuncType) cobraRunFuncType

Returns a function usable by an azldev command as a cobra.Command 'RunE' function. Rejects all positional arguments, retrieves the Env, invokes the provided inner function with the right context objects, and then provides standard result reporting for the opaque result value returned by the inner function. Fails early if no project/configuration was loaded.

func RunFuncWithExtraArgs

func RunFuncWithExtraArgs(innerFunc CmdWithExtraArgsFuncType) cobraRunFuncType

Returns a function usable by an azldev command as a `cobra.Command` 'RunE' function. Retrieves the `Env`, invokes the provided inner function with the right context objects and positional arguments, and then provides standard result reporting for the opaque result value returned by the inner function. Fails early if no project/configuration was loaded.

func RunFuncWithoutRequiredConfig

func RunFuncWithoutRequiredConfig(innerFunc CmdFuncType) cobraRunFuncType

Returns a function usable by an azldev command as a cobra.Command 'RunE' function. Rejects all positional arguments, retrieves the Env, invokes the provided inner function with the right context objects, and then provides standard result reporting for the opaque result value returned by the inner function. Does *not* require valid project/configuration to have been loaded.

func RunFuncWithoutRequiredConfigWithExtraArgs

func RunFuncWithoutRequiredConfigWithExtraArgs(innerFunc CmdWithExtraArgsFuncType) cobraRunFuncType

Returns a function usable by an azldev command as a cobra.Command 'RunE' function. Retrieves the Env, invokes the provided inner function with the right context objects and positional arguments, and then provides standard result reporting for the opaque result value returned by the inner function. Does *not* require valid project/configuration to have been loaded.

Types

type App

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

An instance of the azldev CLI application. This is typically used as a singleton.

func NewApp

func NewApp(fsFactory opctx.FileSystemFactory, osEnvFactory opctx.OSEnvFactory) *App

Constructs a new CLI application instance.

func (*App) AddTopLevelCommand

func (a *App) AddTopLevelCommand(child *cobra.Command)

Adds the given command as a new top-level command to the CLI.

func (*App) CommandNames

func (a *App) CommandNames(ancestors ...string) ([]string, error)

Returns the names of the app's commands. The optional provided list of ancestors instructs this function to traverse through the command hierarchy before retrieving child names. This function is largely intended for tests to introspect on the commands available in a given App instance.

func (*App) Execute

func (a *App) Execute(args []string) int

Main entry point for the azldev CLI. Responsible for parsing command-line arguments, initializing logging, loading configuration, and executing the requested command.

func (*App) RegisterPostInitCallback

func (a *App) RegisterPostInitCallback(callback PostInitCallbackFunc)

Registers a callback that will be executed after configuration has been loaded.

type CmdFuncType

type CmdFuncType = func(env *Env) (interface{}, error)

Type of a function for use with RunFunc and siblings.

type CmdWithExtraArgsFuncType

type CmdWithExtraArgsFuncType = func(env *Env, extraArgs []string) (interface{}, error)

Type of a function for use with RunFuncWithExtraArgs and siblings.

type ColorMode

type ColorMode string

Colorization mode for the application.

const (
	// ColorModeAlways indicates that color should always be used in output.
	ColorModeAlways ColorMode = "always"
	// ColorModeAuto indicates that color should be used if the output is a terminal.
	ColorModeAuto ColorMode = "auto"
	// ColorModeNever indicates that color should never be used in output.
	ColorModeNever ColorMode = "never"
)

func (*ColorMode) Set

func (f *ColorMode) Set(value string) error

Parses the format from a string; used by command-line parser.

func (*ColorMode) String

func (f *ColorMode) String() string

func (*ColorMode) Type

func (f *ColorMode) Type() string

Returns a descriptive string used in command-line help.

type Env

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

Core environment structure, available to CLI commands. Implements opctx.Ctx for use with lower-level packages.

func GetEnvFromCommand

func GetEnvFromCommand(cmd *cobra.Command) (*Env, error)

Helper to retrieve the Env from the context of a cobra.Command.

func NewEnv

func NewEnv(ctx context.Context, options EnvOptions) *Env

Constructs a new Env using specified options.

func (*Env) AllPromptsAccepted

func (env *Env) AllPromptsAccepted() bool

Returns whether all prompts should be auto-accepted without being displayed.

func (*Env) ColorMode

func (env *Env) ColorMode() ColorMode

Returns the color mode for output from this environment.

func (*Env) Command

func (env *Env) Command(cmd *exec.Cmd) (opctx.Cmd, error)

Command implements the opctx.CmdFactory interface.

func (*Env) CommandInSearchPath

func (env *Env) CommandInSearchPath(name string) bool

CommandInSearchPath implements the opctx.CmdFactory interface.

func (*Env) Config

func (env *Env) Config() *projectconfig.ProjectConfig

Returns the loaded project configuration. Note that the configuration may include raw data that hasn't yet been resolved. For querying resolved component configuration, the [components] package should be used instead.

func (*Env) ConfirmAutoResolution

func (env *Env) ConfirmAutoResolution(text string) bool

ConfirmAutoResolution prompts the user to confirm auto-resolution of a problem. The provided text is displayed to the user as explanation.

func (*Env) ConstructionTime

func (env *Env) ConstructionTime() time.Time

Reports the time that this environment was constructed.

func (*Env) Context

func (env *Env) Context() context.Context

Retrieves the ambient context.Context associated with this environment.

func (*Env) Deadline

func (env *Env) Deadline() (deadline time.Time, ok bool)

Deadline implements the context.Context interface.

func (*Env) DefaultReportFormat

func (env *Env) DefaultReportFormat() ReportFormat

Returns the default report format for this environment.

func (*Env) Distro

func (env *Env) Distro() (
	distroDef projectconfig.DistroDefinition, distroVersionDef projectconfig.DistroVersionDefinition, err error,
)

Resolves the environment's default "distro" -- i.e., the distro that is being built in and against. On success, returns back the definition of the distro as well as the definition of the specific version of the distro.

func (*Env) Done

func (env *Env) Done() <-chan struct{}

Done implements the context.Context interface.

func (*Env) DryRun

func (env *Env) DryRun() bool

Indicates whether the user has requested a "dry run" where no changes are made to the host system, and no non-trivial computation occurs.

func (*Env) Err

func (env *Env) Err() error

Err implements the context.Context interface.

func (*Env) Event

func (env *Env) Event(name string, args ...any)

Event implements the opctx.EventListener interface.

Records an event and immediately ends it.

func (*Env) FS

func (env *Env) FS() opctx.FS

FS implements the opctx.FileSystemFactory interface.

func (*Env) LogsDir

func (env *Env) LogsDir() string

Returns the file path to the loaded project's log directory.

func (*Env) NetworkRetries

func (env *Env) NetworkRetries() int

NetworkRetries returns the maximum number of attempts for network operations.

func (*Env) OSEnv

func (env *Env) OSEnv() opctx.OSEnv

OSEnv implements the opctx.OSEnvFactory interface.

func (*Env) OutputDir

func (env *Env) OutputDir() string

Returns the file path to the loaded project's output directory.

func (*Env) PermissiveConfigParsing

func (env *Env) PermissiveConfigParsing() bool

PermissiveConfigParsing returns whether permissive parsing of configuration files is enabled, where unknown fields are ignored instead of causing an error.

func (*Env) ProjectDir

func (env *Env) ProjectDir() string

Returns the file path to the loaded project's root directory.

func (*Env) PromptsAllowed

func (env *Env) PromptsAllowed() bool

Returns whether user blocking prompts are allowed.

func (*Env) Quiet

func (env *Env) Quiet() bool

Returns whether the user has requested a "quiet" run where only minimal output is displayed.

func (*Env) ReportFile

func (env *Env) ReportFile() io.Writer

Returns the writer to be used for writing result reports.

func (*Env) ResolveDistroRef

func (env *Env) ResolveDistroRef(distroRef projectconfig.DistroReference) (
	distroDef projectconfig.DistroDefinition, distroVersionDef projectconfig.DistroVersionDefinition, err error,
)

ResolveDistroRef resolves a distro reference to the actual distro definition and version.

func (*Env) SetAcceptAllPrompts

func (env *Env) SetAcceptAllPrompts(acceptAllPrompts bool)

Enables or disables "accept all prompts" mode.

func (*Env) SetColorMode

func (env *Env) SetColorMode(colorMode ColorMode)

Sets the color mode for output from this environment.

func (*Env) SetDefaultReportFormat

func (env *Env) SetDefaultReportFormat(format ReportFormat)

Sets the default report format for this environment.

func (*Env) SetEventListener

func (env *Env) SetEventListener(eventListener opctx.EventListener)

SetEventListener registers the event listener to be used in this environment.

func (*Env) SetNetworkRetries

func (env *Env) SetNetworkRetries(retries int)

SetNetworkRetries sets the maximum number of attempts for network operations. Values less than 1 are clamped to 1.

func (*Env) SetPermissiveConfigParsing

func (env *Env) SetPermissiveConfigParsing(permissive bool)

SetPermissiveConfigParsing enables or disables permissive parsing of configuration files, where unknown fields are ignored instead of causing an error.

func (*Env) SetQuiet

func (env *Env) SetQuiet(quiet bool)

SetQuiet enables or disables "quiet" mode.

func (*Env) SetReportFile

func (env *Env) SetReportFile(reportFile io.Writer)

Sets the writer to be used for writing result reports.

func (*Env) SetVerbose

func (env *Env) SetVerbose(verbose bool)

SetVerbose enables or disables "verbose" mode.

func (*Env) StartEvent

func (env *Env) StartEvent(name string, args ...any) opctx.Event

StartEvent implements the opctx.EventListener interface.

func (*Env) Value

func (env *Env) Value(key any) any

Value implements the context.Context interface.

func (*Env) Verbose

func (env *Env) Verbose() bool

Returns whether the user has requested a "verbose" run where debug output is displayed to stdio.

func (*Env) WorkDir

func (env *Env) WorkDir() string

Returns the file path to the loaded project's internal working directory.

type EnvOptions

type EnvOptions struct {
	// Path to the project's root directory.
	ProjectDir string

	// The loaded configuration for the project.
	Config *projectconfig.ProjectConfig

	// Injected dependencies.
	DryRunnable   opctx.DryRunnable
	EventListener opctx.EventListener
	Interfaces    SystemInterfaces
}

Parameters used to construct an Env.

func NewEnvOptions

func NewEnvOptions() EnvOptions

Constructs default EnvOptions.

type PostInitCallbackFunc

type PostInitCallbackFunc func(app *App, env *Env) error

Type of a callback function that can be registered for invocation after the application has loaded configuration, but before it fully parses command-line arguments.

type ReportFormat

type ReportFormat string

Format of a results report.

const (
	// ReportFormatTable is a human-readable tabular format.
	ReportFormatTable ReportFormat = "table"
	// ReportFormatCSV is a machine-readable, comma-separated value format.
	ReportFormatCSV ReportFormat = "csv"
	// ReportFormatJSON is a machine-readable JSON format.
	ReportFormatJSON ReportFormat = "json"
	// ReportFormatMarkdown is a markdown format intended for generating formatted readable reports.
	ReportFormatMarkdown ReportFormat = "markdown"
)

func (*ReportFormat) Set

func (f *ReportFormat) Set(value string) error

Parses the format from a string; used by command-line parser.

func (*ReportFormat) String

func (f *ReportFormat) String() string

func (*ReportFormat) Type

func (f *ReportFormat) Type() string

Returns a descriptive string used in command-line help.

type SystemInterfaces

type SystemInterfaces struct {
	// Factory for accessing command execution.
	CmdFactory opctx.CmdFactory
	// Factory for accessing the file system.
	FileSystemFactory opctx.FileSystemFactory
	// Factory for querying the OS environment (e.g,. current working directory).
	OSEnvFactory opctx.OSEnvFactory
}

Encapsulates the abstract interfaces usable for system interaction.

Directories

Path Synopsis
cmds
core
componentbuilder/componentbuilder_test
Package componentbuilder is a generated GoMock package.
Package componentbuilder is a generated GoMock package.
components
Package components provides abstractions and utilities for representing, querying, and managing software components within an Azure Linux project.
Package components provides abstractions and utilities for representing, querying, and managing software components within an Azure Linux project.
components/components_testutils
Package components_testutils is a generated GoMock package.
Package components_testutils is a generated GoMock package.
mcp
specs
Package specs provides abstractions and utilities for accessing and parsing RPM spec files associated with components in Azure Linux projects.
Package specs provides abstractions and utilities for accessing and parsing RPM spec files associated with components in Azure Linux projects.
specs/specs_testutils
Package specs_testutils is a generated GoMock package.
Package specs_testutils is a generated GoMock package.

Jump to

Keyboard shortcuts

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