Skip to content

Commit 1b59dab

Browse files
committed
Implement tern template support
1 parent a18363b commit 1b59dab

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

‎internal/compiler/compile.go‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,11 @@ func (c *Compiler) parseCatalog(schemas []string) error {
3838
continue
3939
}
4040
contents := migrations.RemoveRollbackStatements(string(blob))
41+
contents, err = migrations.TransformStatements(filepath.Dir(filename), contents)
42+
if err != nil {
43+
merr.Add(filename, contents, 0, err)
44+
continue
45+
}
4146
c.schema = append(c.schema, contents)
4247
stmts, err := c.parser.Parse(strings.NewReader(contents))
4348
if err != nil {

‎internal/migrations/migrations.go‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@ package migrations
22

33
import (
44
"bufio"
5+
"errors"
6+
"fmt"
7+
"os"
8+
"path"
9+
"regexp"
510
"strings"
611
)
712

@@ -37,3 +42,38 @@ func IsDown(filename string) bool {
3742
// Remove golang-migrate rollback files.
3843
return strings.HasSuffix(filename, ".down.sql")
3944
}
45+
46+
var ternTemplateRegex *regexp.Regexp
47+
48+
// tern: {{ template "filepath" . }}
49+
func TransformStatements(pwd, content string) (string, error) {
50+
if !strings.Contains(content, "{{ template \"") {
51+
return content, nil
52+
}
53+
54+
var err error
55+
var processed string
56+
57+
if ternTemplateRegex == nil {
58+
defer func() {
59+
if r := recover(); r != nil {
60+
fmt.Printf("failed to compile regexp: %v\n", r)
61+
}
62+
// It is tested, just recovering for it's technically possible to panic
63+
}()
64+
ternTemplateRegex = regexp.MustCompile(`\{\{ template \"(.+)\" \. \}\}`)
65+
}
66+
67+
processed = ternTemplateRegex.ReplaceAllStringFunc(content, func(match string) string {
68+
filePath := ternTemplateRegex.FindStringSubmatch(match)[1]
69+
filePath = path.Join(pwd, filePath)
70+
read, err := os.ReadFile(filePath)
71+
if err != nil {
72+
err = errors.Join(err, fmt.Errorf("error reading file %s: %w", filePath, err))
73+
return match
74+
}
75+
return string(read)
76+
})
77+
78+
return processed, err
79+
}

0 commit comments

Comments
 (0)