promptui

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: May 22, 2018 License: BSD-3-Clause Imports: 12 Imported by: 0

README

promptui

Interactive prompt for command-line applications.

We built Promptui because we wanted to make it easy and fun to explore cloud services with manifold cli.

Code of Conduct | Contribution Guidelines

GitHub release GoDoc Travis Go Report Card License

Overview

promptui

Promptui is a library providing a simple interface to create command-line prompts for go. It can be easily integrated into spf13/cobra, urfave/cli or any cli go application.

Promptui has two main input modes:

  • Prompt provides a single line for user input. Prompt supports optional live validation, confirmation and masking the input.

  • Select provides a list of options to choose from. Select supports pagination, search, detailed view and custom templates.

For a full list of options check GoDoc.

Basic Usage

Prompt
package main

import (
	"errors"
	"fmt"
	"strconv"

	"github.com/manifoldco/promptui"
)

func main() {
	validate := func(input string) error {
		_, err := strconv.ParseFloat(input, 64)
		if err != nil {
			return errors.New("Invalid number")
		}
		return nil
	}

	prompt := promptui.Prompt{
		Label:    "Number",
		Validate: validate,
	}

	result, err := prompt.Run()

	if err != nil {
		fmt.Printf("Prompt failed %v\n", err)
		return
	}

	fmt.Printf("You choose %q\n", result)
}
Select
package main

import (
	"fmt"

	"github.com/manifoldco/promptui"
)

func main() {
	prompt := promptui.Select{
		Label: "Select Day",
		Items: []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
			"Saturday", "Sunday"},
	}

	_, result, err := prompt.Run()

	if err != nil {
		fmt.Printf("Prompt failed %v\n", err)
		return
	}

	fmt.Printf("You choose %q\n", result)
}
More Examples

See full list of examples

Documentation

Overview

Package promptui provides ui elements for the command line prompt.

Index

Constants

View Source
const (
	FGBold attribute
	FGFaint
	FGItalic
	FGUnderline
)

Foreground weight/decoration attributes.

View Source
const (
	FGBlack attribute = iota + 30
	FGRed
	FGGreen
	FGYellow
	FGBlue
	FGMagenta
	FGCyan
	FGWhite
)

Foreground color attributes

View Source
const (
	BGBlack attribute = iota + 40
	BGRed
	BGGreen
	BGYellow
	BGBlue
	BGMagenta
	BGCyan
	BGWhite
)

Background color attributes

View Source
const SelectedAdd = -1

SelectedAdd is returned from SelectWithAdd when add is selected.

Variables

View Source
var (
	// KeyEnter is the default key for submission/selection
	KeyEnter rune = readline.CharEnter

	// KeyBackspace is the default key for deleting input text
	KeyBackspace rune = readline.CharBackspace

	// KeyPrev is the default key to go up during selection
	KeyPrev rune = readline.CharPrev

	// KeyNext is the default key to go down during selection
	KeyNext rune = readline.CharNext

	// KeyBackward is the default key to page up during selection
	KeyBackward rune = readline.CharBackward

	// KeyForward is the default key to page down during selection
	KeyForward rune = readline.CharForward
)
View Source
var (
	IconInitial = Styler(FGBlue)("?")
	IconGood    = Styler(FGGreen)("✔")
	IconWarn    = Styler(FGYellow)("⚠")
	IconBad     = Styler(FGRed)("✗")
	IconSelect  = Styler(FGBold)("▸")
)

Icons used for displaying prompts or status

View Source
var ErrAbort = errors.New("")

ErrAbort is returned when confirm prompts are supplied "n"

View Source
var ErrEOF = errors.New("^D")

ErrEOF is returned from prompts when EOF is encountered.

View Source
var ErrInterrupt = errors.New("^C")

ErrInterrupt is returned from prompts when an interrupt (ctrl-c) is encountered.

View Source
var FuncMap = template.FuncMap{
	"black":     Styler(FGBlack),
	"red":       Styler(FGRed),
	"green":     Styler(FGGreen),
	"yellow":    Styler(FGYellow),
	"blue":      Styler(FGBlue),
	"magenta":   Styler(FGMagenta),
	"cyan":      Styler(FGCyan),
	"white":     Styler(FGWhite),
	"bgBlack":   Styler(BGBlack),
	"bgRed":     Styler(BGRed),
	"bgGreen":   Styler(BGGreen),
	"bgYellow":  Styler(BGYellow),
	"bgBlue":    Styler(BGBlue),
	"bgMagenta": Styler(BGMagenta),
	"bgCyan":    Styler(BGCyan),
	"bgWhite":   Styler(BGWhite),
	"bold":      Styler(FGBold),
	"faint":     Styler(FGFaint),
	"italic":    Styler(FGItalic),
	"underline": Styler(FGUnderline),
}

FuncMap defines template helpers for the output. It can be extended as a regular map.

View Source
var ResetCode = fmt.Sprintf("%s%dm", esc, reset)

ResetCode is the character code used to reset the terminal formatting

Functions

func Styler

func Styler(attrs ...attribute) func(interface{}) string

