tap

package module
v1.7.2 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 9 Imported by: 4 modules, 5 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.

README

Tap - Terminal Argument Parsing

Go Reference

go get github.com/pt-main/tap/go

Tap is a lightweight library for building beautiful CLI applications in Go.
It features a simple command-based API, automatic --flag parsing, colored output, interactive keyboard dialogs, in-place terminal rewriting, and fully customisable help messages.

Features

  • Commands with required / optional arguments and unlimited trailing args
  • Flag parsing - --flag, --flag=value, --flag:value
  • Built‑in colour support - shortcodes like [?GN], [?RD], [?YW] - easy and readable
  • Background colours & colour stack - advanced ANSI control for rich layouts
  • Auto‑generated help - groups aliases, shows arguments, respects custom format
  • Fully configurable - change the look of help via ParserConfig, add your colors to color.Colors, disable colors with color.ColorEnabled = false
  • Hide commands from help using DONT_SHOW docstring
  • Subcommands (inner parsers)
  • Verbose / debug flags - built‑in --verbose and --debug with conditional printing
  • Interactive dialogs - selection menus (using input/selecting)
  • In-place terminal rewriting - update previous output without scrolling

Quick start

Create a simple CLI with a hello command:

package main

import (
	"fmt"

	tap "github.com/pt-main/tap/go"
	"github.com/pt-main/tap/go/color"
)

func helloHandler(p *tap.Parser, args []string) error {
	color.PrintlnColored("[?GN]Hello[?RT], world! Args: %v", args)
	return nil
}

func main() {
	cfg := tap.DefaultParserConfig()
	p := tap.NewParser("demo", "Demo CLI v1.0", nil, cfg)
	p.AddCommand("hello", helloHandler, "Prints a friendly greeting", nil, nil, true)

	if err := p.Main(); err != nil {
		fmt.Println("Error:", err)
	}
}

Run it: demo-run

Commands and arguments

Add a command using AddCommand:

p.AddCommand(
    name               string,
    handler            HandlerFuncType, // func(*Parser, []string) error
    docstring          string,
    requiredArgs       []string,
    optionalArgs       []string,
    unlimitedMaxArgs   bool,
)
  • requiredArgs - shown as <arg> in help. The command fails if they are missing.
  • optionalArgs - shown as [arg] in help.
  • unlimitedMaxArgs - if true, the command accepts any number of trailing arguments. shown as ... in help.

You can create aliases for existing commands using AddAlias:

p.AddCommand("help", helpHandler, tap.HELP_DOCS, nil, nil, false)
p.AddAlias("h", "help")  // now "h" works exactly like "help"

The alias inherits all properties (handler, arguments, docstring) from the original command.

Example
p.AddCommand("copy",
    copyHandler,
    "Copy source to destination",
    []string{"src", "dst"},  // required
    []string{"force"},       // optional
    true,                    // unlimited
)

Help output would show:

copy <src>, <dst>, [force]...

Use tap.DONT_SHOW as the docstring:

p.AddCommand("internal", internalHandler, tap.DONT_SHOW, nil, nil, false)

This command will work but will never appear in the help output.

Use tap.DEFAULT_CMD as name to create handler working when args[0] is not command (for usage like cli_name [args...], not cli_name command_name [args...]). Documentation of 'default' command shows after about.

Sub commands

You can create sub-commands:

p.AddSubcommand(name, tap.NewParser(...))

In call subcomand parser calls subcommand.Parse(args).

Help show only name and about of subcommand.

Flags

Flags are written as --flag or --key=value (also --key:value).
They are parsed automatically and stored in p.Flags (a map[string]string). A flag without a value gets an empty string.

Built‑in flags:

  • --verbose - enables verbose output (messages printed with p.Print("verbose", ...))
  • --debug - enables debug output (similar)

Your handlers can read flags directly:

func myHandler(p *tap.Parser, args []string) error {
    if val, ok := p.Flags["output"]; ok {
        fmt.Println("Output file:", val)
    }
    return nil
}

Use p.Print(flag, format, ...) to output messages only when a specific flag (e.g., --verbose or --debug) is present:

func myHandler(p *tap.Parser, args []string) error {
    p.Print("verbose", "Starting with args: %v", args)
    p.Print("debug", "Debug info...")
    // ...
}

The output is automatically prefixed with the flag name and coloured.

After -- all flags will be positional arguments.

Colors

color-demo

You can just write [?COLOR] with uppercased color name from list to set color. Like [?RED] for red.

All colors: Bold, Underline, Reset, Black, Red, Green, Yellow, Blue, Magenta, Cyan.

Also you can set color using first and last letters of color. Like [?RD] for red.

Bright variants: [?BRED], [?BRD], ...

Use them with color.PrintlnColored or color.PrintColored:

