cliout

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Feb 5, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package cliout provides structured output formatting for CLI commands. It supports multiple output formats including human-readable text and JSON, with consistent styling using ANSI colors and Unicode symbols.

Package cliout provides structured output formatting for CLI commands with cross-platform terminal support and multiple output formats.

Features

  • Multiple output formats (default human-readable and JSON)
  • ANSI color support with consistent color scheme
  • Unicode/emoji detection with ASCII fallbacks for legacy terminals
  • Orchestration mode for composing subcommands
  • Progress bars, tables, and interactive prompts
  • Cross-platform terminal detection (Windows Terminal, VS Code, PowerShell, ConEmu)

Basic Usage

import "github.com/jongio/azd-core/cliout"

// Print success message
cliout.Success("Operation completed successfully")

// Print error message
cliout.Error("Operation failed: %s", err)

// Print warning
cliout.Warning("This feature is deprecated")

// Print info message
cliout.Info("Processing %d items", count)

Output Formats

The package supports two output formats:

  • default: Human-readable text with colors and Unicode symbols
  • json: Structured JSON output for automation and scripting

Set the output format using SetFormat:

if err := cliout.SetFormat("json"); err != nil {
    log.Fatal(err)
}

Check the current format:

if cliout.IsJSON() {
    // Skip interactive prompts
}

Unicode Detection

The package automatically detects terminal Unicode support and falls back to ASCII symbols on legacy terminals. Detection includes:

  • Windows Terminal (via WT_SESSION environment variable)
  • VS Code integrated terminal (via TERM_PROGRAM environment variable)
  • PowerShell (via PSModulePath or POWERSHELL_DISTRIBUTION_CHANNEL)
  • ConEmu (via ConEmuPID environment variable)
  • Unix-like systems (assumed to support Unicode)

Old Windows Command Prompt (cmd.exe) without these environment variables will use ASCII fallback symbols.

Orchestration Mode

Orchestration mode allows composing multiple commands while suppressing redundant headers from subcommands:

cliout.SetOrchestrated(true)
// Now CommandHeader() calls will be skipped

This is useful when building workflows that chain multiple CLI commands together.

Hybrid Output

The Print function supports hybrid output where you provide both JSON data and a formatter function:

data := map[string]interface{}{"status": "success", "count": 42}
err := cliout.Print(data, func() {
    cliout.Success("Processed %d items", 42)
})

In JSON mode, the data is marshaled to JSON. In default mode, the formatter is called.

Tables

Create simple tables with automatic column width calculation:

headers := []string{"Name", "Status", "Port"}
rows := []cliout.TableRow{
    {"Name": "web", "Status": "running", "Port": "8080"},
    {"Name": "api", "Status": "stopped", "Port": "3000"},
}
cliout.Table(headers, rows)

Interactive Prompts

The Confirm function prompts for user confirmation:

if cliout.Confirm("Do you want to continue?") {
    // User confirmed
}

In JSON mode, Confirm always returns true (non-interactive).

Progress Indicators

Create simple progress bars:

bar := cliout.ProgressBar(45, 100, 30)
fmt.Println(bar)  // [█████████████░░░░░░░░░░░░░░░░░] 45%

Color Constants

The package exports ANSI color constants for custom formatting:

  • Reset, Bold, Dim
  • Foreground colors: Black, Red, Green, Yellow, Blue, Magenta, Cyan, White, Gray
  • Bright colors: BrightRed, BrightGreen, BrightYellow, BrightBlue, BrightMagenta, BrightCyan

Unicode Symbols

Unicode symbols with ASCII fallbacks:

  • SymbolCheck (✓) / ASCIICheck ([+])
  • SymbolCross (✗) / ASCIICross ([-])
  • SymbolWarning (⚠) / ASCIIWarning ([!])
  • SymbolInfo (ℹ) / ASCIIInfo ([i])
  • SymbolArrow (→) / ASCIIArrow (->)
  • SymbolDot (•) / ASCIIDot (*)

Design Principles

  • No global state except format and orchestration settings
  • All output goes to stdout (use stderr wrapper if needed)
  • Consistent color scheme across all azd extensions
  • Graceful degradation on legacy terminals
  • JSON mode for automation and scripting scenarios

Index

Constants

View Source
const (
	Reset = "\033[0m"
	Bold  = "\033[1m"
	Dim   = "\033[2m"

	// Foreground colors
	Black   = "\033[30m"
	Red     = "\033[31m"
	Green   = "\033[32m"
	Yellow  = "\033[33m"
	Blue    = "\033[34m"
	Magenta = "\033[35m"
	Cyan    = "\033[36m"
	White   = "\033[37m"
	Gray    = "\033[90m"

	// Bright foreground colors
	BrightRed     = "\033[91m"
	BrightGreen   = "\033[92m"
	BrightYellow  = "\033[93m"
	BrightBlue    = "\033[94m"
	BrightMagenta = "\033[95m"
	BrightCyan    = "\033[96m"
)

ANSI color codes for consistent styling

View Source
const (
	SymbolCheck   = "✓"
	SymbolCross   = "✗"
	SymbolWarning = "⚠"
	SymbolInfo    = "ℹ"
	SymbolArrow   = "→"
	SymbolDot     = "•"
	SymbolSpinner = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏" // Spinner frames
)

