From 16048357a02701732d56e1f05709bca3c574e112 Mon Sep 17 00:00:00 2001 From: Christian Muehlhaeuser Date: Fri, 22 Nov 2019 04:44:54 +0100 Subject: [PATCH] Use cobra to handle command line parameters --- main.go | 45 +++++++++++++++++++++++++++++++++------------ 1 file changed, 33 insertions(+), 12 deletions(-) diff --git a/main.go b/main.go index 853fe1a..90b2ab0 100644 --- a/main.go +++ b/main.go @@ -1,15 +1,31 @@ package main import ( - "flag" + "errors" "fmt" "io" "io/ioutil" "os" + "github.com/spf13/cobra" + "github.com/charmbracelet/gold" ) +var ( + rootCmd = &cobra.Command{ + Use: "gold SOURCE", + Short: "Render markdown on the CLI, with pizzazz!", + SilenceErrors: false, + SilenceUsage: false, + RunE: func(cmd *cobra.Command, args []string) error { + return execute(args) + }, + } + + style string +) + func readerFromArgument(s string) (io.ReadCloser, error) { if s == "-" { return os.Stdin, nil @@ -26,27 +42,32 @@ func readerFromArgument(s string) (io.ReadCloser, error) { return os.Open(s) } -func main() { - s := flag.String("s", "", "style json path") - flag.Parse() - args := flag.Args() +func execute(args []string) error { if len(args) != 1 { - fmt.Println("Missing Markdown file. Usage: ./gold -s STYLE.json FILE.md") - os.Exit(1) + return errors.New("missing markdown source") } in, err := readerFromArgument(args[0]) if err != nil { - fmt.Println(err) - os.Exit(1) + return err } defer in.Close() b, _ := ioutil.ReadAll(in) - out, err := gold.RenderBytes(b, *s) + out, err := gold.RenderBytes(b, style) if err != nil { - fmt.Println(err) - os.Exit(1) + return err } fmt.Printf("%s", string(out)) + return nil +} + +func main() { + if err := rootCmd.Execute(); err != nil { + os.Exit(-1) + } +} + +func init() { + rootCmd.Flags().StringVarP(&style, "style", "s", "dark.json", "style JSON path") }