-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
77 lines (59 loc) · 1.55 KB
/
main.go
File metadata and controls
77 lines (59 loc) · 1.55 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
package main
import (
"bufio"
"io/ioutil"
"log"
"os"
"regexp"
"strings"
)
func main() {
if len(os.Args) < 2 {
log.Fatalln("No input file given")
}
inputFileName := os.Args[1]
var outputFileName string
if len(os.Args) > 2 {
outputFileName = os.Args[2]
log.Printf("Replacing variable references in file %s, output file is %s", inputFileName, outputFileName)
} else {
outputFileName = inputFileName
log.Printf("Replacing variable references in file %s in place", inputFileName)
}
info, err := os.Stat(inputFileName)
origPerms := info.Mode().Perm()
newContent := readAndReplace(inputFileName)
err = ioutil.WriteFile(outputFileName, []byte(newContent), origPerms)
if err != nil {
log.Fatalln(err)
}
}
func readAndReplace(fileName string) string {
file, err := os.Open(fileName)
if err != nil {
log.Fatalln("Failed to open file")
}
defer file.Close()
scanner := bufio.NewScanner(file)
if err := scanner.Err(); err != nil {
log.Fatalln(err)
}
var output []string
for scanner.Scan() {
line := scanner.Text()
r, _ := regexp.Compile(".*(\\${\\w*}).*")
result := r.FindStringSubmatch(line)
if len(result) == 2 {
varName := result[1][2 : len(result[1])-1]
osVar, found := os.LookupEnv(varName)
if found {
line = strings.Replace(result[0], result[1], osVar, -1)
log.Printf("Replacing placeholder '%s' with environment variable\n", result[1])
} else {
log.Printf("Environment variable '%s' was not set or empty\n", result[1])
}
}
output = append(output, line)
}
return strings.Join(output, "\n")
}