-
Notifications
You must be signed in to change notification settings - Fork 230
/
run.go
354 lines (317 loc) · 10.2 KB
/
run.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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
// Copyright 2021-present The Atlas Authors. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
package lint
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"strings"
"text/template"
"ariga.io/atlas/sql/migrate"
"ariga.io/atlas/sql/sqlcheck"
"ariga.io/atlas/sql/sqlclient"
"golang.org/x/exp/slices"
)
// Runner is used to execute CI jobs.
type Runner struct {
// DevClient configures the "dev driver" to calculate
// migration changes by the driver.
Dev *sqlclient.Client
// RunChangeDetector configures the ChangeDetector to
// be used by the runner.
ChangeDetector ChangeDetector
// Dir is used for scanning and validating the migration directory.
Dir migrate.Dir
// Analyzers defines the analysis to be run in the CI job.
Analyzers []sqlcheck.Analyzer
// ReportWriter writes the summary report.
ReportWriter ReportWriter
// summary report. reset on each run.
sum *SummaryReport
}
// Run executes the CI job.
func (r *Runner) Run(ctx context.Context) error {
switch err := r.summary(ctx); err.(type) {
case nil:
if err := r.ReportWriter.WriteReport(r.sum); err != nil {
return err
}
// If any of the analyzers returns
// an error, fail silently.
for _, f := range r.sum.Files {
if f.Error != "" {
return SilentError{}
}
}
return nil
case *FileError:
if err := r.ReportWriter.WriteReport(r.sum); err != nil {
return err
}
return SilentError{error: err}
default:
return err
}
}
const (
stepIntegrityCheck = "Migration Integrity Check"
stepDetectChanges = "Detect New Migration Files"
stepLoadChanges = "Replay Migration Files"
stepAnalyzeFile = "Analyze %s"
)
func (r *Runner) summary(ctx context.Context) error {
r.sum = NewSummaryReport(r.Dev, r.Dir)
// Integrity check.
switch err := migrate.Validate(r.Dir); {
case errors.Is(err, migrate.ErrChecksumNotFound):
case err != nil:
err := &FileError{File: migrate.HashFileName, Err: err}
r.sum.Files = append(r.sum.Files, &FileReport{Name: migrate.HashFileName, Error: err.Error()})
return r.sum.StepError(stepIntegrityCheck, fmt.Sprintf("File %s is invalid", migrate.HashFileName), err)
default:
r.sum.StepResult(stepIntegrityCheck, fmt.Sprintf("File %s is valid", migrate.HashFileName), nil)
}
// Detect new migration files.
base, feat, err := r.ChangeDetector.DetectChanges(ctx)
if err != nil {
return r.sum.StepError(stepDetectChanges, "Failed find new migration files", err)
}
r.sum.StepResult(stepDetectChanges, fmt.Sprintf("Found %d new migration files (from %d total)", len(feat), len(base)+len(feat)), nil)
// Load files into changes.
l := &DevLoader{Dev: r.Dev}
diff, err := l.LoadChanges(ctx, base, feat)
if err != nil {
if fr := (&FileError{}); errors.As(err, &fr) {
r.sum.Files = append(r.sum.Files, &FileReport{Name: fr.File, Error: err.Error()})
}
return r.sum.StepError(stepLoadChanges, "Failed loading changes on dev database", err)
}
r.sum.StepResult(stepLoadChanges, fmt.Sprintf("Loaded %d changes on dev database", len(diff.Files)), nil)
r.sum.WriteSchema(r.Dev, diff)
// Analyze files.
for _, f := range diff.Files {
var (
es []string
nl = nolintRules(f)
fr = NewFileReport(f)
)
for _, az := range r.Analyzers {
if err := az.Analyze(ctx, &sqlcheck.Pass{
File: f,
Dev: r.Dev,
Reporter: nl.reporterFor(fr, az),
}); err != nil && !nl.skipped {
es = append(es, err.Error())
}
}
fr.Error = strings.Join(es, "; ")
r.sum.Files = append(r.sum.Files, fr)
r.sum.StepResult(
fmt.Sprintf(stepAnalyzeFile, f.Name()),
fmt.Sprintf("%d reports were found in analysis", len(fr.Reports)),
fr,
)
}
return nil
}
var (
// TemplateFuncs are global functions available in templates.
TemplateFuncs = template.FuncMap{
"json": func(v any, args ...string) (string, error) {
var (
b []byte
err error
)
switch len(args) {
case 0:
b, err = json.Marshal(v)
case 1:
b, err = json.MarshalIndent(v, "", args[0])
default:
b, err = json.MarshalIndent(v, args[0], args[1])
}
return string(b), err
},
}
// DefaultTemplate is the default template used by the CI job.
DefaultTemplate = template.Must(template.New("report").
Funcs(TemplateFuncs).
Parse(`
{{- range $f := .Files }}
{{- /* If there is an error but not diagnostics, print it. */}}
{{- if and $f.Error (not $f.Reports) }}
{{- printf "%s: %s\n" $f.Name $f.Error }}
{{- else }}
{{- range $r := $f.Reports }}
{{- if $r.Text }}
{{- printf "%s: %s:\n\n" $f.Name $r.Text }}
{{- else if $r.Diagnostics }}
{{- printf "Unnamed diagnostics for file %s:\n\n" $f.Name }}
{{- end }}
{{- range $d := $r.Diagnostics }}
{{- printf "\tL%d: %s\n" ($f.Line $d.Pos) $d.Text }}
{{- end }}
{{- if $r.Diagnostics }}
{{- print "\n" }}
{{- end }}
{{- end }}
{{- end }}
{{- end -}}
`))
)
type (
// A SummaryReport contains a summary of the analysis of all files.
// It is used as an input to templates to report the CI results.
SummaryReport struct {
// Env holds the environment information.
Env struct {
Driver string `json:"Driver,omitempty"` // Driver name.
URL *sqlclient.URL `json:"URL,omitempty"` // URL to dev database.
Dir string `json:"Dir,omitempty"` // Path to migration directory.
}
// Steps of the analysis. Added in verbose mode.
Steps []struct {
Name string `json:"Name,omitempty"` // Step name.
Text string `json:"Text,omitempty"` // Step description.
Error string `json:"Error,omitempty"` // Error that cause the execution to halt.
Result any `json:"Result,omitempty"` // Result of the step. For example, a diagnostic.
}
// Schema versions found by the runner.
Schema struct {
Current string `json:"Current,omitempty"` // Current schema.
Desired string `json:"Desired,omitempty"` // Desired schema.
}
// Files reports. Non-empty in case there are findings.
Files []*FileReport `json:"Files,omitempty"`
}
// FileReport contains a summary of the analysis of a single file.
FileReport struct {
Name string `json:"Name,omitempty"` // Name of the file.
Text string `json:"Text,omitempty"` // Contents of the file.
Reports []sqlcheck.Report `json:"Reports,omitempty"` // List of reports.
Error string `json:"Error,omitempty"` // File specific error.
}
// ReportWriter is a type of report writer that writes a summary of analysis reports.
ReportWriter interface {
WriteReport(*SummaryReport) error
}
// A TemplateWriter is a type of writer that writes output according to a template.
TemplateWriter struct {
T *template.Template
W io.Writer
}
// SilentError is returned in case the wrapped error is already
// printed by the runner and should not be printed by its caller
SilentError struct{ error }
)
// NewSummaryReport returns a new SummaryReport.
func NewSummaryReport(c *sqlclient.Client, dir migrate.Dir) *SummaryReport {
sum := &SummaryReport{
Env: struct {
Driver string `json:"Driver,omitempty"`
URL *sqlclient.URL `json:"URL,omitempty"`
Dir string `json:"Dir,omitempty"`
}{
Driver: c.Name,
URL: c.URL,
},
Files: make([]*FileReport, 0),
}
if p, ok := dir.(interface{ Path() string }); ok {
sum.Env.Dir = p.Path()
}
return sum
}
// StepResult appends step result to the summary.
func (f *SummaryReport) StepResult(name, text string, result any) {
f.Steps = append(f.Steps, struct {
Name string `json:"Name,omitempty"`
Text string `json:"Text,omitempty"`
Error string `json:"Error,omitempty"`
Result any `json:"Result,omitempty"`
}{
Name: name,
Text: text,
Result: result,
})
}
// StepError appends step error to the summary.
func (f *SummaryReport) StepError(name, text string, err error) error {
f.Steps = append(f.Steps, struct {
Name string `json:"Name,omitempty"`
Text string `json:"Text,omitempty"`
Error string `json:"Error,omitempty"`
Result any `json:"Result,omitempty"`
}{
Name: name,
Text: text,
Error: err.Error(),
})
return err
}
// WriteSchema writes the current and desired schema to the summary.
func (f *SummaryReport) WriteSchema(c *sqlclient.Client, diff *Changes) {
if curr, err := c.MarshalSpec(diff.From); err == nil {
f.Schema.Current = string(curr)
}
if desired, err := c.MarshalSpec(diff.To); err == nil {
f.Schema.Desired = string(desired)
}
}
// NewFileReport returns a new FileReport.
func NewFileReport(f migrate.File) *FileReport {
return &FileReport{Name: f.Name(), Text: string(f.Bytes())}
}
// Line returns the line number from a position.
func (f *FileReport) Line(pos int) int {
return strings.Count(f.Text[:pos], "\n") + 1
}
// WriteReport implements sqlcheck.ReportWriter.
func (f *FileReport) WriteReport(r sqlcheck.Report) {
f.Reports = append(f.Reports, r)
}
// WriteReport implements ReportWriter.
func (w *TemplateWriter) WriteReport(r *SummaryReport) error {
return w.T.Execute(w.W, r)
}
func nolintRules(f *sqlcheck.File) *skipRules {
s := &skipRules{pos2rules: make(map[int][]string)}
for _, c := range f.Changes {
for _, d := range c.Stmt.Directive("nolint") {
s.pos2rules[c.Stmt.Pos] = append(s.pos2rules[c.Stmt.Pos], strings.Split(d, " ")...)
}
}
return s
}
type skipRules struct {
pos2rules map[int][]string // statement positions to rules
skipped bool // last one skipped
}
func (s *skipRules) reporterFor(rw sqlcheck.ReportWriter, az sqlcheck.Analyzer) sqlcheck.ReportWriter {
return sqlcheck.ReportWriterFunc(func(r sqlcheck.Report) {
var (
ds = make([]sqlcheck.Diagnostic, 0, len(r.Diagnostics))
az, ok = az.(sqlcheck.NamedAnalyzer)
)
for _, d := range r.Diagnostics {
switch rules := s.pos2rules[d.Pos]; {
case
// A directive without specific classes/codes
// (e.g. atlas:nolint) ignore all diagnostics.
len(rules) == 1 && rules[0] == "",
// Match a specific code/diagnostic. e.g. atlas:nolint DS101.
slices.Contains(rules, d.Code),
// Skip the entire analyzer (class of changes).
ok && slices.Contains(rules, az.Name()):
default:
ds = append(ds, d)
}
}
if s.skipped = len(ds) == 0; !s.skipped {
rw.WriteReport(sqlcheck.Report{Text: r.Text, Diagnostics: ds})
}
})
}