Added CODE_CONVENTIONS.md and linters to enforce it, and applied it across the codebase
CODE_CONVENTIONS.md sets out the conventions for Go code in this repository: naming, layout, comments, errors, logging, configuration and tests. .golangci.json enables the linters that check the parts that can be checked (each limited to the rules the conventions use); the rest is applied by hand. Applied across the codebase: - Naming: full-word names in application code, initialisms in one case (BuyerID, PrintJSON, PrintYAML, ocdsGetBuyerID), no names shadowing built-ins (min/max are minGap/maxGap), mustRaw renamed rawJSON as it returns nil rather than panicking, and config.ConfigLevelToLogLevel renamed LevelToLogLevel. - Layout: lines kept to 80 characters where possible, assignments taken out of if and for statements that don't fit, wrapped arguments all on one line or one per line, steps separated by blank lines, no else after a return, function and struct literals wrapped. - Comments: doc comments on every exported name (including each section's Map, Flatten, TypeOf, ValueOf and SetValue), section banners, British spelling. - Errors: a created error starts with its package name, a wrapping error adds only what was being done, sentinels in one commented var block, errors.Is and errors.As in place of == and type assertions, and no err := shadowing of a named result. That fixes the mock server losing its access log's close error. - Logging: the fetcher passes its workers an untagged logger, so findatender's lines are tagged with their own component rather than with fetcher's as well; cmd/mock-fts logs "stopped" with slog. - Configuration: util.WithTimeout (moved from the websocket package) applies a timeout of 0 or less as no limit, used for the websocket write and ping, TCP close and tcpserver shutdown timeouts; every setting documents what 0 or empty means, including the rate limit rule's keys in internal/config/README.md. - Tests: related tests merged into table-driven ones with named cases. Separately from CODE_CONVENTIONS.md, internal/store/README.md gains a soft SQL style convention for the queries in internal/store/queries.go, and the queries are reformatted to follow it.
This commit is contained in:
1 parent
465358609a
commit
67215a6aaa
104 files changed
+3189
-1206
No files matched your search
@@ -24,15 +24,15 @@ import (
|
||||
// If the database file doesn't exist, create decides between asking whether
|
||||
// to create it (up) and failing (down, status: nothing to work on).
|
||||
func openMigrator(
|
||||
cmd *cobra.Command, opts *cli.Options, create bool, createConfirmed bool,
|
||||
cmd *cobra.Command, opts *cli.Options, create, createConfirmed bool,
|
||||
) (*goose.Provider, *sql.DB, error) {
|
||||
conf, err := opts.RunSetup(cmd, true, true)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("no configuration loaded (%w)", err)
|
||||
return nil, nil, fmt.Errorf("load configuration: %w", err)
|
||||
}
|
||||
|
||||
file := conf.Database.File
|
||||
if len(file) == 0 {
|
||||
if file == "" {
|
||||
return nil, nil, errors.New(
|
||||
"no database file specified. Update your configuration",
|
||||
)
|
||||
@@ -46,8 +46,8 @@ func openMigrator(
|
||||
question := fmt.Sprintf(
|
||||
"Database file '%s' does not exist. Would you like to create it?", file,
|
||||
)
|
||||
if !cli.Confirm(question) {
|
||||
return nil, nil, errors.New("migrate: no database file")
|
||||
if !cli.Confirm(cmd.OutOrStdout(), cmd.InOrStdin(), question) {
|
||||
return nil, nil, errors.New("no database file")
|
||||
}
|
||||
}
|
||||
} else if err != nil {
|
||||
@@ -75,14 +75,14 @@ func closeDB(db *sql.DB, err *error) {
|
||||
// errWriter writes until a write fails, then keeps the error, so a run of
|
||||
// prints needs checking only once.
|
||||
type errWriter struct {
|
||||
w io.Writer
|
||||
out io.Writer
|
||||
err error
|
||||
}
|
||||
|
||||
// printf writes like fmt.Fprintf, unless an earlier write failed.
|
||||
func (e *errWriter) printf(format string, args ...any) {
|
||||
if e.err == nil {
|
||||
_, e.err = fmt.Fprintf(e.w, format, args...)
|
||||
_, e.err = fmt.Fprintf(e.out, format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,7 +91,7 @@ func (e *errWriter) printf(format string, args ...any) {
|
||||
// applied 00003_create_release_tags_table.sql (2ms)
|
||||
func printResults(out io.Writer, results []*goose.MigrationResult) error {
|
||||
output := &errWriter{
|
||||
w: out,
|
||||
out: out,
|
||||
}
|
||||
for _, result := range results {
|
||||
verb := "applied"
|
||||
@@ -136,7 +136,9 @@ func failure(out io.Writer, err error) error {
|
||||
}
|
||||
|
||||
// printVersion reports where the database ended up.
|
||||
func printVersion(ctx context.Context, out io.Writer, migrator *goose.Provider) error {
|
||||
func printVersion(
|
||||
ctx context.Context, out io.Writer, migrator *goose.Provider,
|
||||
) error {
|
||||
dbVersion, err := migrator.GetDBVersion(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -39,7 +39,11 @@ func TestFailurePartial(t *testing.T) {
|
||||
if !errors.Is(err, cause) {
|
||||
t.Errorf("err = %v, want it to wrap the migration error", err)
|
||||
}
|
||||
for _, want := range []string{"00002_second.sql", "rolled back", "last version that succeeded"} {
|
||||
for _, want := range []string{
|
||||
"00002_second.sql",
|
||||
"rolled back",
|
||||
"last version that succeeded",
|
||||
} {
|
||||
if err == nil || !strings.Contains(err.Error(), want) {
|
||||
t.Errorf("err = %v, want it to mention %q", err, want)
|
||||
}
|
||||
@@ -58,7 +62,10 @@ func TestFailureWithoutFailedSource(t *testing.T) {
|
||||
func TestFailureOtherError(t *testing.T) {
|
||||
cause := errors.New("database is locked")
|
||||
var out bytes.Buffer
|
||||
if err := failure(&out, cause); err != cause {
|
||||
if err := failure(
|
||||
&out,
|
||||
cause,
|
||||
); err != cause { //nolint:errorlint // checks the error is returned unchanged
|
||||
t.Errorf("err = %v, want the error unchanged", err)
|
||||
}
|
||||
if out.Len() != 0 {
|
||||
@@ -75,7 +82,8 @@ func TestPrintResults(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := " applied 00001_first.sql (2ms)\n reverted 00002_second.sql (2ms)\n"
|
||||
want := " applied 00001_first.sql (2ms)\n" +
|
||||
" reverted 00002_second.sql (2ms)\n"
|
||||
if out.String() != want {
|
||||
t.Errorf("output = %q, want %q", out.String(), want)
|
||||
}
|
||||
@@ -97,7 +105,9 @@ func TestWriteErrors(t *testing.T) {
|
||||
|
||||
cause := errors.New("boom")
|
||||
err := failure(failingWriter{}, &goose.PartialError{
|
||||
Applied: results, Failed: result("00002_second.sql", "up"), Err: cause,
|
||||
Applied: results,
|
||||
Failed: result("00002_second.sql", "up"),
|
||||
Err: cause,
|
||||
})
|
||||
if !errors.Is(err, cause) || !errors.Is(err, errWrite) {
|
||||
t.Errorf("failure: err = %v, want both the migration and write errors", err)
|
||||
|
||||
@@ -39,12 +39,11 @@ confirmed by providing -yes.`,
|
||||
defer closeDB(db, &err)
|
||||
|
||||
results, err := store.StepDown(cmd.Context(), migrator, int(steps), yes)
|
||||
|
||||
if len(results) == 0 && err == nil {
|
||||
fmt.Println("No changes made to database (empty)")
|
||||
return nil
|
||||
}
|
||||
if err == store.ErrWouldEmptyDatabase {
|
||||
if errors.Is(err, store.ErrWouldEmptyDatabase) {
|
||||
return fmt.Errorf(
|
||||
"%w\n\nTo confirm you wish to proceed, pass the --yes flag", err,
|
||||
)
|
||||
@@ -62,17 +61,14 @@ confirmed by providing -yes.`,
|
||||
},
|
||||
}
|
||||
cmd.Flags().Uint(
|
||||
"steps",
|
||||
0,
|
||||
"number of migrations to roll back. 0 = all (deletes all data)",
|
||||
"steps", 0, "number of migrations to roll back. 0 = all (deletes all data)",
|
||||
)
|
||||
if err := cmd.MarkFlagRequired("steps"); err != nil {
|
||||
panic(err) // only fails if the flag isn't defined
|
||||
}
|
||||
cmd.Flags().BoolP(
|
||||
"yes", "y",
|
||||
false,
|
||||
"confirm you are intending to roll back every migration",
|
||||
"yes", "y", false, "confirm you are intending to roll back every migration",
|
||||
)
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -14,8 +14,8 @@ import (
|
||||
"git.avsdev.uk/Go/job-search/internal/cli"
|
||||
)
|
||||
|
||||
// NewCommand returns the "migrate" command, which migrates the database schema (see
|
||||
// internal/store).
|
||||
// NewCommand returns the "migrate" command, which migrates the database schema
|
||||
// (see internal/store).
|
||||
func NewCommand(opts *cli.Options) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "migrate",
|
||||
@@ -39,5 +39,6 @@ migration is applied.`,
|
||||
cmd.AddCommand(commandUp(opts))
|
||||
cmd.AddCommand(commandDown(opts))
|
||||
cmd.AddCommand(commandStatus(opts))
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package migrate
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
@@ -43,10 +44,12 @@ func latestVersion(t *testing.T) int64 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
m, err := store.NewMigrator(db)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
return store.LatestVersion(m)
|
||||
}
|
||||
|
||||
@@ -83,7 +86,9 @@ func TestMigrateWithoutSubcommand(t *testing.T) {
|
||||
cmdtest.WriteFile(t, "test.db", "") // exists, so no question is asked
|
||||
|
||||
out := mustRun(t, "migrate")
|
||||
cmdtest.Contains(t, out, fmt.Sprintf("Database migrated to version %d", latestVersion(t)))
|
||||
cmdtest.Contains(
|
||||
t, out, fmt.Sprintf("Database migrated to version %d", latestVersion(t)),
|
||||
)
|
||||
}
|
||||
|
||||
func TestMigrateUpAsksBeforeCreating(t *testing.T) {
|
||||
@@ -130,16 +135,24 @@ func TestMigrateDown(t *testing.T) {
|
||||
mustRun(t, "migrate", "up", "--create")
|
||||
|
||||
out := mustRun(t, "migrate", "down", "--steps", "1")
|
||||
cmdtest.Contains(t, out, "reverted", fmt.Sprintf("Database migrated to version %d", latest-1))
|
||||
cmdtest.Contains(
|
||||
t,
|
||||
out,
|
||||
"reverted",
|
||||
fmt.Sprintf("Database migrated to version %d", latest-1),
|
||||
)
|
||||
|
||||
// Rolling back everything deletes all data, so it must be confirmed.
|
||||
for _, args := range [][]string{
|
||||
{"migrate", "down", "--steps", "0"},
|
||||
{"migrate", "down", "--steps", "99"},
|
||||
} {
|
||||
_, err := run(t, "", args...)
|
||||
cmdtest.ErrContains(t, err, "pass the --yes flag")
|
||||
t.Run(strings.Join(args, " "), func(t *testing.T) {
|
||||
_, err := run(t, "", args...)
|
||||
cmdtest.ErrContains(t, err, "pass the --yes flag")
|
||||
})
|
||||
}
|
||||
|
||||
cmdtest.Contains(
|
||||
t,
|
||||
mustRun(t, "migrate", "status"),
|
||||
@@ -166,9 +179,12 @@ func TestMigrateMissingDatabase(t *testing.T) {
|
||||
{"migrate", "status"},
|
||||
{"migrate", "down", "--steps", "1"},
|
||||
} {
|
||||
_, err := run(t, "", args...)
|
||||
cmdtest.ErrContains(t, err, "does not exist")
|
||||
t.Run(strings.Join(args, " "), func(t *testing.T) {
|
||||
_, err := run(t, "", args...)
|
||||
cmdtest.ErrContains(t, err, "does not exist")
|
||||
})
|
||||
}
|
||||
|
||||
if cmdtest.Exists("test.db") {
|
||||
t.Error("status or down created the database")
|
||||
}
|
||||
|
||||
@@ -22,7 +22,9 @@ import (
|
||||
// 1 applied 2026-10-07 10:12:01 00001_create_opportunities_table.sql
|
||||
// ...
|
||||
// 5 pending 00005_create_opportunity_classifications_table.sql
|
||||
func printStatus(ctx context.Context, out io.Writer, migrator *goose.Provider) error {
|
||||
func printStatus(
|
||||
ctx context.Context, out io.Writer, migrator *goose.Provider,
|
||||
) error {
|
||||
statuses, err := migrator.Status(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -43,7 +45,7 @@ func printStatus(ctx context.Context, out io.Writer, migrator *goose.Provider) e
|
||||
}
|
||||
|
||||
output := &errWriter{
|
||||
w: out,
|
||||
out: out,
|
||||
}
|
||||
switch {
|
||||
case current > latest:
|
||||
@@ -55,7 +57,9 @@ func printStatus(ctx context.Context, out io.Writer, migrator *goose.Provider) e
|
||||
case pending == 0:
|
||||
output.printf("Database version %d of %d (up-to-date)\n", current, latest)
|
||||
default:
|
||||
output.printf("Database version %d of %d (%d pending)\n", current, latest, pending)
|
||||
output.printf(
|
||||
"Database version %d of %d (%d pending)\n", current, latest, pending,
|
||||
)
|
||||
}
|
||||
if output.err != nil {
|
||||
return output.err
|
||||
@@ -63,7 +67,7 @@ func printStatus(ctx context.Context, out io.Writer, migrator *goose.Provider) e
|
||||
|
||||
table := tabwriter.NewWriter(out, 0, 0, 2, ' ', 0)
|
||||
output = &errWriter{
|
||||
w: table,
|
||||
out: table,
|
||||
}
|
||||
for _, status := range statuses {
|
||||
applied := ""
|
||||
@@ -78,6 +82,7 @@ func printStatus(ctx context.Context, out io.Writer, migrator *goose.Provider) e
|
||||
filepath.Base(status.Source.Path),
|
||||
)
|
||||
}
|
||||
|
||||
return errors.Join(output.err, table.Flush())
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package migrate
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
@@ -23,14 +24,15 @@ func runStepUp(
|
||||
defer closeDB(db, &err)
|
||||
|
||||
results, err := store.StepUp(cmd.Context(), migrator, int(steps))
|
||||
|
||||
if len(results) == 0 && err == nil {
|
||||
_, err := fmt.Fprintln(cmd.OutOrStdout(), "No changes made to database (up-to-date)")
|
||||
_, err = fmt.Fprintln(
|
||||
cmd.OutOrStdout(), "No changes made to database (up-to-date)",
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
if err := printResults(cmd.OutOrStdout(), results); err != nil {
|
||||
return err
|
||||
if printErr := printResults(cmd.OutOrStdout(), results); printErr != nil {
|
||||
return errors.Join(err, printErr)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
@@ -60,15 +62,10 @@ func commandUp(opts *cli.Options) *cobra.Command {
|
||||
return runStepUp(cmd, opts, int(steps), create)
|
||||
},
|
||||
}
|
||||
cmd.Flags().Uint(
|
||||
"steps",
|
||||
0,
|
||||
"number of migrations to apply. 0 = all pending",
|
||||
)
|
||||
cmd.Flags().Uint("steps", 0, "number of migrations to apply. 0 = all pending")
|
||||
cmd.Flags().Bool(
|
||||
"create",
|
||||
false,
|
||||
"create the database file if it does not already exist",
|
||||
"create", false, "create the database file if it does not already exist",
|
||||
)
|
||||
|
||||
return cmd
|
||||
}
|
||||
Reference in new issue
Block a user