From 91a2fd4f5dd68a90062f936123d4dfbabdfb12eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eric=20Rockst=C3=A4dt?= Date: Tue, 24 Oct 2023 23:30:55 +0200 Subject: [PATCH] Handle error when reading user input --- cmd/validate.go | 7 +++---- cmd/validate_test.go | 15 +++++++++++++-- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/cmd/validate.go b/cmd/validate.go index 7cfcebb..9f66b2c 100644 --- a/cmd/validate.go +++ b/cmd/validate.go @@ -4,7 +4,6 @@ import ( "fmt" "github.com/TwiN/go-color" "github.com/rockstaedt/txtreader" - "log" "rockstaedt/commit-message-check/internal/model" ) @@ -31,9 +30,9 @@ func (h *Handler) validate() int { h.notify("Subject line too long. Do you want to abort? (y/n)", "red") var decision string - _, err := fmt.Fscanln(h.Reader, &decision) - if err != nil { - log.Fatal(err) + if _, err := fmt.Fscanln(h.Reader, &decision); err != nil { + h.notify("Could not read user input.", "red") + return 1 } if decision == "y" { diff --git a/cmd/validate_test.go b/cmd/validate_test.go index 20cfcfc..4ed2a2d 100644 --- a/cmd/validate_test.go +++ b/cmd/validate_test.go @@ -49,7 +49,7 @@ func TestValidate(t *testing.T) { handler := NewHandler(model.Config{CommitMsgFile: testFile}) handler.Writer = buffer - t.Run("user confirms abort", func(t *testing.T) { + t.Run("user confirms abort returns 1", func(t *testing.T) { buffer.Reset() handler.Reader = bytes.NewReader([]byte("y")) @@ -58,7 +58,8 @@ func TestValidate(t *testing.T) { assert.Contains(t, buffer.String(), color.Red+"Subject line too long. Do you want to abort? (y/n)") assert.Equal(t, 1, status) }) - t.Run("user declines abort", func(t *testing.T) { + + t.Run("user declines abort returns 0", func(t *testing.T) { buffer.Reset() handler.Reader = bytes.NewReader([]byte("n")) @@ -66,6 +67,16 @@ func TestValidate(t *testing.T) { assert.Equal(t, 0, status) }) + + t.Run("error at reading user input returns 1", func(t *testing.T) { + buffer.Reset() + handler.Reader = bytes.NewReader([]byte("")) + + status := handler.Run("validate") + + assert.Equal(t, 1, status) + assert.Contains(t, buffer.String(), color.Red+"Could not read user input.") + }) }) t.Run("returns 1 when error at reading file", func(t *testing.T) {