color.PrintlnColored("[?GN]Success[?RT] - file saved as [?YW]%s[?RT]", filename)

To disable colours globally:

color.ColorEnabled = false

You can set color to string with color.Set:

text := color.Set("[?RD]Test")

(Reset will be auto pasted in the end of text)

Background colours

Background colours use the BACK prefix or BK shortcode:

color.PrintlnColored("[?BKRD] ERROR: [?RT] error text...")

Available all colors for text except bold and underlinne.

Interactive dialogs

Tap includes a small utility for interactive user prompts. It supports arrow-key navigation and validated text input.

import "github.com/pt-main/tap/go/utils"

// Arrow-key selection
dialogue := utils.NewDialogue(utils.ArrowsDialogueType, "[?CN]Select action:[?RT]")
choice, err := dialogue.Run([]string{"install", "update", "remove"})
// Navigate with up/down, press enter to confirm, esc to cancel.

For simple typed input with validation against allowed variants:

inputDlg := utils.NewDialogue(utils.InputDialogueType, "Enter mode (fast/slow): ")
mode, err := inputDlg.Run([]string{"fast", "slow"})

Rewriting terminal output

For in-place updates (progress bars, live menus, spinners) use Rewriter:

rw := utils.NewRewriter()
rw.Write("[?YW]Loading... 0%[?RT]")
// ... later ...
rw.Write("[?GN]Loading... 100%[?RT]")  // replaces the previous line without scrolling

Customising parser

Create a ParserConfig and pass it to NewParser.
All help fields support format strings - use %s for the command name or argument list.

cfg := tap.NewParserConfig(
    "[?CN]>>> Command [?RT]%s[?CN] <<<[?RT]",   // command block header format
    "[?CN]>>> Subcommand [?RT]%s[?CN] <<<[?RT]" // subcommand block header format
    "[?CN]Args:[?RT]",                          // args block header format
    "    %s",                                   // args block line format
    "[?CN]Description:[?RT]",                   // description block header format
    "    %s",                                   // description args line format
    "[?CN]---[?RT]",                            // help end line
    true,                                       // builtin --verbose and --debug flags enable
    true,                                       // builtin --no_color flag enable
)
p := tap.NewParser("mycli", "My tool", nil, cfg)

If you pass an empty string for any help format field, the default (coloured, nice looking) will be used.

Use tap.DefaultConfig to get default config with default help format, enabled no_color and disables verbose and debug flags.

Grouping commands / aliases

If multiple commands share the same docstring, they are displayed together in help:

helpDocs := "Show help"
p.AddCommand("help", helpHandler, helpDocd, nil, nil, false)
p.AddCommand("h", helpHandler, helpDocd, nil, nil, false) // Equals to p.AddAlias("h", help)

Help shows: [help / h]

Full example

A minimal but complete CLI with multiple commands:

package main

import (
    "fmt"
    "os"
    tap "github.com/pt-main/tap/go"
    "github.com/pt-main/tap/go/color"
)

func main() {
    cfg := tap.DefaultParserConfig()
    p := tap.NewParser("myapp", "My application v0.1", nil, cfg)

    p.AddCommand("greet", func(p *tap.Parser, args []string) error {
        name := "world"
        if len(args) > 0 {
            name = args[0]
        }
        color.PrintlnColored("[?GN]Hello, %s![?RT]", name)
        return nil
    }, "Say hello", []string{}, []string{"name"}, false)

    p.AddCommand("print", func(p *tap.Parser, args []string) error {
        color.PrintlnColored("[?YW]%s[?RT]", args[0])
        return nil
    }, "Print first argument", []string{"text"}, nil, false)

    if err := p.Main(); err != nil {
        fmt.Fprintln(os.Stderr, "Fatal:", err)
        os.Exit(1)
    }
}

License

MIT - see LICENSE file.

Documentation

Overview

Package tap provides a lightweight command-line argument parser with support for commands, flags, colored output, and customizable help messages.

Index

Constants

View Source
const DEFAULT_CMD = "#[DEFAULT CMD]#"

DEFAULT_CMD is a reserved command name. It is used when no command is specified as the first argument, allowing your CLI to be invoked in two ways: cli args... (implicit default) or cli cmd args... (explicit command). Note: documentation of default command is displayed after about message.

View Source
const DONT_SHOW = "#[DON'T SHOW]#"

DONT_SHOW is a special docstring value that hides the command from the help output. The command remains functional but will not appear in the auto-generated help.

View Source
const Version = "1.7.2"

Variables

View Source
var HELP_DOCS = "Generate and print help message"

HELP_DOCS is the docstring used by the built‑in help command. Commands sharing this docstring will be grouped together as aliases.

Functions

This section is empty.

Types

type HandlerFuncType

type HandlerFuncType func(*Parser, []string) error

