glow/main.go

92 lines
1.6 KiB
Go
Raw Normal View History

2019-11-04 23:17:36 +00:00
package main
import (
"errors"
2019-11-04 23:17:36 +00:00
"fmt"
"io"
2019-11-09 22:12:54 +00:00
"io/ioutil"
"net/http"
"net/url"
2019-11-09 20:07:01 +00:00
"os"
"strings"
2019-11-04 23:17:36 +00:00
"github.com/spf13/cobra"
2019-11-15 18:35:04 +00:00
"github.com/charmbracelet/gold"
2019-11-04 23:17:36 +00:00
)
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
}
if u, err := url.ParseRequestURI(s); err == nil {
if !strings.HasPrefix(u.Scheme, "http") {
return nil, fmt.Errorf("%s is not a supported protocol", u.Scheme)
}
if isGitHubURL(s) {
resp, err := findGitHubREADME(s)
if err != nil {
return nil, err
}
return resp.Body, nil
}
resp, err := http.Get(u.String())
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("HTTP status %d", resp.StatusCode)
}
return resp.Body, nil
}
return os.Open(s)
}
func execute(args []string) error {
2019-11-09 22:12:54 +00:00
if len(args) != 1 {
return errors.New("missing markdown source")
2019-11-09 22:12:54 +00:00
}
in, err := readerFromArgument(args[0])
if err != nil {
return err
2019-11-09 22:12:54 +00:00
}
defer in.Close()
b, _ := ioutil.ReadAll(in)
out, err := gold.RenderBytes(b, style)
2019-11-09 20:07:01 +00:00
if err != nil {
return err
2019-11-09 20:07:01 +00:00
}
2019-11-09 22:12:54 +00:00
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")
2019-11-04 23:17:36 +00:00
}