package setup import ( "strings" ) // Marker styles. Markdown files use HTML comments, config files use hashes. const ( StyleMarkdown = "md" StyleHash = "hash" ) const ( legacyStart = "# codebase map (auto-generated by stacklit" legacyEnd = "# end stacklit map" ) func markers(style string) (string, string) { if style == StyleHash { return "# stacklit:start", "# stacklit:end" } return "", "" } // wrap surrounds body with the markers for style. func wrap(body, style string) string { s, e := markers(style) if !strings.HasSuffix(body, "\n") { body += "\n" } return s + "\n" + body + e + "\n" } // upsertBlock replaces the marked block in content, or appends it. Legacy // pre-marker blocks are migrated in place so reruns never duplicate. func upsertBlock(content, body, style string) string { block := wrap(body, style) s, e := markers(style) if out, ok := replaceRange(content, s, e, block); ok { return out } if out, ok := replaceRange(content, legacyStart, legacyEnd, block); ok { return out } if content == "" { return block } if !strings.HasSuffix(content, "\n") { content += "\n" } if !strings.HasSuffix(content, "\n\n") { content += "\n" } return content + block } // removeBlock strips the marked (or legacy) block. The bool reports a change. func removeBlock(content, style string) (string, bool) { s, e := markers(style) for _, pair := range [][2]string{{s, e}, {legacyStart, legacyEnd}} { if out, ok := replaceRange(content, pair[0], pair[1], ""); ok { return strings.TrimRight(out, "\n") + trailingNL(out), true } } return content, false } func trailingNL(s string) string { if strings.TrimSpace(s) == "" { return "" } return "\n" } func replaceRange(content, start, end, repl string) (string, bool) { si := strings.Index(content, start) if si < 0 { return content, false } rel := strings.Index(content[si:], end) if rel < 0 { return content, false } ei := si + rel + len(end) if ei < len(content) && content[ei] == '\n' { ei++ } out := content[:si] + repl + content[ei:] // Collapse the blank line left behind when removing. if repl == "" { out = strings.ReplaceAll(out, "\n\n\n", "\n\n") } return out, true }