github.com/lelandbatey/lab@v0.12.1-0.20180712064405-55bfd303a5f0/internal/config/config.go (about) 1 package config 2 3 import ( 4 "bufio" 5 "errors" 6 "fmt" 7 "io" 8 "net/url" 9 "strings" 10 "syscall" 11 12 "github.com/spf13/viper" 13 "golang.org/x/crypto/ssh/terminal" 14 ) 15 16 const defaultGitLabHost = "https://gitlab.com" 17 18 // New prompts the user for the default config values to use with lab, and save 19 // them to the provided confpath (default: ~/.config/lab.hcl) 20 func New(confpath string, r io.Reader) error { 21 var ( 22 reader = bufio.NewReader(r) 23 host, user, token string 24 err error 25 ) 26 fmt.Printf("Enter default GitLab host (default: %s): ", defaultGitLabHost) 27 host, err = reader.ReadString('\n') 28 host = strings.TrimSpace(host) 29 if err != nil { 30 return err 31 } 32 if host == "" { 33 host = defaultGitLabHost 34 } 35 36 fmt.Print("Enter default GitLab user: ") 37 user, err = reader.ReadString('\n') 38 user = strings.TrimSpace(user) 39 if err != nil { 40 return err 41 } 42 if user == "" { 43 return errors.New("lab.hcl config core.user must be set") 44 } 45 46 tokenURL, err := url.Parse(host) 47 if err != nil { 48 return err 49 } 50 tokenURL.Path = "profile/personal_access_tokens" 51 52 fmt.Printf("Create a token here: %s\nEnter default GitLab token (scope: api): ", tokenURL.String()) 53 token, err = readPassword() 54 if err != nil { 55 return err 56 } 57 58 viper.Set("core.host", host) 59 viper.Set("core.user", user) 60 viper.Set("core.token", token) 61 if err := viper.WriteConfigAs(confpath); err != nil { 62 return err 63 } 64 fmt.Printf("\nConfig saved to %s\n", confpath) 65 return nil 66 } 67 68 var readPassword = func() (string, error) { 69 byteToken, err := terminal.ReadPassword(int(syscall.Stdin)) 70 if err != nil { 71 return "", err 72 } 73 return strings.TrimSpace(string(byteToken)), nil 74 }