Skip to content

Instantly share code, notes, and snippets.

@jonbretman
Created December 13, 2023 14:29
Migration script for Keel schema validation tests
package main
import (
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"github.com/teamkeel/keel/schema"
"github.com/teamkeel/keel/schema/format"
"github.com/teamkeel/keel/schema/parser"
"github.com/teamkeel/keel/schema/reader"
"github.com/teamkeel/keel/schema/validation/errorhandling"
)
func main() {
testdataDir := "./schema/testdata"
entries, _ := os.ReadDir(testdataDir)
err := os.MkdirAll(filepath.Join(testdataDir, "errors"), os.ModePerm)
if err != nil {
panic(err)
}
err = os.MkdirAll(filepath.Join(testdataDir, "proto"), os.ModePerm)
if err != nil {
panic(err)
}
for _, e := range entries {
if e.Name() == "proto" || e.Name() == "errors" {
continue
}
_, err = os.Stat(filepath.Join(testdataDir, e.Name(), "proto.json"))
if err == nil {
name := strings.TrimPrefix(e.Name(), "proto_")
name = strings.TrimPrefix(name, "validation_")
newPath := filepath.Join(testdataDir, "proto", name)
fmt.Println("moving", filepath.Join(testdataDir, e.Name()), "to", newPath)
err = os.Rename(filepath.Join(testdataDir, e.Name()), newPath)
if err != nil {
panic(err)
}
continue
}
omgwat, _ := os.ReadFile(filepath.Join(testdataDir, e.Name(), "schema.keel"))
ast, err := parser.Parse(&reader.SchemaFile{
Contents: string(omgwat),
})
if err != nil {
panic(err)
}
builder := &schema.Builder{}
_, err = builder.MakeFromString(format.Format(ast))
if err == nil {
panic(fmt.Sprintf("no error from: %s", e.Name()))
}
var verrs *errorhandling.ValidationErrors
if !errors.As(err, &verrs) {
panic(fmt.Sprintf("not validation error: %s", err))
}
sort.Slice(verrs.Errors, func(i, j int) bool {
return verrs.Errors[i].Pos.Line < verrs.Errors[j].Pos.Line
})
lines := strings.Split(format.Format(ast), "\n")
for i, err := range verrs.Errors {
idx := err.Pos.Line - 1 + i
if idx < 0 {
fmt.Println(e.Name(), err.Pos.Line, i)
}
lines = append(lines[:idx+1], lines[idx:]...)
lines[idx] = fmt.Sprintf("//expect-error:%d:%d:%s:%s", err.Pos.Column, err.EndPos.Column, err.Code, err.Message)
}
ast, err = parser.Parse(&reader.SchemaFile{
Contents: strings.Join(lines, "\n"),
})
if err != nil {
panic(err)
}
name := strings.TrimPrefix(e.Name(), "validation_")
name += ".keel"
fmt.Println("moving", filepath.Join(testdataDir, e.Name()), "to", filepath.Join(testdataDir, "errors", name))
err = os.WriteFile(filepath.Join(testdataDir, "errors", name), []byte(format.Format(ast)), os.ModePerm)
if err != nil {
panic(err)
}
err = os.RemoveAll(filepath.Join(testdataDir, e.Name()))
if err != nil {
panic(err)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment