glow/main.go

107 lines
1.8 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"
2019-11-04 23:17:36 +00:00
"github.com/mattn/go-isatty"
"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 (
readmeNames = []string{"README.md", "README"}
rootCmd = &cobra.Command{
Use: "gold SOURCE",
Short: "Render markdown on the CLI, with pizzazz!",
SilenceErrors: false,
SilenceUsage: false,
2019-11-24 01:40:29 +00:00
RunE: execute,
}
style string
)
2019-11-24 01:40:29 +00:00
func readerFromArg(s string) (io.ReadCloser, error) {
if s == "-" {
return os.Stdin, nil
}
2019-11-25 03:55:09 +00:00
if u, ok := isGitHubURL(s); ok {
resp, err := findGitHubREADME(u)
if err != nil {
return nil, err
}
return resp.Body, nil
}
if u, err := url.ParseRequestURI(s); err == nil {
if u.Scheme != "http" && u.Scheme != "https" {
return nil, fmt.Errorf("%s is not a supported protocol", u.Scheme)
}
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
}
if len(s) == 0 {
for _, v := range readmeNames {
r, err := os.Open(v)
if err == nil {
return r, nil
}
}
return nil, errors.New("missing markdown source")
}
return os.Open(s)
}
2019-11-24 01:40:29 +00:00
func execute(cmd *cobra.Command, args []string) error {
var arg string
if len(args) > 0 {
arg = args[0]
2019-11-09 22:12:54 +00:00
}
in, err := readerFromArg(arg)
if err != nil {
return err
2019-11-09 22:12:54 +00:00
}
defer in.Close()
b, _ := ioutil.ReadAll(in)
r := gold.NewPlainTermRenderer()
if isatty.IsTerminal(os.Stdout.Fd()) {
r, err = gold.NewTermRenderer(style)
if err != nil {
return err
}
2019-11-09 20:07:01 +00:00
}
out := r.RenderBytes(b)
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
}