diff --git a/src/main.go b/src/main.go index 6484d6a..93f0197 100644 --- a/src/main.go +++ b/src/main.go @@ -1,7 +1,6 @@ package main import ( - "bufio" "flag" "fmt" "log" @@ -94,16 +93,9 @@ func main() { log.Fatal("Failed to open auth file: ", err) } defer f.Close() - scanner := bufio.NewScanner(f) - for scanner.Scan() { - line := scanner.Text() - parts := strings.Split(line, ":") - if len(parts) != 2 { - log.Fatalf("Invalid auth: %v (expected `username:password`)", line) - } - username = parts[0] - password = parts[1] - break + username, password, err = parseAuthfile(f) + if err != nil { + log.Fatal("Failed to parse auth file: ", err) } } diff --git a/src/password.go b/src/password.go new file mode 100644 index 0000000..8bfc36a --- /dev/null +++ b/src/password.go @@ -0,0 +1,23 @@ +package main + +import ( + "bufio" + "fmt" + "io" + "strings" +) + +func parseAuthfile(authfile io.Reader) (username, password string, err error) { + scanner := bufio.NewScanner(authfile) + for scanner.Scan() { + line := scanner.Text() + parts := strings.SplitN(line, ":", 2) + if len(parts) != 2 { + return "", "", fmt.Errorf("wrong syntax (expected `username:password`)") + } + username = parts[0] + password = parts[1] + break + } + return username, password, nil +} diff --git a/src/password_test.go b/src/password_test.go new file mode 100644 index 0000000..eed0059 --- /dev/null +++ b/src/password_test.go @@ -0,0 +1,47 @@ +package main + +import ( + "strings" + "testing" +) + +func TestPasswordFromAuthfile(t *testing.T) { + for _, tc := range [...]struct { + authfile string + expectedUsername string + expectedPassword string + expectedError bool + }{ + { + authfile: "username:password", + expectedUsername: "username", + expectedPassword: "password", + expectedError: false, + }, + { + authfile: "username-and-no-password", + expectedError: true, + }, + { + authfile: "username:password:with:columns", + expectedUsername: "username", + expectedPassword: "password:with:columns", + expectedError: false, + }, + } { + t.Run(tc.authfile, func(t *testing.T) { + username, password, err := parseAuthfile(strings.NewReader(tc.authfile)) + if tc.expectedUsername != username { + t.Errorf("expected username %q, got %q", tc.expectedUsername, username) + } + if tc.expectedPassword != password { + t.Errorf("expected password %q, got %q", tc.expectedPassword, password) + } + if tc.expectedError && err == nil { + t.Errorf("expected error, got nil") + } else if !tc.expectedError && err != nil { + t.Errorf("unexpected error: %v", err) + } + }) + } +}