yq/pkg/yqlib/front_matter.go

95 lines
2.0 KiB
Go
Raw Normal View History

2021-07-18 02:28:46 +00:00
package yqlib
import (
"bufio"
2021-11-22 06:43:38 +00:00
"errors"
2021-07-18 02:28:46 +00:00
"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() {
2022-01-14 04:22:55 +00:00
tryRemoveTempFile(f.yamlFrontMatterFilename)
2021-07-18 02:28:46 +00:00
}
// 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)
2021-11-22 06:43:38 +00:00
if errors.Is(err, io.EOF) {
2021-07-20 00:38:42 +00:00
// 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-11-22 06:43:38 +00:00
if errReading != nil && !errors.Is(errReading, io.EOF) {
2021-07-20 00:38:42 +00:00
return errReading
}
_, errWriting := yamlTempFile.WriteString(line)
2021-07-20 00:38:42 +00:00
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
}