-
Notifications
You must be signed in to change notification settings - Fork 12
/
main.go
104 lines (89 loc) · 2.44 KB
/
main.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
package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"path"
"strings"
)
var force bool = false
func init() {
flag.BoolVar(&force, "f", false, "Delete existing output directory")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: schelm [options] OUTPUT_DIR\n")
flag.PrintDefaults()
}
}
var yamlSeperator = []byte("---\n# Source: ")
func scanYamlSpecs(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if i := bytes.Index(data, yamlSeperator); i >= 0 {
// We have a full newline-terminated line.
return i + len(yamlSeperator), data[0:i], nil
}
// If we're at EOF, we have a final, non-terminated line. Return it.
if atEOF {
return len(data), data, nil
}
// Request more data.
return 0, nil, nil
}
func splitSpec(token string) (string, string) {
if i := strings.Index(token, "\n"); i >= 0 {
return token[0:i], token[i+1:]
}
return "", ""
}
func main() {
flag.Parse()
if flag.Arg(0) == "" {
flag.Usage()
os.Exit(1)
}
output_directory := flag.Arg(0)
if _, err := os.Stat(output_directory); !os.IsNotExist(err) {
if force {
log.Printf("Deleting %s (force)\n", output_directory)
os.RemoveAll(output_directory)
} else {
log.Fatalf(`Output directory "%v" already exists. Use -f to delete it.`, output_directory)
}
}
scanner := bufio.NewScanner(os.Stdin)
scanner.Split(scanYamlSpecs)
//Allow for tokens (specs) up to 1M in size
scanner.Buffer(make([]byte, bufio.MaxScanTokenSize), 1048576)
//Discard the first result, we only care about everything after the first seperator
scanner.Scan()
for scanner.Scan() {
source, content := splitSpec(scanner.Text())
destinationFile := path.Join(output_directory, source)
dir := path.Dir(destinationFile)
if err := os.MkdirAll(dir, 0750); err != nil {
log.Fatalf("Error creating %s: %s ", dir, err)
}
if _, err := os.Stat(destinationFile); os.IsNotExist(err) {
log.Printf("Creating %s", destinationFile)
if err := ioutil.WriteFile(destinationFile, []byte(content), 0640); err != nil {
log.Fatalf("Error: %s", err)
}
} else {
f, err := os.OpenFile(destinationFile, os.O_APPEND|os.O_WRONLY, 0640)
if err != nil {
log.Fatalf("Error re-opening file %s: %s", destinationFile, err)
}
f.WriteString("\n---\n")
f.WriteString(content)
f.Close()
}
}
if err := scanner.Err(); err != nil {
log.Fatalf("Error while processing manifest: %s", err)
}
}