survey

package module
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: May 16, 2017 License: MIT Imports: 8 Imported by: 0

README

Survey

Build Status GoDoc

A library for building interactive prompts. Heavily inspired by the great inquirer.js.

package main

import (
    "fmt"
    "gopkg.in/AlecAivazis/survey.v1"
)

// the questions to ask
var qs = []*survey.Question{
    {
        Name:     "name",
        Prompt:   &survey.Input{Message: "What is your name?"},
        Validate: survey.Required,
    },
    {
        Name: "color",
        Prompt: &survey.Select{
            Message: "Choose a color:",
            Options: []string{"red", "blue", "green"},
            Default: "red",
        },
    },
}

func main() {
    // the answers will be written to this struct
    answers := struct {
        Name          string                  // survey will match the question and field names
        FavoriteColor string `survey:"color"` // or you can tag fields to match a specific name
    }{}

    // perform the questions
    err := survey.Ask(qs, &answers)
    if err != nil {
        fmt.Println(err.Error())
        return
    }

    fmt.Printf("%s chose %s.", answers.Name, answers.FavoriteColor)
}

Table of Contents

  1. Examples
  2. Prompts
    1. Input
    2. Password
    3. Confirm
    4. Select
    5. MultiSelect
  3. Validation
    1. Built-in Validators
  4. Help Text
    1. Changing the input rune
  5. Customizing Output
  6. Versioning

Examples

Examples can be found in the examples/ directory. Run them to see basic behavior:

go get github.com/AlecAivazis/survey

# ... navigate to the repo in your GOPATH

go run examples/simple.go
go run examples/validation.go

Prompts

Input
name := ""
prompt := &survey.Input{
    Message: "ping",
}
survey.AskOne(prompt, &name, nil)
Password
password := ""
prompt := &survey.Password{
    Message: "Please type your password",
}
survey.AskOne(prompt, &password, nil)
Confirm
name := false
prompt := &survey.Confirm{
    Message: "Do you like pie?",
}
survey.AskOne(prompt, &name, nil)
Select
color := ""
prompt := &survey.Select{
    Message: "Choose a color:",
    Options: []string{"red", "blue", "green"},
}
survey.AskOne(prompt, &color, nil)
MultiSelect
days := []string{}
prompt := &survey.MultiSelect{
    Message: "What days do you prefer:",
    Options: []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"},
}
survey.AskOne(prompt, &days, nil)

Validation

Validating individual responses for a particular question can be done by defining a Validate field on the survey.Question to be validated. This function takes an interface{} type and returns an error to show to the user, prompting them for another response:

q := &survey.Question{
    Prompt: &survey.Input{Message: "Hello world validation"},
    Validate: func (val interface{}) error {
        // since we are validating an Input, the assertion will always succeed
        if str, ok := val.(string) ; ok && len(str) > 10 {
            return errors.New("This response cannot be longer than 10 characters.")
        }
    }
}
Built-in Validators

survey comes prepackaged with a few validators to fit common situations. Currently these validators include:

name valid types description
Required any Rejects zero values of the response type
MinLength(n) string Enforces that a response is at least the given length
MaxLength(n) string Enforces that a response is no longer than the given length

Help Text

All of the prompts have a Help field which can be defined to provide more information to your users:

&survey.Input{
    Message: "What is your phone number:",
    Help:    "Phone number should include the area code",
}
Changing the input rune

In some situations, ? is a perfectly valid response. To handle this, you can change the rune that survey looks for by setting the HelpInputRune variable in survey/core:


import (
    "gopkg.in/AlecAivazis/survey.v1"
    surveyCore "gopkg.in/AlecAivazis/survey.v1/core"
)

number := ""
prompt := &survey.Input{
    Message: "If you have this need, please give me a reasonable message.",
    Help:    "I couldn't come up with one.",
}

surveyCore.HelpInputRune = '^'

survey.AskOne(prompt, &number, nil)

Customizing Output

Customizing the icons and various parts of survey can easily be done by setting the following variables in survey/core:

name default description
ErrorIcon Before an error
HelpIcon Before help text
QuestionIcon ? Before the message of a prompt
SelectFocusIcon Marks the current selection in Select and MultiSelect prompts
MarkedOptionIcon Marks a chosen selection in a MultiSelect prompt
UnmarkedOptionIcon Marks an unselected option in a MultiSelect prompt

Versioning

