code.pablomurad.com

patchwork

Publishes the revisions of your pages as a feed, with notes and readable diffs, written in Go

internal/diff/meta.go raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package diff

import (
	"encoding/json"

	"git.pablomurad.com/pablo/patchwork/internal/doc"
)

// MetaChange is a change to a frontmatter value readers see, like the title.
type MetaChange struct {
	Key string `json:"key"`
	Old any    `json:"old"`
	New any    `json:"new"`
}

// Meta lists changes to the given frontmatter keys and to the maturity.
func Meta(old, new *doc.Doc, keys []string) []MetaChange {
	var out []MetaChange
	for _, k := range keys {
		a, b := old.MetaValue(k), new.MetaValue(k)
		if !sameValue(a, b) {
			out = append(out, MetaChange{Key: k, Old: a, New: b})
		}
	}
	if old.Maturity != new.Maturity {
		out = append(out, MetaChange{Key: "maturity", Old: nullable(old.Maturity), New: nullable(new.Maturity)})
	}
	return out
}

func sameValue(a, b any) bool {
	ja, _ := json.Marshal(a)
	jb, _ := json.Marshal(b)
	return string(ja) == string(jb)
}

func nullable(s string) any {
	if s == "" {
		return nil
	}
	return s
}