-
Notifications
You must be signed in to change notification settings - Fork 14
/
goenvtemplator.go
100 lines (85 loc) · 2.22 KB
/
goenvtemplator.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
package main
import (
"errors"
"flag"
"fmt"
"log"
"os"
"os/exec"
"strings"
"syscall"
)
type templatePaths struct {
source string
destination string
}
func (t templatePaths) String() string {
return fmt.Sprintf("{source: '%s', destination: '%s'}", t.source, t.destination)
}
type templatesPaths []templatePaths
func (ts *templatesPaths) Set(value string) error {
var t templatePaths
parts := strings.Split(value, ":")
if len(parts) == 2 {
t.source = strings.TrimSpace(parts[0])
t.destination = strings.TrimSpace(parts[1])
} else {
return errors.New("Option has invalid format!")
}
*ts = append(*ts, t)
return nil
}
func (ts *templatesPaths) String() string {
return fmt.Sprintf("%v", *ts)
}
func generateTemplates(ts templatesPaths, debug bool) error {
for _, t := range ts {
if v > 0 {
log.Printf("generating %s -> %s", t.source, t.destination)
}
if err := generateFile(t.source, t.destination, debug); err != nil {
return fmt.Errorf("Error while generating '%s' -> '%s'. %v", t.source, t.destination, err)
}
}
return nil
}
var (
v int
buildVersion string = "Build version was not specified."
)
func main() {
var tmpls templatesPaths
flag.Var(&tmpls, "template", "Template (/template:/dest). Can be passed multiple times.")
var debugTemplates bool
flag.BoolVar(&debugTemplates, "debug-templates", false, "Print processed templates to stdout.")
var doExec bool
flag.BoolVar(&doExec, "exec", false, "Activates exec by command. First non-flag arguments is the command, the rest are it's arguments.")
var printVersion bool
flag.BoolVar(&printVersion, "version", false, "Prints version.")
flag.IntVar(&v, "v", 0, "Verbosity level.")
flag.Parse()
if printVersion {
log.Printf("Version: %s", buildVersion)
os.Exit(0)
}
if v > 0 {
log.Print("Generating templates")
}
if err := generateTemplates(tmpls, debugTemplates); err != nil {
log.Fatal(err)
}
if doExec {
if flag.NArg() < 1 {
log.Fatal("Missing command to execute!")
}
args := flag.Args()
cmd := args[0]
cmdPath, err := exec.LookPath(cmd)
if err != nil {
log.Fatal(err)
}
if err := syscall.Exec(cmdPath, args, os.Environ()); err != nil {
log.Fatalf("Unable to exec '%s'! %v", cmdPath, err)
}
}
}