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
@@ -52,9 +52,11 @@ func newCommand(t *testing.T, opts *Options, args ...string) *cobra.Command {
|
||||
Use: "test",
|
||||
}
|
||||
opts.Bind(cmd)
|
||||
|
||||
if err := cmd.ParseFlags(args); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -144,12 +146,16 @@ func TestRunSetupWithoutLoadingConfig(t *testing.T) {
|
||||
"-d -q": "debug", // --debug wins
|
||||
} {
|
||||
opts := &Options{}
|
||||
conf, err := opts.RunSetup(newCommand(t, opts, strings.Fields(args)...), false, true)
|
||||
conf, err := opts.RunSetup(
|
||||
newCommand(t, opts, strings.Fields(args)...), false, true,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if conf.Logging.Level != want {
|
||||
t.Errorf("%q: Logging.Level = %q, want %q", args, conf.Logging.Level, want)
|
||||
t.Errorf(
|
||||
"%q: Logging.Level = %q, want %q", args, conf.Logging.Level, want,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -192,22 +198,18 @@ func confirmWithInput(t *testing.T, input string) bool {
|
||||
dir := t.TempDir()
|
||||
in := filepath.Join(dir, "stdin")
|
||||
writeFile(t, in, input)
|
||||
|
||||
stdin, err := os.Open(filepath.Clean(in))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer stdin.Close()
|
||||
|
||||
stdout, err := os.Create(filepath.Clean(filepath.Join(dir, "stdout")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer stdout.Close()
|
||||
|
||||
oldIn, oldOut := os.Stdin, os.Stdout
|
||||
os.Stdin, os.Stdout = stdin, stdout
|
||||
defer func() {
|
||||
os.Stdin, os.Stdout = oldIn, oldOut
|
||||
}()
|
||||
|
||||
return Confirm("Proceed?")
|
||||
return Confirm(stdout, stdin, "Proceed?")
|
||||
}
|
||||
@@ -28,10 +28,12 @@ func Setup(t *testing.T, config string) string {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
t.Chdir(dir)
|
||||
|
||||
WriteFile(t, ".env", "")
|
||||
if config != "" {
|
||||
WriteFile(t, "config.yaml", config)
|
||||
}
|
||||
|
||||
return dir
|
||||
}
|
||||
|
||||
@@ -78,6 +80,7 @@ func NewRoot(opts *cli.Options, cmds ...*cobra.Command) *cobra.Command {
|
||||
cobra.EnableTraverseRunHooks = true
|
||||
opts.Bind(root)
|
||||
root.AddCommand(cmds...)
|
||||
|
||||
return root
|
||||
}
|
||||
|
||||
@@ -95,18 +98,19 @@ func Run(
|
||||
dir := t.TempDir()
|
||||
inPath, outPath := filepath.Join(dir, "stdin"), filepath.Join(dir, "stdout")
|
||||
WriteFile(t, inPath, stdin)
|
||||
in, err := os.Open(filepath.Clean(inPath))
|
||||
input, err := os.Open(filepath.Clean(inPath))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer in.Close() //nolint:errcheck // read only
|
||||
defer input.Close() //nolint:errcheck // read only
|
||||
|
||||
out, err := os.Create(filepath.Clean(outPath))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
oldIn, oldOut, oldLog := os.Stdin, os.Stdout, slog.Default()
|
||||
os.Stdin, os.Stdout = in, out
|
||||
os.Stdin, os.Stdout = input, out
|
||||
defer func() {
|
||||
os.Stdin, os.Stdout = oldIn, oldOut
|
||||
slog.SetDefault(oldLog)
|
||||
@@ -120,11 +124,14 @@ func Run(
|
||||
if err := out.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
return ReadFile(t, outPath), runErr
|
||||
}
|
||||
|
||||
// MustRun is Run with no input, for commands that must succeed.
|
||||
func MustRun(t *testing.T, newRoot func() *cobra.Command, args ...string) string {
|
||||
func MustRun(
|
||||
t *testing.T, newRoot func() *cobra.Command, args ...string,
|
||||
) string {
|
||||
t.Helper()
|
||||
out, err := Run(t, newRoot, "", args...)
|
||||
if err != nil {
|
||||
@@ -136,9 +143,9 @@ func MustRun(t *testing.T, newRoot func() *cobra.Command, args ...string) string
|
||||
// Contains fails the test unless out contains every string in want.
|
||||
func Contains(t *testing.T, out string, want ...string) {
|
||||
t.Helper()
|
||||
for _, w := range want {
|
||||
if !strings.Contains(out, w) {
|
||||
t.Errorf("output does not contain %q:\n%s", w, out)
|
||||
for _, wanted := range want {
|
||||
if !strings.Contains(out, wanted) {
|
||||
t.Errorf("output does not contain %q:\n%s", wanted, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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])
|
||||
|
||||
@@ -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, ¬Found) {
|
||||
// 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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -3,7 +3,7 @@ package cli
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
@@ -11,15 +11,19 @@ import (
|
||||
// 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(prompt string) bool {
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
func Confirm(out io.Writer, in io.Reader, prompt string) bool {
|
||||
reader := bufio.NewReader(in)
|
||||
|
||||
for {
|
||||
fmt.Printf("%s [y/n]: ", prompt)
|
||||
_, err := fmt.Fprintf(out, "%s [y/n]: ", prompt)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "error asking question: %s\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
response, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
slog.Error("reading the answer", "error", err)
|
||||
fmt.Fprintf(os.Stderr, "error reading answer: %s\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,8 @@ import (
|
||||
"git.avsdev.uk/Go/job-search/internal/cli"
|
||||
)
|
||||
|
||||
// NewCommand returns the "fetch" command, which fetches opportunities once or as a service.
|
||||
// NewCommand returns the "fetch" command, which fetches opportunities once or
|
||||
// as a service.
|
||||
func NewCommand(opts *cli.Options) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "fetch",
|
||||
@@ -22,5 +23,6 @@ func NewCommand(opts *cli.Options) *cobra.Command {
|
||||
}
|
||||
cmd.AddCommand(commandOnce(opts))
|
||||
cmd.AddCommand(commandService(opts))
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -29,7 +29,9 @@ 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(opportunities []*types.Opportunity, stage string) []*types.Opportunity {
|
||||
func filter(
|
||||
opportunities []*types.Opportunity, stage string,
|
||||
) []*types.Opportunity {
|
||||
var matching []*types.Opportunity
|
||||
|
||||
for _, opportunity := range opportunities {
|
||||
@@ -63,7 +65,7 @@ func commandOnce(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)
|
||||
}
|
||||
|
||||
since, sinceErr := cmd.Flags().GetTime("since")
|
||||
@@ -96,15 +98,15 @@ func commandOnce(opts *cli.Options) *cobra.Command {
|
||||
filterTag = "award"
|
||||
}
|
||||
|
||||
if len(filterTag) > 0 {
|
||||
if filterTag != "" {
|
||||
results = filter(results, filterTag)
|
||||
}
|
||||
|
||||
jbytes, err := json.MarshalIndent(results, "", " ")
|
||||
encoded, err := json.MarshalIndent(results, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(string(jbytes))
|
||||
fmt.Println(string(encoded))
|
||||
|
||||
return nil
|
||||
},
|
||||
@@ -118,17 +120,24 @@ func commandOnce(opts *cli.Options) *cobra.Command {
|
||||
"contract updates published since YYYY-MM-DD[ hh:mm:ss]",
|
||||
)
|
||||
cmd.Flags().Bool(
|
||||
"planning", false, "only return planning (i.e. exclude opportunities and awards)",
|
||||
"planning",
|
||||
false,
|
||||
"only return planning (i.e. exclude opportunities and awards)",
|
||||
)
|
||||
cmd.Flags().Bool(
|
||||
"opportunities", false, "only return opportunities (i.e. exclude awards and planning)",
|
||||
"opportunities",
|
||||
false,
|
||||
"only return opportunities (i.e. exclude awards and planning)",
|
||||
)
|
||||
cmd.Flags().Bool(
|
||||
"awards", false, "only return awards (i.e. exclude planning and opportunities)",
|
||||
"awards",
|
||||
false,
|
||||
"only return awards (i.e. exclude planning and opportunities)",
|
||||
)
|
||||
cmd.Flags().Bool(
|
||||
"ignore-rate-limit", false, "ignore the rate limit and fail if exceeded",
|
||||
)
|
||||
cmd.MarkFlagsMutuallyExclusive("planning", "opportunities", "awards")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -17,7 +17,9 @@ func opp(uuid string, tags ...string) *types.Opportunity {
|
||||
}
|
||||
for _, tag := range tags {
|
||||
o.Releases = append(o.Releases, types.OpportunityRelease{
|
||||
Tags: []types.OpportunityReleaseTag{{Tag: tag}},
|
||||
Tags: []types.OpportunityReleaseTag{{
|
||||
Tag: tag,
|
||||
}},
|
||||
})
|
||||
}
|
||||
return o
|
||||
@@ -56,6 +58,7 @@ func TestOnceFiltersExclusive(t *testing.T) {
|
||||
cmd.SetArgs([]string{"--planning", "--awards"})
|
||||
cmd.SetOut(io.Discard)
|
||||
cmd.SetErr(io.Discard)
|
||||
|
||||
err := cmd.Execute()
|
||||
if err == nil || !strings.Contains(err.Error(), "none of the others can be") {
|
||||
t.Fatalf("err = %v; want a mutually exclusive flags error", err)
|
||||
|
||||
@@ -32,7 +32,7 @@ func commandService(opts *cli.Options) *cobra.Command {
|
||||
|
||||
conf, err := opts.RunSetup(cmd, true, foreground)
|
||||
if err != nil {
|
||||
return fmt.Errorf("no configuration loaded (%w)", err)
|
||||
return fmt.Errorf("load configuration: %w", err)
|
||||
}
|
||||
|
||||
since, sinceErr := cmd.Flags().GetTime("since")
|
||||
@@ -65,5 +65,6 @@ func commandService(opts *cli.Options) *cobra.Command {
|
||||
"contract updates published since YYYY-MM-DD[ hh:mm:ss]",
|
||||
)
|
||||
cmd.Flags().Bool("foreground", false, "run in the foreground")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package cli_test
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
@@ -49,8 +50,10 @@ func TestLogLevelFlags(t *testing.T) {
|
||||
{[]string{"-q"}, "level: error"},
|
||||
{[]string{"-q", "-d"}, "level: debug"},
|
||||
} {
|
||||
out := cmdtest.MustRun(t, newRoot, append([]string{"level"}, tt.args...)...)
|
||||
cmdtest.Contains(t, out, tt.want)
|
||||
args := append([]string{"level"}, tt.args...)
|
||||
t.Run(strings.Join(args, " "), func(t *testing.T) {
|
||||
cmdtest.Contains(t, cmdtest.MustRun(t, newRoot, args...), tt.want)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -34,13 +34,13 @@ func (o *Options) Bind(cmd *cobra.Command) {
|
||||
// terminalLog is true, switches logging to the configured log file (staying
|
||||
// on the terminal, with a warning, if none is configured).
|
||||
func (o *Options) RunSetup(
|
||||
cmd *cobra.Command, loadConfig bool, terminalLog bool,
|
||||
cmd *cobra.Command, loadConfig, terminalLog bool,
|
||||
) (*config.JobSearchConfig, error) {
|
||||
// Flags and arguments are valid from here on, so errors are runtime
|
||||
// failures: report them without cobra's usage text.
|
||||
cmd.SilenceUsage = true
|
||||
|
||||
// Check for debug level or quiet supression via args
|
||||
// Check for debug level or quiet suppression via args
|
||||
conf := &config.JobSearchConfig{
|
||||
Logging: config.JSCLogging{},
|
||||
}
|
||||
@@ -64,7 +64,7 @@ func (o *Options) RunSetup(
|
||||
|
||||
// Check if the logging should be switched to file
|
||||
if !terminalLog {
|
||||
if len(conf.Logging.File) == 0 {
|
||||
if conf.Logging.File == "" {
|
||||
slog.Warn("no log file configured; logging to the terminal")
|
||||
} else if err := logging.LogToFile(conf.Logging.File); err != nil {
|
||||
return nil, fmt.Errorf("opening log file: %w", err)
|
||||
|
||||
@@ -2,6 +2,7 @@ package wsserve
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
@@ -39,21 +40,21 @@ func NewCommand(opts *cli.Options) *cobra.Command {
|
||||
if addrOverride != "" {
|
||||
listenParts := strings.Split(addrOverride, ":")
|
||||
if len(listenParts) != 2 {
|
||||
return fmt.Errorf(
|
||||
return errors.New(
|
||||
"--listen should be in the format of 127.0.0.1:9393",
|
||||
)
|
||||
}
|
||||
i, err := strconv.Atoi(listenParts[1])
|
||||
port, err := strconv.Atoi(listenParts[1])
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to parse --listen port: %w", err)
|
||||
}
|
||||
hostOverride = listenParts[0]
|
||||
portOverride = i
|
||||
portOverride = port
|
||||
}
|
||||
|
||||
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 portOverride != 0 {
|
||||
@@ -82,11 +83,16 @@ func NewCommand(opts *cli.Options) *cobra.Command {
|
||||
return server.Run(ctx)
|
||||
},
|
||||
}
|
||||
cmd.Flags().String("listen", "", "listen address (default from config, 127.0.0.1:9393)")
|
||||
cmd.Flags().String("host", "", "listen address (default from config, 127.0.0.1)")
|
||||
cmd.Flags().String(
|
||||
"listen", "", "listen address (default from config, 127.0.0.1:9393)",
|
||||
)
|
||||
cmd.Flags().String(
|
||||
"host", "", "listen address (default from config, 127.0.0.1)",
|
||||
)
|
||||
cmd.Flags().Int("port", 0, "listen address (default from config, 9393)")
|
||||
cmd.Flags().Bool("foreground", false, "run in the foreground")
|
||||
cmd.MarkFlagsMutuallyExclusive("listen", "host")
|
||||
cmd.MarkFlagsMutuallyExclusive("listen", "port")
|
||||
|
||||
return cmd
|
||||
}
|
||||
Reference in new issue
Block a user