Support fetching READMEs from GitHub

When passing a valid GitHub URL instead of a filename to gold,
it will fetch either README.md or README (in that order) from
GitHub and displays the markdown content.

Example:

./gold -s dark.json https://github.com/muesli/beehive
This commit is contained in:
Christian Muehlhaeuser 2019-11-22 03:52:21 +01:00
commit 55eb9ee65a
No known key found for this signature in database
GPG key ID: 3CF9FA45CA1EBB7E
2 changed files with 68 additions and 6 deletions

45
cmd/gold/github.go Normal file
View file

@ -0,0 +1,45 @@
package main
import (
"errors"
"net/http"
"net/url"
"strings"
)
// isGitHubURL tests a string to determine if it is a well-structured GitHub URL
func isGitHubURL(s string) bool {
u, err := url.ParseRequestURI(s)
if err != nil {
return false
}
return strings.ToLower(u.Host) == "github.com"
}
// findGitHubREADME tries to find the correct README filename in a repository
func findGitHubREADME(s string) (*http.Response, error) {
u, err := url.ParseRequestURI(s)
if err != nil {
return nil, err
}
u.Host = "raw.githubusercontent.com"
readmeNames := []string{"README.md", "README"}
for _, r := range readmeNames {
v := u
v.Path += "/master/" + r
resp, err := http.Get(v.String())
if err != nil {
return nil, err
}
if resp.StatusCode == http.StatusOK {
return resp, nil
}
}
return nil, errors.New("can't find README in GitHub repository")
}

View file

@ -3,6 +3,7 @@ package main
import (
"flag"
"fmt"
"io"
"io/ioutil"
"os"
@ -17,13 +18,29 @@ func main() {
fmt.Println("Missing Markdown file. Usage: ./gold -s STYLE.json FILE.md")
os.Exit(1)
}
f, err := os.Open(args[0])
if err != nil {
fmt.Println(err)
os.Exit(1)
var in io.Reader
if isGitHubURL(args[0]) {
resp, err := findGitHubREADME(args[0])
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer resp.Body.Close()
in = resp.Body
} else {
f, err := os.Open(args[0])
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer f.Close()
in = f
}
defer f.Close()
b, _ := ioutil.ReadAll(f)
b, _ := ioutil.ReadAll(in)
out, err := gold.RenderBytes(b, *s)
if err != nil {
fmt.Println(err)