HandlerFuncType defines the signature for command handler functions. It receives the parser instance and the slice of command arguments. Returns an error if the command execution fails.

type Parser

type Parser struct {
	Flags   map[string]string
	Super   *Parser
	Scope   core.ScopeType
	RawArgs []string

	TermWidth int
	// contains filtered or unexported fields
}

Tap - Terminal Argument Parsing

This parser is the main object in tap.

Main methods:

- AddCommand(name string, handler HandlerFuncType)

- Main() - start parser

func NewParser

func NewParser(cli_name string, about string, help_commands []string, config ParserConfig) *Parser

NewParser creates a new Parser instance. Parameters:

  • cli_name: name of the CLI application (used in help).
  • about: informational text printed when no command is given.
  • help_commands: slice of command names that trigger the help handler. If nil, defaults to []string{"help", "h"}.
  • config: ParserConfig controlling help message formatting.

Returns a pointer to the initialized Parser.

func (*Parser) AddAlias

func (p *Parser) AddAlias(aliasName, cmdName string) error

Add alias for command.

func (*Parser) AddCommand

func (p *Parser) AddCommand(
	name string,
	handler HandlerFuncType,
	docs string,
	required_args []string,
	optional_args []string,
	unlimited_max_args bool,
)

AddCommand registers a new command with the parser. Parameters:

  • name: command name (string used in CLI).
  • handler: function called when the command is invoked.
  • docs: description shown in help; use DONT_SHOW to hide the command.
  • required_args: slice of required argument names.
  • optional_args: slice of optional argument names.
  • unlimited_max_args: if true, command accepts any number of trailing arguments.

func (*Parser) AddSubcommand

func (p *Parser) AddSubcommand(name string, parser *Parser)

AddSubCommand registers a nested sub-parser for a given subcommand name.

This method stores the provided Parser instance under the specified name, automatically integrate it into the main command dispatch flow.

Parameters:

  • name: the subcommand name.
  • parser: the Parser instance that will handle the subcommand.

func (*Parser) GetSubcommand

func (p *Parser) GetSubcommand(name string) (pr *Parser)

SubCommand retrieves a previously registered sub-parser by name.

It returns the Parser pointer if the name exists; otherwise, it panic.

func (*Parser) Main

func (p *Parser) Main() error

Main is the primary entry point of the parser. It parses os.Args[1:], extracts flags, finds the command, and executes the corresponding handler. Returns an error if no command is provided, the command is unknown, or the handler fails.

func (*Parser) Parse

func (p *Parser) Parse(cmdArgs []string) (err error)

Parse args.

func (*Parser) Print

func (p *Parser) Print(flag string, format string, args ...any)

Print outputs a formatted message only if the given flag (e.g., "debug", "verbose") is enabled. The message can contain color shortcodes. Each newline is prefixed with the flag’s name for alignment.

func (*Parser) Subcommand

func (p *Parser) Subcommand(name string) (err error, pr *Parser)

SubCommand retrieves a previously registered sub-parser by name.

It returns the Parser pointer and a nil error if the name exists; otherwise, it returns an error describing the invalid name.

type ParserConfig

type ParserConfig struct {
	BuiltinVerboseDebug bool
	BuiltinNoColor      bool
	// contains filtered or unexported fields
}

ParserConfig defines the formatting templates for the auto-generated help message. Each field is a format string that may contain "%s" placeholders for dynamic content. If an empty string is passed to NewParserConfig, the corresponding default format will be used.

func DefaultParserConfig

func DefaultParserConfig() ParserConfig

Create default parser config.

func NewParserConfig

func NewParserConfig(
	help_command_block_fmt string,
	help_subcommand_block_fmt string,
	help_args_header_block_fmt string,
	help_args_data_block_fmt string,
	help_args_data_block_padding int,
	help_docs_header_block_fmt string,
	help_docs_data_block_fmt string,
	help_end_block_fmt string,
	BuiltinVerboseDebug bool,
	BuiltinNoColor bool,
) ParserConfig

NewParserConfig creates a new ParserConfig with the given format strings. Any empty string parameter will be replaced with a sensible default. Parameters:

  • help_command_block_fmt: format for the command name block (e.g., "╭─────── Command [%s]").
  • help_subcommand_block_fmt: format for the subcommand name block (e.g., "╭─────── Subcommand [%s]").
  • help_args_header_block_fmt: format for the arguments section header.
  • help_args_data_block_fmt: format for each argument line.
  • help_docs_header_block_fmt: format for the description section header.
  • help_docs_data_block_fmt: format for each line of the description.
  • help_end_block_fmt: format for the closing block.

Returns a populated ParserConfig.

Directories

Path Synopsis
Package color provides ANSI color formatting for terminal output.
Package color provides ANSI color formatting for terminal output.

Jump to

Keyboard shortcuts

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