From 49fbbe5545afedbd3d224a959143a46d466ea360 Mon Sep 17 00:00:00 2001 From: Martin Lindhe Date: Tue, 27 Sep 2016 15:17:34 +0200 Subject: [PATCH] also accept data from stdin --- main.go | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/main.go b/main.go index 6846bf6..4a84706 100644 --- a/main.go +++ b/main.go @@ -6,11 +6,12 @@ import ( "os" "github.com/BurntSushi/toml" + termutil "github.com/andrew-d/go-termutil" "gopkg.in/alecthomas/kingpin.v2" ) var ( - inFile = kingpin.Arg("file", "TOML file.").Required().ExistingFile() + inFile = kingpin.Arg("file", "TOML file.").String() quiet = kingpin.Flag("quiet", "Don't output on success.").Short('q').Bool() ) @@ -20,10 +21,14 @@ func main() { kingpin.CommandLine.HelpFlag.Short('h') kingpin.Parse() - data, _ := ioutil.ReadFile(*inFile) + data, err := readPipeOrFile(*inFile) + if err != nil { + fmt.Println("error:", err) + os.Exit(1) + } var f interface{} - _, err := toml.Decode(string(data), &f) + _, err = toml.Decode(string(data), &f) if err != nil { fmt.Println("ERROR:", *inFile, err) os.Exit(1) @@ -33,3 +38,14 @@ func main() { fmt.Println("OK:", *inFile) } } + +// readPipeOrFile reads from stdin if pipe exists, else from provided file +func readPipeOrFile(fileName string) ([]byte, error) { + if !termutil.Isatty(os.Stdin.Fd()) { + return ioutil.ReadAll(os.Stdin) + } + if fileName == "" { + return nil, fmt.Errorf("no piped data and no file provided") + } + return ioutil.ReadFile(fileName) +}