Select displays a list of user options.
(inv *serpent.Invocation, opts SelectOptions)
| 102 | |
| 103 | // Select displays a list of user options. |
| 104 | func Select(inv *serpent.Invocation, opts SelectOptions) (string, error) { |
| 105 | // The survey library used *always* fails when testing on Windows, |
| 106 | // as it requires a live TTY (can't be a conpty). We should fork |
| 107 | // this library to add a dummy fallback, that simply reads/writes |
| 108 | // to the IO provided. See: |
| 109 | // https://github.com/AlecAivazis/survey/blob/master/terminal/runereader_windows.go#L94 |
| 110 | if flag.Lookup("test.v") != nil { |
| 111 | return opts.Options[0], nil |
| 112 | } |
| 113 | |
| 114 | initialModel := selectModel{ |
| 115 | search: textinput.New(), |
| 116 | hideSearch: opts.HideSearch, |
| 117 | options: opts.Options, |
| 118 | height: opts.Size, |
| 119 | message: opts.Message, |
| 120 | } |
| 121 | |
| 122 | if initialModel.height == 0 { |
| 123 | initialModel.height = defaultSelectModelHeight |
| 124 | } |
| 125 | |
| 126 | if idx := slices.Index(opts.Options, opts.Default); idx >= 0 { |
| 127 | initialModel.cursor = idx |
| 128 | } |
| 129 | |
| 130 | initialModel.search.Prompt = "" |
| 131 | initialModel.search.Focus() |
| 132 | |
| 133 | p := tea.NewProgram( |
| 134 | initialModel, |
| 135 | tea.WithoutSignalHandler(), |
| 136 | tea.WithContext(inv.Context()), |
| 137 | tea.WithInput(inv.Stdin), |
| 138 | tea.WithOutput(inv.Stdout), |
| 139 | ) |
| 140 | |
| 141 | closeSignalHandler := installSignalHandler(p) |
| 142 | defer closeSignalHandler() |
| 143 | |
| 144 | m, err := p.Run() |
| 145 | if err != nil { |
| 146 | return "", err |
| 147 | } |
| 148 | |
| 149 | model, ok := m.(selectModel) |
| 150 | if !ok { |
| 151 | return "", xerrors.New(fmt.Sprintf("unknown model found %T (%+v)", m, m)) |
| 152 | } |
| 153 | |
| 154 | if model.canceled { |
| 155 | return "", ErrCanceled |
| 156 | } |
| 157 | |
| 158 | return model.selected, nil |
| 159 | } |
| 160 | |
| 161 | type selectModel struct { |