diff --git a/encode.go b/encode.go index debec81..c8090b2 100644 --- a/encode.go +++ b/encode.go @@ -31,7 +31,7 @@ var encode = &cli.Command{ Name: "npub", Usage: "encode a hex private key into bech32 'npub' format", Action: func(c *cli.Context) error { - target := c.Args().First() + target := getStdinOrFirstArgument(c) if err := validate32BytesHex(target); err != nil { return err } @@ -48,7 +48,7 @@ var encode = &cli.Command{ Name: "nsec", Usage: "encode a hex private key into bech32 'nsec' format", Action: func(c *cli.Context) error { - target := c.Args().First() + target := getStdinOrFirstArgument(c) if err := validate32BytesHex(target); err != nil { return err } @@ -72,7 +72,7 @@ var encode = &cli.Command{ }, }, Action: func(c *cli.Context) error { - target := c.Args().First() + target := getStdinOrFirstArgument(c) if err := validate32BytesHex(target); err != nil { return err } @@ -105,7 +105,7 @@ var encode = &cli.Command{ }, }, Action: func(c *cli.Context) error { - target := c.Args().First() + target := getStdinOrFirstArgument(c) if err := validate32BytesHex(target); err != nil { return err } @@ -191,7 +191,7 @@ var encode = &cli.Command{ Name: "note", Usage: "generate note1 event codes (not recommended)", Action: func(c *cli.Context) error { - target := c.Args().First() + target := getStdinOrFirstArgument(c) if err := validate32BytesHex(target); err != nil { return err } diff --git a/fetch.go b/fetch.go index e6dc299..fa284be 100644 --- a/fetch.go +++ b/fetch.go @@ -17,7 +17,7 @@ var fetch = &cli.Command{ ArgsUsage: "[nip19code]", Action: func(c *cli.Context) error { filter := nostr.Filter{} - code := c.Args().First() + code := getStdinOrFirstArgument(c) prefix, value, err := nip19.Decode(code) if err != nil { diff --git a/helpers.go b/helpers.go new file mode 100644 index 0000000..d71c02a --- /dev/null +++ b/helpers.go @@ -0,0 +1,29 @@ +package main + +import ( + "bytes" + "io" + "os" + + "github.com/urfave/cli/v2" +) + +func getStdin() string { + stat, _ := os.Stdin.Stat() + if (stat.Mode() & os.ModeCharDevice) == 0 { + read := bytes.NewBuffer(make([]byte, 0, 1000)) + _, err := io.Copy(read, os.Stdin) + if err == nil { + return read.String() + } + } + return "" +} + +func getStdinOrFirstArgument(c *cli.Context) string { + target := c.Args().First() + if target != "" { + return target + } + return getStdin() +}