Unicode symbols for modern CLI output

View Source
const (
	ASCIICheck   = "[+]"
	ASCIICross   = "[-]"
	ASCIIWarning = "[!]"
	ASCIIInfo    = "[i]"
	ASCIIArrow   = "->"
	ASCIIDot     = "*"
)

ASCII fallback symbols for terminals that don't support Unicode

Variables

View Source
var (
	IconSearch  = "🔍"
	IconTool    = "🔧"
	IconRefresh = "🔄"
	IconPackage = "📦"
	IconPython  = "🐍"
	IconDotnet  = "🔷"
	IconDocker  = "🐳"
	IconCheck   = "📋"
	IconBulb    = "💡"
	IconRocket  = "🚀"
	IconWarning = "⚠️"
	IconError   = "❌"
	IconInfo    = "ℹ️"
	IconFolder  = "📁"
)

Emoji icons with ASCII fallbacks

Functions

func Bullet

func Bullet(format string, args ...interface{})

Bullet prints a bulleted list item

func CommandHeader

func CommandHeader(command, _ string)

CommandHeader prints a minimal command header. Shows just the command name with a short divider. Skipped when in orchestrated mode (subcommands don't print headers).

func Confirm

func Confirm(message string) bool

Confirm prompts the user for confirmation and returns true if they confirm. Returns true immediately if in JSON mode (non-interactive). The prompt displays the message and waits for y/n input.

func Count

func Count(n int) string

Count prints a count badge

func Divider

func Divider()

Divider prints a horizontal divider

func Emphasize

func Emphasize(format string, args ...interface{}) string

Emphasize prints emphasized text

func Error

func Error(format string, args ...interface{})

Error prints an error message with red X

func ForceColor added in v0.4.1

func ForceColor()

ForceColor enables color output regardless of terminal detection.

func Header(text string)

Header prints a bold header with a divider

func Highlight

func Highlight(format string, args ...interface{}) string

Highlight prints highlighted text

func Hint

func Hint(hints ...string)

Hint prints compact hints on a single line with bullet separators. Example: Hint("Press Ctrl+C to stop", "Use --web to open browser")

func Info

func Info(format string, args ...interface{})

Info prints an info message with blue info icon

func IsJSON

func IsJSON() bool

IsJSON returns true if the output format is JSON.

func IsOrchestrated

func IsOrchestrated() bool

IsOrchestrated returns true if running in orchestrated mode.

func Item

func Item(format string, args ...interface{})

Item prints an indented item

func ItemError

func ItemError(format string, args ...interface{})

ItemError prints an indented error item

func ItemInfo

func ItemInfo(format string, args ...interface{})

ItemInfo prints an indented info item

func ItemSuccess

func ItemSuccess(format string, args ...interface{})

ItemSuccess prints an indented success item

func ItemWarning

func ItemWarning(format string, args ...interface{})

ItemWarning prints an indented warning item

func Label

func Label(label, value string)

Label prints a label and value pair

func LabelColored

func LabelColored(label, value, color string)

LabelColored prints a label and colored value pair

func Muted

func Muted(format string, args ...interface{}) string

Muted prints muted/dim text

func Newline

func Newline()

Newline prints a blank line

func NoColor added in v0.4.1

func NoColor()

NoColor disables color output.

func Phase

func Phase(label string)

Phase prints a phase label like "Installing dependencies..." or "Starting services..."

func Plain

func Plain(format string, args ...interface{})

Plain prints plain text without any formatting.

func Print

func Print(data interface{}, formatter func()) error

Print outputs data in the configured format. For default format, uses the formatter function. For JSON format, marshals the data object.

func PrintDefault

func PrintDefault(formatter func())

PrintDefault prints data in default format using a custom formatter function.

func PrintJSON

func PrintJSON(data interface{}) error

PrintJSON prints data as JSON to stdout.

func ProgressBar

func ProgressBar(current, total int, width int) string

ProgressBar prints a simple progress bar

func Section

func Section(icon, text string)

Section prints a section header

func SetFormat

func SetFormat(format string) error

SetFormat sets the global output format.

func SetOrchestrated

func SetOrchestrated(value bool)

SetOrchestrated sets the orchestration mode flag. When true, subcommands skip their headers.

func Status

func Status(status string) string

Status prints a status badge with appropriate color

func Step

func Step(icon, format string, args ...interface{})

Step prints a step message with an icon

func Success

func Success(format string, args ...interface{})

Success prints a success message with green checkmark

func Table

func Table(headers []string, rows []TableRow)

Table prints a simple table with the given headers and rows.

func URL

func URL(url string) string

URL prints a URL in bright blue

func Warning

func Warning(format string, args ...interface{})

Warning prints a warning message with yellow triangle

Types

type Format

type Format string

Format represents the output format.

const (
	// FormatDefault is the default human-readable format.
	FormatDefault Format = "default"
	// FormatJSON is JSON format.
	FormatJSON Format = "json"
)

func GetFormat

func GetFormat() Format

GetFormat returns the current output format.

type TableRow

type TableRow map[string]string

TableRow represents a row in a table as a map of column header to value.

Jump to

Keyboard shortcuts

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