executor

package
v0.0.0-...-0bc6d30 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2025 License: MIT Imports: 21 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 executor provides confirmation prompt functionality for destructive operations.

The confirmation system reads the x-cli-confirmation extension from OpenAPI specs and prompts users before executing potentially dangerous operations like deletions.

Features

  • Automatic confirmation prompts for operations marked with x-cli-confirmation
  • Bypass flag support (e.g., --yes, --force) to skip prompts in automation
  • Parameter substitution in confirmation messages (e.g., "Delete {cluster_id}?")
  • Support for kebab-case, camelCase, and snake_case parameter names
  • Styled terminal output using pterm for clear visual feedback
  • Optional explicit confirmation requiring typing "yes" for highly destructive operations

Example OpenAPI Configuration

delete:
  operationId: deleteCluster
  x-cli-confirmation:
    enabled: true
    message: "Are you sure you want to delete cluster '{cluster_id}'?"
    flag: "--yes"

Usage

The executor automatically checks for confirmation before executing operations. Users can bypass prompts with:

mycli delete cluster my-cluster --yes

Or they will be prompted interactively:

┌─ Confirmation Required ─┐
│ Delete cluster 'my-cluster'? │
└─────────────────────────┘
Do you want to continue? [y/N]:

Package executor handles execution of OpenAPI operations from Cobra commands.

The executor package implements the runtime execution engine for generated CLIs, handling HTTP requests, authentication, response formatting, async operations, workflows, and error handling. It bridges Cobra commands with OpenAPI operations.

Execution Flow

  1. Extract operation metadata from command annotations
  2. Build HTTP request from command flags and args
  3. Apply authentication headers
  4. Execute HTTP request
  5. Handle response (sync, async, workflow)
  6. Format and display output
  7. Update state and history

Features

  • Automatic request building from OpenAPI specs
  • Authentication injection (API key, OAuth2, Basic)
  • Path/query/header parameter mapping
  • Request body construction from flags
  • Async operation polling with progress display
  • Multi-step workflow execution
  • Response formatting (JSON, YAML, table, etc.)
  • Error handling with helpful messages

Example Usage

// Create executor
executor, _ := executor.NewExecutor(spec, &executor.ExecutorConfig{
    BaseURL: "https://api.example.com",
    AuthManager: authManager,
    OutputManager: outputManager,
})

// Wire to command
cmd.RunE = func(cmd *cobra.Command, args []string) error {
    return executor.Execute(cmd, args)
}

Async Operations

For operations marked with x-cli-async, the executor automatically polls for completion:

x-cli-async:
  enabled: true
  status-field: status
  terminal-states: [completed, failed]
  polling:
    interval: 5
    timeout: 300

Workflow Execution

For x-cli-workflow operations, the executor delegates to the workflow engine for multi-step execution with dependencies, retries, and rollback.

The executor integrates with progress indicators, state management, and secrets masking for a complete CLI execution experience.

Package executor provides preflight check execution for OpenAPI operations.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ShowConfirmationPrompt

func ShowConfirmationPrompt(message string) (bool, error)

ShowConfirmationPrompt displays a confirmation prompt to the user. Returns true if the user confirms, false otherwise.

func ShowExplicitConfirmationPrompt

func ShowExplicitConfirmationPrompt(message string) (bool, error)

ShowExplicitConfirmationPrompt requires the user to type "yes" to confirm. Returns true if the user types "yes", false otherwise.

Types

type ConfirmationOptions

type ConfirmationOptions struct {
	// Config from the OpenAPI spec
	Config *openapi.CLIConfirmation
	// Parameters to use for template substitution in the message
	Parameters map[string]interface{}
}

ConfirmationOptions contains options for confirmation prompts.

type Executor

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

Executor executes OpenAPI operations from Cobra commands.

func NewExecutor

func NewExecutor(spec *openapi.ParsedSpec, config *ExecutorConfig) (*Executor, error)

