Giter Club home page Giter Club logo

promptui's Introduction

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

promptui's People

Contributors

awinterman avatar bdwyertech avatar chenrui333 avatar davidharrigan avatar enmand avatar gssbzn avatar hallazzang avatar hassansin avatar j-martin avatar j-vizcaino avatar jamesdobson avatar jbowes avatar jeffandersen avatar jelmersnoeck avatar jyggen avatar larissavoigt avatar mack avatar mdanzinger avatar micnncim avatar nguyer avatar preethamrn avatar quentinbrosse avatar royeo avatar songmu avatar tim-speed avatar tslocum avatar wotzhs avatar xwjdsh avatar yskopets avatar ywwg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

promptui's Issues

Problem with types in prompt.go

Hi,

I try to run basic examples on Mac, golang version 1.10. I got an error:
vendor/github.com/manifoldco/promptui/prompt.go:88:11: cannot use p.stdin (type io.Reader) as type io.ReadCloser in assignment: io.Reader does not implement io.ReadCloser (missing Close method)
When I comment this line it works fine.

Screen flashes (MacOS 10.13.2)

When I tried some of the example projects, when I pressed the up/down keys the entire screen flashes white temporarily.

You can see the same effect if you open up a new terminal and press down (not up, as you will get your prior commands autocompleted).

This white flashing is clearly not intended and can clearly be disabled somehow.

Prompts filling the terminal width causes bad UI

Description

When a prompt and the user input fills the terminal width and the input has to go to the next line, the prompt is written again in a new line.

In a small terminal, the proof of concept bellow will cause multiple lines like:

$ go run longprompt.go
✔ Please enter a long very long answer so it has to go to the next line: abcdefg
✔ Please enter a long very long answer so it has to go to the next line: abcdefg
✔ Please enter a long very long answer so it has to go to the next line: abcdefg
hi

Proof of concept:

package main

import (
	"fmt"

	"github.com/manifoldco/promptui"
)

func main() {

	prompt := promptui.Prompt{
		Label: "Please enter a long very long answer so it has to go to the next line",
	}

	result, err := prompt.Run()
	if err != nil {
		fmt.Printf("Prompt failed %v\n", err)
		return
	}
	fmt.Printf("You choose %q\n", result)
}

Consider using asciinema for the demo

Asciinema renders the prompt using native font rendering, which scales to different subpixel layouts, subpixel rendering in general, and high-dpi scenarios.

Compile error

I'm getting a compile error if I try version 0.2.1:

github.com/manifoldco/promptui/prompt.go:88:11: cannot use p.stdin (type io.Reader) as type io.ReadCloser in assignment:
io.Reader does not implement io.ReadCloser (missing Close method)

captures ctrl + z

Is it possible to increase the signal SIGTSTP that captures ctrl + z, sorry m my English is not very good

Success template in Prompt is never rendered

I'm not sure if this is intended or not but the Success template in PromptTemplates is never rendered. I tried the custom_prompt example and had the same behavior.

I think in this line we could render success template instead. I can send a PR if you agree.

Thanks for this really cool package!

Capture Keyboard Keys

#72 mentions the use case of selecting multiple items.

This can be implemented by showing the prompt again, and checking if the "finished" field was selected.

This would be easier if instead of a finished field, user could input ^D to quit when they have selected everything.

This would require keyboard bindings to be detectable. Is that something that can be added here?

export attribute

This library would be more useful if attribute were exported, currently its difficult to even make a list of possible colors because it isn't exported.

the select_add example panics

Eg

~/go/src/github.com/manifoldco/promptui/_examples/select_add$ go run main.go
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x54d8f8]

goroutine 1 [running]:
github.com/manifoldco/promptui.(*Select).innerRun.func1(0x0, 0x0, 0x0, 0x0, 0xc400000000, 0x50c75c, 0xc420093260, 0xc42007ec60, 0xc4200bba60, 0xc42007ec60)
	/home/ncw/go/src/github.com/manifoldco/promptui/select.go:159 +0x78
