Skip to content

Instantly share code, notes, and snippets.

@teghnet
Last active December 12, 2021 23:20
Show Gist options
  • Save teghnet/0f598a7141cbadd9448853f206bfc2c4 to your computer and use it in GitHub Desktop.
Save teghnet/0f598a7141cbadd9448853f206bfc2c4 to your computer and use it in GitHub Desktop.
Homemade CLI Tools
// This is an example for:
// https://www.tegh.net/2021/12/12/homemade-cli-tools/
package main
import (
"errors"
"fmt"
"io"
"log"
"os"
"github.com/spf13/cobra"
)
func main() {
var name string
c := &cobra.Command{
Use: "tool",
Run: func(cmd *cobra.Command, args []string) {
if name != "" {
fmt.Println(name + ": ")
}
for _, a := range args {
fmt.Print(a, " ")
}
if len(args) > 0 {
fmt.Println()
}
file, fileClose, err := inputFileOrStdin("")
if err != nil {
log.Fatalln(err)
}
defer fileClose()
b, err := io.ReadAll(file)
if err != nil {
log.Fatalln(err)
}
fmt.Println(string(b))
},
}
c.Flags().StringVarP(
&name, // a pointer to the variable to be set
"name", // the name of the flag (use it with `double dash`)
"n", // a short name of the flag (to be used with a single `dash`)
"", // the default value
"a name", // a short usage description
)
if err := c.Execute(); err != nil {
os.Exit(1)
}
}
func inputFileOrStdin(inputFilePath string) (*os.File, func() error, error) {
if inputFilePath != "" {
file, err := os.Open(inputFilePath)
if err != nil {
return nil, nil, err
}
return file, file.Close, nil
}
fi, err := os.Stdin.Stat()
if err != nil {
return nil, nil, err
}
if fi.Size() == 0 && fi.Mode()&os.ModeNamedPipe == 0 {
return nil, nil, errors.New("no input file provided and stdin is empty")
}
log.Println("os.Stdin size:", fi.Size())
return os.Stdin, func() error { return nil }, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment