-
-
Notifications
You must be signed in to change notification settings - Fork 181
/
process.go
123 lines (106 loc) · 2.51 KB
/
process.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
)
// == Direct input processing ========================================
func processInputFiles(stringTemplate string, input []string, output []string, g *Gomplate) error {
input, err := readInputs(stringTemplate, input)
if err != nil {
return err
}
if len(output) == 0 {
output = []string{"-"}
}
for n, input := range input {
if err := renderTemplate(g, input, output[n]); err != nil {
return err
}
}
return nil
}
// == Recursive input dir processing ======================================
func processInputDir(input string, output string, g *Gomplate) error {
input = filepath.Clean(input)
output = filepath.Clean(output)
// assert tha input path exists
si, err := os.Stat(input)
if err != nil {
return err
}
// read directory
entries, err := ioutil.ReadDir(input)
if err != nil {
return err
}
// ensure output directory
if err = os.MkdirAll(output, si.Mode()); err != nil {
return err
}
// process or dive in again
for _, entry := range entries {
nextInPath := filepath.Join(input, entry.Name())
nextOutPath := filepath.Join(output, entry.Name())
if entry.IsDir() {
err := processInputDir(nextInPath, nextOutPath, g)
if err != nil {
return err
}
} else {
inString, err := readInput(nextInPath)
if err != nil {
return err
}
if err := renderTemplate(g, inString, nextOutPath); err != nil {
return err
}
}
}
return nil
}
// == File handling ================================================
func readInputs(input string, files []string) ([]string, error) {
if input != "" {
return []string{input}, nil
}
if len(files) == 0 {
files = []string{"-"}
}
ins := make([]string, len(files))
for n, filename := range files {
inString, err := readInput(filename)
if err != nil {
return nil, err
}
ins[n] = inString
}
return ins, nil
}
func readInput(filename string) (string, error) {
var err error
var inFile *os.File
if filename == "-" {
inFile = os.Stdin
} else {
inFile, err = os.Open(filename)
if err != nil {
return "", fmt.Errorf("failed to open %s\n%v", filename, err)
}
// nolint: errcheck
defer inFile.Close()
}
bytes, err := ioutil.ReadAll(inFile)
if err != nil {
err = fmt.Errorf("read failed for %s\n%v", filename, err)
return "", err
}
return string(bytes), nil
}
func openOutFile(filename string) (out *os.File, err error) {
if filename == "-" {
return os.Stdout, nil
}
return os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
}