Files
skillshare/internal/utils/frontmatter_write.go
T
Willie a9c3189ce3 feat(utils): add a line-based frontmatter string setter
Prefixed target naming has to rewrite name: in each copied SKILL.md.
ToggleFrontmatterFlag only adds or removes a boolean, so SetFrontmatterValue
sets a plain scalar the same way: one line edited, key order, comments,
CRLF and the body untouched. Both now share the delimiter scan.
2026-10-09 00:44:47 +08:00

213 lines
5.9 KiB
Go

package utils
import (
"os"
"strings"
"gopkg.in/yaml.v3"
)
// SetFrontmatterList writes a YAML list field into a SKILL.md file's frontmatter.
// The field parameter uses dot notation: "metadata.targets" operates on fm["metadata"]["targets"].
// When values is nil, the field is removed. When non-nil, the field is set.
// For "metadata.targets", any legacy top-level "targets" field is also removed.
// All other frontmatter fields and the body content are preserved.
func SetFrontmatterList(filePath string, field string, values []string) error {
data, err := os.ReadFile(filePath)
if err != nil {
return err
}
data, err = RewriteFrontmatterList(data, field, values)
if err != nil {
return err
}
return os.WriteFile(filePath, data, 0644)
}
// RewriteFrontmatterList returns updated frontmatter while preserving the body.
// It has the same field and removal semantics as SetFrontmatterList.
func RewriteFrontmatterList(data []byte, field string, values []string) ([]byte, error) {
fmRaw, body := splitFrontmatterAndBody(data)
var fm map[string]any
if len(fmRaw) > 0 {
if err := yaml.Unmarshal(fmRaw, &fm); err != nil {
return nil, err
}
}
if fm == nil {
fm = make(map[string]any)
}
parts := strings.SplitN(field, ".", 2)
if len(parts) == 2 && parts[0] == "metadata" {
subField := parts[1]
md, _ := fm["metadata"].(map[string]any)
if md == nil {
md = make(map[string]any)
}
if values == nil {
delete(md, subField)
} else {
list := make([]any, len(values))
for i, v := range values {
list[i] = v
}
md[subField] = list
}
if len(md) == 0 {
delete(fm, "metadata")
} else {
fm["metadata"] = md
}
// Always remove legacy top-level field when operating on metadata.<field>
delete(fm, subField)
} else {
topField := parts[0]
if values == nil {
delete(fm, topField)
} else {
list := make([]any, len(values))
for i, v := range values {
list[i] = v
}
fm[topField] = list
}
}
fmBytes, err := MarshalYAML(fm)
if err != nil {
return nil, err
}
var sb strings.Builder
sb.WriteString("---\n")
sb.Write(fmBytes)
sb.WriteString("---\n")
sb.Write(body)
return []byte(sb.String()), nil
}
// splitFrontmatterAndBody splits SKILL.md content into raw frontmatter YAML
// and the remaining body. Returns (nil, content) if no frontmatter found.
func splitFrontmatterAndBody(content []byte) (fmRaw, body []byte) {
block := locateFrontmatter(content, rewriteBlock)
if !block.closed {
return nil, content
}
return block.withoutLastNewline(), block.body
}
// ToggleFrontmatterFlag flips a top-level boolean frontmatter key and reports the new state.
// Absent or false becomes "key: true"; true removes the line, so toggling twice hands back
// the original file byte for byte — which keeps a tracked repo clean once the flag is off again.
// It edits one line instead of round-tripping YAML: key order, comments, line endings and the
// body are never touched.
func ToggleFrontmatterFlag(filePath, key string) (bool, error) {
data, err := os.ReadFile(filePath)
if err != nil {
return false, err
}
fm := splitFrontmatterLines(string(data))
flagLine := key + ": true" + fm.cr
if fm.end < 0 {
return true, os.WriteFile(filePath, []byte(fm.prepend(flagLine)), 0644)
}
lines := fm.lines
on := true
i := fm.keyLine(key)
switch {
case i < 0:
lines = append(lines[:fm.end], append([]string{flagLine}, lines[fm.end:]...)...)
case isTrueValue(lines[i][len(key)+1:]):
lines = append(lines[:i], lines[i+1:]...)
on = false
default:
lines[i] = flagLine
}
return on, os.WriteFile(filePath, []byte(strings.Join(lines, "\n")), 0644)
}
// SetFrontmatterValue sets a top-level frontmatter key to a plain scalar value,
// adding the key (or the whole frontmatter block) when it is missing. Like
// ToggleFrontmatterFlag it edits one line, so key order, comments, line endings
// and the body are kept. value is written unquoted and must be a plain YAML scalar.
func SetFrontmatterValue(filePath, key, value string) error {
data, err := os.ReadFile(filePath)
if err != nil {
return err
}
fm := splitFrontmatterLines(string(data))
line := key + ": " + value + fm.cr
if fm.end < 0 {
return os.WriteFile(filePath, []byte(fm.prepend(line)), 0644)
}
lines := fm.lines
if i := fm.keyLine(key); i >= 0 {
lines[i] = line
} else {
lines = append(lines[:fm.end], append([]string{line}, lines[fm.end:]...)...)
}
return os.WriteFile(filePath, []byte(strings.Join(lines, "\n")), 0644)
}
// frontmatterLines is a file split on "\n" only, so CRLF files keep their "\r"
// on every untouched line; open and end index the "---" delimiters (end < 0
// when there is no frontmatter block).
type frontmatterLines struct {
content string
cr string
lines []string
open, end int
}
func splitFrontmatterLines(content string) frontmatterLines {
fm := frontmatterLines{content: content, lines: strings.Split(content, "\n"), open: -1, end: -1}
if strings.Contains(content, "\r\n") {
fm.cr = "\r"
}
isDelim := func(l string) bool { return strings.TrimRight(l, " \t\r") == "---" }
for i, l := range fm.lines {
if fm.open < 0 {
if isDelim(l) {
fm.open = i
} else if strings.TrimSpace(l) != "" {
break // body starts before any delimiter: no frontmatter
}
} else if isDelim(l) {
fm.end = i
break
}
}
return fm
}
// keyLine returns the index of the line holding key at column 0 (nested keys
// do not count), or -1.
func (fm frontmatterLines) keyLine(key string) int {
for i := fm.open + 1; i < fm.end; i++ {
if strings.HasPrefix(fm.lines[i], key+":") {
return i
}
}
return -1
}
// prepend returns the content with a new frontmatter block holding line.
func (fm frontmatterLines) prepend(line string) string {
return "---" + fm.cr + "\n" + line + "\n" + "---" + fm.cr + "\n" + fm.content
}
func isTrueValue(rest string) bool {
v, _, _ := strings.Cut(rest, " #")
return strings.EqualFold(strings.Trim(v, " \t\r\"'"), "true")
}