github.com/jlmeeker/kismatic@v1.10.1-0.20180612190640-57f9005a1f1a/pkg/util/io.go (about) 1 package util 2 3 import ( 4 "bufio" 5 "encoding/base64" 6 "fmt" 7 "io" 8 "io/ioutil" 9 "os" 10 "strconv" 11 "strings" 12 ) 13 14 // PromptForInt read command line input 15 func PromptForInt(in io.Reader, out io.Writer, prompt string, defaultValue int) (int, error) { 16 fmt.Fprintf(out, "=> %s [%d]: ", prompt, defaultValue) 17 s := bufio.NewScanner(in) 18 // Scan the first token 19 s.Scan() 20 if s.Err() != nil { 21 return defaultValue, fmt.Errorf("error reading number: %v", s.Err()) 22 } 23 ans := s.Text() 24 if ans == "" { 25 return defaultValue, nil 26 } 27 // Convert input into integer 28 i, err := strconv.Atoi(ans) 29 if err != nil { 30 return defaultValue, fmt.Errorf("%q is not a number", ans) 31 } 32 return i, nil 33 } 34 35 func PromptForString(in io.Reader, out io.Writer, prompt string, defaultValue string, choices []string) (string, error) { 36 fmt.Fprintf(out, "=> %s [%s]: ", prompt, strings.Join(choices, "/")) 37 s := bufio.NewScanner(in) 38 // Scan the first token 39 s.Scan() 40 if s.Err() != nil { 41 return defaultValue, fmt.Errorf("error reading string: %v", s.Err()) 42 } 43 ans := s.Text() 44 if ans == "" { 45 return defaultValue, nil 46 } 47 if !Contains(ans, choices) { 48 return defaultValue, fmt.Errorf("error, %s is not a valid option %v", ans, choices) 49 } 50 return ans, nil 51 } 52 53 // CreateDir check if directory exists and create it 54 func CreateDir(dir string, perm os.FileMode) error { 55 if _, err := os.Stat(dir); os.IsNotExist(err) { 56 err := os.Mkdir(dir, perm) 57 if err != nil { 58 return fmt.Errorf("error creating destination dir: %v", err) 59 } 60 } 61 62 return nil 63 } 64 65 // Base64String read file and return base64 string 66 func Base64String(path string) (string, error) { 67 file, err := ioutil.ReadFile(path) 68 if err != nil { 69 return "", err 70 } 71 fileEncoded := base64.StdEncoding.EncodeToString(file) 72 73 return fileEncoded, nil 74 }