Skip to content

feat: CLI use multiselect for list(string) #6631

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Mar 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion cli/cliui/parameter.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cliui

import (
"encoding/json"
"fmt"
"strings"

Expand Down Expand Up @@ -69,7 +70,28 @@ func RichParameter(cmd *cobra.Command, templateVersionParameter codersdk.Templat

var err error
var value string
if len(templateVersionParameter.Options) > 0 {
if templateVersionParameter.Type == "list(string)" {
// Move the cursor up a single line for nicer display!
_, _ = fmt.Fprint(cmd.OutOrStdout(), "\033[1A")

var options []string
err = json.Unmarshal([]byte(templateVersionParameter.DefaultValue), &options)
if err != nil {
return "", err
}

values, err := MultiSelect(cmd, options)
if err == nil {
v, err := json.Marshal(&values)
if err != nil {
return "", err
}

_, _ = fmt.Fprintln(cmd.OutOrStdout())
_, _ = fmt.Fprintln(cmd.OutOrStdout(), " "+Styles.Prompt.String()+Styles.Field.Render(strings.Join(values, ", ")))
value = string(v)
}
} else if len(templateVersionParameter.Options) > 0 {
// Move the cursor up a single line for nicer display!
_, _ = fmt.Fprint(cmd.OutOrStdout(), "\033[1A")
var richParameterOption *codersdk.TemplateVersionParameterOption
Expand Down
38 changes: 38 additions & 0 deletions cli/cliui/select.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,21 @@ func init() {
{{- template "option" $.IterateOption $ix $option}}
{{- end}}
{{- end }}`

survey.MultiSelectQuestionTemplate = `
{{- define "option"}}
{{- if eq .SelectedIndex .CurrentIndex }}{{color .Config.Icons.SelectFocus.Format }}{{ .Config.Icons.SelectFocus.Text }}{{color "reset"}}{{else}} {{end}}
{{- if index .Checked .CurrentOpt.Index }}{{color .Config.Icons.MarkedOption.Format }} {{ .Config.Icons.MarkedOption.Text }} {{else}}{{color .Config.Icons.UnmarkedOption.Format }} {{ .Config.Icons.UnmarkedOption.Text }} {{end}}
{{- color "reset"}}
{{- " "}}{{- .CurrentOpt.Value}}
{{end}}
{{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }} {{ .Help }}{{color "reset"}}{{"\n"}}{{end}}
{{- if not .ShowAnswer }}
{{- "\n"}}
{{- range $ix, $option := .PageEntries}}
{{- template "option" $.IterateOption $ix $option}}
{{- end}}
{{- end}}`
}

type SelectOptions struct {
Expand Down Expand Up @@ -118,6 +133,29 @@ func Select(cmd *cobra.Command, opts SelectOptions) (string, error) {
return value, err
}

func MultiSelect(cmd *cobra.Command, items []string) ([]string, error) {
// Similar hack is applied to Select()
if flag.Lookup("test.v") != nil {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, so it looks like we're not actually testing the multi select behavior with this hack?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I was surprised about it too, it just goes with the default. I wasn't able to properly simulate the user marking options.

return items, nil
}

prompt := &survey.MultiSelect{
Options: items,
Default: items,
}

var values []string
err := survey.AskOne(prompt, &values, survey.WithStdio(fileReadWriter{
Reader: cmd.InOrStdin(),
}, fileReadWriter{
Writer: cmd.OutOrStdout(),
}, cmd.OutOrStdout()))
if errors.Is(err, terminal.InterruptErr) {
return nil, Canceled
}
return values, err
}

type fileReadWriter struct {
io.Reader
io.Writer
Expand Down
33 changes: 33 additions & 0 deletions cli/cliui/select_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,36 @@ func newRichSelect(ptty *ptytest.PTY, opts cliui.RichSelectOptions) (string, err
cmd.SetIn(ptty.Input())
return value, cmd.ExecuteContext(context.Background())
}

func TestMultiSelect(t *testing.T) {
t.Parallel()
t.Run("MultiSelect", func(t *testing.T) {
items := []string{"aaa", "bbb", "ccc"}

t.Parallel()
ptty := ptytest.New(t)
msgChan := make(chan []string)
go func() {
resp, err := newMultiSelect(ptty, items)
assert.NoError(t, err)
msgChan <- resp
}()
require.Equal(t, items, <-msgChan)
})
}

func newMultiSelect(ptty *ptytest.PTY, items []string) ([]string, error) {
var values []string
cmd := &cobra.Command{
RunE: func(cmd *cobra.Command, args []string) error {
selectedItems, err := cliui.MultiSelect(cmd, items)
if err == nil {
values = selectedItems
}
return err
},
}
cmd.SetOutput(ptty.Output())
cmd.SetIn(ptty.Input())
return values, cmd.ExecuteContext(context.Background())
}
85 changes: 85 additions & 0 deletions cli/create_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,8 @@ func TestCreateValidateRichParameters(t *testing.T) {
stringParameterName = "string_parameter"
stringParameterValue = "abc"

listOfStringsParameterName = "list_of_strings_parameter"

numberParameterName = "number_parameter"
numberParameterValue = "7"

Expand All @@ -468,6 +470,10 @@ func TestCreateValidateRichParameters(t *testing.T) {
{Name: stringParameterName, Type: "string", Mutable: true, ValidationRegex: "^[a-z]+$", ValidationError: "this is error"},
}

listOfStringsRichParameters := []*proto.RichParameter{
{Name: listOfStringsParameterName, Type: "list(string)", Mutable: true, DefaultValue: `["aaa","bbb","ccc"]`},
}

boolRichParameters := []*proto.RichParameter{
{Name: boolParameterName, Type: "bool", Mutable: true},
}
Expand Down Expand Up @@ -607,6 +613,85 @@ func TestCreateValidateRichParameters(t *testing.T) {
}
<-doneChan
})

t.Run("ValidateListOfStrings", func(t *testing.T) {
t.Parallel()

client := coderdtest.New(t, &coderdtest.Options{IncludeProvisionerDaemon: true})
user := coderdtest.CreateFirstUser(t, client)
version := coderdtest.CreateTemplateVersion(t, client, user.OrganizationID, prepareEchoResponses(listOfStringsRichParameters))
coderdtest.AwaitTemplateVersionJob(t, client, version.ID)
template := coderdtest.CreateTemplate(t, client, user.OrganizationID, version.ID)

cmd, root := clitest.New(t, "create", "my-workspace", "--template", template.Name)
clitest.SetupConfig(t, client, root)
doneChan := make(chan struct{})
pty := ptytest.New(t)
cmd.SetIn(pty.Input())
cmd.SetOut(pty.Output())
go func() {
defer close(doneChan)
err := cmd.Execute()
assert.NoError(t, err)
}()

matches := []string{
listOfStringsParameterName, "",
"aaa, bbb, ccc", "",
"Confirm create?", "yes",
}
for i := 0; i < len(matches); i += 2 {
match := matches[i]
value := matches[i+1]
pty.ExpectMatch(match)
if value != "" {
pty.WriteLine(value)
}
}
<-doneChan
})

t.Run("ValidateListOfStrings_YAMLFile", func(t *testing.T) {
t.Parallel()

client := coderdtest.New(t, &coderdtest.Options{IncludeProvisionerDaemon: true})
user := coderdtest.CreateFirstUser(t, client)
version := coderdtest.CreateTemplateVersion(t, client, user.OrganizationID, prepareEchoResponses(listOfStringsRichParameters))
coderdtest.AwaitTemplateVersionJob(t, client, version.ID)
template := coderdtest.CreateTemplate(t, client, user.OrganizationID, version.ID)

tempDir := t.TempDir()
removeTmpDirUntilSuccessAfterTest(t, tempDir)
parameterFile, _ := os.CreateTemp(tempDir, "testParameterFile*.yaml")
_, _ = parameterFile.WriteString(listOfStringsParameterName + `:
- ddd
- eee
- fff`)
cmd, root := clitest.New(t, "create", "my-workspace", "--template", template.Name, "--rich-parameter-file", parameterFile.Name())
clitest.SetupConfig(t, client, root)
doneChan := make(chan struct{})
pty := ptytest.New(t)
cmd.SetIn(pty.Input())
cmd.SetOut(pty.Output())
go func() {
defer close(doneChan)
err := cmd.Execute()
assert.NoError(t, err)
}()

matches := []string{
"Confirm create?", "yes",
}
for i := 0; i < len(matches); i += 2 {
match := matches[i]
value := matches[i+1]
pty.ExpectMatch(match)
if value != "" {
pty.WriteLine(value)
}
}
<-doneChan
})
}

func TestCreateWithGitAuth(t *testing.T) {
Expand Down
23 changes: 19 additions & 4 deletions cli/parameter.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package cli

import (
"encoding/json"
"fmt"
"os"

"github.com/spf13/cobra"
Expand All @@ -15,19 +17,32 @@ import (
// Throws an error if the file name is empty.
func createParameterMapFromFile(parameterFile string) (map[string]string, error) {
if parameterFile != "" {
parameterMap := make(map[string]string)

parameterFileContents, err := os.ReadFile(parameterFile)
if err != nil {
return nil, err
}

err = yaml.Unmarshal(parameterFileContents, &parameterMap)

mapStringInterface := make(map[string]interface{})
err = yaml.Unmarshal(parameterFileContents, &mapStringInterface)
if err != nil {
return nil, err
}

parameterMap := map[string]string{}
for k, v := range mapStringInterface {
switch val := v.(type) {
case string, bool, int:
parameterMap[k] = fmt.Sprintf("%v", val)
case []interface{}:
b, err := json.Marshal(&val)
if err != nil {
return nil, err
}
parameterMap[k] = string(b)
default:
return nil, xerrors.Errorf("invalid parameter type: %T", v)
}
}
return parameterMap, nil
}

Expand Down
2 changes: 1 addition & 1 deletion cli/parameter_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ func TestCreateParameterMapFromFile(t *testing.T) {
parameterMapFromFile, err := createParameterMapFromFile(parameterFile.Name())

assert.Nil(t, parameterMapFromFile)
assert.EqualError(t, err, "yaml: unmarshal errors:\n line 1: cannot unmarshal !!str `region ...` into map[string]string")
assert.EqualError(t, err, "yaml: unmarshal errors:\n line 1: cannot unmarshal !!str `region ...` into map[string]interface {}")

removeTmpDirUntilSuccess(t, tempDir)
})
Expand Down