Improved command line parsing, started on json-based parsing instructions

This commit is contained in:
Christopher Ramey 2019-10-06 20:16:19 -08:00 committed by Christopher Ramey
parent 6a9d3e1a0f
commit e64fae50b0
2 changed files with 65 additions and 27 deletions

View File

@ -1,26 +1,63 @@
package main
import (
"git.binarythought.com/cdramey/sutron"
"fmt"
"bytes"
"flag"
"fmt"
"encoding/json"
"git.binarythought.com/cdramey/sutron"
"io/ioutil"
"os"
)
type ParserConfig struct {
ParserType string `json:"parser_type"`
}
func main() {
if len(os.Args) < 2 {
fmt.Fprintf(os.Stderr,
"required argument missing\n")
flags := flag.NewFlagSet("sutron", flag.ExitOnError)
flags.SetOutput(os.Stdout)
flags.Usage = func() {
fmt.Fprintf(flags.Output(),
"Usage: %s [OPTION] <files> ...\nOptions:\n",
os.Args[0])
flags.PrintDefaults()
}
jsonfn := flags.String("json", "sutron.json",
"json parser definition file name")
flags.Parse(os.Args[1:])
if flags.NArg() < 1 {
fmt.Fprintf(os.Stderr, "files parameter cannot be empty\n")
os.Exit(1)
}
jsonsrc, err := ioutil.ReadFile(*jsonfn)
if err != nil {
fmt.Fprintf(os.Stderr,
"error reading \"%s\": %s\n",
os.Args[1], err.Error())
}
var pcfg ParserConfig
err = json.Unmarshal(jsonsrc, &pcfg)
if err != nil {
fmt.Fprintf(os.Stderr,
"parser config error: %s\n", err.Error())
os.Exit(1)
}
fmt.Printf("Parser type: %s\n", pcfg.ParserType)
for _, fn := range flags.Args() {
var raw []byte
var err error
if os.Args[1] == "-" {
if fn == "-" {
raw, err = ioutil.ReadAll(os.Stdin)
} else {
raw, err = ioutil.ReadFile(os.Args[1])
raw, err = ioutil.ReadFile(fn)
}
if err != nil {
fmt.Fprintf(os.Stderr,
@ -43,3 +80,4 @@ func main() {
fmt.Printf("Sutron Voltage: %s\n", string(sutrondata.Voltage))
}
}
}