-
Notifications
You must be signed in to change notification settings - Fork 522
/
provider_collect.go
196 lines (188 loc) · 5.97 KB
/
provider_collect.go
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
package goose
import (
"errors"
"fmt"
"io/fs"
"path/filepath"
"sort"
"strings"
)
// fileSources represents a collection of migration files on the filesystem.
type fileSources struct {
sqlSources []Source
goSources []Source
}
// collectFilesystemSources scans the file system for migration files that have a numeric prefix
// (greater than one) followed by an underscore and a file extension of either .go or .sql. fsys may
// be nil, in which case an empty fileSources is returned.
//
// If strict is true, then any error parsing the numeric component of the filename will result in an
// error. The file is skipped otherwise.
//
// This function DOES NOT parse SQL migrations or merge registered Go migrations. It only collects
// migration sources from the filesystem.
func collectFilesystemSources(
fsys fs.FS,
strict bool,
excludePaths map[string]bool,
excludeVersions map[int64]bool,
) (*fileSources, error) {
if fsys == nil {
return new(fileSources), nil
}
sources := new(fileSources)
versionToBaseLookup := make(map[int64]string) // map[version]filepath.Base(fullpath)
for _, pattern := range []string{
"*.sql",
"*.go",
} {
files, err := fs.Glob(fsys, pattern)
if err != nil {
return nil, fmt.Errorf("failed to glob pattern %q: %w", pattern, err)
}
for _, fullpath := range files {
base := filepath.Base(fullpath)
if strings.HasSuffix(base, "_test.go") {
continue
}
if excludePaths[base] {
// TODO(mf): log this?
continue
}
// If the filename has a valid looking version of the form: NUMBER_.{sql,go}, then use
// that as the version. Otherwise, ignore it. This allows users to have arbitrary
// filenames, but still have versioned migrations within the same directory. For
// example, a user could have a helpers.go file which contains unexported helper
// functions for migrations.
version, err := NumericComponent(base)
if err != nil {
if strict {
return nil, fmt.Errorf("failed to parse numeric component from %q: %w", base, err)
}
continue
}
if excludeVersions[version] {
// TODO: log this?
continue
}
// Ensure there are no duplicate versions.
if existing, ok := versionToBaseLookup[version]; ok {
return nil, fmt.Errorf("found duplicate migration version %d:\n\texisting:%v\n\tcurrent:%v",
version,
existing,
base,
)
}
switch filepath.Ext(base) {
case ".sql":
sources.sqlSources = append(sources.sqlSources, Source{
Type: TypeSQL,
Path: fullpath,
Version: version,
})
case ".go":
sources.goSources = append(sources.goSources, Source{
Type: TypeGo,
Path: fullpath,
Version: version,
})
default:
// Should never happen since we already filtered out all other file types.
return nil, fmt.Errorf("invalid file extension: %q", base)
}
// Add the version to the lookup map.
versionToBaseLookup[version] = base
}
}
return sources, nil
}
func newSQLMigration(source Source) *Migration {
return &Migration{
Type: source.Type,
Version: source.Version,
Source: source.Path,
construct: true,
Next: -1, Previous: -1,
sql: sqlMigration{
Parsed: false, // SQL migrations are parsed lazily.
},
}
}
func merge(sources *fileSources, registered map[int64]*Migration) ([]*Migration, error) {
var migrations []*Migration
migrationLookup := make(map[int64]*Migration)
// Add all SQL migrations to the list of migrations.
for _, source := range sources.sqlSources {
m := newSQLMigration(source)
migrations = append(migrations, m)
migrationLookup[source.Version] = m
}
// If there are no Go files in the filesystem and no registered Go migrations, return early.
if len(sources.goSources) == 0 && len(registered) == 0 {
return migrations, nil
}
// Return an error if the given sources contain a versioned Go migration that has not been
// registered. This is a sanity check to ensure users didn't accidentally create a valid looking
// Go migration file on disk and forget to register it.
//
// This is almost always a user error.
var unregistered []string
for _, s := range sources.goSources {
m, ok := registered[s.Version]
if !ok {
unregistered = append(unregistered, s.Path)
} else {
// Populate the source path for registered Go migrations that have a corresponding file
// on disk.
m.Source = s.Path
}
}
if len(unregistered) > 0 {
return nil, unregisteredError(unregistered)
}
// Add all registered Go migrations to the list of migrations, checking for duplicate versions.
//
// Important, users can register Go migrations manually via goose.Add_ functions. These
// migrations may not have a corresponding file on disk. Which is fine! We include them
// wholesale as part of migrations. This allows users to build a custom binary that only embeds
// the SQL migration files.
for version, r := range registered {
// Ensure there are no duplicate versions.
if existing, ok := migrationLookup[version]; ok {
fullpath := r.Source
if fullpath == "" {
fullpath = "no source path"
}
return nil, fmt.Errorf("found duplicate migration version %d:\n\texisting:%v\n\tcurrent:%v",
version,
existing.Source,
fullpath,
)
}
migrations = append(migrations, r)
migrationLookup[version] = r
}
// Sort migrations by version in ascending order.
sort.Slice(migrations, func(i, j int) bool {
return migrations[i].Version < migrations[j].Version
})
return migrations, nil
}
func unregisteredError(unregistered []string) error {
const (
hintURL = "https://github.com/pressly/goose/tree/master/examples/go-migrations"
)
f := "file"
if len(unregistered) > 1 {
f += "s"
}
var b strings.Builder
b.WriteString(fmt.Sprintf("error: detected %d unregistered Go %s:\n", len(unregistered), f))
for _, name := range unregistered {
b.WriteString("\t" + name + "\n")
}
hint := fmt.Sprintf("hint: go functions must be registered and built into a custom binary see:\n%s", hintURL)
b.WriteString(hint)
b.WriteString("\n")
return errors.New(b.String())
}