Use cobra to handle command line parameters

This commit is contained in:
Christian Muehlhaeuser 2019-11-22 04:44:54 +01:00
parent b58f777e91
commit 16048357a0

45
main.go
View file

@ -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")
}