This project tries to maintain semantic GitHub releases as closely as possible. As such, services like gopkg.in work very well to ensure non-breaking changes whenever you build your application. For example, importing v1 of survey could look something like

package main

import "gopkg.in/AlecAivazis/survey.v1"

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ConfirmQuestionTemplate = `` /* 497-byte string literal not displayed */

Templates with Color formatting. See Documentation: https://github.com/mgutz/ansi#style-format

View Source
var InputQuestionTemplate = `` /* 496-byte string literal not displayed */

Templates with Color formatting. See Documentation: https://github.com/mgutz/ansi#style-format

View Source
var MultiSelectQuestionTemplate = `` /* 779-byte string literal not displayed */
View Source
var PasswordQuestionTemplate = `` /* 318-byte string literal not displayed */

Templates with Color formatting. See Documentation: https://github.com/mgutz/ansi#style-format

View Source
var SelectQuestionTemplate = `` /* 643-byte string literal not displayed */

Functions

func Ask

func Ask(qs []*Question, t interface{}) error

Ask performs the prompt loop

func AskOne

func AskOne(p Prompt, t interface{}, v Validator) error

AskOne asks a single question without performing validation on the answer.

func Required

func Required(val interface{}) error

Required does not allow an empty value

Types

type Confirm

type Confirm struct {
	core.Renderer
	Message string
	Default bool
	Help    string
}

Confirm is a regular text input that accept yes/no answers.

func (*Confirm) Cleanup

func (c *Confirm) Cleanup(val interface{}) error

Cleanup overwrite the line with the finalized formatted version

func (*Confirm) Prompt

func (c *Confirm) Prompt() (interface{}, error)

Prompt prompts the user with a simple text field and expects a reply followed by a carriage return.

type ConfirmTemplateData

type ConfirmTemplateData struct {
	Confirm
	Answer   string
	ShowHelp bool
}

data available to the templates when processing

type Input

type Input struct {
	core.Renderer
	Message string
	Default string
	Help    string
}

Input is a regular text input that prints each character the user types on the screen and accepts the input with the enter key.

func (*Input) Cleanup

func (i *Input) Cleanup(val interface{}) error

func (*Input) Prompt

func (i *Input) Prompt() (interface{}, error)

type InputTemplateData

type InputTemplateData struct {
	Input
	Answer     string
	ShowAnswer bool
	ShowHelp   bool
}

data available to the templates when processing

type MultiSelect added in v1.0.1

type MultiSelect struct {
	core.Renderer
	Message string
	Options []string
	Default []string
	Help    string
	// contains filtered or unexported fields
}

MultiSelect is a prompt that presents a list of various options to the user for them to select using the arrow keys and enter.

func (*MultiSelect) Cleanup added in v1.0.1

func (m *MultiSelect) Cleanup(val interface{}) error

Cleanup removes the options section, and renders the ask like a normal question.

func (*MultiSelect) OnChange added in v1.0.1

func (m *MultiSelect) OnChange(line []rune, pos int, key rune) (newLine []rune, newPos int, ok bool)

OnChange is called on every keypress.

func (*MultiSelect) Prompt added in v1.0.1

func (m *MultiSelect) Prompt() (interface{}, error)

type MultiSelectTemplateData added in v1.0.1

type MultiSelectTemplateData struct {
	MultiSelect
	Answer        string
	ShowAnswer    bool
	Checked       map[int]bool
	SelectedIndex int
	ShowHelp      bool
}

data available to the templates when processing

type Password

type Password struct {
	core.Renderer
	Message string
	Help    string
}

Password is like a normal Input but the text shows up as *'s and there is no default.

func (*Password) Cleanup

func (prompt *Password) Cleanup(val interface{}) error

Cleanup hides the string with a fixed number of characters.

func (*Password) Prompt

func (p *Password) Prompt() (line interface{}, err error)

type PasswordTemplateData added in v1.1.1

type PasswordTemplateData struct {
	Password
	ShowHelp bool
}

type Prompt

type Prompt interface {
	Prompt() (interface{}, error)
	Cleanup(interface{}) error
	Error(error) error
}

Prompt is the primary interface for the objects that can take user input and return a string value.

type Question

type Question struct {
	Name     string
	Prompt   Prompt
	Validate Validator
}

Question is the core data structure for a survey questionnaire.

type Select added in v1.0.1

type Select struct {
	core.Renderer
	Message string
	Options []string
	Default string
	Help    string
	// contains filtered or unexported fields
}

