-
-
Notifications
You must be signed in to change notification settings - Fork 753
Expand file tree
/
Copy pathutils.go
More file actions
91 lines (77 loc) · 2.31 KB
/
utils.go
File metadata and controls
91 lines (77 loc) · 2.31 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
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
package yqlib
import (
"bufio"
"container/list"
"errors"
"fmt"
"io"
"os"
)
// filenameAliases maps real file paths to display names.
// Used by front matter handling to preserve original filenames
// when the actual content is read from temporary files.
var filenameAliases = map[string]string{}
// SetFilenameAlias registers a display name for a file path so that
// the filename operator returns the original name instead of a temp path.
func SetFilenameAlias(realPath string, displayName string) {
filenameAliases[realPath] = displayName
}
// ClearFilenameAliases removes all filename aliases.
func ClearFilenameAliases() {
filenameAliases = map[string]string{}
}
func resolveFilename(filename string) string {
if alias, ok := filenameAliases[filename]; ok {
return alias
}
return filename
}
func readStream(filename string) (io.Reader, error) {
var reader *bufio.Reader
if filename == "-" {
reader = bufio.NewReader(os.Stdin)
} else {
// ignore CWE-22 gosec issue - that's more targeted for http based apps that run in a public directory,
// and ensuring that it's not possible to give a path to a file outside that directory.
file, err := os.Open(filename) // #nosec
if err != nil {
return nil, err
}
reader = bufio.NewReader(file)
}
return reader, nil
}
func writeString(writer io.Writer, txt string) error {
_, errorWriting := writer.Write([]byte(txt))
return errorWriting
}
func ReadDocuments(reader io.Reader, decoder Decoder) (*list.List, error) {
return readDocuments(reader, "", 0, decoder)
}
func readDocuments(reader io.Reader, filename string, fileIndex int, decoder Decoder) (*list.List, error) {
filename = resolveFilename(filename)
err := decoder.Init(reader)
if err != nil {
return nil, err
}
inputList := list.New()
var currentIndex uint
for {
candidateNode, errorReading := decoder.Decode()
if errors.Is(errorReading, io.EOF) {
switch reader := reader.(type) {
case *os.File:
safelyCloseFile(reader)
}
return inputList, nil
} else if errorReading != nil {
return nil, fmt.Errorf("bad file '%v': %w", filename, errorReading)
}
candidateNode.document = currentIndex
candidateNode.filename = filename
candidateNode.fileIndex = fileIndex
candidateNode.EvaluateTogether = true
inputList.PushBack(candidateNode)
currentIndex = currentIndex + 1
}
}