yq/pkg/yqlib/front_matter.go

94 lines
2.0 KiB
Go
Raw Normal View History

2021-07-18 02:28:46 +00:00
package yqlib
import (
"bufio"
"io"
"os"
)
type frontMatterHandler interface {
Split() error
GetYamlFrontMatterFilename() string
2021-07-20 00:38:42 +00:00
GetContentReader() io.Reader
2021-07-18 02:28:46 +00:00
CleanUp()
}
type frontMatterHandlerImpl struct {
originalFilename string
yamlFrontMatterFilename string
2021-07-20 00:38:42 +00:00
contentReader io.Reader
2021-07-18 02:28:46 +00:00
}
func NewFrontMatterHandler(originalFilename string) frontMatterHandler {
2021-07-20 00:38:42 +00:00
return &frontMatterHandlerImpl{originalFilename, "", nil}
2021-07-18 02:28:46 +00:00
}
func (f *frontMatterHandlerImpl) GetYamlFrontMatterFilename() string {
return f.yamlFrontMatterFilename
}
2021-07-20 00:38:42 +00:00
func (f *frontMatterHandlerImpl) GetContentReader() io.Reader {
return f.contentReader
2021-07-18 02:28:46 +00:00
}
func (f *frontMatterHandlerImpl) CleanUp() {
tryRemoveFile(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 {
2021-07-20 00:38:42 +00:00
var reader *bufio.Reader
2021-07-18 02:28:46 +00:00
var err error
if f.originalFilename == "-" {
reader = bufio.NewReader(os.Stdin)
} else {
2021-07-20 00:38:42 +00:00
file, err := os.Open(f.originalFilename) // #nosec
2021-07-18 02:28:46 +00:00
if err != nil {
return err
}
2021-07-20 00:38:42 +00:00
reader = bufio.NewReader(file)
2021-07-18 02:28:46 +00:00
}
2021-07-20 00:38:42 +00:00
f.contentReader = reader
2021-07-18 02:28:46 +00:00
yamlTempFile, err := createTempFile()
if err != nil {
return err
}
f.yamlFrontMatterFilename = yamlTempFile.Name()
log.Debug("yamlTempFile: %v", yamlTempFile.Name())
lineCount := 0
2021-07-20 00:38:42 +00:00
for {
peekBytes, err := reader.Peek(3)
if err == io.EOF {
// we've finished reading the yaml content..I guess
break
} else if err != nil {
2021-07-18 02:28:46 +00:00
return err
}
2021-07-20 00:38:42 +00:00
if lineCount > 0 && string(peekBytes) == "---" {
// we've finished reading the yaml content..
break
}
line, errReading := reader.ReadString('\n')
2021-07-18 02:28:46 +00:00
lineCount = lineCount + 1
2021-07-20 00:38:42 +00:00
if errReading != nil && errReading != io.EOF {
return errReading
}
_, errWriting := yamlTempFile.Write([]byte(line))
if errWriting != nil {
return errWriting
}
2021-07-18 02:28:46 +00:00
}
safelyCloseFile(yamlTempFile)
2021-07-20 00:38:42 +00:00
return nil
2021-07-18 02:28:46 +00:00
}