github.com/chzyer/readline.(*DumpListener).OnChange(0xc42000e0d8, 0x0, 0x0, 0x0, 0x0, 0x0, 0xc4200bbb10, 0x48f40b, 0xc42000e018, 0x0, ...)
	/home/ncw/go/src/github.com/chzyer/readline/operation.go:516 +0x63
github.com/chzyer/readline.(*Operation).Runes(0xc420093260, 0x0, 0x0, 0x0, 0x0, 0x0)
	/home/ncw/go/src/github.com/chzyer/readline/operation.go:385 +0x37e
github.com/chzyer/readline.(*Operation).String(0xc420093260, 0x8, 0x583860, 0x1, 0xc42000e0d8)
	/home/ncw/go/src/github.com/chzyer/readline/operation.go:375 +0x2b
github.com/chzyer/readline.(*Instance).Readline(0xc42000c5c0, 0xc42000e0d8, 0x6, 0x8, 0x6)
	/home/ncw/go/src/github.com/chzyer/readline/readline.go:255 +0x2f
github.com/manifoldco/promptui.(*Select).innerRun(0xc4200621e0, 0x1, 0x2b, 0xc42000c400, 0x0, 0x0, 0x5, 0x5)
	/home/ncw/go/src/github.com/manifoldco/promptui/select.go:257 +0x320
github.com/manifoldco/promptui.(*SelectWithAdd).Run(0xc420072280, 0xc4200722d0, 0x56f220, 0x5cc790, 0xc420018430, 0xb)
	/home/ncw/go/src/github.com/manifoldco/promptui/select.go:421 +0x45e
main.main()
	/home/ncw/go/src/github.com/manifoldco/promptui/_examples/select_add/main.go:16 +0x158
exit status 2

Export stdin and stderr for unit test ?

First of all, thanks for your work. This library is so awesome! ❤️

I have a question: Is there any suggestion for write unit test for project that use this library?
Maybe export stdin and stderr is a way?

Terminal bell is ringing when try to select item using up-down arrow(↑↓) keys

I'm on macOS High Sierra, using iTerm2 3.1.5, zsh 5.3, Go 1.9.2 darwin/amd64 and the latest version of promptui.

While taking a look at #41, I found that my terminal alerts me with a ringing bell when I try to select item using up-down arrow(↑↓) keys, even I'm not on the top-most or the bottom-most.

It is happening on different terminals, for instance macOS' default terminal 'Terminal.app' and different shells, like sh, bash or csh.

It's not that important problem at all, but users might get annoyed by this.

Go get compiler error with screenbuf.go

Promptui is being pulled in as a dependency within another project when using go get. I get the following:

# github.com/manifoldco/promptui/screenbuf
src/github.com/manifoldco/promptui/screenbuf/screenbuf.go:46: undefined: bytes.ContainsAny

Please advise.

Ctrl-C causes panic

I'm getting random panics if I press ctrl-C instead of answering, it's a simple prompt.

I'm checking for promptui.ErrInterrupt but it happens before that inside Run.

		prompt := promptui.Prompt{
			Label:    "Enter the current date in UTC in the format YYYY-MM-DD ",
		}

		_, err := prompt.Run()

		if err == promptui.ErrInterrupt {
			os.Exit(-1)
		}

trace

? Is this the current time: 21:07:03 UTC? [y/N] █
panic: bytes.Buffer: truncation out of range

goroutine 42 [running]:
bytes.(*Buffer).Truncate(0xc4200cc4d0, 0x0)
	/home/stuart/go/src/bytes/buffer.go:74 +0xc1
bytes.(*Buffer).WriteTo(0xc4200cc4d0, 0x7599e0, 0xc42012e260, 0x467754, 0xc4200cc4d0, 0x0)
	/home/stuart/go/src/bytes/buffer.go:228 +0x5b
github.com/manifoldco/promptui/screenbuf.(*ScreenBuf).Flush(0xc42012ce10, 0xc420138240, 0x50)
	/home/stuart/gocode/src/github.com/manifoldco/promptui/screenbuf/screenbuf.go:115 +0x107
