llms-full.txt, per-page Markdown, and hotdog-cms indexnow #44
No files matched your search
@@ -42,6 +42,7 @@ The editor, previews and the pull agent also need `git`.
|
||||
hotdog-cms build write the finished site to public/
|
||||
hotdog-cms check [-csp] [-fix] build, then check it: tracking, privacy, links, SEO, security (docs/checks.md)
|
||||
hotdog-cms publish <target> build, then publish: a folder, a server over SSH, a container image, or your own command
|
||||
hotdog-cms indexnow after deploying public/ some other way: tell search engines what changed
|
||||
hotdog-cms pull -repo URL -out DIR on the web server: publish from git when the branch moves
|
||||
hotdog-cms preview -repo URL every branch built as it would be published, at <branch>.localhost:8160
|
||||
hotdog-cms endpoint -config FILE forms and search, behind your web server (docs/forms.md)
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
@@ -41,6 +42,7 @@ Usage:
|
||||
hotdog-cms build [flags] build the site into public/
|
||||
hotdog-cms check [flags] build, then look for broken links and forbidden strings
|
||||
hotdog-cms publish [target...] build, then publish to targets in publish.yaml
|
||||
hotdog-cms indexnow [flags] after deploying public/ some other way: tell search engines which pages changed
|
||||
hotdog-cms pull -repo URL -out DIR on a web server: publish from git when the branch moves
|
||||
hotdog-cms preview -repo URL build every branch as it would be published, each at its own address
|
||||
hotdog-cms ci <platform> write the CI file for github, gitea, forgejo, gitlab, bitbucket, woodpecker, or a git hook
|
||||
@@ -85,6 +87,8 @@ func main() {
|
||||
err = cmdCheck(args)
|
||||
case "publish":
|
||||
err = cmdPublish(args)
|
||||
case "indexnow":
|
||||
err = cmdIndexNow(args)
|
||||
case "pull":
|
||||
isolate.Enabled = true
|
||||
err = cmdPull(args)
|
||||
@@ -297,6 +301,39 @@ func cmdPublish(args []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// cmdIndexNow tells search engines which pages changed, for a site that is
|
||||
// built here but put online by something other than publish or pull: run it
|
||||
// after the deploy, against the build that went out.
|
||||
func cmdIndexNow(args []string) error {
|
||||
fl := flag.NewFlagSet("indexnow", flag.ExitOnError)
|
||||
dir := fl.String("site", ".", "the site's folder")
|
||||
outDir := fl.String("out", "", "the build that was deployed (default <site>/public)")
|
||||
name := fl.String("name", "", "what to remember this deploy's last ping under (default the site's address); use one name per place the site is deployed")
|
||||
dry := fl.Bool("dry-run", false, "list the pages that would be sent, and send nothing")
|
||||
_ = fl.Parse(args)
|
||||
out := *outDir
|
||||
if out == "" {
|
||||
out = filepath.Join(*dir, "public")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(out, build.Marker)); err != nil {
|
||||
return fmt.Errorf("%s is not a hotdog-cms build; run hotdog-cms build first", out)
|
||||
}
|
||||
n := *name
|
||||
if n == "" {
|
||||
note, err := os.ReadFile(filepath.Join(out, build.IndexNowFile))
|
||||
if err != nil {
|
||||
return fmt.Errorf("the build has no IndexNow key: set indexnow.key in site.yaml and build again")
|
||||
}
|
||||
var info build.IndexNowInfo
|
||||
if err := json.Unmarshal(note, &info); err != nil || info.URL == "" {
|
||||
return fmt.Errorf("%s: unreadable", build.IndexNowFile)
|
||||
}
|
||||
n = info.URL
|
||||
}
|
||||
publish.IndexNow(n, out, *dry, os.Stdout)
|
||||
return nil
|
||||
}
|
||||
|
||||
func cmdPull(args []string) error {
|
||||
fl := flag.NewFlagSet("pull", flag.ExitOnError)
|
||||
repo := fl.String("repo", "", "the site's git repository (required)")
|
||||
|
||||
@@ -198,6 +198,16 @@ func Run(opt Options) (*Result, error) {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if cfg.Outputs.LLMsFull {
|
||||
if err := writeLLMsFull(s, work); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if cfg.Outputs.Markdown {
|
||||
if err := writeMarkdown(s, work); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := writeSearchFiles(work, s.Config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -484,3 +484,41 @@ func TestDataFolderFunc(t *testing.T) {
|
||||
t.Errorf("data folders: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
// outputs: llms_full and markdown: the whole site's Markdown in one file, and
|
||||
// each page's Markdown beside its HTML; a file static/ put there is kept.
|
||||
func TestMarkdownOutputs(t *testing.T) {
|
||||
dir := writeStarter(t)
|
||||
cfg, _ := os.ReadFile(filepath.Join(dir, "site.yaml"))
|
||||
cfg = []byte(strings.Replace(string(cfg), "outputs:", "outputs:\n llms_full: true\n markdown: true", 1))
|
||||
if !strings.Contains(string(cfg), "llms_full") {
|
||||
cfg = append(cfg, []byte("\noutputs:\n llms: true\n llms_full: true\n markdown: true\n")...)
|
||||
}
|
||||
os.WriteFile(filepath.Join(dir, "site.yaml"), cfg, 0o644)
|
||||
os.MkdirAll(filepath.Join(dir, "static", "articles", "hello-world"), 0o755)
|
||||
os.WriteFile(filepath.Join(dir, "static", "articles", "hello-world", "index.md"), []byte("mine"), 0o644)
|
||||
res, err := Run(Options{SiteDir: dir})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
full, err := os.ReadFile(filepath.Join(res.Out, "llms-full.txt"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(full), "Source: https://") || !strings.Contains(string(full), "\n---\n") {
|
||||
t.Errorf("llms-full.txt: %.400s", full)
|
||||
}
|
||||
about, err := os.ReadFile(filepath.Join(res.Out, "about", "index.md"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(string(about), "# ") || !strings.Contains(string(about), "/about/") {
|
||||
t.Errorf("about/index.md: %.300s", about)
|
||||
}
|
||||
if b, _ := os.ReadFile(filepath.Join(res.Out, "articles", "hello-world", "index.md")); string(b) != "mine" {
|
||||
t.Errorf("static file replaced: %q", b)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(res.Out, "tags", "hotdog-cms", "index.md")); err == nil {
|
||||
t.Error("a generated tag page got a Markdown copy")
|
||||
}
|
||||
}
|
||||
@@ -173,6 +173,78 @@ func writeLLMs(s *site.Site, out string) error {
|
||||
return os.WriteFile(filepath.Join(out, "llms.txt"), []byte(b.String()), 0o644)
|
||||
}
|
||||
|
||||
// mdPages is what llms-full.txt and the per-page Markdown carry: pages that
|
||||
// are in the sitemap and were written in Markdown, not generated lists.
|
||||
func mdPages(s *site.Site) []*site.Page {
|
||||
var out []*site.Page
|
||||
for _, p := range s.Pages {
|
||||
if !inSitemap(p) || p.Kind == site.KindTerm || p.Kind == site.KindTerms {
|
||||
continue
|
||||
}
|
||||
if strings.TrimSpace(p.Raw) == "" {
|
||||
continue
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// pageMarkdown is one page as Markdown: its title, its address and summary,
|
||||
// then its body as written, with its links made absolute (body).
|
||||
func pageMarkdown(p *site.Page, body func(*site.Page) string) string {
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "# %s\n\n", p.Title)
|
||||
fmt.Fprintf(&b, "Source: %s\n", p.Permalink)
|
||||
if lm := p.Lastmod(); !lm.IsZero() {
|
||||
fmt.Fprintf(&b, "Updated: %s\n", lm.Format("2006-01-02"))
|
||||
}
|
||||
if p.Summary != "" {
|
||||
fmt.Fprintf(&b, "\n> %s\n", p.Summary)
|
||||
}
|
||||
b.WriteString("\n")
|
||||
b.WriteString(strings.TrimSpace(body(p)))
|
||||
b.WriteString("\n")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// writeLLMsFull writes llms-full.txt: the whole site's text in one file,
|
||||
// every page's Markdown in sitemap order, for tools that read a site at once
|
||||
// rather than page by page.
|
||||
func writeLLMsFull(s *site.Site, out string) error {
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "# %s\n\n", s.Config.Name)
|
||||
if s.Config.Description != "" {
|
||||
fmt.Fprintf(&b, "> %s\n\n", s.Config.Description)
|
||||
}
|
||||
body := s.AbsoluteMarkdown()
|
||||
for _, p := range mdPages(s) {
|
||||
b.WriteString("---\n\n")
|
||||
b.WriteString(pageMarkdown(p, body))
|
||||
b.WriteString("\n")
|
||||
}
|
||||
return os.WriteFile(filepath.Join(out, "llms-full.txt"), []byte(b.String()), 0o644)
|
||||
}
|
||||
|
||||
// writeMarkdown writes each page's Markdown beside its HTML: /guide/ gets
|
||||
// /guide/index.md. A page whose address isn't a folder (/404.html) has no
|
||||
// Markdown copy, and a file static/ already put there is left alone.
|
||||
func writeMarkdown(s *site.Site, out string) error {
|
||||
body := s.AbsoluteMarkdown()
|
||||
for _, p := range mdPages(s) {
|
||||
if !strings.HasSuffix(p.Path, "/") {
|
||||
continue
|
||||
}
|
||||
dst := filepath.Join(filepath.Dir(pageFile(out, p.Path)), "index.md")
|
||||
if _, err := os.Stat(dst); err == nil {
|
||||
continue
|
||||
}
|
||||
if err := os.WriteFile(dst, []byte(pageMarkdown(p, body)), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeXML(path string, v any) error {
|
||||
var buf bytes.Buffer
|
||||
buf.WriteString(xml.Header)
|
||||
|
||||
@@ -66,6 +66,18 @@ func changedPages(before, after map[string]string) []string {
|
||||
|
||||
// indexNow pings for what changed since this target's last publish.
|
||||
func indexNow(name string, t Target, out string, log io.Writer) {
|
||||
indexNowRun(name, t, out, false, log)
|
||||
}
|
||||
|
||||
// IndexNow pings for what changed in the build at out since the last ping
|
||||
// remembered under name, for a site that something other than publish or
|
||||
// pull puts online (hotdog-cms indexnow, run after a deploy). With dryRun it
|
||||
// lists those pages and sends and remembers nothing.
|
||||
func IndexNow(name, out string, dryRun bool, log io.Writer) {
|
||||
indexNowRun(name, Target{Type: "indexnow"}, out, dryRun, log)
|
||||
}
|
||||
|
||||
func indexNowRun(name string, t Target, out string, dryRun bool, log io.Writer) {
|
||||
note, err := os.ReadFile(filepath.Join(out, build.IndexNowFile))
|
||||
if err != nil {
|
||||
fmt.Fprintln(log, "indexnow: the site has no indexnow.key in site.yaml; nothing sent")
|
||||
@@ -93,6 +105,13 @@ func indexNow(name string, t Target, out string, log io.Writer) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if dryRun {
|
||||
for _, p := range pages {
|
||||
fmt.Fprintln(log, strings.TrimRight(info.URL, "/")+p)
|
||||
}
|
||||
fmt.Fprintf(log, "indexnow: would tell search engines about %d changed page(s); nothing sent\n", len(pages))
|
||||
return
|
||||
}
|
||||
for start := 0; start < len(pages); start += 10000 {
|
||||
batch := pages[start:min(start+10000, len(pages))]
|
||||
urls := make([]string, len(batch))
|
||||
|
||||
@@ -96,3 +96,46 @@ func TestIndexNow(t *testing.T) {
|
||||
t.Error("a target without indexnow: true pinged")
|
||||
}
|
||||
}
|
||||
|
||||
// hotdog-cms indexnow: a site deployed some other way pings after the deploy.
|
||||
// A dry run lists the pages and sends and remembers nothing; the real run
|
||||
// sends them; a second run with nothing changed sends nothing.
|
||||
func TestIndexNowStandalone(t *testing.T) {
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
t.Setenv("HOME", t.TempDir())
|
||||
var pings []map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]any
|
||||
json.NewDecoder(r.Body).Decode(&body)
|
||||
pings = append(pings, body)
|
||||
}))
|
||||
defer srv.Close()
|
||||
old := indexNowEndpoint
|
||||
indexNowEndpoint = srv.URL
|
||||
defer func() { indexNowEndpoint = old }()
|
||||
|
||||
site := t.TempDir()
|
||||
starterSite(t, site)
|
||||
cfg, _ := os.ReadFile(filepath.Join(site, "site.yaml"))
|
||||
os.WriteFile(filepath.Join(site, "site.yaml"), append(cfg, []byte("indexnow: { key: abcdef0123456789 }\n")...), 0o644)
|
||||
res, err := build.Run(build.Options{SiteDir: site})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var dry bytes.Buffer
|
||||
IndexNow("https://example.org", res.Out, true, &dry)
|
||||
if len(pings) != 0 || !strings.Contains(dry.String(), "https://example.org/about/") || !strings.Contains(dry.String(), "nothing sent") {
|
||||
t.Fatalf("dry run: %d pings, %s", len(pings), dry.String())
|
||||
}
|
||||
var log bytes.Buffer
|
||||
IndexNow("https://example.org", res.Out, false, &log)
|
||||
if len(pings) != 1 || !strings.Contains(log.String(), "told search engines about") {
|
||||
t.Fatalf("first run: %d pings, %s", len(pings), log.String())
|
||||
}
|
||||
log.Reset()
|
||||
IndexNow("https://example.org", res.Out, false, &log)
|
||||
if len(pings) != 1 || !strings.Contains(log.String(), "no pages changed") {
|
||||
t.Errorf("unchanged: %d pings, %s", len(pings), log.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package site
|
||||
|
||||
import "testing"
|
||||
|
||||
// Markdown read away from the site has nothing to be relative to: every
|
||||
// link is made absolute, source-file links become page addresses, and code
|
||||
// shows links as written.
|
||||
func TestAbsoluteMarkdown(t *testing.T) {
|
||||
guide := &Page{Source: "docs/install/fresh.md", Path: "/install/fresh/", Permalink: "https://example.org/install/fresh/"}
|
||||
server := &Page{Source: "docs/install/server.md", Path: "/install/server/", Permalink: "https://example.org/install/server/"}
|
||||
guide.Raw = "See [the server](server.md#ports), [home](/), , " +
|
||||
"[elsewhere](https://other.example/x.md), [here](#top) and <a href=\"../run/\">run</a>.\n" +
|
||||
"Write `[x](server.md)` like that.\n\n```md\n[x](server.md)\n```\n"
|
||||
s := &Site{Pages: []*Page{guide, server}}
|
||||
got := s.AbsoluteMarkdown()(guide)
|
||||
want := "See [the server](https://example.org/install/server/#ports), [home](https://example.org/), " +
|
||||
", [elsewhere](https://other.example/x.md), " +
|
||||
"[here](#top) and <a href=\"https://example.org/install/run/\">run</a>.\n" +
|
||||
"Write `[x](server.md)` like that.\n\n```md\n[x](server.md)\n```\n"
|
||||
if got != want {
|
||||
t.Errorf("got\n%s\nwant\n%s", got, want)
|
||||
}
|
||||
}
|
||||
@@ -186,6 +186,13 @@ type OutputsConfig struct {
|
||||
Sitemap *bool `yaml:"sitemap"` // default on
|
||||
Robots *bool `yaml:"robots"` // default on, unless static/robots.txt exists
|
||||
LLMs bool `yaml:"llms"` // llms.txt, default off
|
||||
// LLMsFull writes llms-full.txt: every page's own Markdown in one file,
|
||||
// for tools that read a whole site at once. Default off.
|
||||
LLMsFull bool `yaml:"llms_full"`
|
||||
// Markdown writes each page's Markdown beside its HTML, as index.md
|
||||
// (/guide/ is also /guide/index.md), for tools that would rather read
|
||||
// the source than the rendered page. Default off.
|
||||
Markdown bool `yaml:"markdown"`
|
||||
}
|
||||
|
||||
// CheckConfig tunes `hotdog-cms check`.
|
||||
|
||||
+140
-23
@@ -2,6 +2,7 @@ package site
|
||||
|
||||
import (
|
||||
"html/template"
|
||||
"net/url"
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
@@ -20,12 +21,7 @@ var srcLinkRe = regexp.MustCompile(`(<a\s[^>]*?href=")([^"#?:]+\.md)((?:#[^"]*)?
|
||||
// calls _index.md. A link to a .md file no page came from is left as written,
|
||||
// for the link check to report.
|
||||
func (s *Site) resolveSourceLinks() {
|
||||
bySource := map[string]*Page{}
|
||||
for _, p := range s.Pages {
|
||||
if p.Source != "" {
|
||||
bySource[p.Source] = p
|
||||
}
|
||||
}
|
||||
bySource := s.sourceIndex()
|
||||
for _, p := range s.Pages {
|
||||
if p.Source == "" || !strings.Contains(string(p.Content), ".md") {
|
||||
continue
|
||||
@@ -33,23 +29,7 @@ func (s *Site) resolveSourceLinks() {
|
||||
dir := path.Dir(p.Source)
|
||||
p.Content = template.HTML(srcLinkRe.ReplaceAllStringFunc(string(p.Content), func(m string) string {
|
||||
sub := srcLinkRe.FindStringSubmatch(m)
|
||||
target := sub[2]
|
||||
var rel string
|
||||
if strings.HasPrefix(target, "/") {
|
||||
rel = path.Clean(strings.TrimPrefix(target, "/"))
|
||||
} else {
|
||||
rel = path.Clean(path.Join(dir, target))
|
||||
}
|
||||
if strings.HasPrefix(rel, "../") || rel == ".." {
|
||||
return m
|
||||
}
|
||||
to := bySource[rel]
|
||||
if to == nil && path.Base(rel) == "index.md" {
|
||||
to = bySource[path.Join(path.Dir(rel), "_index.md")]
|
||||
}
|
||||
if to == nil && path.Base(rel) == "README.md" {
|
||||
to = bySource[path.Join(path.Dir(rel), "_index.md")]
|
||||
}
|
||||
to := sourceTarget(bySource, dir, sub[2])
|
||||
if to == nil {
|
||||
return m
|
||||
}
|
||||
@@ -57,3 +37,140 @@ func (s *Site) resolveSourceLinks() {
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Site) sourceIndex() map[string]*Page {
|
||||
out := map[string]*Page{}
|
||||
for _, p := range s.Pages {
|
||||
if p.Source != "" {
|
||||
out[p.Source] = p
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// sourceTarget is the page a link to a source file (about.md,
|
||||
// ../install/linux.md, /guide.md) written in a file in dir points at, or nil.
|
||||
func sourceTarget(bySource map[string]*Page, dir, target string) *Page {
|
||||
var rel string
|
||||
if strings.HasPrefix(target, "/") {
|
||||
rel = path.Clean(strings.TrimPrefix(target, "/"))
|
||||
} else {
|
||||
rel = path.Clean(path.Join(dir, target))
|
||||
}
|
||||
if strings.HasPrefix(rel, "../") || rel == ".." {
|
||||
return nil
|
||||
}
|
||||
to := bySource[rel]
|
||||
if to == nil && path.Base(rel) == "index.md" {
|
||||
to = bySource[path.Join(path.Dir(rel), "_index.md")]
|
||||
}
|
||||
if to == nil && path.Base(rel) == "README.md" {
|
||||
to = bySource[path.Join(path.Dir(rel), "_index.md")]
|
||||
}
|
||||
return to
|
||||
}
|
||||
|
||||
// mdLinkRe finds a Markdown link or image target, ](target) or ](target
|
||||
// "title"); attrLinkRe an href or src in HTML written into the Markdown.
|
||||
var (
|
||||
mdLinkRe = regexp.MustCompile(`(\]\()([^)\s]+)((?:\s+"[^"]*")?\))`)
|
||||
attrLinkRe = regexp.MustCompile(`(\s(?:href|src)=")([^"]+)(")`)
|
||||
)
|
||||
|
||||
// AbsoluteMarkdown returns a function that gives a page's Markdown with every
|
||||
// relative link made absolute: a link to a source file becomes that page's
|
||||
// address, and any other relative address is resolved against the page's
|
||||
// own. For Markdown read away from the site (llms-full.txt, a page's
|
||||
// index.md), where a relative link has nothing to be relative to. Code
|
||||
// blocks and code spans are left as written: they show links, not use them.
|
||||
func (s *Site) AbsoluteMarkdown() func(p *Page) string {
|
||||
bySource := s.sourceIndex()
|
||||
return func(p *Page) string {
|
||||
base, err := url.Parse(p.Permalink)
|
||||
if err != nil || p.Raw == "" {
|
||||
return p.Raw
|
||||
}
|
||||
dir := path.Dir(p.Source)
|
||||
fix := func(target string) string {
|
||||
if target == "" || strings.HasPrefix(target, "#") || strings.HasPrefix(target, "//") {
|
||||
return target
|
||||
}
|
||||
if u, err := url.Parse(target); err != nil || u.Scheme != "" {
|
||||
return target
|
||||
}
|
||||
file, frag, _ := strings.Cut(target, "#")
|
||||
if strings.HasSuffix(file, ".md") && !strings.ContainsAny(file, "?:") {
|
||||
if to := sourceTarget(bySource, dir, file); to != nil {
|
||||
if frag != "" {
|
||||
return to.Permalink + "#" + frag
|
||||
}
|
||||
return to.Permalink
|
||||
}
|
||||
}
|
||||
ref, err := url.Parse(target)
|
||||
if err != nil {
|
||||
return target
|
||||
}
|
||||
return base.ResolveReference(ref).String()
|
||||
}
|
||||
rewrite := func(text string) string {
|
||||
text = mdLinkRe.ReplaceAllStringFunc(text, func(m string) string {
|
||||
sub := mdLinkRe.FindStringSubmatch(m)
|
||||
return sub[1] + fix(sub[2]) + sub[3]
|
||||
})
|
||||
return attrLinkRe.ReplaceAllStringFunc(text, func(m string) string {
|
||||
sub := attrLinkRe.FindStringSubmatch(m)
|
||||
return sub[1] + fix(sub[2]) + sub[3]
|
||||
})
|
||||
}
|
||||
return outsideCode(p.Raw, rewrite)
|
||||
}
|
||||
}
|
||||
|
||||
// outsideCode applies f to the parts of Markdown that aren't code: fenced
|
||||
// blocks (``` or ~~~) and `code spans` pass through untouched.
|
||||
func outsideCode(md string, f func(string) string) string {
|
||||
var out, prose strings.Builder
|
||||
flush := func() {
|
||||
if prose.Len() > 0 {
|
||||
out.WriteString(outsideSpans(prose.String(), f))
|
||||
prose.Reset()
|
||||
}
|
||||
}
|
||||
fence := ""
|
||||
for _, line := range strings.SplitAfter(md, "\n") {
|
||||
trim := strings.TrimLeft(line, " \t")
|
||||
switch {
|
||||
case fence != "":
|
||||
out.WriteString(line)
|
||||
if strings.HasPrefix(trim, fence) {
|
||||
fence = ""
|
||||
}
|
||||
continue
|
||||
case strings.HasPrefix(trim, "```"):
|
||||
fence = "```"
|
||||
case strings.HasPrefix(trim, "~~~"):
|
||||
fence = "~~~"
|
||||
}
|
||||
if fence != "" {
|
||||
flush()
|
||||
out.WriteString(line)
|
||||
continue
|
||||
}
|
||||
prose.WriteString(line)
|
||||
}
|
||||
flush()
|
||||
return out.String()
|
||||
}
|
||||
|
||||
// outsideSpans applies f between `code spans`, which pass through untouched.
|
||||
func outsideSpans(text string, f func(string) string) string {
|
||||
parts := strings.Split(text, "`")
|
||||
if len(parts)%2 == 0 { // an unmatched backtick: no spans to trust
|
||||
return f(text)
|
||||
}
|
||||
for i := 0; i < len(parts); i += 2 {
|
||||
parts[i] = f(parts[i])
|
||||
}
|
||||
return strings.Join(parts, "`")
|
||||
}
|
||||
Reference in new issue
Block a user