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:
bwilliams committed 2026-10-15 16:26:42 +01:00
1 parent 465358609a
commit 67215a6aaa
104 files changed
+3189 -1206

No files matched your search

+3 -1
View File
@@ -8,7 +8,8 @@ import (
"git.avsdev.uk/Go/job-search/internal/cli"
)
// NewCommand returns the "config" command, which shows and edits the configuration.
// NewCommand returns the "config" command, which shows and edits the
// configuration.
func NewCommand(opts *cli.Options) *cobra.Command {
cmd := &cobra.Command{
Use: "config",
@@ -24,5 +25,6 @@ func NewCommand(opts *cli.Options) *cobra.Command {
cmd.AddCommand(commandGet(opts))
cmd.AddCommand(commandSet(opts))
cmd.AddCommand(commandInit())
return cmd
}
+36 -10
View File
@@ -41,9 +41,12 @@ func mustRun(t *testing.T, args ...string) string {
func fileSettings(t *testing.T, path string) map[string]any {
t.Helper()
var nested map[string]any
if err := yaml.Unmarshal([]byte(cmdtest.ReadFile(t, path)), &nested); err != nil {
if err := yaml.Unmarshal(
[]byte(cmdtest.ReadFile(t, path)), &nested,
); err != nil {
t.Fatal(err)
}
flat := map[string]any{}
var walk func(prefix string, m map[string]any)
walk = func(prefix string, m map[string]any) {
@@ -56,6 +59,7 @@ func fileSettings(t *testing.T, path string) map[string]any {
}
}
walk("", nested)
return flat
}
@@ -69,11 +73,17 @@ func TestConfigShow(t *testing.T) {
"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)
t.Errorf(
"config show output changed between runs:\n%s\n---\n%s", out, again,
)
}
if i, j := strings.Index(out, "database.file"), strings.Index(out, "logging.level"); i > j {
database := strings.Index(out, "database.file")
logging := strings.Index(out, "logging.level")
if database > logging {
t.Errorf("keys not sorted:\n%s", out)
}
@@ -87,9 +97,17 @@ func TestConfigShow(t *testing.T) {
func TestConfigGet(t *testing.T) {
cmdtest.Setup(t, appConfig)
cmdtest.Contains(t, mustRun(t, "config", "get", "logging.level"), "info <string>")
cmdtest.Contains(t, mustRun(t, "config", "get", "sources.sleeper.interval"), "2m0s <string>")
cmdtest.Contains(t, mustRun(t, "config", "get", "sources.sleeper.enabled"), "false <bool>")
for _, tt := range []struct {
key, want string
}{
{"logging.level", "info <string>"},
{"sources.sleeper.interval", "2m0s <string>"},
{"sources.sleeper.enabled", "false <bool>"},
} {
t.Run(tt.key, func(t *testing.T) {
cmdtest.Contains(t, mustRun(t, "config", "get", tt.key), tt.want)
})
}
if _, err := run(t, "config", "get", "no.such.key"); err == nil {
t.Error("get of an unknown key succeeded")
@@ -104,7 +122,9 @@ func TestConfigSet(t *testing.T) {
out := mustRun(t, "config", "set", "logging.level", "debug")
cmdtest.Contains(t, out, "logging.level = debug <string>")
cmdtest.Contains(t, mustRun(t, "config", "get", "logging.level"), "debug <string>")
cmdtest.Contains(
t, mustRun(t, "config", "get", "logging.level"), "debug <string>",
)
out = mustRun(t, "config", "set", "sources.sleeper.enabled", "true")
cmdtest.Contains(t, out, "sources.sleeper.enabled = true <bool>")
@@ -156,11 +176,13 @@ func TestConfigSetUnset(t *testing.T) {
cmdtest.Setup(t, appConfig)
mustRun(t, "config", "set", "--unset", "sources.sleeper.interval")
// Only the unset key is gone: no defaults are written in its place.
want := map[string]any{"logging.level": "info"}
if got := fileSettings(t, "config.yaml"); !equalSettings(got, want) {
t.Errorf("config.yaml settings = %v; want %v", got, want)
}
// Back to the default.
cmdtest.Contains(
t,
@@ -180,7 +202,9 @@ func TestConfigInit(t *testing.T) {
out := mustRun(t, "config", "init", "./new.yaml")
cmdtest.Contains(t, out, "writing default configuration to file: ./new.yaml")
cmdtest.Contains(t, cmdtest.ReadFile(t, "new.yaml"), "level: warn", "interval: 10m0s")
cmdtest.Contains(
t, cmdtest.ReadFile(t, "new.yaml"), "level: warn", "interval: 10m0s",
)
_, err := run(t, "config", "init", "./new.yaml")
cmdtest.ErrContains(t, err, "already exists")
@@ -199,8 +223,10 @@ func TestConfigInitDefaultLocations(t *testing.T) {
{"config", "init"},
{"config", "init", " "},
} {
_, err := run(t, args...)
cmdtest.ErrContains(t, err, "already exists")
t.Run(strings.Join(args, " "), func(t *testing.T) {
_, err := run(t, args...)
cmdtest.ErrContains(t, err, "already exists")
})
}
}
+1 -1
View File
@@ -29,7 +29,7 @@ func commandGet(opts *cli.Options) *cobra.Command {
conf, err := opts.RunSetup(cmd, true, true)
if err != nil {
return fmt.Errorf("no configuration loaded (%w)", err)
return fmt.Errorf("load configuration: %w", err)
}
value, err := conf.ValueOf(args[0])
+10 -8
View File
@@ -39,13 +39,13 @@ func commandInit() *cobra.Command {
cmd.SilenceUsage = true
// With no path, the default locations are used.
cfgFile := ""
configFile := ""
if len(args) > 0 {
cfgFile = strings.TrimSpace(args[0])
configFile = strings.TrimSpace(args[0])
}
if cfgFile != "" {
if configFile != "" {
// Use the config file given.
viper.SetConfigFile(cfgFile)
viper.SetConfigFile(configFile)
} else {
// Search config in /etc or local directory.
viper.AddConfigPath(config.EtcConfigPath)
@@ -58,8 +58,8 @@ func commandInit() *cobra.Command {
return errors.New("configuration file already exists")
}
_, ok := err.(viper.ConfigFileNotFoundError)
if !errors.Is(err, os.ErrNotExist) && !ok {
var notFound viper.ConfigFileNotFoundError
if !errors.Is(err, os.ErrNotExist) && !errors.As(err, &notFound) {
// Config file was found but another error was produced
return err
}
@@ -80,13 +80,15 @@ func commandInit() *cobra.Command {
if err := viper.WriteConfig(); err != nil {
return err
}
return nil
},
}
// Config flag should be hidden as the config path should be provided
cmd.SetHelpFunc(func(command *cobra.Command, strings []string) {
cmd.SetHelpFunc(func(command *cobra.Command, args []string) {
command.Flags().MarkHidden("config") //nolint:errcheck,gosec // a root flag, so it always exists
command.Parent().HelpFunc()(command, strings)
command.Parent().HelpFunc()(command, args)
})
return cmd
}
+2 -1
View File
@@ -43,7 +43,7 @@ func commandSet(opts *cli.Options) *cobra.Command {
conf, err := opts.RunSetup(cmd, true, true)
if err != nil {
return fmt.Errorf("no configuration loaded (%w)", err)
return fmt.Errorf("load configuration: %w", err)
}
if viper.ConfigFileUsed() == "" {
@@ -65,5 +65,6 @@ func commandSet(opts *cli.Options) *cobra.Command {
},
}
cmd.Flags().BoolP("unset", "x", false, "clear configuration setting")
return cmd
}
+4 -3
View File
@@ -24,13 +24,13 @@ func commandShow(opts *cli.Options) *cobra.Command {
conf, err := opts.RunSetup(cmd, true, true)
if err != nil {
return fmt.Errorf("no configuration loaded (%w)", err)
return fmt.Errorf("load configuration: %w", err)
}
if yaml, _ := cmd.Flags().GetBool("yaml"); yaml {
conf.PrintYaml()
conf.PrintYAML()
} else if json, _ := cmd.Flags().GetBool("json"); json {
conf.PrintJson()
conf.PrintJSON()
} else {
conf.PrintTerminal()
}
@@ -40,5 +40,6 @@ func commandShow(opts *cli.Options) *cobra.Command {
}
cmd.Flags().Bool("json", false, "format configuration as json")
cmd.Flags().Bool("yaml", false, "format configuration as yaml")
return cmd
}