Files
gas-stack/cmd/subcmd_sqlite_lint.go

80 lines
2.2 KiB
Go

package main
import (
"errors"
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
"git.offline-twitter.com/offline-labs/gas-stack/pkg/schema"
"git.offline-twitter.com/offline-labs/gas-stack/pkg/schema/lint"
)
var sqliteLint = &cobra.Command{
Use: "sqlite_lint <path/to/schema.sql>",
Short: "Lint a SQLite schema",
Args: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return errors.New("required: filepath as first argument")
}
return nil
},
Run: func(rootCmd *cobra.Command, args []string) {
filename := args[0]
fmt.Printf("-----------------\nLinting %s\n", filename)
schema, err := schema.SchemaFromSQLFile(args[0])
if err != nil {
fmt.Println(err)
os.Exit(1)
}
isFailure := false
// Execute each check against the database
for _, check := range lint.Checks {
// Checks can be disabled via Github config / environment variables
if !isCheckEnabled(check) {
continue
}
results := check.Execute(schema)
// If there are results, print them as lint errors
if len(results) > 0 {
isFailure = true
fmt.Printf(RED+"Check '%s' failed:\n"+RESET, check.Name)
for _, result := range results {
fmt.Printf(RED+"- %s: %s.%s\n"+RESET, result.ErrorMsg, result.TableName, result.ColumnName)
}
fmt.Printf(RED+"Explanation: %s\n\n"+RESET, check.Explanation)
}
}
if isFailure {
fmt.Println(RED + "Errors found" + RESET)
os.Exit(1)
}
fmt.Println(GREEN + "Success" + RESET)
},
}
// github_actions_input_env_var converts an input name to the corresponding
// environment variable name used by GitHub Actions.
func githubActionsInputEnvVar(name string) string {
// GitHub normalizes both hyphens and underscores to underscores, then uppercases the name
normalized := strings.NewReplacer("-", "_", " ", "_").Replace(name)
return "INPUT_" + strings.ToUpper(normalized)
}
// Setting the environment variable INPUT_REQUIRE_NOT_NULL="false" disables the "require_not_null" check
func isCheckEnabled(c lint.Check) bool {
val, isSet := os.LookupEnv(githubActionsInputEnvVar(c.Name))
if !isSet {
// Enable all checks by default
return true
}
// Anything except "false" is true
return val != "false"
}