github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/generate/filetoconst/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 {{.Pkgname}}
    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) < 5 {
    30  		fmt.Println("Usage: filetoconst <constname> <infile> <gofile> <copyrightyear> <pkgname>")
    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  		Pkgname       string
    49  	}
    50  	contextData := fmt.Sprintf("%s", string(data))
    51  	// Quote any ` in the data.
    52  	contextData = strings.Replace(contextData, "`", "`+\"`\"+`", -1)
    53  	t.Execute(&buf, content{
    54  		ConstName:     os.Args[1],
    55  		Content:       fmt.Sprintf("`%s`", contextData),
    56  		CopyrightYear: os.Args[4],
    57  		Pkgname:       os.Args[5],
    58  	})
    59  
    60  	err = ioutil.WriteFile(os.Args[3], buf.Bytes(), 0644)
    61  	if err != nil {
    62  		fmt.Println(err)
    63  		os.Exit(1)
    64  	}
    65  }