Skip to content

Commit

Permalink
correct input reading logic
Browse files Browse the repository at this point in the history
This addresses #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.
  • Loading branch information
mdb committed Jan 13, 2024
1 parent 5c19269 commit ed100ee
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 11 deletions.
2 changes: 1 addition & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
24 changes: 14 additions & 10 deletions reader/reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ package reader

import (
"bufio"
"errors"
"fmt"
"io"
"os"
"strings"
)

type Reader interface {
Expand All @@ -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
}

0 comments on commit ed100ee

Please sign in to comment.