/
filetoconst.go
64 lines (55 loc) · 1.41 KB
/
filetoconst.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
// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package main
import (
"bytes"
"fmt"
"os"
"strings"
"text/template"
)
var fileTemplate = `
// Copyright {{.CopyrightYear}} Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
// Code generated by github.com/juju/juju/generate/filetoconst. DO NOT EDIT.
package {{.Pkgname}}
const {{.ConstName}} = {{.Content}}
`[1:]
// This generator reads from a file and generates a Go file with the
// file's content assigned to a go constant.
func main() {
if len(os.Args) < 5 {
fmt.Println("Usage: filetoconst <constname> <infile> <gofile> <copyrightyear> <pkgname>")
}
data, err := os.ReadFile(os.Args[2])
if err != nil {
fmt.Println(err)
os.Exit(1)
}
t, err := template.New("").Parse(fileTemplate)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
var buf bytes.Buffer
type content struct {
ConstName string
Content string
CopyrightYear string
Pkgname string
}
contextData := fmt.Sprintf("%s", string(data))
// Quote any ` in the data.
contextData = strings.Replace(contextData, "`", "`+\"`\"+`", -1)
_ = t.Execute(&buf, content{
ConstName: os.Args[1],
Content: fmt.Sprintf("`%s`", contextData),
CopyrightYear: os.Args[4],
Pkgname: os.Args[5],
})
err = os.WriteFile(os.Args[3], buf.Bytes(), 0644)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}