Skip to content

Commit 9773758

Browse files
committed
feat: front matter keys are sorted alphabetically
1 parent a274e60 commit 9773758

File tree

2 files changed

+31
-4
lines changed

2 files changed

+31
-4
lines changed

main.go

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -92,12 +92,17 @@ func parseUnquotedProperties(param string) []string {
9292
}
9393

9494
func render(p page, dontQuote []string) string {
95+
sortedKeys := make([]string, 0, len(p.attributes))
96+
for k := range p.attributes {
97+
sortedKeys = append(sortedKeys, k)
98+
}
99+
slices.Sort(sortedKeys)
95100
attributeBuilder := strings.Builder{}
96-
for name, value := range p.attributes {
97-
if slices.Contains(dontQuote, name) {
98-
attributeBuilder.WriteString(fmt.Sprintf("%s: %s\n", name, value))
101+
for _, key := range sortedKeys {
102+
if slices.Contains(dontQuote, key) {
103+
attributeBuilder.WriteString(fmt.Sprintf("%s: %s\n", key, p.attributes[key]))
99104
} else {
100-
attributeBuilder.WriteString(fmt.Sprintf("%s: %q\n", name, value))
105+
attributeBuilder.WriteString(fmt.Sprintf("%s: %q\n", key, p.attributes[key]))
101106
}
102107
}
103108
return fmt.Sprintf("---\n%s---\n%s", attributeBuilder.String(), p.text)

main_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,28 @@ func TestRender(t *testing.T) {
2121
first: "1"
2222
second: "2"
2323
---
24+
page text`, result)
25+
})
26+
t.Run("it renders attributes in alphabetical order", func(t *testing.T) {
27+
testPage := page{
28+
filename: "",
29+
attributes: map[string]string{
30+
"e": "1",
31+
"d": "1",
32+
"c": "1",
33+
"b": "1",
34+
"a": "1",
35+
},
36+
text: "page text",
37+
}
38+
result := render(testPage, []string{})
39+
require.Equal(t, `---
40+
a: "1"
41+
b: "1"
42+
c: "1"
43+
d: "1"
44+
e: "1"
45+
---
2446
page text`, result)
2547
})
2648
t.Run("it renders attributes without quotes", func(t *testing.T) {

0 commit comments

Comments
 (0)