Select is a prompt that presents a list of various options to the user for them to select using the arrow keys and enter.

func (*Select) Cleanup added in v1.0.1

func (s *Select) Cleanup(val interface{}) error

func (*Select) OnChange added in v1.0.1

func (s *Select) OnChange(line []rune, pos int, key rune) (newLine []rune, newPos int, ok bool)

OnChange is called on every keypress.

func (*Select) Prompt added in v1.0.1

func (s *Select) Prompt() (interface{}, error)

type SelectTemplateData

type SelectTemplateData struct {
	Select
	SelectedIndex int
	Answer        string
	ShowAnswer    bool
	ShowHelp      bool
}

the data available to the templates when processing

type Validator

type Validator func(interface{}) error

Validator is a function passed to a Question in order to redefine

func ComposeValidators

func ComposeValidators(validators ...Validator) Validator

ComposeValidators is a variadic function used to create one validator from many.

func MaxLength

func MaxLength(length int) Validator

MaxLength requires that the string is no longer than the specified value

func MinLength

func MinLength(length int) Validator

MinLength requires that the string is longer or equal in length to the specified value

Directories

Path Synopsis
autoplay
////////////////////////////////////////////////////////////////////////////// DO NOT MODIFY THIS FILE! This file was automatically generated via the commands: go get github.com/coryb/autoplay autoplay -n autoplay/ask.go go run ask.go ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// DO NOT MODIFY THIS FILE! This file was automatically generated via the commands: go get github.com/coryb/autoplay autoplay -n autoplay/confirm.go go run confirm.go ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// DO NOT MODIFY THIS FILE! This file was automatically generated via the commands: go get github.com/coryb/autoplay autoplay -n autoplay/doubleSelect.go go run doubleSelect.go ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// DO NOT MODIFY THIS FILE! This file was automatically generated via the commands: go get github.com/coryb/autoplay autoplay -n autoplay/help.go go run help.go ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// DO NOT MODIFY THIS FILE! This file was automatically generated via the commands: go get github.com/coryb/autoplay autoplay -n autoplay/input.go go run input.go ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// DO NOT MODIFY THIS FILE! This file was automatically generated via the commands: go get github.com/coryb/autoplay autoplay -n autoplay/multiselect.go go run multiselect.go ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// DO NOT MODIFY THIS FILE! This file was automatically generated via the commands: go get github.com/coryb/autoplay autoplay -n autoplay/password.go go run password.go ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// DO NOT MODIFY THIS FILE! This file was automatically generated via the commands: go get github.com/coryb/autoplay autoplay -n autoplay/select.go go run select.go ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// DO NOT MODIFY THIS FILE! This file was automatically generated via the commands: go get github.com/coryb/autoplay autoplay -n autoplay/selectThenInput.go go run selectThenInput.go //////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////// DO NOT MODIFY THIS FILE! This file was automatically generated via the commands: go get github.com/coryb/autoplay autoplay -n autoplay/ask.go go run ask.go ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// DO NOT MODIFY THIS FILE! This file was automatically generated via the commands: go get github.com/coryb/autoplay autoplay -n autoplay/confirm.go go run confirm.go ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// DO NOT MODIFY THIS FILE! This file was automatically generated via the commands: go get github.com/coryb/autoplay autoplay -n autoplay/doubleSelect.go go run doubleSelect.go ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// DO NOT MODIFY THIS FILE! This file was automatically generated via the commands: go get github.com/coryb/autoplay autoplay -n autoplay/help.go go run help.go ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// DO NOT MODIFY THIS FILE! This file was automatically generated via the commands: go get github.com/coryb/autoplay autoplay -n autoplay/input.go go run input.go ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// DO NOT MODIFY THIS FILE! This file was automatically generated via the commands: go get github.com/coryb/autoplay autoplay -n autoplay/multiselect.go go run multiselect.go ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// DO NOT MODIFY THIS FILE! This file was automatically generated via the commands: go get github.com/coryb/autoplay autoplay -n autoplay/password.go go run password.go ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// DO NOT MODIFY THIS FILE! This file was automatically generated via the commands: go get github.com/coryb/autoplay autoplay -n autoplay/select.go go run select.go ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// DO NOT MODIFY THIS FILE! This file was automatically generated via the commands: go get github.com/coryb/autoplay autoplay -n autoplay/selectThenInput.go go run selectThenInput.go //////////////////////////////////////////////////////////////////////////////

Jump to

Keyboard shortcuts

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