prompt.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package prompt
  14. import (
  15. "github.com/AlecAivazis/survey/v2"
  16. )
  17. //go:generate mockgen -destination=./prompt_mock.go -self_package "github.com/docker/compose/v2/pkg/prompt" -package=prompt . UI
  18. // UI - prompt user input
  19. type UI interface {
  20. Select(message string, options []string) (int, error)
  21. Input(message string, defaultValue string) (string, error)
  22. Confirm(message string, defaultValue bool) (bool, error)
  23. Password(message string) (string, error)
  24. }
  25. // User - aggregates prompt methods
  26. type User struct{}
  27. // Select - displays a list
  28. func (u User) Select(message string, options []string) (int, error) {
  29. qs := &survey.Select{
  30. Message: message,
  31. Options: options,
  32. }
  33. var selected int
  34. err := survey.AskOne(qs, &selected, nil)
  35. return selected, err
  36. }
  37. // Input text with default value
  38. func (u User) Input(message string, defaultValue string) (string, error) {
  39. qs := &survey.Input{
  40. Message: message,
  41. Default: defaultValue,
  42. }
  43. var s string
  44. err := survey.AskOne(qs, &s, nil)
  45. return s, err
  46. }
  47. // Confirm asks for yes or no input
  48. func (u User) Confirm(message string, defaultValue bool) (bool, error) {
  49. qs := &survey.Confirm{
  50. Message: message,
  51. Default: defaultValue,
  52. }
  53. var b bool
  54. err := survey.AskOne(qs, &b, nil)
  55. return b, err
  56. }
  57. // Password implements a text input with masked characters.
  58. func (u User) Password(message string) (string, error) {
  59. qs := &survey.Password{
  60. Message: message,
  61. }
  62. var p string
  63. err := survey.AskOne(qs, &p, nil)
  64. return p, err
  65. }