cli

package
v0.0.0-...-83c0f70 Latest Latest
Warning

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

Go to latest
Published: Jan 7, 2026 License: Apache-2.0 Imports: 5 Imported by: 0

README

CLI

Professional command-line output formatting for Go applications.

Features

  • Clean, professional startup banners
  • Automatic color detection (respects NO_COLOR)
  • Command adapter support for auto-extracting parameters
  • Fluent API for easy configuration
  • Customizable output writer for testing

Quick Start

import "github.com/chinayin/gox/cli"

func main() {
    cli.NewStartup("MyApp", "v1.0.0").
        AddSection(
            cli.NewSection("Configuration").
                Add("Port", 8080).
                Add("Workers", 4),
        ).
        AddEndpoint("Health", "http://localhost:8080/health").
        Print()
}

Output:

MyApp v1.0.0
--------------------------------------------------------------------------------

Configuration
  Port:                8080
  Workers:             4

Server Endpoints
  Health:              http://localhost:8080/health

--------------------------------------------------------------------------------
✓ Server started successfully
  Press Ctrl+C to shutdown gracefully

Cobra Adapter

Automatically extract application info and parameters:

import (
    "github.com/chinayin/gox/cli"
    clicobra "github.com/chinayin/gox/cli/cobra"
    "github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
    Use:     "myapp",
    Version: "1.0.0",
    RunE:    run,
}

func run(cmd *cobra.Command, args []string) error {
    adapter := clicobra.NewAdapter(cmd)
    
    // Automatically extracts name, version, and changed flags
    cli.NewStartupWithAdapter(adapter).
        AutoAddFlags("help", "version").
        AddSection(
            cli.NewSection("Configuration").
                Add("Port", port).
                Add("Debug", debug),
        ).
        Print()
    
    return nil
}

API Reference

Startup
func NewStartup(name, version string) *Startup
func NewStartupWithAdapter(adapter CommandAdapter) *Startup
func (s *Startup) WithWriter(w io.Writer) *Startup
func (s *Startup) WithAdapter(adapter CommandAdapter) *Startup
func (s *Startup) AutoAddFlags(excludeNames ...string) *Startup
func (s *Startup) AddSection(section *Section) *Startup
func (s *Startup) AddEndpoint(name, url string) *Startup
func (s *Startup) Print()
Section
func NewSection(title string) *Section
func (s *Section) Add(key string, value any) *Section
CommandAdapter
type CommandAdapter interface {
    GetName() string
    GetVersion() string
    GetFlags() map[string]FlagInfo
}

Documentation

For complete documentation and advanced usage, see doc.go or pkg.go.dev

中文文档请查看 README_zh.md

Documentation

Overview

Package cli provides professional command-line output formatting.

This package offers standardized startup banners, configuration summaries, and status messages for CLI applications, with automatic parameter extraction from command-line frameworks.

Basic Usage

Create a startup banner with configuration sections:

import "github.com/chinayin/gox/cli"

startup := cli.NewStartup("MyApp", "v1.0.0").
	AddSection(
		cli.NewSection("Configuration").
			Add("Port", 8080).
			Add("Workers", 4),
	).
	AddEndpoint("Health", "http://localhost:8080/health")

startup.Print()

Output:

MyApp v1.0.0
--------------------------------------------------------------------------------

Configuration
  Port:                8080
  Workers:             4

Server Endpoints
  Health:              http://localhost:8080/health

--------------------------------------------------------------------------------
✓ Server started successfully
  Press Ctrl+C to shutdown gracefully

Cobra Adapter

Automatically extract application info and parameters from Cobra commands:

import (
	"github.com/chinayin/gox/cli"
	clicobra "github.com/chinayin/gox/cli/cobra"
	"github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
	Use:     "myapp",
	Version: "1.0.0",
	RunE:    run,
}

func run(cmd *cobra.Command, args []string) error {
	adapter := clicobra.NewAdapter(cmd)

	// Automatically extracts name, version, and changed flags
	cli.NewStartupWithAdapter(adapter).
		AutoAddFlags("help", "version"). // Exclude these flags
		AddSection(...).
		Print()

	return nil
}

