Naming, layout and comments: descriptive full-word names, one item per line in wrapped calls and literals, and doc comments on exported names

Short and single-letter names in application code become full words (tests
keep theirs). Wrapped calls, signatures and composite literals put one item
per line, and one-line function bodies are expanded. Exported names and
groups of constants get doc comments, and comments refer to the renamed
identifiers.
This commit is contained in:
bwilliams committed 2026-10-15 16:12:56 +01:00
1 parent 043e307663
commit 465358609a
78 files changed
+2374 -1402

No files matched your search

+6 -2
View File
@@ -48,7 +48,9 @@ func writeFile(t *testing.T, path, contents string) {
// root command has, after parsing args.
func newCommand(t *testing.T, opts *Options, args ...string) *cobra.Command {
t.Helper()
cmd := &cobra.Command{Use: "test"}
cmd := &cobra.Command{
Use: "test",
}
opts.Bind(cmd)
if err := cmd.ParseFlags(args); err != nil {
t.Fatal(err)
@@ -203,7 +205,9 @@ func confirmWithInput(t *testing.T, input string) bool {
oldIn, oldOut := os.Stdin, os.Stdout
os.Stdin, os.Stdout = stdin, stdout
defer func() { os.Stdin, os.Stdout = oldIn, oldOut }()
defer func() {
os.Stdin, os.Stdout = oldIn, oldOut
}()
return Confirm("Proceed?")
}
+11 -4
View File
@@ -63,8 +63,12 @@ func TestConfigShow(t *testing.T) {
cmdtest.Setup(t, appConfig)
out := mustRun(t, "config", "show")
cmdtest.Contains(t, out,
"logging.level = info <string>", "sources.sleeper.interval = 2m0s <string>")
cmdtest.Contains(
t,
out,
"logging.level = info <string>",
"sources.sleeper.interval = 2m0s <string>",
)
// Keys are listed in order, the same every time.
if again := mustRun(t, "config", "show"); again != out {
t.Errorf("config show output changed between runs:\n%s\n---\n%s", out, again)
@@ -158,8 +162,11 @@ func TestConfigSetUnset(t *testing.T) {
t.Errorf("config.yaml settings = %v; want %v", got, want)
}
// Back to the default.
cmdtest.Contains(t, mustRun(t, "config", "get", "sources.sleeper.interval"),
"10m0s <string>")
cmdtest.Contains(
t,
mustRun(t, "config", "get", "sources.sleeper.interval"),
"10m0s <string>",
)
}
func TestConfigSetWithoutConfigFile(t *testing.T) {
+3 -3
View File
@@ -32,12 +32,12 @@ func commandGet(opts *cli.Options) *cobra.Command {
return fmt.Errorf("no configuration loaded (%w)", err)
}
v, err := conf.ValueOf(args[0])
value, err := conf.ValueOf(args[0])
if err != nil {
return err
}
t, _ := conf.TypeOf(args[0])
fmt.Println(v, "<"+t.String()+">")
kind, _ := conf.TypeOf(args[0])
fmt.Println(value, "<"+kind.String()+">")
return nil
},
+2 -1
View File
@@ -74,7 +74,8 @@ func commandInit() *cobra.Command {
fmt.Print(
"writing default configuration to file: " +
viper.ConfigFileUsed() +
"\n")
"\n",
)
if err := viper.WriteConfig(); err != nil {
return err
+3 -3
View File
@@ -8,14 +8,14 @@ import (
"strings"
)
// Confirm asks the user the yes/no question s on stdin and reports whether
// Confirm asks the user the yes/no question prompt on stdin and reports whether
// they answered yes. "y" and "yes" confirm, "n" and "no" refuse, in any case;
// anything else asks again. It exits the program if stdin can't be read.
func Confirm(s string) bool {
func Confirm(prompt string) bool {
reader := bufio.NewReader(os.Stdin)
for {
fmt.Printf("%s [y/n]: ", s)
fmt.Printf("%s [y/n]: ", prompt)
response, err := reader.ReadString('\n')
if err != nil {
+10 -10
View File
@@ -29,23 +29,23 @@ var stageTags = map[string][]string{
// filter keeps the opportunities whose latest release is at stage. Releases
// are oldest first, so the last one is the procedure's current stage.
func filter(opps []*types.Opportunity, stage string) []*types.Opportunity {
var resp []*types.Opportunity
func filter(opportunities []*types.Opportunity, stage string) []*types.Opportunity {
var matching []*types.Opportunity
for _, opp := range opps {
if len(opp.Releases) == 0 {
for _, opportunity := range opportunities {
if len(opportunity.Releases) == 0 {
continue
}
latest := opp.Releases[len(opp.Releases)-1]
latest := opportunity.Releases[len(opportunity.Releases)-1]
for _, tag := range latest.Tags {
if slices.Contains(stageTags[stage], tag.Tag) {
resp = append(resp, opp)
matching = append(matching, opportunity)
break
}
}
}
return resp
return matching
}
func commandOnce(opts *cli.Options) *cobra.Command {
@@ -71,12 +71,12 @@ func commandOnce(opts *cli.Options) *cobra.Command {
return sinceErr
}
ft := findatender.New(conf, conf.Sources.FindATender.APIRoot)
defer ft.Shutdown()
findATender := findatender.New(conf, conf.Sources.FindATender.APIRoot)
defer findATender.Shutdown()
ignoreRateLimit, _ := cmd.Flags().GetBool("ignore-rate-limit")
results, err := ft.FetchAll(since, !ignoreRateLimit)
results, err := findATender.FetchAll(since, !ignoreRateLimit)
if err != nil {
return err
}
+3 -1
View File
@@ -12,7 +12,9 @@ import (
// opp makes an opportunity whose releases, oldest first, have these tags.
func opp(uuid string, tags ...string) *types.Opportunity {
o := &types.Opportunity{UUID: uuid}
o := &types.Opportunity{
UUID: uuid,
}
for _, tag := range tags {
o.Releases = append(o.Releases, types.OpportunityRelease{
Tags: []types.OpportunityReleaseTag{{Tag: tag}},
+37 -26
View File
@@ -59,12 +59,12 @@ func openMigrator(
return nil, nil, err
}
m, err := store.NewMigrator(db)
migrator, err := store.NewMigrator(db)
if err != nil {
return nil, nil, errors.Join(err, db.Close())
}
return m, db, nil
return migrator, db, nil
}
// closeDB closes db when deferred, adding any error to *err.
@@ -80,61 +80,72 @@ type errWriter struct {
}
// printf writes like fmt.Fprintf, unless an earlier write failed.
func (e *errWriter) printf(format string, a ...any) {
func (e *errWriter) printf(format string, args ...any) {
if e.err == nil {
_, e.err = fmt.Fprintf(e.w, format, a...)
_, e.err = fmt.Fprintf(e.w, format, args...)
}
}
// printResults lists migrations that ran, e.g.
//
// applied 00003_create_release_tags_table.sql (2ms)
func printResults(w io.Writer, results []*goose.MigrationResult) error {
ew := &errWriter{w: w}
for _, r := range results {
func printResults(out io.Writer, results []*goose.MigrationResult) error {
output := &errWriter{
w: out,
}
for _, result := range results {
verb := "applied"
if r.Direction == "down" {
if result.Direction == "down" {
verb = "reverted"
}
ew.printf(" %-9s %s (%s)\n",
verb, filepath.Base(r.Source.Path), r.Duration.Round(time.Millisecond))
output.printf(
" %-9s %s (%s)\n",
verb,
filepath.Base(result.Source.Path),
result.Duration.Round(time.Millisecond),
)
}
return ew.err
return output.err
}
// failure prints what ran before a failed migration and describes the
// failure. Each migration runs in a transaction, so the failed one has been
// rolled back and the database is at the last version that succeeded.
func failure(w io.Writer, err error) error {
var pe *goose.PartialError
if !errors.As(err, &pe) {
func failure(out io.Writer, err error) error {
var partialErr *goose.PartialError
if !errors.As(err, &partialErr) {
return err
}
printErr := printResults(w, pe.Applied)
printErr := printResults(out, partialErr.Applied)
name := "unknown migration"
if pe.Failed != nil && pe.Failed.Source != nil {
name = filepath.Base(pe.Failed.Source.Path)
if partialErr.Failed != nil && partialErr.Failed.Source != nil {
name = filepath.Base(partialErr.Failed.Source.Path)
}
return errors.Join(fmt.Errorf(
"migration %s failed and was rolled back; the database is at the last "+
"version that succeeded.\nMigration error: %w",
name, pe.Err), printErr)
return errors.Join(
fmt.Errorf(
"migration %s failed and was rolled back; the database is at the last "+
"version that succeeded.\nMigration error: %w",
name,
partialErr.Err,
),
printErr,
)
}
// printVersion reports where the database ended up.
func printVersion(ctx context.Context, w io.Writer, m *goose.Provider) error {
v, err := m.GetDBVersion(ctx)
func printVersion(ctx context.Context, out io.Writer, migrator *goose.Provider) error {
dbVersion, err := migrator.GetDBVersion(ctx)
if err != nil {
return err
}
if v == 0 {
_, err = fmt.Fprintln(w, "Database cleared")
if dbVersion == 0 {
_, err = fmt.Fprintln(out, "Database cleared")
} else {
_, err = fmt.Fprintf(w, "Database migrated to version %d\n", v)
_, err = fmt.Fprintf(out, "Database migrated to version %d\n", dbVersion)
}
return err
}
+6 -2
View File
@@ -16,7 +16,9 @@ import (
func result(path, direction string) *goose.MigrationResult {
return &goose.MigrationResult{
Source: &goose.Source{Path: "migrations/" + path},
Source: &goose.Source{
Path: "migrations/" + path,
},
Direction: direction,
Duration: 1500 * time.Microsecond,
}
@@ -45,7 +47,9 @@ func TestFailurePartial(t *testing.T) {
}
func TestFailureWithoutFailedSource(t *testing.T) {
err := failure(&bytes.Buffer{}, &goose.PartialError{Err: errors.New("boom")})
err := failure(&bytes.Buffer{}, &goose.PartialError{
Err: errors.New("boom"),
})
if err == nil || !strings.Contains(err.Error(), "unknown migration") {
t.Errorf("err = %v, want unknown migration", err)
}
+3 -3
View File
@@ -32,13 +32,13 @@ confirmed by providing -yes.`,
yes, _ := cmd.Flags().GetBool("yes")
steps, _ := cmd.Flags().GetUint("steps")
m, db, err := openMigrator(cmd, opts, false, false)
migrator, db, err := openMigrator(cmd, opts, false, false)
if err != nil {
return err
}
defer closeDB(db, &err)
results, err := store.StepDown(cmd.Context(), m, int(steps), yes)
results, err := store.StepDown(cmd.Context(), migrator, int(steps), yes)
if len(results) == 0 && err == nil {
fmt.Println("No changes made to database (empty)")
@@ -58,7 +58,7 @@ confirmed by providing -yes.`,
return failure(cmd.OutOrStdout(), err)
}
return printVersion(cmd.Context(), cmd.OutOrStdout(), m)
return printVersion(cmd.Context(), cmd.OutOrStdout(), migrator)
},
}
cmd.Flags().Uint(
+21 -8
View File
@@ -55,7 +55,9 @@ func TestMigrateUpCreateThenStatus(t *testing.T) {
latest := latestVersion(t)
out := mustRun(t, "migrate", "up", "--create")
cmdtest.Contains(t, out,
cmdtest.Contains(
t,
out,
"applied 00001_create_opportunities_table.sql",
fmt.Sprintf("Database migrated to version %d", latest),
)
@@ -64,7 +66,9 @@ func TestMigrateUpCreateThenStatus(t *testing.T) {
}
out = mustRun(t, "migrate", "status")
cmdtest.Contains(t, out,
cmdtest.Contains(
t,
out,
fmt.Sprintf("Database version %d of %d (up-to-date)", latest, latest),
"00001_create_opportunities_table.sql",
)
@@ -87,8 +91,11 @@ func TestMigrateUpAsksBeforeCreating(t *testing.T) {
out, err := run(t, "n\n", "migrate", "up")
cmdtest.ErrContains(t, err, "no database file")
cmdtest.Contains(t, out,
"Database file './test.db' does not exist. Would you like to create it?")
cmdtest.Contains(
t,
out,
"Database file './test.db' does not exist. Would you like to create it?",
)
if cmdtest.Exists("test.db") {
t.Error("test.db was created after answering no")
}
@@ -110,8 +117,11 @@ func TestMigrateUpBySteps(t *testing.T) {
cmdtest.Contains(t, out, "Database migrated to version 2")
out = mustRun(t, "migrate", "status")
cmdtest.Contains(t, out,
fmt.Sprintf("Database version 2 of %d (%d pending)", latest, latest-2))
cmdtest.Contains(
t,
out,
fmt.Sprintf("Database version 2 of %d (%d pending)", latest, latest-2),
)
}
func TestMigrateDown(t *testing.T) {
@@ -130,8 +140,11 @@ func TestMigrateDown(t *testing.T) {
_, err := run(t, "", args...)
cmdtest.ErrContains(t, err, "pass the --yes flag")
}
cmdtest.Contains(t, mustRun(t, "migrate", "status"),
fmt.Sprintf("Database version %d of %d", latest-1, latest))
cmdtest.Contains(
t,
mustRun(t, "migrate", "status"),
fmt.Sprintf("Database version %d of %d", latest-1, latest),
)
out = mustRun(t, "migrate", "down", "--steps", "0", "--yes")
cmdtest.Contains(t, out, "Database cleared")
+37 -25
View File
@@ -22,51 +22,63 @@ 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, w io.Writer, m *goose.Provider) error {
statuses, err := m.Status(ctx)
func printStatus(ctx context.Context, out io.Writer, migrator *goose.Provider) error {
statuses, err := migrator.Status(ctx)
if err != nil {
return err
}
current, err := m.GetDBVersion(ctx)
current, err := migrator.GetDBVersion(ctx)
if err != nil {
return err
}
latest := store.LatestVersion(m)
latest := store.LatestVersion(migrator)
pending := 0
for _, s := range statuses {
if s.State == goose.StatePending {
for _, status := range statuses {
if status.State == goose.StatePending {
pending++
}
}
ew := &errWriter{w: w}
output := &errWriter{
w: out,
}
switch {
case current > latest:
ew.printf("Database version %d is newer than this build (latest %d)\n",
current, latest)
output.printf(
"Database version %d is newer than this build (latest %d)\n",
current,
latest,
)
case pending == 0:
ew.printf("Database version %d of %d (up-to-date)\n", current, latest)
output.printf("Database version %d of %d (up-to-date)\n", current, latest)
default:
ew.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 ew.err != nil {
return ew.err
if output.err != nil {
return output.err
}
tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
ew = &errWriter{w: tw}
for _, s := range statuses {
applied := ""
if s.State == goose.StateApplied {
applied = s.AppliedAt.Local().Format("2006-01-02 15:04:05")
}
ew.printf(" %d\t%s\t%s\t%s\n",
s.Source.Version, s.State, applied, filepath.Base(s.Source.Path))
table := tabwriter.NewWriter(out, 0, 0, 2, ' ', 0)
output = &errWriter{
w: table,
}
return errors.Join(ew.err, tw.Flush())
for _, status := range statuses {
applied := ""
if status.State == goose.StateApplied {
applied = status.AppliedAt.Local().Format("2006-01-02 15:04:05")
}
output.printf(
" %d\t%s\t%s\t%s\n",
status.Source.Version,
status.State,
applied,
filepath.Base(status.Source.Path),
)
}
return errors.Join(output.err, table.Flush())
}
func commandStatus(opts *cli.Options) *cobra.Command {
@@ -83,13 +95,13 @@ func commandStatus(opts *cli.Options) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) (err error) {
slog.Debug("command run", "command", "migrate.status")
m, db, err := openMigrator(cmd, opts, false, false)
migrator, db, err := openMigrator(cmd, opts, false, false)
if err != nil {
return err
}
defer closeDB(db, &err)
return printStatus(cmd.Context(), cmd.OutOrStdout(), m)
return printStatus(cmd.Context(), cmd.OutOrStdout(), migrator)
},
}
}
+3 -3
View File
@@ -16,13 +16,13 @@ import (
func runStepUp(
cmd *cobra.Command, opts *cli.Options, steps int, create bool,
) (err error) {
m, db, err := openMigrator(cmd, opts, true, create)
migrator, db, err := openMigrator(cmd, opts, true, create)
if err != nil {
return err
}
defer closeDB(db, &err)
results, err := store.StepUp(cmd.Context(), m, int(steps))
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)")
@@ -37,7 +37,7 @@ func runStepUp(
return failure(cmd.OutOrStdout(), err)
}
return printVersion(cmd.Context(), cmd.OutOrStdout(), m)
return printVersion(cmd.Context(), cmd.OutOrStdout(), migrator)
}
func commandUp(opts *cli.Options) *cobra.Command {
+4 -4
View File
@@ -20,10 +20,10 @@ type Options struct {
// Bind registers the shared flags as persistent flags on the root command cmd.
func (o *Options) Bind(cmd *cobra.Command) {
pf := cmd.PersistentFlags()
pf.StringVarP(&o.configFile, "config", "c", "", "configuration file")
pf.BoolVarP(&o.debug, "debug", "d", false, "enable debug messages")
pf.BoolVarP(
flags := cmd.PersistentFlags()
flags.StringVarP(&o.configFile, "config", "c", "", "configuration file")
flags.BoolVarP(&o.debug, "debug", "d", false, "enable debug messages")
flags.BoolVarP(
&o.quiet, "quiet", "q", false, "don't report info or warning messages",
)
}
+5 -3
View File
@@ -17,6 +17,8 @@ import (
"git.avsdev.uk/Go/job-search/internal/websocket/tcpserver"
)
// NewCommand returns the wsserve command, which runs a plain TCP server for
// websocket hub clients (see tcpserver).
func NewCommand(opts *cli.Options) *cobra.Command {
cmd := &cobra.Command{
Use: "wsserve",
@@ -43,7 +45,7 @@ func NewCommand(opts *cli.Options) *cobra.Command {
}
i, err := strconv.Atoi(listenParts[1])
if err != nil {
return fmt.Errorf("Failed to parse --listen port: %w", err)
return fmt.Errorf("failed to parse --listen port: %w", err)
}
hostOverride = listenParts[0]
portOverride = i
@@ -75,9 +77,9 @@ func NewCommand(opts *cli.Options) *cobra.Command {
}()
hub := websocket.NewHub(conf.Server.WebSocket)
svr := tcpserver.New(&conf.Server, hub)
server := tcpserver.New(&conf.Server, hub)
return svr.Run(ctx)
return server.Run(ctx)
},
}
cmd.Flags().String("listen", "", "listen address (default from config, 127.0.0.1:9393)")