From c85c38df76f6329af4bce3ac3d079c722fb7f388 Mon Sep 17 00:00:00 2001 From: blinkthethings Date: Fri, 25 Dec 2020 11:27:57 -0500 Subject: [PATCH] Add modhex cli --- cmd/modhex.go | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 cmd/modhex.go diff --git a/cmd/modhex.go b/cmd/modhex.go new file mode 100644 index 0000000..20ec8b8 --- /dev/null +++ b/cmd/modhex.go @@ -0,0 +1,81 @@ +package main + +import ( + "encoding/hex" + "flag" + "fmt" + "os" + "strings" + + "git.trashheap.io/blinkthethings/modhex" +) + +func main() { + // configure command line flags + var decode, hexdata bool + flag.BoolVar(&decode, "d", false, "decode data (the default is to encode).") + flag.BoolVar(&hexdata, "x", false, "Use hex encoding for non-modhex data.") + flag.Usage = func() { + fmt.Println("modhex - encode/decode data using modhex encoding.") + fmt.Println() + fmt.Println("Usage:\n\n modex [-d] [-x] ") + fmt.Println() + fmt.Println(" Convert input DATA as specified and print output to STDOUT.") + fmt.Println() + fmt.Printf("Flags:\n\n") + flag.PrintDefaults() + fmt.Println() + } + flag.Parse() + + if decode { + // decode was selected + + // read the modhex string from the command line + src := []byte(strings.Join(flag.Args(), " ")) + + // create a buffer to hold the decoded data + dst := make([]byte, modhex.DecodedLen(len(src))) + + // decode the input + _, err := modhex.Decode(dst, src) + if err != nil { + // report the error to the user + fmt.Fprintln(os.Stderr, err) + os.Exit(-1) + } + + // should the output be a hex string? + if hexdata { + // print out the decoded data as a hex string + fmt.Println(hex.EncodeToString(src)) + } else { + // print out the decoded bytes stdout + os.Stdout.Write(dst) + } + } else { + // encode was selected + + // read the input data + var src []byte + if hexdata { + // read the input as a hex string + var err error + src, err = hex.DecodeString(flag.Arg(0)) + if err != nil { + // report the hex decode error and exit + fmt.Fprintf(os.Stderr, "modhex: %s\n", err) + os.Exit(-1) + } + } else { + // read the input as bytes + src = []byte(strings.Join(flag.Args(), "")) + } + + // encode the input + s := modhex.EncodeToString(src) + + // print out the modhex encoded string + fmt.Println(s) + } +}