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 package main
import ( import (
"git.binarythought.com/cdramey/sutron"
"fmt"
"bytes" "bytes"
"flag"
"fmt"
"encoding/json"
"git.binarythought.com/cdramey/sutron"
"io/ioutil" "io/ioutil"
"os" "os"
) )
type ParserConfig struct {
ParserType string `json:"parser_type"`
}
func main() { func main() {
if len(os.Args) < 2 { flags := flag.NewFlagSet("sutron", flag.ExitOnError)
fmt.Fprintf(os.Stderr, flags.SetOutput(os.Stdout)
"required argument missing\n") 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) 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 raw []byte
var err error var err error
if os.Args[1] == "-" { if fn == "-" {
raw, err = ioutil.ReadAll(os.Stdin) raw, err = ioutil.ReadAll(os.Stdin)
} else { } else {
raw, err = ioutil.ReadFile(os.Args[1]) raw, err = ioutil.ReadFile(fn)
} }
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, fmt.Fprintf(os.Stderr,
@ -42,4 +79,5 @@ func main() {
fmt.Printf("Sutron Delta: %s\n", string(sutrondata.Delta)) fmt.Printf("Sutron Delta: %s\n", string(sutrondata.Delta))
fmt.Printf("Sutron Voltage: %s\n", string(sutrondata.Voltage)) fmt.Printf("Sutron Voltage: %s\n", string(sutrondata.Voltage))
} }
}
} }

View File

@ -40,7 +40,7 @@ func ParseSutronB(raw []byte) (*SutronB, error) {
data.Block = raw[0] data.Block = raw[0]
data.Group = raw[1] data.Group = raw[1]
data.Delta = raw[2] data.Delta = raw[2]
data.Data = raw[3:raw_len - 1] data.Data = raw[3 : raw_len-1]
data.Voltage = raw[raw_len - 1] data.Voltage = raw[raw_len-1]
return &data, nil return &data, nil
} }