photoprism/internal/migrate/generate.go

94 lines
1.8 KiB
Go
Raw Normal View History

//go:build ignore
// +build ignore
// This generates countries.go by running "go generate"
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"text/template"
)
func gen_migrations(name string) {
if name == "" {
return
}
dialect := strings.ToLower(name)
type Migration struct {
ID string
Dialect string
Query string
}
var migrations []Migration
// Folder in which migration files are stored.
folder := "./" + dialect
// Returns directory entries sorted by filename.
files, _ := os.ReadDir(folder)
fmt.Printf("generating %s...", dialect)
// Read migrations from files.
for _, file := range files {
filePath := filepath.Join(folder, file.Name())
if file.IsDir() {
continue
} else if id := strings.SplitN(filepath.Base(file.Name()), ".", 2)[0]; id == "" {
fmt.Printf("e")
// Ignore.
} else if query, err := os.ReadFile(filePath); err == nil && len(query) > 0 {
fmt.Printf(".")
migrations = append(migrations, Migration{ID: id, Dialect: dialect, Query: string(query)})
} else {
fmt.Printf("f")
fmt.Println(err.Error())
}
}
fmt.Printf(" found %d migrations\n", len(migrations))
// Create source file from migrations.
f, err := os.Create(fmt.Sprintf("dialect_%s.go", dialect))
if err != nil {
panic(err)
}
defer f.Close()
// Render source template.
migrationsTemplate.Execute(f, struct {
Name string
Migrations []Migration
}{
Name: name,
Migrations: migrations,
})
}
func main() {
gen_migrations("MySQL")
gen_migrations("SQLite")
}
var migrationsTemplate = template.Must(template.New("").Parse(`// Code generated by go generate; DO NOT EDIT.
package migrate
var Dialect{{ print .Name }} = Migrations{
{{- range .Migrations }}
{
ID: {{ printf "%q" .ID }},
Dialect: {{ printf "%q" .Dialect }},
Query: {{ printf "%q" .Query }},
},
{{- end }}
}`))