NewExecutor creates a new command executor.

func (*Executor) CheckConfirmation

func (e *Executor) CheckConfirmation(cmd *cobra.Command, op *openapi.Operation) (bool, error)

CheckConfirmation checks if confirmation is required and prompts the user. Returns true if the operation should proceed, false if it should be canceled.

Example

Example usage of confirmation system

// Parse spec
parser := openapi.NewParser()
spec, _ := parser.ParseFile(context.Background(), "../../examples/openapi/swagger2-example.json")

// Create executor
executor, _ := NewExecutor(spec, &ExecutorConfig{
	BaseURL: "https://api.example.com",
})

// Create operation with confirmation
op := &openapi.Operation{
	CLIConfirmation: &openapi.CLIConfirmation{
		Enabled: true,
		Message: "Are you sure you want to delete this resource?",
		Flag:    "--yes",
	},
}

// Create command with bypass flag
cmd := &cobra.Command{Use: "delete"}
cmd.Flags().Bool("yes", false, "Bypass confirmation")
_ = cmd.Flags().Set("yes", "true")

// Check confirmation (bypassed by flag)
proceed, err := executor.CheckConfirmation(cmd, op)
if err != nil {
	panic(err)
}

if proceed {
	// Operation proceeds
	println("Operation confirmed")
}

func (*Executor) Execute

func (e *Executor) Execute(cmd *cobra.Command, args []string) error

Execute executes a command by making the appropriate HTTP request.

type ExecutorConfig

type ExecutorConfig struct {
	BaseURL       string
	HTTPClient    *http.Client
	AuthManager   *auth.Manager
	OutputManager *output.Manager
	StateManager  *state.Manager
	ProgressMgr   *progress.Manager
}

ExecutorConfig configures the executor.

type PreflightResult

type PreflightResult struct {
	Name        string
	Description string
	Passed      bool
	Required    bool
	Error       error
	Response    *http.Response
	Body        []byte
}

PreflightResult represents the result of a single preflight check.

type PreflightResults

type PreflightResults struct {
	Checks  []*PreflightResult
	AllPass bool
	Failed  []*PreflightResult
}

PreflightResults contains the results of all preflight checks.

type Runtime

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

Runtime wires together all subsystems and manages the CLI lifecycle.

func NewRuntime

func NewRuntime(ctx context.Context, runtimeConfig *RuntimeConfig) (*Runtime, error)

NewRuntime creates a new runtime instance.

func (*Runtime) Execute

func (rt *Runtime) Execute() error

Execute executes the CLI.

func (*Runtime) ExecuteContext

func (rt *Runtime) ExecuteContext(ctx context.Context) error

ExecuteContext executes the CLI with a context.

func (*Runtime) GetAuthManager

func (rt *Runtime) GetAuthManager() *auth.Manager

GetAuthManager returns the auth manager.

func (*Runtime) GetOutputManager

func (rt *Runtime) GetOutputManager() *output.Manager

GetOutputManager returns the output manager.

func (*Runtime) GetPluginRegistry

func (rt *Runtime) GetPluginRegistry() *plugin.Registry

GetPluginRegistry returns the plugin registry.

func (*Runtime) GetProgressManager

func (rt *Runtime) GetProgressManager() *progress.Manager

GetProgressManager returns the progress manager.

func (*Runtime) GetRootCommand

func (rt *Runtime) GetRootCommand() *cobra.Command

GetRootCommand returns the root Cobra command.

func (*Runtime) GetStateManager

func (rt *Runtime) GetStateManager() *state.Manager

GetStateManager returns the state manager.

func (*Runtime) Shutdown

func (rt *Runtime) Shutdown() error

Shutdown performs cleanup operations.

type RuntimeConfig

type RuntimeConfig struct {
	CLIName    string
	SpecPath   string
	ConfigPath string
	BaseURL    string
}

RuntimeConfig configures the runtime.

Jump to

Keyboard shortcuts

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