Created
September 30, 2020 05:26
-
-
Save bemasher/0f1387c593683237cf943800a8ecce44 to your computer and use it in GitHub Desktop.
Walks a directory and lists links and text for markdown files.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"fmt" | |
"io" | |
"io/ioutil" | |
"log" | |
"os" | |
"path/filepath" | |
"strings" | |
bf "github.com/russross/blackfriday/v2" | |
) | |
const ( | |
walkPath = `loki\docs\sources` | |
) | |
func linkCollector(n *bf.Node, entering bool) bf.WalkStatus { | |
// Do nothing when exiting a node. | |
if !entering { | |
return bf.GoToNext | |
} | |
// If the current node is a link. | |
if n.Type == bf.Link { | |
// Render descendant content into a buffer. | |
buf := &bytes.Buffer{} | |
n.Walk(render(buf)) | |
// Print the link and it's content. | |
fmt.Printf(" %q %q\n", buf.String(), n.Destination) | |
// We've already walked the children, skip them. | |
return bf.SkipChildren | |
} | |
return bf.GoToNext | |
} | |
// Render returns a visitor that writes the node+descendant content to the | |
// supplied writer. | |
func render(w io.Writer) bf.NodeVisitor { | |
return func(n *bf.Node, entering bool) bf.WalkStatus { | |
if !entering { | |
return bf.GoToNext | |
} | |
w.Write(n.Literal) | |
return bf.GoToNext | |
} | |
} | |
func init() { | |
log.SetFlags(log.Lshortfile | log.Lmicroseconds) | |
} | |
func main() { | |
// Walk the specified path. | |
err := filepath.Walk(walkPath, func(path string, fi os.FileInfo, err error) error { | |
// Skip directories. | |
if fi.IsDir() { | |
return nil | |
} | |
// Skip files that aren't markdown. | |
ext := strings.ToLower(filepath.Ext(path)) | |
if ext != ".md" { | |
return nil | |
} | |
fmt.Println(path) | |
// Read the file. | |
mdBytes, err := ioutil.ReadFile(path) | |
if err != nil { | |
log.Fatal(fmt.Errorf("ioutil.ReadFile: %w", err)) | |
} | |
// Make a new markdown parser. | |
md := bf.New(bf.WithExtensions(bf.CommonExtensions)) | |
// Parse the file's contents. | |
root := md.Parse(mdBytes) | |
if err != nil { | |
log.Fatal(fmt.Errorf("md.Parse: %w", err)) | |
} | |
// Walk the root node | |
root.Walk(linkCollector) | |
return nil | |
}) | |
if err != nil { | |
log.Fatal(fmt.Errorf("filepath.Walk: %w", err)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment