forked from howeyc/ledger
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ledgerReader.go
93 lines (76 loc) · 2.01 KB
/
ledgerReader.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
package ledger
import (
"bufio"
"bytes"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
)
const (
markerPrefix = ";__ledger_file"
)
var includedFiles = make(map[string]bool)
func NewLedgerReader(filename string) (*bytes.Buffer, error) {
var buf bytes.Buffer
err := includeFile(filename, &buf)
return &buf, err
}
// includeFile reads filename into buf, adding special marker comments
// when there are step changes in file location due to 'include' directive.
func includeFile(filename string, buf *bytes.Buffer) error {
filename = filepath.Clean(filename)
lineNum := 0
// check for include cyles
if includedFiles[filename] {
return fmt.Errorf("include cycle: '%s'", filename)
} else {
includedFiles[filename] = true
}
defer delete(includedFiles, filename)
f, err := os.Open(filename)
if err != nil {
return err
}
defer f.Close()
s := bufio.NewScanner(f)
// mark the start of this file
fmt.Fprintln(buf, marker(filename, lineNum))
for s.Scan() {
line := s.Text()
if strings.HasPrefix(line, "include") {
pieces := strings.Split(line, " ")
if len(pieces) != 2 {
return fmt.Errorf("%s:%d: invalid include directive", filename, lineNum)
}
// Resolve filepaths
includedPath := filepath.Join(filename, "..", pieces[1])
includedPaths, err := filepath.Glob(includedPath)
// Include all resolved filepaths
for i := 0; i < len(includedPaths) && err == nil; i++ {
if !includedFiles[includedPaths[i]] {
err = includeFile(includedPaths[i], buf)
}
}
if err != nil {
return fmt.Errorf("%s:%d: %s", filename, lineNum, err.Error())
}
lineNum++
// mark the resumption point for this file
fmt.Fprintln(buf, marker(filename, lineNum))
} else {
fmt.Fprintln(buf, s.Text())
lineNum++
}
}
return nil
}
func marker(filename string, lineNum int) string {
return fmt.Sprintf("%s*-*%s*-*%d", markerPrefix, filename, lineNum)
}
func parseMarker(s string) (string, int) {
v := strings.Split(s, "*-*")
lineNum, _ := strconv.Atoi(v[2])
return v[1], lineNum
}