github.com/manifoldco/promptui.(*Prompt).Run.func2(0x78e658, 0x0, 0x0, 0x0, 0xc400000003, 0x5812d7, 0xc42014c090, 0x6629a0, 0xc42014c090, 0xc42014c090)
	/home/stuart/gocode/src/github.com/manifoldco/promptui/prompt.go:179 +0x2d8
github.com/chzyer/readline.(*DumpListener).OnChange(0xc420136058, 0x78e658, 0x0, 0x0, 0x0, 0x3, 0x3, 0x0, 0x0, 0x0, ...)
	/home/stuart/gocode/src/github.com/chzyer/readline/operation.go:516 +0x63
github.com/chzyer/readline.(*Operation).ioloop(0xc4200cc380)
	/home/stuart/gocode/src/github.com/chzyer/readline/operation.go:339 +0x405
created by github.com/chzyer/readline.NewOperation
	/home/stuart/gocode/src/github.com/chzyer/readline/operation.go:88 +0x3bc

Horizontal selection

Is horizontal selection supported?

I wanted to make a selection screen that would look something like the following.

Select the correct translation for the following phrase: Bonjour

              Hello                   |               Goodbye

                ✅

The user would then be able to use the left and right keys to select between Hello and Goodbye.

No space in confirmation text?

I am seeing a lack of a space in the confirmation message of the prompt:

I would assume a space should be appended between the label and the value?

Also, how can one turn off the confirmation message in the first place?

I am using iTerm on a Mac.

Prompt interrupt not catched

Hello,
When I use the basic prompt the Ctrl-C interrupt is never catched, and the error is never throwed.
I found the origin of the bug, I will make a PR.

Remove Copyright Assignment from the CLA

The CLA for contributing to this project requires copyright assignment, which is unnecessary. Please consider removing the copyright assignment from your CLA and instead replacing it with only copyright license.

Examples of decent CLAs that only contain copyright license:


Disclaimer: I'm not a lawyer and this isn't legal advice. I'm a software engineer who would like to submit a contribution without signing an agreement that contains copyright assignment.

Running inside a bash script causes invisible select navigation

I noticed that the select functionality (as shown in the README example) fails to update and give visual feedback when running inside a bash script.

I have this script for my project:

#!/bin/bash

clear

# Do a lot of help tools and automated work

go run $(find . -maxdepth 1 -type f -name '*.go' ! -name '*_test.go' | xargs)

Running the go run line in Bash or ZSH works fine when navigating the list, but inside the script there's no feedback, although in the Select Day: example, if I press down twice for example and hit enter it did choose Wednesday. So it works, but just doesn't visually update.

  • I'm running macOS High Sierra 10.13.1
  • Go version is go1.9.2 darwin/amd64
  • My ZSH version is 5.3 and Bash version is 3.2

When will there be a new release?

There seems to have been lots of changes since 26 Nov 2018 but they are not in the latest (v0.3.2) tag so are not being included when doing go get.

Will there be a new release soon?

Thanks

Edit default value

It'd be really handy if there were an option to allow the default value to be edited. At the moment it gets deleted if you try.

Use case is e.g. asking for something like a hostname where you may want to make a minor adjustment rather than accept the default.

A after hook to change the received value

It would be nice to have some sort of an after hook added to promptui.Prompt{} struct so we can for example cast a received string to a number. So some sort of value a transformer:

AfterHook: func(input string) (error, uint64) {
	transformed, err := strconv.ParseUint(input, 10, 64)
	if err != nil {
		return fmt.Errorf("failed transforming received input to uint64: %v", input), 0
	}
	return nil, transformed
}

Or does this not fall into what promptui should do?

Customized background support

Hello, this tool is awesome!
Do you have a plan to support the customized background color for select templates?
For example, support customized background color for active, inactive, selected items, etc.

Hide help message

There seems to be no way of suppressing the help message in a select template.

If you set the help message to blank string "", then it defaults to 'Use the arrow keys to navigate'. As per (in select.go):

