promptui

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 4, 2022 License: MIT Imports: 11 Imported by: 0

README

PromptUI

GoDoc Go Report Card

A library for building interactive prompts.

demo

See examples/main.go.

package main

import (
	"fmt"
	"os"
	"strings"
	"unicode"

	bb "github.com/karantin2020/promptui"
)

func main() {
	p := bb.Prompt{
		BasicPrompt: bb.BasicPrompt{
			Label: "test masked",
			Validate: func(s string) error {
				if s == "err" {
					return bb.NewValidationError("input must not be equal to 'err'")
				}
				if s == "" {
					return bb.NewValidationError("input must not be empty string")
				}
				return nil
			},
			Default: "hi there",
		},
		Mask: '*',
		// IsVimMode: false,
	}
	checkError(p.Run())
	checkError(bb.Ask("easy prompt", "Yepp"))
	checkError(bb.AskMasked("easy masked prompt", "Yepp"))
	c := bb.ConfirmPrompt{
		BasicPrompt: bb.BasicPrompt{
			Label:   "test confirm",
			Default: "y",
		},
		ConfirmOpt: "?",
	}
	checkError(c.Run())
	checkError(bb.Confirm("easy confirm", "Y", false))

	ml := bb.MultilinePrompt{
		BasicPrompt: bb.BasicPrompt{
			Label:   "test multiline",
			Default: "Request",
			Formatter: func(s string) string {
				var upl = func(sl string) string {
					rs := []rune(sl)
					if len(rs) > 0 {
						rs[0] = unicode.ToUpper(rs[0])
					}
					return string(rs)
				}
				out := []string{}
				ins := strings.Split(s, "\n")
				for i := range ins {
					out = append(out, upl(ins[i]))
				}
				return strings.Join(out, "\n")
			},
			Validate: func(s string) error {
				if s == "Err" {
					return bb.NewValidationError("input must not be equal to 'err'")
				}
				if s == "" {
					return bb.NewValidationError("input must not be empty string")
				}
				return nil
			},
		},
	}
	checkError(ml.Run())
	checkError(bb.MultiLine("easy multi", "Ready to go"))

	s := bb.Select{
		Label:   "test select",
		Items:   []string{"one", "two", "three", "1one", "1two", "1three", "2one", "2two", "2three"},
		Default: 3,
	}
	_, res, err := s.Run()
	checkError(res, err)
	checkError(bb.PromptAfterSelect("prompt after select", []string{"feat", "fix", "doc", "other"}))
}

Documentation

Overview

Package promptui provides ui elements for the command line prompt.

Index

Constants

View Source
const (
	FGBold attribute
	FGFaint
	FGItalic
	FGUnderline
)

Forground weight/decoration attributes.

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

Forground color attributes

View Source
const SelectedAdd = -1

SelectedAdd is returned from SelectWithAdd when add is selected.

Variables

View Source
var (
	// ErrorOpen describes open editor error
	ErrorOpen = errors.New("in promptui:Editor: Error open temp file")
	// ErrorWrite describes write editor error
	ErrorWrite = errors.New("in promptui:Editor: Error write temp file")
	// ErrorRead describes read editor error
	ErrorRead = errors.New("in promptui:Editor: Error read temp file")
	// ErrorClose describes close editor error
	ErrorClose = errors.New("in promptui:Editor: Error close temp file")
)
View Source
var (
	IconInitial = Styler(FGBlue)("?")
	IconGood    = Styler(FGGreen)("✔")
	IconQuest   = Styler(FGBlue)("✔")
	IconWarn    = Styler(FGYellow)("⚠")
	IconBad     = Styler(FGRed)("✗")
)

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 (
	// ErrorIncorrect describes incorrect default confirm value
	ErrorIncorrect = errors.New("Incorrect default values")
)
View Source
var ResetCode = fmt.Sprintf("%s%dm", esc, reset)

ResetCode is the character code used to reset the terminal formatting

Functions

func Ask

func Ask(label, startString string) (string, error)

Ask func is default prompt

func AskMasked

func AskMasked(label, startString string) (string, error)

AskMasked func is default masked prompt

func ClearUpLine

func ClearUpLine() string

ClearUpLine is Upline and clear that line

func ClearUpLines

func ClearUpLines(n int) string

ClearUpLines is Upline and clear that line

func Confirm

func Confirm(label, answer string, noIcons bool) (string, error)

Confirm func is predefined easy confirm promp

func Editor