The Parameters section only shows flags that were changed from their default values.

Custom Adapters

Implement the CommandAdapter interface for other CLI frameworks:

type CommandAdapter interface {
	GetName() string
	GetVersion() string
	GetFlags() map[string]FlagInfo
}

Color Support

Color output is automatically detected and can be disabled:

  • Disabled when NO_COLOR environment variable is set
  • Disabled when TERM=dumb
  • Disabled when output is not a terminal

Testing

Redirect output to a buffer for testing:

var buf bytes.Buffer
startup := cli.NewStartup("TestApp", "v1.0.0").
	WithWriter(&buf)
startup.Print()
output := buf.String()
// Assert on output

Features

  • Fluent API for easy configuration
  • Automatic color detection (respects NO_COLOR)
  • Command adapter support for auto-extracting CLI parameters
  • Customizable output writer (useful for testing)
  • Clean, professional formatting
  • Minimal dependencies (only golang.org/x/term)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FormatFlagValue

func FormatFlagValue(info FlagInfo) string

FormatFlagValue formats flag value for display.

Types

type CommandAdapter

type CommandAdapter interface {
	// GetName 获取应用名称
	GetName() string

	// GetVersion 获取应用版本
	GetVersion() string

	// GetFlags 获取所有命令行参数信息
	// 返回 map[string]FlagInfo,key 为参数名
	GetFlags() map[string]FlagInfo
}

CommandAdapter 命令行框架适配器接口

该接口用于从不同的命令行框架(如 cobra、flag 等)中提取信息, 以便在启动横幅中自动显示命令参数和配置。

type Endpoint

type Endpoint struct {
	Name string
	URL  string
}

Endpoint represents a server endpoint.

type FlagInfo

type FlagInfo struct {
	Name         string // 参数名称
	Value        string // 当前值
	DefaultValue string // 默认值
	Usage        string // 参数说明
	Changed      bool   // 是否被用户修改(非默认值)
	Type         string // 参数类型:string/int/bool 等
}

FlagInfo 命令行参数信息

type Item

type Item struct {
	Key   string
	Value any
}

Item represents a single configuration item.

type Section

type Section struct {
	Title string
	Items []Item
}

Section represents a configuration section with key-value pairs.

func NewSection

func NewSection(title string) *Section

NewSection creates a new section with the given title.

func (*Section) Add

func (s *Section) Add(key string, value any) *Section

Add adds an item to the section.

type Startup

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

Startup provides a fluent interface for printing startup information.

func NewStartup

func NewStartup(name, version string) *Startup

NewStartup creates a new startup printer.

func NewStartupWithAdapter

func NewStartupWithAdapter(adapter CommandAdapter) *Startup

NewStartupWithAdapter creates a new startup printer from a command adapter. It automatically extracts the application name and version from the adapter.

func (*Startup) AddEndpoint

func (s *Startup) AddEndpoint(name, url string) *Startup

AddEndpoint adds a server endpoint.

func (*Startup) AddSection

func (s *Startup) AddSection(section *Section) *Startup

AddSection adds a configuration section.

func (*Startup) AutoAddFlags

func (s *Startup) AutoAddFlags(excludeNames ...string) *Startup

AutoAddFlags automatically adds command line flags section (requires adapter). excludeNames: flag names to exclude (e.g., "help", "version")

func (*Startup) Print

func (s *Startup) Print()

Print outputs all startup information.

func (*Startup) WithAdapter

func (s *Startup) WithAdapter(adapter CommandAdapter) *Startup

WithAdapter sets the command adapter (optional).

func (*Startup) WithWriter

func (s *Startup) WithWriter(w io.Writer) *Startup

WithWriter sets the output writer.

Directories

Path Synopsis
Package cobra provides a CommandAdapter implementation for spf13/cobra.
Package cobra provides a CommandAdapter implementation for spf13/cobra.

Jump to

Keyboard shortcuts

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