if tpls.Help == "" {
	tpls.Help = fmt.Sprintf(`{{ "Use the arrow keys to navigate:" | faint }} {{ .NextKey | faint }} ` +
		`{{ .PrevKey | faint }} {{ .PageDownKey | faint }} {{ .PageUpKey | faint }} ` +
		`{{ if .Search }} {{ "and" | faint }} {{ .SearchKey | faint }} {{ "toggles search" | faint }}{{ end }}`)
}

Have I missed something? Thanks

Compile error ( go get)

Hi,

I am getting the below error while compilation

"../../../../github.com/manifoldco/promptui/prompt.go:88:11: cannot use p.stdin (type io.Reader) as type io.ReadCloser in assignment:
io.Reader does not implement io.ReadCloser (missing Close method)"

Please implement the method and update so that I can start using it

Request: Remove dependency linters for go.mod

If I do not need the linter dependency to run promptui, can I remove it from go.mod?
Dependencies of tools using promptui also include linter, which can not be excluded.
I do not want to include dependencies in go.sum that are unnecessary for execution.

It would be greatly appreciated if you could explain the another solution.

module github.com/d-kuro/go-sandbox

go 1.12

require github.com/manifoldco/promptui v0.3.2

exclude (
	golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3
	gopkg.in/alecthomas/kingpin.v3-unstable v3.0.0-20180810215634-df19058c872c
)
$ go mod tidy
go: github.com/manifoldco/promptui(v0.3.2) depends on excluded golang.org/x/lint(v0.0.0-20181026193005-c67002cb31c3) with no newer version available
go.sum

github.com/alecthomas/gometalinter v2.0.11+incompatible h1:ENdXMllZNSVDTJUUVIzBW9CSEpntTrQa76iRsEFLX/M=
github.com/alecthomas/gometalinter v2.0.11+incompatible/go.mod h1:qfIpQGGz3d+NmgyPBqv+LSh50emm1pt72EtcX2vKYQk=
github.com/chzyer/logex v1.1.10 h1:Swpa1K6QvQznwJRcfTfQJmTE72DqScAa40E+fbHEXEE=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e h1:fY5BOSpyZCqRo5OhCuC+XN+r/bBCmeuuJtjz+bCNIf8=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1 h1:q763qf9huN11kDQavWsoZXJNW3xEE4JJyHa5Q25/sd8=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
github.com/client9/misspell v0.3.4 h1:ta993UF76GwbvJcIo3Y68y/M3WxlpEHPWIGDkJYwzJI=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/golang/lint v0.0.0-20181026193005-c67002cb31c3 h1:I4BOK3PBMjhWfQM2zPJKK7lOBGsrsvOB7kBELP33hiE=
github.com/golang/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:tluoj9z5200jBnyusfRPU2LqT6J+DAorxEvtC7LHB+E=
github.com/google/shlex v0.0.0-20181106134648-c34317bd91bf h1:7+FW5aGwISbqUtkfmIpZJGRgNFg2ioYPvFaUxdqpDsg=
github.com/google/shlex v0.0.0-20181106134648-c34317bd91bf/go.mod h1:RpwtwJQFrIEPstU94h88MWPXP2ektJZ8cZ0YntAmXiE=
github.com/gordonklaus/ineffassign v0.0.0-20180909121442-1003c8bd00dc h1:cJlkeAx1QYgO5N80aF5xRGstVsRQwgLR7uA2FnP1ZjY=
github.com/gordonklaus/ineffassign v0.0.0-20180909121442-1003c8bd00dc/go.mod h1:cuNKsD1zp2v6XfE/orVX2QE1LC+i254ceGcVeDT3pTU=
github.com/juju/ansiterm v0.0.0-20180109212912-720a0952cc2a h1:FaWFmfWdAUKbSCtOU2QjDaorUexogfaMgbipgYATUMU=
github.com/juju/ansiterm v0.0.0-20180109212912-720a0952cc2a/go.mod h1:UJSiEoRfvx3hP73CvoARgeLjaIOjybY9vj8PUPPFGeU=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/lunixbochs/vtclean v0.0.0-20180621232353-2d01aacdc34a h1:weJVJJRzAJBFRlAiJQROKQs8oC9vOxvm4rZmBBk0ONw=
github.com/lunixbochs/vtclean v0.0.0-20180621232353-2d01aacdc34a/go.mod h1:pHhQNgMf3btfWnGBVipUOjRYhoOsdGqdm/+2c2E2WMI=
github.com/manifoldco/promptui v0.3.2 h1:rir7oByTERac6jhpHUPErHuopoRDvO3jxS+FdadEns8=
github.com/manifoldco/promptui v0.3.2/go.mod h1:8JU+igZ+eeiiRku4T5BjtKh2ms8sziGpSYl1gN8Bazw=
github.com/mattn/go-colorable v0.0.9 h1:UVL0vNpWh04HeJXV0KLcaT7r06gOH2l4OW6ddYRUIY4=
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
github.com/mattn/go-isatty v0.0.4 h1:bnP0vzxcAdeI1zdubAl5PjU6zsERjGZb7raWodagDYs=
github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/tsenart/deadcode v0.0.0-20160724212837-210d2dc333e9 h1:vY5WqiEon0ZSTGM3ayVVi+twaHKHDFUVloaQ/wug9/c=
github.com/tsenart/deadcode v0.0.0-20160724212837-210d2dc333e9/go.mod h1:q+QjxYvZ+fpjMXqs+XEriussHjSYqeXVnAdSV1tkMYk=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3 h1:x/bBzNauLQAlE3fLku/xy92Y8QwKX5HZymrMz2IiKFc=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b h1:MQE+LT/ABUuuvEZ+YQAMSXindAdUh7slEmAkup74op4=
golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/tools v0.0.0-20181122213734-04b5d21e00f1 h1:bsEj/LXbv3BCtkp/rBj9Wi/0Nde4OMaraIZpndHAhdI=
golang.org/x/tools v0.0.0-20181122213734-04b5d21e00f1/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=