func Editor(editor, s string) (string, error)

Editor func opens default editor to edit `s string`. Returns edit result. Creates temp file to edit string

func FailedValue

func FailedValue(label, value string) string

FailedValue returns a value as if it were entered via prompt, invalid

func MultiLine

func MultiLine(label, answer string) (string, error)

MultiLine func is default multiline prompt

func PromptAfterSelect

func PromptAfterSelect(label string, answers []string) (string, error)

PromptAfterSelect func is predefined easy confirm promp Answers may contain option description wrapped in `[]`

func Styler

func Styler(attrs ...attribute) func(string) string

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

func SuccessfulValue

func SuccessfulValue(label, value string) string

SuccessfulValue returns a value as if it were entered via prompt, valid

func UpLine

func UpLine() string

UpLine move cursor one line above

Types

type BasicPrompt

type BasicPrompt struct {
	Label string // Label is the value displayed on the command line prompt

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

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

	// Indent will be placed before the prompt's state symbol
	Indent string

	// InterruptPrompt to send to readline
	InterruptPrompt string

	// NoIcons flag to set empty string icons
	NoIcons bool
	// IconSet contains prompt icons
	IconSet
	// LabelStyle contains Label styles
	LabelStyle
	// InputStyle contains Input styles
	InputStyle
	// PromptStyle contains Prompt styles
	PromptStyle

	// IsVimMode option
	IsVimMode bool
	// Preamble option
	Preamble *string

	// Formatter formats input result
	Formatter StyleFn
	// contains filtered or unexported fields
}

BasicPrompt represents a single line text field input.

func (*BasicPrompt) Init

func (bp *BasicPrompt) Init() error

Init func to setup BasicPrompt

type ConfirmPrompt

type ConfirmPrompt struct {
	BasicPrompt

	// ConfirmOpt is the 3d answer option
	ConfirmOpt string
	// contains filtered or unexported fields
}

ConfirmPrompt represents a single line text field input.

func (*ConfirmPrompt) Run

func (cp *ConfirmPrompt) Run() (string, error)

Run func implements confirn prompt

type IconSet

type IconSet struct {
	// IconInitial icon to render
	IconInitial string
	// IconGood icon to render
	IconGood string
	// IconQuest icon to render
	IconQuest string
	// IconWarn icon to render
	IconWarn string
	// IconBad icon to render
	IconBad string
}

IconSet struct holds all inner icons to render

type InputStyle

type InputStyle struct {
	// InputInitial styler for initial Input text
	InputInitial StyleFn
	// InputResult styler for result Input text
	InputResult StyleFn
}

InputStyle contains Input styles

type LabelStyle

type LabelStyle struct {
	// LabelInitial styler for initial Label text
	LabelInitial StyleFn
	// LabelResult styler for result Label text
	LabelResult StyleFn
}

LabelStyle contains Label styles

type MultilinePrompt

type MultilinePrompt struct {
	BasicPrompt

	// OnError func is called when prompt.Run() return error
	// alternative way to fix error
	OnError func(string) (string, error)

	// Editor is default editor to edit multiline
	Editor string
}

MultilinePrompt represents a single line text field input.

func (*MultilinePrompt) Run

func (mp *MultilinePrompt) Run() (string, error)

Run func implements multiline prompt logic

type Prompt

type Prompt struct {
	BasicPrompt

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

	// Handlers catch key input events, user defined
	Handlers []func(line []rune, pos int, key rune) ([]rune, int, bool)
}

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 PromptStyle

type PromptStyle struct {
	// PromptInitial styler for initial Prompt text
	PromptInitial StyleFn
	// PromptResult styler for result Prompt text
	PromptResult StyleFn
}

PromptStyle contains Prompt styles for including label, punctuation, suggested

type Select

type Select struct {
	Label     string   // Label is the value displayed on the command line prompt.
	Items     []string // Items are the items to use in the list.
	Default   int      // Index of default item starting from 0
	IsVimMode bool     // Whether readline is using Vim mode.
}

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 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 StyleFn

type StyleFn func(string) string

StyleFn is a type of style functions

type ValidateFunc

type ValidateFunc func(string) error

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

type ValidationError

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

ValidationError is the class of errors resulting from invalid inputs, returned from a ValidateFunc.

func NewValidationError

func NewValidationError(msg string) *ValidationError

NewValidationError creates a new validation error with the given message.

func (*ValidationError) Error

func (v *ValidationError) Error() string

Error implements the error interface for ValidationError.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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