-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexport.go
More file actions
57 lines (49 loc) · 1.39 KB
/
export.go
File metadata and controls
57 lines (49 loc) · 1.39 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package parser
import (
"fmt"
"gopkg.in/yaml.v3"
)
// yamlSection is the serializable form of a Section for YAML export.
type yamlSection struct {
Title string `yaml:"title"`
Content string `yaml:"content,omitempty"`
Tokens int `yaml:"tokens"`
Children []yamlSection `yaml:"children,omitempty"`
}
// yamlDocument is the serializable form of a Document for YAML export.
type yamlDocument struct {
Docmap string `yaml:"docmap"`
Filename string `yaml:"filename,omitempty"`
Tokens int `yaml:"tokens"`
Sections []yamlSection `yaml:"sections"`
}
// ExportYAML serializes a Document to structured YAML.
// The output can be read back by ParseYAML to reconstruct the document.
func ExportYAML(doc *Document) (string, error) {
yd := yamlDocument{
Docmap: "1.0",
Filename: doc.Filename,
Tokens: doc.TotalTokens,
Sections: convertToYAMLSections(doc.Sections),
}
data, err := yaml.Marshal(yd)
if err != nil {
return "", fmt.Errorf("failed to marshal YAML: %w", err)
}
return string(data), nil
}
func convertToYAMLSections(sections []*Section) []yamlSection {
var result []yamlSection
for _, s := range sections {
ys := yamlSection{
Title: s.Title,
Tokens: s.Tokens,
Children: convertToYAMLSections(s.Children),
}
if s.Content != "" {
ys.Content = s.Content
}
result = append(result, ys)
}
return result
}