Flush function in Screenbuf/screenbuf.go assumes one line in terminal per line entry

The Flush function, which prints to the terminal, resets the pointer after every user input, by traversing up the terminal pointer with a value of s.height.
This works if s.height is exactly the amount of lines actually taken in the terminal output.

However, I have a line in my output that wraps more than one line (Actual line taken: 5, s.height: 4).
This results in the future user input being pushed down one line, as the for loop

for i := 0; i < s.height; i++ {
	_, err := s.buf.Write(moveUp)
	if err != nil {
		return err
	}
}

doesn't point towards the starting point anymore

Promptui clears the entire screen/buffer in windows.

When it runs into the promptui function and sometimes if there's even not a selection it'll just clear the entire screen. This happens only on windows. I'm running 7 Home Premium and the default cmd.

Example

1st case is normal
2nd case is with it showing the prompt and clearing the entire buffer beforehand
3rd case is normal again
4th case is when it doesn't show a prompt but still clears the screen/buffer

	var result string

	if len(searchresults) > 1 {
		prompt := promptui.Select{
			Label: "Pick one of the following",
			Items: searchresults, // []string containing entries
		}

		_, finalresult, err := prompt.Run()
		
		result = finalresult
		if err != nil {
			fmt.Printf("Error %v\n", err)
			return
		}
	} else {
		return
	}

Data race

When you build/run with -race you'll get the following stack using any of the basic examples:

==================
WARNING: DATA RACE
Write at 0x00c420311640 by goroutine 32:
  github.com/manifoldco/promptui.(*Prompt).Run.func2()
      /Users/jhaynie/go/src/github.com/manifoldco/promptui/prompt.go:136 +0xa7b
  github.com/chzyer/readline.(*DumpListener).OnChange()
      /Users/jhaynie/go/src/github.com/chzyer/readline/operation.go:516 +0x96
  github.com/chzyer/readline.(*Operation).ioloop()
      /Users/jhaynie/go/src/github.com/chzyer/readline/operation.go:339 +0x771

