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)
- Automatic color and prompt suppression when the terminal cannot support it
Relationship to azdext ¶
JSON and table rendering delegate to azdext.Output, so azd-core and the azd host agree on encoding and on what JSON mode means. Color and prompt gating come from azdext.DetectInteractive.
Color is enabled only when azdext reports the terminal can colorize, which honors FORCE_COLOR=1 first, then any non-empty NO_COLOR, then whether stdout is a terminal. ForceColor and NoColor override that detection. Suppression is applied where the package writes, not where it composes, so the string returning helpers (Highlight, Emphasize, Muted, URL, Count, Status) always return ANSI codes and callers stay free to route the result anywhere.
Confirm declines instead of prompting whenever azdext reports that prompting is impossible: a redirected stdin or stdout, AZD_NO_PROMPT, a CI runner, or an AI agent host. In JSON mode it continues to assume yes. Use an explicit skip-confirmation flag for unattended runs rather than relying on either.
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]any{"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
- Variables
- func Bullet(format string, args ...any)
- func CommandHeader(command, _ string)
- func Confirm(message string) bool
- func Count(n int) string
- func Divider()
- func Emphasize(format string, args ...any) string
- func Error(format string, args ...any)
- func ForceColor()
- func Header(text string)
- func Highlight(format string, args ...any) string
- func Hint(hints ...string)
- func Info(format string, args ...any)
- func IsJSON() bool
- func IsOrchestrated() bool
- func Item(format string, args ...any)
- func ItemError(format string, args ...any)
- func ItemInfo(format string, args ...any)
- func ItemSuccess(format string, args ...any)
- func ItemWarning(format string, args ...any)
- func Label(label, value string)
- func LabelColored(label, value, color string)
- func Muted(format string, args ...any) string
- func Newline()
- func NoColor()
- func Phase(label string)
- func Plain(format string, args ...any)
- func Print(data any, formatter func()) error
- func PrintDefault(formatter func())
- func PrintJSON(data any) error
- func ProgressBar(current, total int, width int) string
- func Section(icon, text string)
- func SetFormat(format string) error
- func SetOrchestrated(value bool)
- func Status(status string) string
- func Step(icon, format string, args ...any)
- func Success(format string, args ...any)
- func Table(headers []string, rows []TableRow)
- func URL(url string) string
- func Warning(format string, args ...any)
- type Format
- type TableRow
Constants ¶
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
const ( SymbolCheck = "✓" SymbolCross = "✗" SymbolWarning = "⚠" SymbolInfo = "ℹ" SymbolArrow = "→" SymbolDot = "•" SymbolSpinner = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏" // Spinner frames )
Unicode symbols for modern CLI output
const ( ASCIICheck = "[+]" ASCIICross = "[-]" ASCIIWarning = "[!]" ASCIIInfo = "[i]" ASCIIArrow = "->" ASCIIDot = "*" )
ASCII fallback symbols for terminals that don't support Unicode
Variables ¶
var ( IconSearch = "🔍" IconTool = "🔧" IconRefresh = "🔄" IconPackage = "📦" IconPython = "🐍" IconDotnet = "🔷" IconDocker = "🐳" IconCheck = "📋" IconBulb = "💡" IconRocket = "🚀" IconWarning = "⚠️" IconError = "❌" IconInfo = "ℹ️" IconFolder = "📁" )
Emoji icons with ASCII fallbacks
Functions ¶
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 ¶
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 ForceColor ¶ added in v0.4.1
func ForceColor()
ForceColor enables color output regardless of terminal detection.
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 IsOrchestrated ¶
func IsOrchestrated() bool
IsOrchestrated returns true if running in orchestrated mode.
func ItemSuccess ¶
ItemSuccess prints an indented success item
func ItemWarning ¶
ItemWarning prints an indented warning item
func LabelColored ¶
func LabelColored(label, value, color string)
LabelColored prints a label and colored value pair
func Phase ¶
func Phase(label string)
Phase prints a phase label like "Installing dependencies..." or "Starting services..."
func Print ¶
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 ProgressBar ¶
ProgressBar prints a simple progress bar
func SetOrchestrated ¶
func SetOrchestrated(value bool)
SetOrchestrated sets the orchestration mode flag. When true, subcommands skip their headers.