mirror of
https://github.com/charmbracelet/glow
synced 2024-09-20 06:22:02 +00:00
Use cobra to handle command line parameters
This commit is contained in:
parent
b58f777e91
commit
16048357a0
1 changed files with 33 additions and 12 deletions
45
main.go
45
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")
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue