From ed100ee0d20d1a7058d82652562bbf5a95f1b64b Mon Sep 17 00:00:00 2001 From: Mike Ball Date: Sat, 13 Jan 2024 12:48:52 -0500 Subject: [PATCH] correct input reading logic This addresses https://github.com/dineshba/tf-summarize/issues/20 and ensures input is read from the plan file -- and not via STDIN -- if a plan file argument is provided. This also seeks to improve some of the error messaging to be a bit more clear. --- main.go | 2 +- reader/reader.go | 24 ++++++++++++++---------- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/main.go b/main.go index 5fc1815..91223be 100644 --- a/main.go +++ b/main.go @@ -37,7 +37,7 @@ func main() { err := validateFlags(*tree, *separateTree, *drawable, *md, args) logIfErrorAndExit("invalid input flags: %s\n", err, flag.Usage) - newReader, err := reader.CreateReader(os.Stdin, args) + newReader, err := reader.CreateReader(args) logIfErrorAndExit("error creating input reader: %s\n", err, flag.Usage) input, err := newReader.Read() diff --git a/reader/reader.go b/reader/reader.go index 5caead1..4319fa3 100644 --- a/reader/reader.go +++ b/reader/reader.go @@ -2,9 +2,10 @@ package reader import ( "bufio" + "errors" "fmt" "io" - "os" + "strings" ) type Reader interface { @@ -22,19 +23,22 @@ func readFile(f io.Reader) ([]byte, error) { input = append(input, line...) } if err != io.EOF { - return nil, fmt.Errorf("error reading file: %s", err.Error()) + return nil, fmt.Errorf("error reading input: %s", err.Error()) + } + if len(input) == 0 { + return nil, errors.New("no input data; expected input via a non-empty file or via STDIN") } return input, nil } -func CreateReader(stdin *os.File, args []string) (Reader, error) { - stat, _ := stdin.Stat() - if (stat.Mode() & os.ModeCharDevice) == 0 { - return NewStdinReader(), nil +func CreateReader(args []string) (Reader, error) { + if len(args) > 1 { + return nil, fmt.Errorf("expected input via a single filename argument or via STDIN; received multiple arguments: %s", strings.Join(args, ", ")) } - if len(args) < 1 { - return nil, fmt.Errorf("should have either stdin input through pipe or first argument should be file") + + if len(args) == 1 { + return NewFileReader(args[0]), nil } - fileName := args[0] - return NewFileReader(fileName), nil + + return NewStdinReader(), nil }