Styler returns a func that applies the attributes given in the Styler call to the provided string.

Types

type Key added in v0.2.0

type Key struct {
	Code    rune
	Display string
}

Key defines a keyboard code and a display representation for the help Check https://github.com/chzyer/readline for a list of codes

type Prompt

type Prompt struct {
	// Label is the value displayed on the command line prompt. It can be any
	// value one would pass to a text/template Execute(), including just a string.
	Label interface{}

	Default string // Default is the initial value to populate in the prompt

	// AllowEdit lets the user edit the default value. If false, any key press
	// other than <Enter> automatically clears the default value.
	AllowEdit bool

	// Validate is optional. If set, this function is used to validate the input
	// after each character entry.
	Validate ValidateFunc

	// If mask is set, this value is displayed instead of the actual input
	// characters.
	Mask rune

	// Templates can be used to customize the prompt output. If nil is passed, the
	// default templates are used.
	Templates *PromptTemplates

	// IsConfirm sets the prompt to be a [y/N] question.
	IsConfirm bool

	// IsVimMode enables vi-like movements (hjkl) and editing.
	IsVimMode bool
	// contains filtered or unexported fields
}

Prompt represents a single line text field input.

func (*Prompt) Run

func (p *Prompt) Run() (string, error)

Run runs the prompt, returning the validated input.

type PromptTemplates

type PromptTemplates struct {
	// Prompt is a text/template for the initial prompt question.
	Prompt string

	// Prompt is a text/template if the prompt is a confirmation.
	Confirm string

	// Valid is a text/template for when the current input is valid.
	Valid string

	// Invalid is a text/template for when the current input is invalid.
	Invalid string

	// Success is a text/template for the successful result.
	Success string

	// Prompt is a text/template when there is a validation error.
	ValidationError string

	// FuncMap is a map of helpers for the templates. If nil, the default helpers
	// are used.
	FuncMap template.FuncMap
	// contains filtered or unexported fields
}

PromptTemplates allow a prompt to be customized following stdlib text/template syntax. If any field is blank a default template is used.

type Select

type Select struct {
	// Label is the value displayed on the command line prompt. It can be any
	// value one would pass to a text/template Execute(), including just a string.
	Label interface{}

	// Items are the items to use in the list. It can be any slice type one would
	// pass to a text/template execute, including a string slice.
	Items interface{}

	// Size is the number of items that should appear on the select before
	// scrolling. If it is 0, defaults to 5.
	Size int

	// IsVimMode sets whether readline is using Vim mode.
	IsVimMode bool

	// Templates can be used to customize the select output. If nil is passed, the
	// default templates are used.
	Templates *SelectTemplates

	// Keys can be used to change movement and search keys.
	Keys *SelectKeys

	// Searcher can be implemented to teach the select how to search for items.
	Searcher list.Searcher

	// Starts the prompt in search mode.
	StartInSearchMode bool
	// contains filtered or unexported fields
}

Select represents a list for selecting a single item

func (*Select) Run

func (s *Select) Run() (int, string, error)

Run runs the Select list. It returns the index of the selected element, and its value.

type SelectKeys added in v0.2.0

type SelectKeys struct {
	Next     Key // Next defaults to down arrow key
	Prev     Key // Prev defaults to up arrow key
	PageUp   Key // PageUp defaults to left arrow key
	PageDown Key // PageDown defaults to right arrow key
	Search   Key // Search defaults to '/' key
}

SelectKeys defines which keys can be used for movement and search.

type SelectTemplates

type SelectTemplates struct {
	// Active is a text/template for the label.
	Label string

	// Active is a text/template for when an item is current active.
	Active string

	// Inactive is a text/template for when an item is not current active.
	Inactive string

	// Selected is a text/template for when an item was successfully selected.
	Selected string

	// Details is a text/template for when an item current active to show
	// additional information. It can have multiple lines.
	Details string

	// Help is a text/template for displaying instructions at the top. By default
	// it shows keys for movement and search.
	Help string

	// FuncMap is a map of helpers for the templates. If nil, the default helpers
	// are used.
	FuncMap template.FuncMap
	// contains filtered or unexported fields
}

SelectTemplates allow a select prompt to be customized following stdlib text/template syntax. If any field is blank a default template is used.

type SelectWithAdd

type SelectWithAdd struct {
	Label string   // Label is the value displayed on the command line prompt.
	Items []string // Items are the items to use in the list.

	AddLabel string // The label used in the item list for creating a new item.

	// Validate is optional. If set, this function is used to validate the input
	// after each character entry.
	Validate ValidateFunc

	IsVimMode bool // Whether readline is using Vim mode.
}

SelectWithAdd represents a list for selecting a single item, or selecting a newly created item.

func (*SelectWithAdd) Run

func (sa *SelectWithAdd) Run() (int, string, error)

Run runs the Select list. It returns the index of the selected element, and its value. If a new element is created, -1 is returned as the index.

type ValidateFunc

type ValidateFunc func(string) error

ValidateFunc validates the given input. It should return a ValidationError if the input is not valid.

Directories

Path Synopsis
_examples

Jump to

Keyboard shortcuts

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