-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathmigrations.go
More file actions
79 lines (70 loc) · 1.88 KB
/
migrations.go
File metadata and controls
79 lines (70 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package migrations
import (
"bufio"
"errors"
"fmt"
"os"
"path"
"regexp"
"strings"
)
// Remove all lines after a rollback comment.
//
// goose: -- +goose Down
// sql-migrate: -- +migrate Down
// tern: ---- create above / drop below ----
// dbmate: -- migrate:down
func RemoveRollbackStatements(contents string) string {
s := bufio.NewScanner(strings.NewReader(contents))
var lines []string
for s.Scan() {
statement := strings.ToLower(s.Text())
if strings.HasPrefix(statement, "-- +goose down") {
break
}
if strings.HasPrefix(statement, "-- +migrate down") {
break
}
if strings.HasPrefix(statement, "---- create above / drop below ----") {
break
}
if strings.HasPrefix(statement, "-- migrate:down") {
break
}
lines = append(lines, s.Text())
}
return strings.Join(lines, "\n")
}
func IsDown(filename string) bool {
// Remove golang-migrate rollback files.
return strings.HasSuffix(filename, ".down.sql")
}
var ternTemplateRegex *regexp.Regexp
// tern: {{ template "filepath" . }}
func TransformStatements(pwd, content string) (string, error) {
if !strings.Contains(content, "{{ template \"") {
return content, nil
}
var err error
var processed string
if ternTemplateRegex == nil {
defer func() {
if r := recover(); r != nil {
fmt.Printf("failed to compile regexp: %v\n", r)
}
// It is tested, just recovering for it's technically possible to panic
}()
ternTemplateRegex = regexp.MustCompile(`\{\{ template \"(.+)\" \. \}\}`)
}
processed = ternTemplateRegex.ReplaceAllStringFunc(content, func(match string) string {
filePath := ternTemplateRegex.FindStringSubmatch(match)[1]
filePath = path.Join(pwd, filePath)
read, err := os.ReadFile(filePath)
if err != nil {
err = errors.Join(err, fmt.Errorf("error reading file %s: %w", filePath, err))
return match
}
return string(read)
})
return processed, err
}