Previous read at 0x00c420311640 by main goroutine:
  github.com/manifoldco/promptui.(*Prompt).Run()
      /Users/jhaynie/go/src/github.com/manifoldco/promptui/prompt.go:194 +0x77a
  github.com/pinpt/worker/cmd/customer.glob..func12()
      /Users/jhaynie/go/src/github.com/pinpt/worker/cmd/customer/enroll.go:33 +0x118
  github.com/pinpt/worker/vendor/github.com/spf13/cobra.(*Command).execute()
      /Users/jhaynie/go/src/github.com/pinpt/worker/vendor/github.com/spf13/cobra/command.go:702 +0x8ac
  github.com/pinpt/worker/vendor/github.com/spf13/cobra.(*Command).ExecuteC()
      /Users/jhaynie/go/src/github.com/pinpt/worker/vendor/github.com/spf13/cobra/command.go:783 +0x444
  github.com/pinpt/worker/vendor/github.com/spf13/cobra.(*Command).Execute()
      /Users/jhaynie/go/src/github.com/pinpt/worker/vendor/github.com/spf13/cobra/command.go:736 +0x38
  github.com/pinpt/worker/cmd.Execute()
      /Users/jhaynie/go/src/github.com/pinpt/worker/cmd/root.go:148 +0xec
  main.main()
      /Users/jhaynie/go/src/github.com/pinpt/worker/main.go:8 +0x2f

since promptui is reading and writing on 2 different goroutines ... probably should switch to either using a mutex (or ideally a channel)

For completeness of issue, here's the code:

prompt := promptui.Prompt{
	Label: "Customer Name",
	Validate: func(input string) error {
		if len(input) < 3 {
			return fmt.Errorf("customer name must be at least 3 characters")
		}
		return nil
	},
}
customerName, err := prompt.Run()

capture arrow keys and modify users input during prompt.Run()

I want to add user input history (like in bash) to my console app.
Pressing UP-Key will get previously used command string and paste it to prompt.
That wold be graet if app could capture special keys, like arrows, TAB, ESC, ALT, CTRL etc
And there must be some way to modify current promp.
With that it would be possible to add autocompletion feature like pressing TAB in bash

bug: `StartInSearchMode` does overwrite `RunCursorAt`

Hey there

I found a little bug when using your select prompt and I don't know if it's intended:
When one does calculate the page and position of a list of elements and runs the select at a specific cursor, it works like a charm:

elements := []string{"a","b","c","d","e","f","g","h","i"}
// search for actual index that we want to use
actualIndex := 7
page := actualIndex / 5 // will be 1
pos := actualIndex % 5 // will be 2

prompt := promptui.Select{
  Label: "select",
  Items: elements,
  Searcher: func(input string, index int) bool {
    if found := strings.Index(contexts[index], input); found != -1 {
      return true
    }
    return false
  }
}

_, _, _ := prompt.RunCursorAt(position, page)
// *snip

Now, page "two" with the third element will be selected, as expected.

But when I run the same code with StartInSearchMode set to true:

prompt := promptui.Select{
  Label: "select",
  Items: elements,
  StartInSearchMode: true,
  Searcher: func(input string, index int) bool {
    if found := strings.Index(contexts[index], input); found != -1 {
      return true
    }
    return false
  }
}

_, _, _ := prompt.RunCursorAt(position, page)
// *snip

The searcher gets activated (as intended), but the list beneath it is set to page 0 and cursor position 0. As long as no first search is executed, I'd expect the list to be set to the cursor position that is given at the start.

Or does this break some functionality ?

Thanks for the reply,
Cheers

IsConfirm generates error if response is not "y"

when I perform a confirmation prompt, I am getting an empty error when entering any value other than y is this expected behavior?

to reproduce

package main

import (
	"fmt"

	"github.com/manifoldco/promptui"
)

func main() {
	prompt := promptui.Prompt{
		Label:     "does this work?",
		IsConfirm: true,
		Default:   "n",
	}
	answer, err := prompt.Run()
	fmt.Printf("error <%v>, answer <%s> \n", err, answer)
}

