-
-
Notifications
You must be signed in to change notification settings - Fork 611
/
Copy pathfront_matter.go
94 lines (78 loc) · 1.98 KB
/
front_matter.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
89
90
91
92
93
94
package yqlib
import (
"bufio"
"errors"
"io"
"os"
)
type frontMatterHandler interface {
Split() error
GetYamlFrontMatterFilename() string
GetContentReader() io.Reader
CleanUp()
}
type frontMatterHandlerImpl struct {
originalFilename string
yamlFrontMatterFilename string
contentReader io.Reader
}
func NewFrontMatterHandler(originalFilename string) frontMatterHandler {
return &frontMatterHandlerImpl{originalFilename, "", nil}
}
func (f *frontMatterHandlerImpl) GetYamlFrontMatterFilename() string {
return f.yamlFrontMatterFilename
}
func (f *frontMatterHandlerImpl) GetContentReader() io.Reader {
return f.contentReader
}
func (f *frontMatterHandlerImpl) CleanUp() {
tryRemoveTempFile(f.yamlFrontMatterFilename)
}
// Splits the given file by yaml front matter
// yaml content will be saved to first temporary file
// remaining content will be saved to second temporary file
func (f *frontMatterHandlerImpl) Split() error {
var reader *bufio.Reader
var err error
if f.originalFilename == "-" {
reader = bufio.NewReader(os.Stdin)
} else {
file, err := os.Open(f.originalFilename) // #nosec
if err != nil {
return err
}
reader = bufio.NewReader(file)
}
f.contentReader = reader
yamlTempFile, err := createTempFile()
if err != nil {
return err
}
f.yamlFrontMatterFilename = yamlTempFile.Name()
log.Debug("yamlTempFile: %v", yamlTempFile.Name())
lineCount := 0
for {
peekBytes, err := reader.Peek(3)
if errors.Is(err, io.EOF) {
// we've finished reading the yaml content..I guess
break
} else if err != nil {
return err
}
if lineCount > 0 && string(peekBytes) == "---" {
// we've finished reading the yaml content..
break
}
line, errReading := reader.ReadString('\n')
lineCount = lineCount + 1
if errReading != nil && !errors.Is(errReading, io.EOF) {
return errReading
}
_, errWriting := yamlTempFile.WriteString(line)
if errWriting != nil {
return errWriting
}
}
safelyCloseFile(yamlTempFile)
return nil
}