github.com/1aal/kubeblocks@v0.0.0-20231107070852-e1c03e598921/pkg/cli/util/prompt/prompt.go (about) 1 /* 2 Copyright (C) 2022-2023 ApeCloud Co., Ltd 3 4 This file is part of KubeBlocks project 5 6 This program is free software: you can redistribute it and/or modify 7 it under the terms of the GNU Affero General Public License as published by 8 the Free Software Foundation, either version 3 of the License, or 9 (at your option) any later version. 10 11 This program is distributed in the hope that it will be useful 12 but WITHOUT ANY WARRANTY; without even the implied warranty of 13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 GNU Affero General Public License for more details. 15 16 You should have received a copy of the GNU Affero General Public License 17 along with this program. If not, see <http://www.gnu.org/licenses/>. 18 */ 19 20 package prompt 21 22 import ( 23 "fmt" 24 "io" 25 "sort" 26 "strings" 27 28 "github.com/manifoldco/promptui" 29 "golang.org/x/exp/slices" 30 ) 31 32 func NewPrompt(label string, validate promptui.ValidateFunc, in io.Reader) *promptui.Prompt { 33 template := &promptui.PromptTemplates{ 34 Prompt: "{{ . }} ", 35 Valid: "{{ . | green }} ", 36 Invalid: "{{ . | red }} ", 37 Success: "{{ . | bold }} ", 38 } 39 40 if validate == nil { 41 template = &promptui.PromptTemplates{ 42 Prompt: "{{ . }} ", 43 Valid: "{{ . | red }} ", 44 Invalid: "{{ . | red }} ", 45 Success: "{{ . | bold }} ", 46 } 47 } 48 p := promptui.Prompt{ 49 Label: label, 50 Stdin: io.NopCloser(in), 51 Templates: template, 52 Validate: validate, 53 } 54 return &p 55 } 56 57 // Confirm let user double-check for the cluster ops 58 // use customMessage to display more information 59 // when names are empty, require validation for 'yes'. 60 func Confirm(names []string, in io.Reader, customMessage string, prompt string) error { 61 if len(names) == 0 { 62 names = []string{"yes"} 63 } 64 if len(customMessage) != 0 { 65 fmt.Println(customMessage) 66 } 67 if prompt == "" { 68 prompt = "Please type the name again(separate with white space when more than one):" 69 } 70 _, err := NewPrompt(prompt, 71 func(entered string) error { 72 if len(names) == 1 && names[0] == "yes" { 73 entered = strings.ToLower(entered) 74 } 75 enteredNames := strings.Split(entered, " ") 76 sort.Strings(names) 77 sort.Strings(enteredNames) 78 if !slices.Equal(names, enteredNames) { 79 return fmt.Errorf("typed \"%s\" does not match \"%s\"", entered, strings.Join(names, " ")) 80 } 81 return nil 82 }, in).Run() 83 return err 84 }