From ef71828ce218fee816f46ec1b1b2654be1c4b044 Mon Sep 17 00:00:00 2001 From: ~wispem-wantex Date: Sat, 24 Oct 2026 18:56:45 -0700 Subject: [PATCH] lint: convert snake to camel case --- .golangci.yaml | 1 - cmd/main.go | 14 ++++++------- cmd/subcmd_generate_models.go | 8 ++++---- cmd/subcmd_init.go | 32 +++++++++++++++--------------- cmd/subcmd_sqlite_lint.go | 18 ++++++++--------- cmd/subcmd_version.go | 2 +- pkg/db/connect.go | 26 ++++++++++++------------ pkg/db/connect_test.go | 28 +++++++++++++------------- pkg/schema/lint/checks.go | 8 ++++---- pkg/schema/lint/checks_test.go | 20 +++++++++---------- pkg/schema/parse.go | 8 ++++---- pkg/schema/parse_test.go | 36 +++++++++++++++++----------------- 12 files changed, 100 insertions(+), 101 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index 179e628..aa7d2fc 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -57,7 +57,6 @@ linters: checks: - all - -ST1000 # Re-enable this once we have docstrings - - -ST1003 # I like snake_case - -ST1013 # HTTP status codes are shorter and more readable than names wrapcheck: report-internal-errors: false diff --git a/cmd/main.go b/cmd/main.go index 99697a0..8b1fa4a 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -16,19 +16,19 @@ const ( ) func main() { - root_cmd := &cobra.Command{ + rootCmd := &cobra.Command{ Use: "gas", Version: version.String(), SilenceErrors: true, SilenceUsage: true, } // Print a bare version string ("v0.0.4"), rather than cobra's "gas version v0.0.4". - root_cmd.SetVersionTemplate("{{.Version}}\n") - root_cmd.AddCommand(sqlite_lint) - root_cmd.AddCommand(cmd_init) - root_cmd.AddCommand(generate_model) - root_cmd.AddCommand(cmd_version) - if err := root_cmd.Execute(); err != nil { + rootCmd.SetVersionTemplate("{{.Version}}\n") + rootCmd.AddCommand(sqliteLint) + rootCmd.AddCommand(cmdInit) + rootCmd.AddCommand(generateModel) + rootCmd.AddCommand(cmdVersion) + if err := rootCmd.Execute(); err != nil { fmt.Println(RED + err.Error() + RESET) os.Exit(1) } diff --git a/cmd/subcmd_generate_models.go b/cmd/subcmd_generate_models.go index 2d6ddc0..f156de9 100644 --- a/cmd/subcmd_generate_models.go +++ b/cmd/subcmd_generate_models.go @@ -17,7 +17,7 @@ import ( var ErrNoSuchTable = errors.New("no such table") -var generate_model = &cobra.Command{ +var generateModel = &cobra.Command{ Use: "generate ", Short: "Generate a model type", @@ -119,7 +119,7 @@ var generate_model = &cobra.Command{ } func init() { - generate_model.Flags().String("schema", "pkg/db/schema.sql", "Path to SQL schema file") - generate_model.Flags().String("modname", "mymodule", "Name of project's Go module (TODO: detect automatically)") - generate_model.Flags().Bool("test", false, "Generate test file instead of regular file") + generateModel.Flags().String("schema", "pkg/db/schema.sql", "Path to SQL schema file") + generateModel.Flags().String("modname", "mymodule", "Name of project's Go module (TODO: detect automatically)") + generateModel.Flags().Bool("test", false, "Generate test file instead of regular file") } diff --git a/cmd/subcmd_init.go b/cmd/subcmd_init.go index eeb12a9..6a480fb 100644 --- a/cmd/subcmd_init.go +++ b/cmd/subcmd_init.go @@ -12,7 +12,7 @@ import ( "git.offline-twitter.com/offline-labs/gas-stack/pkg/must" ) -var cmd_init = &cobra.Command{ +var cmdInit = &cobra.Command{ Use: "init [path]", Short: "Initialize a new project", Long: "Initialize a new Gas Stack project at the given path. If no path is given, defaults to current directory.", @@ -31,7 +31,7 @@ var cmd_init = &cobra.Command{ } // Get all the config values - get_val := func(prompt string, val *string) { + getVal := func(prompt string, val *string) { fmt.Printf("%s (%q): ", prompt, *val) scanner := bufio.NewScanner(os.Stdin) scanner.Scan() @@ -40,31 +40,31 @@ var cmd_init = &cobra.Command{ *val = input } } - pkg_opts := codegen.PkgOpts{ + pkgOpts := codegen.PkgOpts{ ModuleName: must.Get(cmd.Flags().GetString("module")), DBFilename: must.Get(cmd.Flags().GetString("db")), BinaryName: must.Get(cmd.Flags().GetString("binary")), } - if pkg_opts.ModuleName == "" { - pkg_opts.ModuleName = filepath.Base(target) - get_val("module name", &pkg_opts.ModuleName) + if pkgOpts.ModuleName == "" { + pkgOpts.ModuleName = filepath.Base(target) + getVal("module name", &pkgOpts.ModuleName) } - if pkg_opts.DBFilename == "" { - pkg_opts.DBFilename = pkg_opts.ModuleName + ".db" - get_val("db name", &pkg_opts.DBFilename) + if pkgOpts.DBFilename == "" { + pkgOpts.DBFilename = pkgOpts.ModuleName + ".db" + getVal("db name", &pkgOpts.DBFilename) } - if pkg_opts.BinaryName == "" { - pkg_opts.BinaryName = pkg_opts.ModuleName - get_val("binary name", &pkg_opts.BinaryName) + if pkgOpts.BinaryName == "" { + pkgOpts.BinaryName = pkgOpts.ModuleName + getVal("binary name", &pkgOpts.BinaryName) } // Run project initialization - codegen.InitPkg(pkg_opts) + codegen.InitPkg(pkgOpts) }, } func init() { - cmd_init.Flags().String("module", "", "Module name") - cmd_init.Flags().String("db", "", "Database filename") - cmd_init.Flags().String("binary", "", "Binary name") + cmdInit.Flags().String("module", "", "Module name") + cmdInit.Flags().String("db", "", "Database filename") + cmdInit.Flags().String("binary", "", "Binary name") } diff --git a/cmd/subcmd_sqlite_lint.go b/cmd/subcmd_sqlite_lint.go index 6d48c05..95f670a 100644 --- a/cmd/subcmd_sqlite_lint.go +++ b/cmd/subcmd_sqlite_lint.go @@ -12,7 +12,7 @@ import ( "git.offline-twitter.com/offline-labs/gas-stack/pkg/schema/lint" ) -var sqlite_lint = &cobra.Command{ +var sqliteLint = &cobra.Command{ Use: "sqlite_lint ", Short: "Lint a SQLite schema", @@ -32,18 +32,18 @@ var sqlite_lint = &cobra.Command{ os.Exit(1) } - is_failure := false + isFailure := false // Execute each check against the database for _, check := range lint.Checks { // Checks can be disabled via Github config / environment variables - if !is_check_enabled(check) { + if !isCheckEnabled(check) { continue } results := check.Execute(schema) // If there are results, print them as lint errors if len(results) > 0 { - is_failure = true + 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) @@ -51,7 +51,7 @@ var sqlite_lint = &cobra.Command{ fmt.Printf(RED+"Explanation: %s\n\n"+RESET, check.Explanation) } } - if is_failure { + if isFailure { fmt.Println(RED + "Errors found" + RESET) os.Exit(1) } @@ -61,16 +61,16 @@ var sqlite_lint = &cobra.Command{ // github_actions_input_env_var converts an input name to the corresponding // environment variable name used by GitHub Actions. -func github_actions_input_env_var(name string) string { +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 is_check_enabled(c lint.Check) bool { - val, is_set := os.LookupEnv(github_actions_input_env_var(c.Name)) - if !is_set { +func isCheckEnabled(c lint.Check) bool { + val, isSet := os.LookupEnv(githubActionsInputEnvVar(c.Name)) + if !isSet { // Enable all checks by default return true } diff --git a/cmd/subcmd_version.go b/cmd/subcmd_version.go index 0e6503e..fe55164 100644 --- a/cmd/subcmd_version.go +++ b/cmd/subcmd_version.go @@ -8,7 +8,7 @@ import ( "git.offline-twitter.com/offline-labs/gas-stack/pkg/version" ) -var cmd_version = &cobra.Command{ +var cmdVersion = &cobra.Command{ Use: "version", Short: "Print the version of `gas`", Args: cobra.NoArgs, diff --git a/pkg/db/connect.go b/pkg/db/connect.go index b154b28..94492ae 100644 --- a/pkg/db/connect.go +++ b/pkg/db/connect.go @@ -17,18 +17,18 @@ type DBConfig struct { // is_initialized bool // The SQL schema of the database under management - sql_schema *string + sqlSchema *string // Database starts at version 0. First migration brings us to version 1 - migrations *[]Migration - version_number uint + migrations *[]Migration + versionNumber uint } func Init(schema *string, migrationsList *[]Migration) DBConfig { return DBConfig{ - sql_schema: schema, - migrations: migrationsList, - version_number: uint(len(*migrationsList)), + sqlSchema: schema, + migrations: migrationsList, + versionNumber: uint(len(*migrationsList)), } } @@ -52,7 +52,7 @@ func (c DBConfig) Create(path string) (*sqlx.DB, error) { if _, err = db.Exec("pragma foreign_keys=on; pragma journal_mode=WAL;"); err != nil { return nil, fmt.Errorf("running pragma statements: %w", err) } - if _, err = db.Exec(*c.sql_schema); err != nil { + if _, err = db.Exec(*c.sqlSchema); err != nil { return nil, fmt.Errorf("creating schema: %w", err) } @@ -79,18 +79,18 @@ func (c DBConfig) CheckAndUpdateVersion(db *sqlx.DB) error { return fmt.Errorf("couldn't check database version: %w", err) } - if version > c.version_number { - return VersionMismatchError{c.version_number, version} + if version > c.versionNumber { + return VersionMismatchError{c.versionNumber, version} } - if c.version_number > version { + if c.versionNumber > version { fmt.Print(textutils.ColorYellow) fmt.Printf("================================================\n") fmt.Printf("Database version is out of date. Upgrading database from version %d to version %d!\n", version, - c.version_number) + c.versionNumber) fmt.Print(textutils.ColorReset) - for i := version; i < c.version_number; i++ { + for i := version; i < c.versionNumber; i++ { m := (*c.migrations)[i] if err := m.Apply(db); err != nil { return fmt.Errorf("migration %d: %w", m.ID, err) @@ -103,7 +103,7 @@ func (c DBConfig) CheckAndUpdateVersion(db *sqlx.DB) error { fmt.Print(textutils.ColorGreen) fmt.Printf("================================================\n") - fmt.Printf("Database version has been upgraded to version %d.\n", c.version_number) + fmt.Printf("Database version has been upgraded to version %d.\n", c.versionNumber) fmt.Print(textutils.ColorReset) } diff --git a/pkg/db/connect_test.go b/pkg/db/connect_test.go index f7cb288..7b76da5 100644 --- a/pkg/db/connect_test.go +++ b/pkg/db/connect_test.go @@ -15,17 +15,17 @@ import ( func TestCreateAndConnectToDB(t *testing.T) { assert := assert.New(t) - _schema_sql, err := os.ReadFile("../../sample_data/test_schemas/food.sql") + _schemaSQL, err := os.ReadFile("../../sample_data/test_schemas/food.sql") require.NoError(t, err) - schema_sql := string(_schema_sql) + schemaSQL := string(_schemaSQL) migrations := []db.Migration{} - config := db.Init(&schema_sql, &migrations) + config := db.Init(&schemaSQL, &migrations) - data_dir := "../../sample_data/data" - _ = os.MkdirAll(data_dir, os.FileMode(0o644)) + dataDir := "../../sample_data/data" + _ = os.MkdirAll(dataDir, os.FileMode(0o644)) // Create then connect to a new empty DB - dbPath := filepath.Join(data_dir, "test.db") + dbPath := filepath.Join(dataDir, "test.db") _ = os.Remove(dbPath) // Delete it if it exists _, err = config.Create(dbPath) @@ -38,18 +38,18 @@ func TestVersionUpgrade(t *testing.T) { require := require.New(t) // Create a little schema - initial_schema := ` + initialSchema := ` create table items(rowid integer primary key); create table db_version (version integer primary key) strict, without rowid; insert into db_version values(0); ` migrations := []db.Migration{} - config := db.Init(&initial_schema, &migrations) + config := db.Init(&initialSchema, &migrations) connection, err := config.Create(":memory:") require.NoError(err) - get_version := func(c *sqlx.DB) (ret int) { + getVersion := func(c *sqlx.DB) (ret int) { // TODO: this should be a function exposed by the `db` package itself require.NoError(c.Get(&ret, "select version from db_version")) return @@ -58,21 +58,21 @@ func TestVersionUpgrade(t *testing.T) { var items []int require.NoError(connection.Select(&items, "select * from items")) require.Len(items, 0) - require.Equal(0, get_version(connection)) + require.Equal(0, getVersion(connection)) // Create a migration to add a new Item migrations = append(migrations, db.Migration{ID: 1, SQL: "insert into items (rowid) values (1)"}) - config = db.Init(&initial_schema, &migrations) // Reinitialize with the new migration + config = db.Init(&initialSchema, &migrations) // Reinitialize with the new migration require.NoError(config.CheckAndUpdateVersion(connection)) var items2 []int require.NoError(connection.Select(&items2, "select * from items")) require.Len(items2, 1) - require.Equal(1, get_version(connection)) + require.Equal(1, getVersion(connection)) // Create a migration to add a new Item migrations = append(migrations, db.Migration{ID: 2, SQL: `alter table items add column name string default 'asdf'`}) - config = db.Init(&initial_schema, &migrations) // Reinitialize with the new migration + config = db.Init(&initialSchema, &migrations) // Reinitialize with the new migration require.NoError(config.CheckAndUpdateVersion(connection)) var items3 []struct { @@ -82,5 +82,5 @@ func TestVersionUpgrade(t *testing.T) { require.NoError(connection.Select(&items3, "select * from items")) require.Len(items2, 1) assert.Equal(t, "asdf", items3[0].Name) - require.Equal(2, get_version(connection)) + require.Equal(2, getVersion(connection)) } diff --git a/pkg/schema/lint/checks.go b/pkg/schema/lint/checks.go index be52abb..1be000a 100644 --- a/pkg/schema/lint/checks.go +++ b/pkg/schema/lint/checks.go @@ -114,8 +114,8 @@ var Checks = []Check{ } // Check if target column is a primary key - for _, target_col := range s.Tables[column.ForeignKeyTargetTable].Columns { - if target_col.Name == column.ForeignKeyTargetColumn && target_col.IsPrimaryKey { + for _, targetCol := range s.Tables[column.ForeignKeyTargetTable].Columns { + if targetCol.Name == column.ForeignKeyTargetColumn && targetCol.IsPrimaryKey { continue fk_loop } } @@ -125,8 +125,8 @@ var Checks = []Check{ if idx.TableName != column.ForeignKeyTargetTable { continue } - for _, idx_col_name := range idx.Columns { - if column.ForeignKeyTargetColumn == idx_col_name { + for _, idxColName := range idx.Columns { + if column.ForeignKeyTargetColumn == idxColName { continue fk_loop } break // Only look at 1st column diff --git a/pkg/schema/lint/checks_test.go b/pkg/schema/lint/checks_test.go index a989957..7df670d 100644 --- a/pkg/schema/lint/checks_test.go +++ b/pkg/schema/lint/checks_test.go @@ -12,7 +12,7 @@ import ( ) func TestFailureCases(t *testing.T) { - test_cases := []struct { + testCases := []struct { sqlFile string expectedFailures []string }{ @@ -34,24 +34,24 @@ func TestFailureCases(t *testing.T) { }}, } - for _, test_case := range test_cases { - t.Run(test_case.sqlFile, func(t *testing.T) { - schema, err := schema.SchemaFromSQLFile(test_case.sqlFile) + for _, testCase := range testCases { + t.Run(testCase.sqlFile, func(t *testing.T) { + schema, err := schema.SchemaFromSQLFile(testCase.sqlFile) require.NoError(t, err) for _, check := range lint.Checks { results := check.Execute(schema) - is_failure := len(results) > 0 - is_failure_expected := slices.Contains(test_case.expectedFailures, check.Name) + isFailure := len(results) > 0 + isFailureExpected := slices.Contains(testCase.expectedFailures, check.Name) - if is_failure != is_failure_expected { - if is_failure_expected { - t.Errorf("Expected check '%s' to fail, but it passed: %s", check.Name, test_case.sqlFile) + if isFailure != isFailureExpected { + if isFailureExpected { + t.Errorf("Expected check '%s' to fail, but it passed: %s", check.Name, testCase.sqlFile) } else { t.Errorf("Expected check '%s' to pass, but it failed: %s (%q.%q)", check.Name, - test_case.sqlFile, + testCase.sqlFile, results[0].TableName, results[0].ColumnName, ) } diff --git a/pkg/schema/parse.go b/pkg/schema/parse.go index ac0c5a1..5ba2808 100644 --- a/pkg/schema/parse.go +++ b/pkg/schema/parse.go @@ -15,12 +15,12 @@ import ( ) //go:embed views.sql -var create_views string +var createViews string // InitDB creates an in-memory DB from a given schema string. -func InitDB(sql_schema string) *sqlx.DB { +func InitDB(sqlSchema string) *sqlx.DB { db := sqlx.MustOpen("sqlite3", ":memory:") - db.MustExec(sql_schema) + db.MustExec(sqlSchema) return db } @@ -35,7 +35,7 @@ func SchemaFromSQLFile(filepath string) (Schema, error) { // SchemaFromDB takes a DB connection, checks its schema metadata tables, and returns a Schema. func SchemaFromDB(db *sqlx.DB) Schema { ret := Schema{Tables: map[string]Table{}, Indexes: map[string]Index{}} - db.MustExec(create_views) + db.MustExec(createViews) var tables []Table must.Do(db.Select(&tables, `select name, table_type, is_strict, is_without_rowid from tables`)) diff --git a/pkg/schema/parse_test.go b/pkg/schema/parse_test.go index 7e652f2..d83d3e0 100644 --- a/pkg/schema/parse_test.go +++ b/pkg/schema/parse_test.go @@ -12,15 +12,15 @@ import ( func TestParseSchema(t *testing.T) { assert := assert.New(t) - schema_sql, err := os.ReadFile("../../sample_data/test_schemas/food.sql") + schemaSQL, err := os.ReadFile("../../sample_data/test_schemas/food.sql") require.NoError(t, err) - db := schema.InitDB(string(schema_sql)) + db := schema.InitDB(string(schemaSQL)) schema := schema.SchemaFromDB(db) - expected_tbls := []string{"food_types", "foods", "units", "ingredients", "recipes", "iterations", "db_version"} - for _, tbl_name := range expected_tbls { - _, is_ok := schema.Tables[tbl_name] - assert.True(is_ok) + expectedTbls := []string{"food_types", "foods", "units", "ingredients", "recipes", "iterations", "db_version"} + for _, tblName := range expectedTbls { + _, isOk := schema.Tables[tblName] + assert.True(isOk) } foods := schema.Tables["foods"] @@ -57,23 +57,23 @@ func TestParseSchema(t *testing.T) { // ------- // Unique index - units_name_idx, isOk := schema.Indexes["sqlite_autoindex_units_1"] + unitsNameIdx, isOk := schema.Indexes["sqlite_autoindex_units_1"] require.True(t, isOk) - assert.True(units_name_idx.IsUnique) - assert.Equal("units", units_name_idx.TableName) - assert.Equal([]string{"name"}, units_name_idx.Columns) + assert.True(unitsNameIdx.IsUnique) + assert.Equal("units", unitsNameIdx.TableName) + assert.Equal([]string{"name"}, unitsNameIdx.Columns) // Non-unique, declared index - foods_protein_idx, isOk := schema.Indexes["foods_protein"] + foodsProteinIdx, isOk := schema.Indexes["foods_protein"] require.True(t, isOk) - assert.False(foods_protein_idx.IsUnique) - assert.Equal("foods", foods_protein_idx.TableName) - assert.Equal([]string{"protein"}, foods_protein_idx.Columns) + assert.False(foodsProteinIdx.IsUnique) + assert.Equal("foods", foodsProteinIdx.TableName) + assert.Equal([]string{"protein"}, foodsProteinIdx.Columns) // Multi-column index - ingr_seq_idx, isOk := schema.Indexes["sqlite_autoindex_ingredients_1"] + ingrSeqIdx, isOk := schema.Indexes["sqlite_autoindex_ingredients_1"] require.True(t, isOk) - assert.True(ingr_seq_idx.IsUnique) - assert.Equal("ingredients", ingr_seq_idx.TableName) - assert.Equal([]string{"in_recipe_id", "list_order"}, ingr_seq_idx.Columns) + assert.True(ingrSeqIdx.IsUnique) + assert.Equal("ingredients", ingrSeqIdx.TableName) + assert.Equal([]string{"in_recipe_id", "list_order"}, ingrSeqIdx.Columns) }