diff --git a/exercism.go b/exercism.go index b5151a81..557257f2 100644 --- a/exercism.go +++ b/exercism.go @@ -1,10 +1,12 @@ package main import ( + "bufio" "fmt" "github.com/exercism/cli/configuration" "os" "path/filepath" + "strings" ) func logout(path string) { @@ -21,6 +23,9 @@ func absolutePath(path string) (string, error) { func askForConfigInfo() (c configuration.Config) { var un, key, dir string + delim := "\r\n" + + bio := bufio.NewReader(os.Stdin) currentDir, err := os.Getwd() if err != nil { @@ -28,13 +33,13 @@ func askForConfigInfo() (c configuration.Config) { } fmt.Print("Your GitHub username: ") - _, err = fmt.Scanln(&un) + un, err = bio.ReadString('\n') if err != nil { panic(err) } fmt.Print("Your exercism.io API key: ") - _, err = fmt.Scanln(&key) + key, err = bio.ReadString('\n') if err != nil { panic(err) } @@ -42,11 +47,15 @@ func askForConfigInfo() (c configuration.Config) { fmt.Println("What is your exercism exercises project path?") fmt.Printf("Press Enter to select the default (%s):\n", currentDir) fmt.Print("> ") - _, err = fmt.Scanln(&dir) + dir, err = bio.ReadString('\n') if err != nil && err.Error() != "unexpected newline" { panic(err) } + key = strings.TrimRight(key, delim) + un = strings.TrimRight(un, delim) + dir = strings.TrimRight(dir, delim) + if dir == "" { dir = currentDir } diff --git a/exercism_test.go b/exercism_test.go index 42b88488..de9f2d12 100644 --- a/exercism_test.go +++ b/exercism_test.go @@ -1,6 +1,7 @@ package main import ( + "fmt" "github.com/exercism/cli/configuration" "github.com/stretchr/testify/assert" "io/ioutil" @@ -28,3 +29,35 @@ func TestLogoutDeletesConfigFile(t *testing.T) { asserFileDoesNotExist(t, configuration.Filename(tmpDir)) } + +func TestAskForConfigInfoAllowsSpaces(t *testing.T) { + oldStdin := os.Stdin + dirName := "dirname with spaces" + userName := "TestUsername" + apiKey := "abc123" + + fakeStdin, err := ioutil.TempFile("", "stdin_mock") + assert.NoError(t, err) + + fakeStdin.WriteString(fmt.Sprintf("%s\r\n%s\r\n%s\r\n", userName, apiKey, dirName)) + assert.NoError(t, err) + + file, err := os.Open(fakeStdin.Name()) + defer file.Close() + + os.Stdin = file + + c := askForConfigInfo() + os.Stdin = oldStdin + absoluteDirName, _ := absolutePath(dirName) + _, err = os.Stat(absoluteDirName) + if err != nil { + t.Errorf("Excercism directory [%s] was not created.", absoluteDirName) + } + os.Remove(absoluteDirName) + os.Remove(fakeStdin.Name()) + + assert.Equal(t, c.ExercismDirectory, absoluteDirName) + assert.Equal(t, c.GithubUsername, userName) + assert.Equal(t, c.ApiKey, apiKey) +}