Skip to content

Instantly share code, notes, and snippets.

@seblegall
Created March 28, 2018 13:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seblegall/1c96281c5d99a903fba002e8e54f0bc0 to your computer and use it in GitHub Desktop.
Save seblegall/1c96281c5d99a903fba002e8e54f0bc0 to your computer and use it in GitHub Desktop.
package main
import (
"github.com/golang-commonmark/markdown"
"fmt"
"net/http"
"io/ioutil"
"log"
"flag"
"net/url"
)
//snippet represents the snippet we will output.
type snippet struct {
content string
lang string
}
//getSnippet extract only code snippet from markdown object.
func getSnippet(tok markdown.Token) snippet {
switch tok := tok.(type) {
case *markdown.CodeBlock:
return snippet{
tok.Content,
"code",
}
case *markdown.CodeInline:
return snippet{
tok.Content,
"code inline",
}
case *markdown.Fence:
return snippet{
tok.Content,
tok.Params,
}
}
return snippet{}
}
//readFromWeb call the given url and return the content of the readme.
func readFromWeb(url string) ([]byte, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}
func main() {
//Flag management
var urlString string
flag.StringVar(&urlString, "url", "", `The url of the github repository`)
flag.Parse()
if urlString == "" {
log.Fatalln("Please, provide an url for the readme to parse.")
}
//Parse URL
u, err := url.Parse(urlString)
if err != nil {
log.Fatalln("Impossible to parse the URL")
}
//Read the readme file
readMe, err := readFromWeb(
fmt.Sprintf("https://raw.githubusercontent.com%s/master/README.md",
u.Path)
)
if err != nil {
log.Fatalf(err.Error())
}
//Parse the markdown
md := markdown.New(markdown.XHTMLOutput(true), markdown.Nofollow(true))
tokens := md.Parse(readMe)
//Print the result
for _, t := range tokens {
snippet := getSnippet(t)
if snippet.content != "" {
fmt.Printf("##### Lang : %s ###### \n", snippet.lang)
fmt.Println(snippet.content)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment