Skip to content

Commit

Permalink
Add hex cmd
Browse files Browse the repository at this point in the history
  • Loading branch information
aburdulescu committed Mar 24, 2024
1 parent f6d7525 commit bebec1a
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
62 changes: 62 additions & 0 deletions internal/misc/hex.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package misc

import (
"encoding/hex"
"fmt"

"bandr.me/p/pocryp/internal/cli/cmd"
"bandr.me/p/pocryp/internal/util/stdfile"
)

var HexCmd = &cmd.Command{
Name: "hex",
Run: runHex,
Brief: "Hex encode or decode",

Usage: `Usage: pocryp hex [-in INPUT] [-out OUTPUT]
Hex encode or decode(if -d is specified) input to output.
If -in is not specified, stdin will be read.
If -out is not specified, the output will be printed to stdout.
`,
}

func runHex(cmd *cmd.Command) error {
fOutput := cmd.Flags.String("out", "", "Write the result to the file at path OUTPUT.")
fInput := cmd.Flags.String("in", "", "Read data from the file at path INPUT.")
fDecode := cmd.Flags.Bool("d", false, "Decode data.")

if isHelp, err := cmd.Parse(); err != nil {
if isHelp {
return nil
}
return err
}

sf, err := stdfile.New(*fInput, *fOutput)
if err != nil {
return err
}
defer sf.Close()

input, err := sf.Read()
if err != nil {
return err
}

var output string
if *fDecode {
b, err := hex.DecodeString(string(input))
if err != nil {
return fmt.Errorf("failed to decode input: %w", err)
}
output = string(b)
} else {
output = hex.EncodeToString(input)
}

fmt.Fprint(sf.Out, output)

return nil
}
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ func main() {
a.Add(
"Miscellaneous",
misc.Base64Cmd,
misc.HexCmd,
)

if err := a.Run(os.Args[1:]...); err != nil {
Expand Down

0 comments on commit bebec1a

Please sign in to comment.