github.com/mwhudson/juju@v0.0.0-20160512215208-90ff01f3497f/generate/filetoconst.go (about) 1 // Copyright 2015 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package main 5 6 import ( 7 "bytes" 8 "fmt" 9 "io/ioutil" 10 "os" 11 "strings" 12 "text/template" 13 ) 14 15 var fileTemplate = ` 16 // Copyright {{.CopyrightYear}} Canonical Ltd. 17 // Licensed under the AGPLv3, see LICENCE file for details. 18 19 package cloud 20 21 // Generated code - do not edit. 22 23 const {{.ConstName}} = {{.Content}} 24 `[1:] 25 26 // This generator reads from a file and generates a Go file with the 27 // file's content assigned to a go constant. 28 func main() { 29 if len(os.Args) < 4 { 30 fmt.Println("Usage: filetoconst <constname> <infile> <gofile> <copyrightyear>") 31 } 32 data, err := ioutil.ReadFile(os.Args[2]) 33 if err != nil { 34 fmt.Println(err) 35 os.Exit(1) 36 } 37 38 t, err := template.New("").Parse(fileTemplate) 39 if err != nil { 40 fmt.Println(err) 41 os.Exit(1) 42 } 43 var buf bytes.Buffer 44 type content struct { 45 ConstName string 46 Content string 47 CopyrightYear string 48 } 49 contextData := fmt.Sprintf("\n%s", string(data)) 50 // Quote any ` in the data. 51 contextData = strings.Replace(contextData, "`", "`+\"`\"+`", -1) 52 t.Execute(&buf, content{ 53 ConstName: os.Args[1], 54 Content: fmt.Sprintf("`%s`", contextData), 55 CopyrightYear: os.Args[4], 56 }) 57 58 err = ioutil.WriteFile(os.Args[3], buf.Bytes(), 0644) 59 if err != nil { 60 fmt.Println(err) 61 os.Exit(1) 62 } 63 }