-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
111 lines (105 loc) · 2.6 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
105
106
107
108
109
110
111
package main
import (
"encoding/base64"
"flag"
"fmt"
"io/ioutil"
"os"
)
const (
missingParameter = "missing-parameter"
outputLinesMaxLength = 64
)
func main() {
var err error
var packageName string
var variableName string
var outputFileName string
flag.StringVar(&packageName,
"package",
missingParameter,
"package name to use on generated files",
)
flag.StringVar(&variableName,
"variable",
missingParameter,
"output variable name",
)
flag.StringVar(&outputFileName,
"output",
missingParameter,
"output file name",
)
flag.Parse()
inputFileName := flag.Arg(0)
if packageName == "" || packageName == missingParameter {
fmt.Println("invalid or missing package name")
os.Exit(1)
}
if variableName == "" || variableName == missingParameter {
fmt.Println("invalid or missing constant name")
os.Exit(1)
}
if outputFileName == "" || outputFileName == missingParameter {
fmt.Println("invalid or missing output file name")
os.Exit(1)
}
var inputContentBytes []byte
if inputFileName == "-" {
inputContentBytes, err = ioutil.ReadAll(os.Stdin)
} else {
inputContentBytes, err = ioutil.ReadFile(inputFileName)
}
if err != nil {
fmt.Printf("invalid or missing input file or file name: %s\n", err.Error())
os.Exit(1)
}
encodedInput := base64.StdEncoding.EncodeToString(inputContentBytes)
var outputFile *os.File
if outputFileName == "-" {
outputFile = os.Stdout
} else {
outputFile, err = os.OpenFile(outputFileName, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
defer func() {
_ = outputFile.Close()
}()
if err != nil {
fmt.Printf("unable to open output file: %s\n", err.Error())
os.Exit(1)
}
}
outputDataLines := []string{
fmt.Sprintf("package %s", packageName),
"",
"import (",
fmt.Sprintf("\t%#v", "encoding/base64"),
")",
"",
fmt.Sprintf("var %s []byte", variableName),
"",
"func init() {",
fmt.Sprintf("\t%s, _ = base64.StdEncoding.DecodeString(", variableName),
fmt.Sprintf("\t\t%#v +", ""),
}
for len(encodedInput) > 0 {
lineLength := outputLinesMaxLength
if len(encodedInput) < outputLinesMaxLength {
lineLength = len(encodedInput)
}
outputLine := fmt.Sprintf("\t\t\t%#v +", encodedInput[0:lineLength])
outputDataLines = append(outputDataLines, outputLine)
encodedInput = encodedInput[lineLength:]
}
outputDataLines = append(outputDataLines, []string{
fmt.Sprintf("\t\t\t%#v,", ""),
"\t)",
"}",
}...)
for _, outputLine := range outputDataLines {
_, err := fmt.Fprintln(outputFile, outputLine)
if err != nil {
fmt.Printf("error writing to output file line %#v: %s\n", outputLine, err.Error())
os.Exit(1)
}
}
}