Embed data files in the binary (#180)
Now that we're on Go 1.16+ we can do this easily! The main advantage is it means users can build a genqlient binary and use that portably (or we could distribute one, or whatever). Plus the code is marginally simpler; the `embed` API is really quite nice. Fixes #9. Test plan: ``` make check go build . rm -rf generate # pretend we have no checkout ./genqlient ./internal/integration/genqlient.yaml ./genqlient --init # fails after generating a default config ```
This commit is contained in:
+5
-11
@@ -1,19 +1,14 @@
|
||||
package generate
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"io"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"text/template"
|
||||
)
|
||||
|
||||
var (
|
||||
// TODO(benkraft): Embed templates into the binary, see
|
||||
// https://github.com/Khan/genqlient/issues/9.
|
||||
_, thisFilename, _, _ = runtime.Caller(0)
|
||||
thisDir = filepath.Dir(thisFilename)
|
||||
)
|
||||
//go:embed *.tmpl
|
||||
var templates embed.FS
|
||||
|
||||
func repeat(n int, s string) string {
|
||||
var builder strings.Builder
|
||||
@@ -37,7 +32,6 @@ func sub(x, y int) int { return x - y }
|
||||
func (g *generator) render(tmplRelFilename string, w io.Writer, data interface{}) error {
|
||||
tmpl := g.templateCache[tmplRelFilename]
|
||||
if tmpl == nil {
|
||||
absFilename := filepath.Join(thisDir, tmplRelFilename)
|
||||
funcMap := template.FuncMap{
|
||||
"ref": g.ref,
|
||||
"repeat": repeat,
|
||||
@@ -45,9 +39,9 @@ func (g *generator) render(tmplRelFilename string, w io.Writer, data interface{}
|
||||
"sub": sub,
|
||||
}
|
||||
var err error
|
||||
tmpl, err = template.New(tmplRelFilename).Funcs(funcMap).ParseFiles(absFilename)
|
||||
tmpl, err = template.New(tmplRelFilename).Funcs(funcMap).ParseFS(templates, tmplRelFilename)
|
||||
if err != nil {
|
||||
return errorf(nil, "could not load template %v: %v", absFilename, err)
|
||||
return errorf(nil, "could not load template %v: %v", tmplRelFilename, err)
|
||||
}
|
||||
g.templateCache[tmplRelFilename] = tmpl
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user