all repos — searchix @ a4c441fe30ae008460149a06a5937ca37b4c2d72

Search engine for NixOS, nix-darwin, home-manager and NUR users

feat: parse {file} in markdown documentation

Alan Pearce
commit

a4c441fe30ae008460149a06a5937ca37b4c2d72

parent

d2962720cfd4b4f022ccd564f39189db1ccfa0b7

A internal/nixdocs/filepath/example/main.go
@@ -0,0 +1,44 @@
+package main + +import ( + "bytes" + "fmt" + "os" + + "github.com/yuin/goldmark" + "go.alanpearce.eu/searchix/internal/nixdocs/filepath" +) + +func main() { + // Create a new Goldmark instance with our file path extension + md := goldmark.New( + goldmark.WithExtensions( + filepath.New(), + ), + ) + + // Some example Markdown content with file path references + src := []byte(` +# File Path References Example + +System configuration files like {file}` + "`/etc/passwd`" + ` and {file}` + "`/etc/shadow`" + + ` contain user account information. + +The {file}` + "`/etc/fstab`" + ` file defines the file systems to be mounted. + +Configuration files are often found in the following locations: +- {file}` + "`/etc/`" + ` for system-wide configuration +- {file}` + "`~/.config/`" + ` for user-specific configuration +- {file}` + "`/usr/local/etc/`" + ` for locally installed software +`) + + // Convert the markdown to HTML + var buf bytes.Buffer + if err := md.Convert(src, &buf); err != nil { + fmt.Println("Conversion error:", err) + os.Exit(1) + } + + // Print the HTML output + fmt.Println(buf.String()) +}
A internal/nixdocs/filepath/filepath.go
@@ -0,0 +1,172 @@
+//nolint:wrapcheck +package filepath + +import ( + "bytes" + + "github.com/yuin/goldmark" + "github.com/yuin/goldmark/ast" + "github.com/yuin/goldmark/parser" + "github.com/yuin/goldmark/renderer" + "github.com/yuin/goldmark/renderer/html" + "github.com/yuin/goldmark/text" + "github.com/yuin/goldmark/util" +) + +// Node represents a file path reference node in markdown AST. +type Node struct { + ast.BaseInline + FilePath []byte +} + +// Inline implements ast.Inline interface. +func (n *Node) Inline() bool { + return true +} + +// Kind implements ast.Node.Kind interface. +func (n *Node) Kind() ast.NodeKind { + return KindFilePath +} + +// Dump implements ast.Node.Dump interface. +func (n *Node) Dump(source []byte, level int) { + ast.DumpHelper(n, source, level, map[string]string{ + "FilePath": string(n.FilePath), + }, nil) +} + +// KindFilePath is a NodeKind for file path nodes. +var KindFilePath = ast.NewNodeKind("FilePath") + +// Parser is a Goldmark inline parser for parsing file path nodes. +// +// File path references have the format {file}`/etc/passwd` which will be rendered as +// a span with the file path. +type Parser struct{} + +var _ parser.InlineParser = (*Parser)(nil) + +// Trigger reports characters that trigger this parser. +func (*Parser) Trigger() []byte { + return []byte{'{'} +} + +// Parse parses a file path node. +func (p *Parser) Parse(_ ast.Node, block text.Reader, _ parser.Context) ast.Node { + line, segment := block.PeekLine() + + // Check if we have enough characters for {file}` + if len(line) < 7 || line[0] != '{' { + return nil + } + + // Check for {file}` prefix + if !bytes.HasPrefix(line, []byte("{file}`")) { + return nil + } + + // Skip the {file}` prefix + line = line[7:] + start := segment.Start + 7 + + // Find the closing backtick + endPos := bytes.IndexByte(line, '`') + if endPos < 0 { + return nil + } + + // Extract the file path + filePath := line[:endPos] + if len(filePath) == 0 { + return nil + } + + // Create the node + n := &Node{ + FilePath: filePath, + } + + // Set the text segment to include the entire {file}`path` text + textSegment := text.NewSegment(segment.Start, start+endPos+1) + n.AppendChild(n, ast.NewTextSegment(textSegment)) + + // Advance the reader past this node + block.Advance(7 + endPos + 1) // {file}` + path + ` + + return n +} + +// HTMLRenderer is a renderer for file path nodes. +type HTMLRenderer struct { + html.Config +} + +// NewHTMLRenderer returns a new HTMLRenderer. +func NewHTMLRenderer(opts ...html.Option) renderer.NodeRenderer { + r := &HTMLRenderer{ + Config: html.NewConfig(), + } + for _, opt := range opts { + opt.SetHTMLOption(&r.Config) + } + + return r +} + +// RegisterFuncs implements renderer.NodeRenderer.RegisterFuncs. +func (r *HTMLRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) { + reg.Register(KindFilePath, r.renderFilePath) +} + +func (r *HTMLRenderer) renderFilePath( + w util.BufWriter, + source []byte, //nolint:revive + node ast.Node, + entering bool, +) (ast.WalkStatus, error) { + if !entering { + return ast.WalkContinue, nil + } + + n := node.(*Node) + + if _, err := w.WriteString(`<span class="file-path">`); err != nil { + return ast.WalkStop, err + } + + if _, err := w.Write(n.FilePath); err != nil { + return ast.WalkStop, err + } + + if _, err := w.WriteString("</span>"); err != nil { + return ast.WalkStop, err + } + + return ast.WalkSkipChildren, nil +} + +// Extension is a goldmark extension for file path references. +type Extension struct{} + +// Extend implements goldmark.Extender.Extend. +func (e *Extension) Extend(m goldmark.Markdown) { + // Register the parser + m.Parser().AddOptions( + parser.WithInlineParsers( + util.Prioritized(new(Parser), 100), + ), + ) + + // Register the renderer + m.Renderer().AddOptions( + renderer.WithNodeRenderers( + util.Prioritized(NewHTMLRenderer(), 500), + ), + ) +} + +// New returns a new file path extension. +func New() goldmark.Extender { + return &Extension{} +}
A internal/nixdocs/filepath/filepath_test.go
@@ -0,0 +1,79 @@
+package filepath + +import ( + "bytes" + "testing" + + "github.com/yuin/goldmark" +) + +func TestFilePathExtension(t *testing.T) { + markdown := goldmark.New( + goldmark.WithExtensions( + New(), + ), + ) + + tests := []struct { + name string + input string + expected string + }{ + { + name: "basic file path reference", + input: "{file}`/etc/passwd`", + expected: "<p><span class=\"file-path\">/etc/passwd</span></p>\n", + }, + { + name: "file path reference in sentence", + input: "The configuration file {file}`/etc/fstab` contains file system information.", + expected: "<p>The configuration file <span class=\"file-path\">/etc/fstab</span>" + + " contains file system information.</p>\n", + }, + { + name: "multiple file path references", + input: "Both {file}`/etc/hosts` and {file}`/etc/resolv.conf` define DNS settings.", + expected: "<p>Both <span class=\"file-path\">/etc/hosts</span> and <span class=\"file-path\">" + + "/etc/resolv.conf</span> define DNS settings.</p>\n", + }, + { + name: "incomplete file path reference - no closing backtick", + input: "{file}`/missing/backtick", + expected: "<p>{file}`/missing/backtick</p>\n", + }, + { + name: "incomplete file path reference - empty path", + input: "{file}``", + expected: "<p>{file}``</p>\n", + }, + { + name: "file path reference with code block", + input: "Edit {file}`~/.bashrc` using your favorite `text editor`.", + expected: "<p>Edit <span class=\"file-path\">~/.bashrc</span> " + + "using your favorite <code>text editor</code>.</p>\n", + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + var buf bytes.Buffer + if err := markdown.Convert([]byte(test.input), &buf); err != nil { + t.Fatalf("Failed to convert markdown: %v", err) + } + + if got := buf.String(); got != test.expected { + t.Errorf("Expected:\n%q\nGot:\n%q", test.expected, got) + } + }) + } +} + +func TestFilePathNodeKind(t *testing.T) { + n := &Node{} + if kind := n.Kind(); kind != KindFilePath { + t.Errorf("Expected node kind %v, got %v", KindFilePath, kind) + } + if !n.Inline() { + t.Error("Expected node to be inline") + } +}
M internal/nixdocs/nixdocs.gointernal/nixdocs/nixdocs.go
@@ -7,6 +7,7 @@ "github.com/yuin/goldmark/extension"
"go.alanpearce.eu/searchix/internal/nixdocs/command" "go.alanpearce.eu/searchix/internal/nixdocs/envvar" + "go.alanpearce.eu/searchix/internal/nixdocs/filepath" "go.alanpearce.eu/searchix/internal/nixdocs/option" "go.alanpearce.eu/searchix/internal/nixdocs/optlink" "go.alanpearce.eu/searchix/internal/nixdocs/variable"
@@ -21,5 +22,6 @@ option.New(),
command.New(), envvar.New(), variable.New(), + filepath.New(), ) }