// type "y" => error <<nil>>, answer <y>	// err == nil (true)
// type "n" => error <>, answer <n> 		// err == nil (false)
// type "" => error <>, answer <>		// err == nil (false)
// type "foo" => error <>, answer <foo>		// err == nil (false)

Integrating with CLI-Cobra

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.

Is there an example project giving some guidelines or a starting-off point on how to integrate with cobra?

Capture SIGINT gracefully

If I press Ctrl+C while entering my information, it outputs a full stack trace.

I don't really care if my users interrupt the process, it doesn't hurt anything, and I don't want to make them think they've just broken anything.

Is there anyway to handle signal interrupts without crashing the app?

Go version 2 support?

Does this package support go version 2, I noticed it isn’t in the travis confit and had issues running your examples

Use tab to navigate a select

Can you add a small feature to navigate through the list of item in a select prompt using tab, that goes from first to last of item in a circular way, much like how readline does it.

how to implement Searcher to support children node search ?

I have an object like this, I want to search node no matter which layer it is

type Node struct {
	Name           string           `yaml:"name"`
	Children       []*Node          `yaml:"children"`
}

because limited by the interface,I dont know how to implement it?

	// Searcher is a function that can be implemented to refine the base searching algorithm in selects.
	//
	// Search is a function that will receive the searched term and the item's index and should return a boolean
	// for whether or not the terms are alike. It is unimplemented by default and search will not work unless
	// it is implemented.
	Searcher list.Searcher

The following code can only implement top level search. but it could support multi level select.

func choose(parent, trees []*sshw.Node) *sshw.Node {
	prompt := promptui.Select{
		Label:     "select host",
		Items:     trees,
		Templates: templates,
		Size:      20,
		Searcher: func(input string, index int) bool {
			node := trees[index]
			content := node.Name
			if strings.Contains(input, " ") {
				for _, key := range strings.Split(input, " ") {
					key = strings.TrimSpace(key)
					if key != "" {
						if !strings.Contains(content, key) {
							return false
						}
						}
				}
				return true
			}
			if strings.Contains(content, input) {
				return true
			}
			return false
		},
	}
	index, _, err := prompt.Run()
	if err != nil {
		return nil
	}

	node := trees[index]
	if len(node.Children) > 0 {
		first := node.Children[0]
		if first.Name != prev {
			first = &sshw.Node{Name: prev}
			node.Children = append(node.Children[:0], append([]*sshw.Node{first}, node.Children...)...)
		}
		return choose(trees, node.Children)
	}

	if node.Name == prev {
		return choose(nil, parent)
	}

	return node
}

ppc64le: select does not work

Hi,

if I compile select in _examples with "GOARCH=ppc64le", and execute it on a POWER machine it does not work as expected and shows the following behavior:

  • when I press j it prints a j at the bottom of the list and does not update the TUI (i.e., does not move the "selection arrow". If I do the same with the "down-key", I see the key-code of that key at the bottom.
  • when I finally press enter, the correct item is selected. For example if I press jj, I see these two jjs at the bottom, then I press <enter> and it prints You choose "Wednesday".

Do you think this updating bug is a bug in promptui or actually a bug in one of the dependencies? Any hints are welcome.

go mod fails to pull dependencies for promptui

Getting this error when trying to import promptui using go mod.

github.com/manifoldco/promptui imports
	github.com/alecthomas/gometalinter imports
	gopkg.in/alecthomas/kingpin.v3-unstable imports
	github.com/nicksnyder/go-i18n/i18n: module github.com/nicksnyder/go-i18n@latest (v2.0.2+incompatible) found, but does not contain package github.com/nicksnyder/go-i18n/i18n

This does not exist -> github.com/nicksnyder/go-i18n/i18n
It has been changed to github.com/nicksnyder/go-i18n/v2/i18n

backspace not working on windows.

This might have more to do with one of the underlying dependencies, but on windows 10 backspace is not working for me when using Prompt.Run()

Here's how I'm using it:

// This is within a loop with a new field on each iteration.

prompt := promptui.Prompt{
    Label: field,
}

result, err := prompt.Run()
if err != nil {
	panic(err)
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.