comptplus

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: May 1, 2026 License: MIT Imports: 10 Imported by: 0

README

Русская версия

This is a fork of comptplus. The original package is based on go-prompt, which—like the original go-prompt—does not support custom interrupt handling. This fork solves that issue by using go-prompt-ctrl-c internally, which introduces a new constructor option WithInterruptCallback. This option allows you to pass a function that will be invoked when interrupt signals are received.

Supported Signals

  • SIGINT
  • SIGTERM
  • SIGQUIT

Usage Example

package main

import (
	"fmt"

	cobraprompt "github.com/1ight181/comptplus-ctrl-c"
	prompt "github.com/1ight181/go-prompt-ctrl-c"
	"github.com/spf13/cobra"
)

func main() {
	rootCmd := &cobra.Command{
		SilenceUsage:  true,
		SilenceErrors: true,
		Short:         "root cmd example",
	}

	cobraPrompt := cobraprompt.CobraPrompt{
		RootCmd:                 rootCmd,
		ShowHelpCommandAndFlags: true,
		GoPromptOptions: []prompt.Option{
			prompt.WithTitle("example 0.1"),
			prompt.WithMaxSuggestion(5),
			prompt.WithPrefix("example> "),
			prompt.WithInterruptCallback(interruptCallback),
		},
	}

	cobraPrompt.Run()
}

// Custom Ctrl+C handling
func interruptCallback(code int) {
	fmt.Println("\nCtrl+C pressed, but we handle it ourselves")
	// os.Exit(code) // Default behavior
}

Community

Email: danil.odinzov181@gmail.com

Documentation

Index

Constants

View Source
const CacheIntervalFlag = "cache-interval"
View Source
const DynamicSuggestionsAnnotation = "cobra-prompt-dynamic-suggestions"

DynamicSuggestionsAnnotation for dynamic suggestions.

Variables

This section is empty.

Functions

This section is empty.

Types

type CobraLexer

type CobraLexer struct {

	// Colors are configurable. Zero values fall back to defaults.
	CommandColor Color
	FlagColor    Color
	ValueColor   Color
	ErrorColor   Color
	// contains filtered or unexported fields
}

CobraLexer provides syntax highlighting for cobra command input. It colorizes commands, flags, flag values, and unknown tokens by walking the cobra command tree on each keystroke.

func NewCobraLexer

func NewCobraLexer(root *cobra.Command) *CobraLexer

NewCobraLexer creates a lexer that highlights input based on the given cobra command tree.

func (*CobraLexer) Init

func (l *CobraLexer) Init(input string)

func (*CobraLexer) Next

func (l *CobraLexer) Next() (prompt.Token, bool)

type CobraPrompt

type CobraPrompt struct {
	// RootCmd is the start point, all its sub commands and flags will be available as suggestions
	RootCmd *cobra.Command

	// GoPromptOptions is for customize go-prompt
	// see https://github.com/1ight181/go-prompt-ctrl-c
	GoPromptOptions []prompt.Option

	// DynamicSuggestionsFunc will be executed if a command has CallbackAnnotation as an annotation. If it's included
	// the value will be provided to the DynamicSuggestionsFunc function.
	// The *cobra.Command parameter is the resolved command, allowing use of ValidArgsFunction for completions.
	DynamicSuggestionsFunc func(cmd *cobra.Command, annotationValue string, document *prompt.Document) []prompt.Suggest

	// PersistFlagValues will persist flags. For example have verbose turned on every command.
	PersistFlagValues bool

	// CustomFlagResetBehaviour allows you to specify custom behaviour which will be run after each command, if PersistFlagValues is false
	CustomFlagResetBehaviour func(flag *pflag.Flag)

	// ShowHelpCommandAndFlags will make help command and flag for every command available.
	ShowHelpCommandAndFlags bool

	// DisableCompletionCommand will disable the default completion command for cobra
	DisableCompletionCommand bool

	// ShowHiddenCommands makes hidden commands available
	ShowHiddenCommands bool

	// ShowHiddenFlags makes hidden flags available
	ShowHiddenFlags bool

	// AddDefaultExitCommand adds a command for exiting prompt loop
	AddDefaultExitCommand bool

	// OnErrorFunc handle error for command.Execute, if not set print error and exit
	OnErrorFunc func(err error)

	// HookAfter is a hook that will be executed every time after a command has been executed
	HookAfter func(cmd *cobra.Command, input string) error

	// HookBefore is a hook that will be executed every time before a command is executed
	HookBefore func(cmd *cobra.Command, input string) error

	// InArgsParser adds a custom parser for the command line arguments (default: shellquote.Split)
	InArgsParser func(args string) []string

	// SuggestionFilter will be uses when filtering suggestions as typing
	SuggestionFilter func(suggestions []prompt.Suggest, document *prompt.Document) []prompt.Suggest

	// AsyncFlagValueSuggestions enables non-blocking flag value completions.
	// When enabled, flag value suggestions are fetched in a background goroutine
	// instead of blocking the prompt. The first completion for a flag may return
	// empty results; subsequent keystrokes will return the fetched data.
	AsyncFlagValueSuggestions bool

	// FuzzyFilter uses fuzzy matching for suggestion filtering instead of prefix matching.
	// When enabled, typing "dpl" can match "deploy", "srvlst" can match "server-list", etc.
	FuzzyFilter bool

	// PrefixCallback returns the prompt prefix dynamically on each render.
	// Useful for showing context like current resource or output format.
	// Overrides any static prefix set via GoPromptOptions WithPrefix.
	PrefixCallback func() string

	// CompletionOnDown allows the Down arrow key to open the completion dropdown.
	CompletionOnDown bool

	// BreakLineCallback is called after every line break (Enter press) with the
	// current document state. Useful for logging, analytics, or cache pre-warming.
	BreakLineCallback func(doc *prompt.Document)

	// KeyBindings adds custom key bindings to the prompt.
	// Each KeyBind maps a key to a handler function.
	KeyBindings []prompt.KeyBind
	// contains filtered or unexported fields
}

CobraPrompt given a Cobra command it will make every flag and sub commands available as suggestions. Command.Short will be used as description for the suggestion.

func (*CobraPrompt) Run

func (co *CobraPrompt) Run()

Run will automatically generate suggestions for all cobra commands and flags defined by RootCmd and execute the selected commands. Run will also reset all given flags by default, see PersistFlagValues

func (*CobraPrompt) RunContext

func (co *CobraPrompt) RunContext(ctx context.Context)

type Color

type Color = prompt.Color

Color wraps prompt.Color so consumers don't need to import go-prompt directly.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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