diff --git a/jinja2.go b/jinja2.go index a7b3f73..d8d2778 100644 --- a/jinja2.go +++ b/jinja2.go @@ -17,7 +17,7 @@ import ( ) type Jinja2 struct { - ep *python.EmbeddedPython + ep python.Python extractDir string jinja2Lib *embed_util.EmbeddedFiles rendererSrc *embed_util.EmbeddedFiles @@ -69,9 +69,13 @@ func NewJinja2(name string, parallelism int, opts ...Jinja2Opt) (*Jinja2, error) } tmpDir = filepath.Join(tmpDir, name) - j2.ep, err = python.NewEmbeddedPythonWithTmpDir(tmpDir+"-python", true) - if err != nil { - return nil, err + if j2.defaultOptions.python != nil { + j2.ep = j2.defaultOptions.python + } else { + j2.ep, err = python.NewEmbeddedPythonWithTmpDir(tmpDir+"-python", true) + if err != nil { + return nil, err + } } j2.jinja2Lib, err = embed_util.NewEmbeddedFilesWithTmpDir(data.Data, tmpDir+"-jinja2-lib", true) if err != nil { @@ -120,7 +124,10 @@ func (j *Jinja2) Close() { func (j *Jinja2) Cleanup() { _ = j.rendererSrc.Cleanup() _ = j.jinja2Lib.Cleanup() - _ = j.ep.Cleanup() + + if ep, ok := j.ep.(*python.EmbeddedPython); ok { + _ = ep.Cleanup() + } } func (j *Jinja2) RenderStrings(jobs []*RenderJob, opts ...Jinja2Opt) error { diff --git a/jinja2_external_python_test.go b/jinja2_external_python_test.go new file mode 100644 index 0000000..dce2fca --- /dev/null +++ b/jinja2_external_python_test.go @@ -0,0 +1,36 @@ +package jinja2 + +import ( + "fmt" + "github.com/kluctl/go-embed-python/python" + "github.com/stretchr/testify/assert" + "math/rand" + "testing" +) + +func TestExternalPython(t *testing.T) { + rndName := fmt.Sprintf("test-%d", rand.Uint32()) + ep, err := python.NewEmbeddedPython(rndName) + assert.NoError(t, err) + + j2 := newJinja2(t, WithPython(ep)) + t1 := newTemplateFile(t, `{{ "a" }}`) + + r1, err := j2.RenderFile(t1) + assert.NoError(t, err) + assert.Equal(t, "a", r1) +} + +func TestSystemPython(t *testing.T) { + ep := python.NewPython() + if _, err := ep.GetExePath(); err != nil { + t.Skipf("skipping due to missing python binary") + } + + j2 := newJinja2(t, WithPython(ep)) + t1 := newTemplateFile(t, `{{ "a" }}`) + + r1, err := j2.RenderFile(t1) + assert.NoError(t, err) + assert.Equal(t, "a", r1) +} diff --git a/opts.go b/opts.go index 9e5a310..3cd1815 100644 --- a/opts.go +++ b/opts.go @@ -1,5 +1,7 @@ package jinja2 +import "github.com/kluctl/go-embed-python/python" + type jinja2Options struct { DebugTrace bool `json:"debugTrace"` NonStrict bool `json:"nonStrict"` @@ -13,6 +15,7 @@ type jinja2Options struct { Extensions []string `json:"extensions"` // not passed to renderer + python python.Python pythonPath []string embeddedExtractDir string templateIgnoreRootPath string @@ -28,6 +31,12 @@ func WithDebugTrace(debugTrace bool) Jinja2Opt { } } +func WithPython(p python.Python) Jinja2Opt { + return func(o *jinja2Options) { + o.python = p + } +} + func WithPythonPath(p string) Jinja2Opt { return func(o *jinja2Options) { o.pythonPath = append(o.pythonPath, p)