/
document.go
88 lines (70 loc) · 2.07 KB
/
document.go
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package project
import (
"io"
"os"
"github.com/go-git/go-billy/v5"
"github.com/go-git/go-billy/v5/osfs"
"github.com/go-git/go-billy/v5/util"
"github.com/pkg/errors"
"github.com/stateful/runme/internal/document"
"github.com/stateful/runme/internal/renderer/cmark"
)
func ReadMarkdownFile(filepath string, fs billy.Basic) ([]byte, error) {
if fs == nil {
fs = osfs.Default
}
f, err := fs.Open(filepath)
if err != nil {
var pathError *os.PathError
if errors.As(err, &pathError) {
return nil, errors.Errorf("failed to %s markdown file %s: %s", pathError.Op, pathError.Path, pathError.Err.Error())
}
return nil, errors.Wrapf(err, "failed to read %s", filepath)
}
defer func() { _ = f.Close() }()
data, err := io.ReadAll(f)
if err != nil {
return nil, errors.Wrapf(err, "failed to read data")
}
return data, nil
}
func WriteMarkdownFile(filename string, fs billy.Basic, data []byte) error {
if fs == nil {
fs = osfs.Default
}
return util.WriteFile(fs, filename, data, 0o600)
}
func parseDocumentForCodeBlocks(filepath string, fs billy.Basic, doFrontmatter bool) (document.CodeBlocks, *document.Frontmatter, error) {
data, err := ReadMarkdownFile(filepath, fs)
if err != nil {
return nil, nil, err
}
var fmtr *document.Frontmatter
if doFrontmatter {
sections, err := document.ParseSections(data)
if err != nil {
return nil, nil, err
}
f, _ := document.ParseFrontmatter(string(sections.FrontMatter))
fmtr = &f
}
doc := document.New(data, cmark.Render)
node, _, err := doc.Parse()
if err != nil {
return nil, nil, err
}
blocks := document.CollectCodeBlocks(node)
return blocks, fmtr, nil
}
func GetCodeBlocksAndParseFrontmatter(filepath string, fs billy.Basic) (document.CodeBlocks, document.Frontmatter, error) {
blocks, fmtr, err := parseDocumentForCodeBlocks(filepath, fs, true)
var f document.Frontmatter
if fmtr != nil {
f = *fmtr
}
return blocks, f, err
}
func GetCodeBlocks(filepath string, fs billy.Basic) (document.CodeBlocks, error) {
blocks, _, err := parseDocumentForCodeBlocks(filepath, fs, false)
return blocks, err
}