Skip to content

Commit

Permalink
Merge pull request sequelize#68 from Tonkpils/fix-panic
Browse files Browse the repository at this point in the history
Use bufio.ReadString to read user input.
  • Loading branch information
kytrinyx committed Mar 16, 2014
2 parents da145a6 + 157f69e commit 621f41d
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 3 deletions.
15 changes: 12 additions & 3 deletions exercism.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package main

import (
"bufio"
"fmt"
"github.com/exercism/cli/configuration"
"os"
"path/filepath"
"strings"
)

func logout(path string) {
Expand All @@ -21,32 +23,39 @@ 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 {
panic(err)
}

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)
}

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
}
Expand Down
33 changes: 33 additions & 0 deletions exercism_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"fmt"
"github.com/exercism/cli/configuration"
"github.com/stretchr/testify/assert"
"io/ioutil"
Expand Down Expand Up @@ -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)
}

0 comments on commit 621f41d

Please sign in to comment.