diff --git a/pkg/frontmatter/frontmatter.go b/pkg/frontmatter/frontmatter.go index cad29c63..ca3ea72c 100644 --- a/pkg/frontmatter/frontmatter.go +++ b/pkg/frontmatter/frontmatter.go @@ -1,6 +1,7 @@ package frontmatter import ( + "bytes" "errors" "strings" @@ -61,26 +62,27 @@ func SetKey(content, key, value string) (string, error) { return Delimiter + "\n" + string(fmStr) + Delimiter + "\n" + content, nil } - // Parse existing frontmatter - fm, body, err := Parse(content) - if err != nil { + var valueNode yaml.Node + if err := valueNode.Encode(parsedValue); err != nil { return "", err } - if fm == nil { - fm = make(map[string]interface{}) - } - - // Update the key - fm[key] = parsedValue - - // Reconstruct content - fmStr, err := yaml.Marshal(fm) + fm, body, err := parseNode(content) if err != nil { return "", err } - return Delimiter + "\n" + string(fmStr) + Delimiter + "\n" + body, nil + if i := keyIndex(fm, key); i >= 0 { + old := fm.Content[i+1] + valueNode.HeadComment, valueNode.LineComment, valueNode.FootComment = old.HeadComment, old.LineComment, old.FootComment + fm.Content[i+1] = &valueNode + resolveAliases(fm, old) + removeKey(fm, key, i+2) + } else { + fm.Content = append(fm.Content, &yaml.Node{Kind: yaml.ScalarNode, Value: key}, &valueNode) + } + + return formatNode(fm, body) } // DeleteKey removes a key from the frontmatter, returning the full updated content. @@ -89,30 +91,116 @@ func DeleteKey(content, key string) (string, error) { return "", errors.New(NoFrontmatterError) } - fm, body, err := Parse(content) + fm, body, err := parseNode(content) if err != nil { return "", err } - if fm == nil { - return "", errors.New(NoFrontmatterError) - } - - // Delete the key - delete(fm, key) + removeKey(fm, key, 0) // If no keys left, return just the body - if len(fm) == 0 { + if len(fm.Content) == 0 { return strings.TrimPrefix(body, "\n"), nil } - // Reconstruct content - fmStr, err := yaml.Marshal(fm) + return formatNode(fm, body) +} + +// parseNode parses the frontmatter as a YAML mapping node, so that edits keep +// the other properties as written (values, order and comments). +func parseNode(content string) (*yaml.Node, string, error) { + var raw []byte + format := frontmatter.NewFormat(Delimiter, Delimiter, func(data []byte, v interface{}) error { + *v.(*[]byte) = data + return nil + }) + rest, err := frontmatter.Parse(strings.NewReader(content), &raw, format) if err != nil { - return "", err + return nil, "", errors.New(InvalidFrontmatterError) + } + + var doc yaml.Node + if err := yaml.Unmarshal(raw, &doc); err != nil { + return nil, "", errors.New(InvalidFrontmatterError) + } + if len(doc.Content) == 0 { + return &yaml.Node{Kind: yaml.MappingNode}, string(rest), nil + } + if doc.Content[0].Kind != yaml.MappingNode { + return nil, "", errors.New(InvalidFrontmatterError) } + return doc.Content[0], string(rest), nil +} + +// removeKey removes every entry for key at or after index from, so that a +// duplicated key does not keep its old value. Aliases to a removed value are +// replaced by a copy of it, so the frontmatter stays valid. +func removeKey(mapping *yaml.Node, key string, from int) { + for i := from; i+1 < len(mapping.Content); { + if mapping.Content[i].Value != key { + i += 2 + continue + } + removed := mapping.Content[i+1] + mapping.Content = append(mapping.Content[:i], mapping.Content[i+2:]...) + resolveAliases(mapping, removed) + } +} + +// resolveAliases replaces aliases in node that point into the removed subtree +// with copies of the nodes they point to. +func resolveAliases(node, removed *yaml.Node) { + anchors := map[*yaml.Node]bool{} + var collect func(*yaml.Node) + collect = func(n *yaml.Node) { + if n.Anchor != "" { + anchors[n] = true + } + for _, c := range n.Content { + collect(c) + } + } + collect(removed) + if len(anchors) == 0 { + return + } + + var walk func(*yaml.Node) + walk = func(n *yaml.Node) { + for i, c := range n.Content { + if c.Kind == yaml.AliasNode && anchors[c.Alias] { + copied := *c.Alias + copied.Anchor = "" + n.Content[i] = &copied + continue + } + walk(c) + } + } + walk(node) +} + +// keyIndex returns the index of key in a mapping node's content, or -1. +func keyIndex(mapping *yaml.Node, key string) int { + for i := 0; i+1 < len(mapping.Content); i += 2 { + if mapping.Content[i].Value == key { + return i + } + } + return -1 +} - return Delimiter + "\n" + string(fmStr) + Delimiter + "\n" + body, nil +func formatNode(fm *yaml.Node, body string) (string, error) { + var buf bytes.Buffer + enc := yaml.NewEncoder(&buf) + enc.SetIndent(2) + if err := enc.Encode(fm); err != nil { + return "", err + } + if err := enc.Close(); err != nil { + return "", err + } + return Delimiter + "\n" + buf.String() + Delimiter + "\n" + body, nil } // parseValue attempts to parse the value into appropriate Go types. diff --git a/pkg/frontmatter/frontmatter_test.go b/pkg/frontmatter/frontmatter_test.go index 5e7d1ed5..f631e1e3 100644 --- a/pkg/frontmatter/frontmatter_test.go +++ b/pkg/frontmatter/frontmatter_test.go @@ -170,3 +170,39 @@ func TestDeleteKey(t *testing.T) { assert.Contains(t, result, "title: Test") }) } + +func TestEditKeepsOtherProperties(t *testing.T) { + content := "---\ncountry: NO\nvisa needed: no # answered\noptions: [y, n, on, off]\nversion: 1.10\nzip: 02134\n---\nBody" + + t.Run("SetKey", func(t *testing.T) { + result, err := frontmatter.SetKey(content, "status", "done") + assert.NoError(t, err) + assert.Equal(t, "---\ncountry: NO\nvisa needed: no # answered\noptions: [y, n, on, off]\nversion: 1.10\nzip: 02134\nstatus: done\n---\nBody", result) + }) + + t.Run("DeleteKey", func(t *testing.T) { + result, err := frontmatter.DeleteKey(content, "zip") + assert.NoError(t, err) + assert.Equal(t, "---\ncountry: NO\nvisa needed: no # answered\noptions: [y, n, on, off]\nversion: 1.10\n---\nBody", result) + }) +} + +func TestEditEdgeCases(t *testing.T) { + t.Run("SetKey keeps the line comment of the replaced value", func(t *testing.T) { + result, err := frontmatter.SetKey("---\ntitle: a # note\n---\nBody", "title", "b") + assert.NoError(t, err) + assert.Equal(t, "---\ntitle: b # note\n---\nBody", result) + }) + + t.Run("SetKey replaces duplicated keys", func(t *testing.T) { + result, err := frontmatter.SetKey("---\ntitle: a\ntitle: b\n---\nBody", "title", "c") + assert.NoError(t, err) + assert.Equal(t, "---\ntitle: c\n---\nBody", result) + }) + + t.Run("DeleteKey keeps aliases to the deleted value valid", func(t *testing.T) { + result, err := frontmatter.DeleteKey("---\nbase: &b x\ncopy: *b\n---\nBody", "base") + assert.NoError(t, err) + assert.Equal(t, "---\ncopy: x\n---\nBody", result) + }) +}