Refactor code style for improved readability and consistency.

This commit is contained in:
Overlord committed 2026-10-14 00:28:32 +02:00
1 parent 463c013056
commit 94bfc87e9d
4 files changed
+118 -156

No files matched your search

+23 -33
View File
@@ -35,35 +35,31 @@ func main() {
func run(args []string, stdout, stderr io.Writer) int { func run(args []string, stdout, stderr io.Writer) int {
if len(args) > 0 { if len(args) > 0 {
switch args[0] { switch args[0] {
case "config": case "config":
return runConfig(args[1:], stdout, stderr) return runConfig(args[1:], stdout, stderr)
case "version": case "version":
printVersion(stdout) printVersion(stdout)
return 0 return 0
case "check", "plugin": case "check", "plugin":
_, _ = fmt.Fprintf(stderr, "dibs %s: not implemented yet\n", args[0]) _, _ = fmt.Fprintf(stderr, "dibs %s: not implemented yet\n", args[0])
return 1 return 1
case "help", "-h", "--help": case "help", "-h", "--help":
_, _ = fmt.Fprint(stdout, usage) _, _ = fmt.Fprint(stdout, usage)
return 0 return 0
} }
} }
flags, configPath := newFlagSet("dibs", stderr) flags, configPath := newFlagSet("dibs", stderr)
flags.Bool("headless", false, "run without the TUI, log to stdout") flags.Bool("headless", false, "run without the TUI, log to stdout")
if err := flags.Parse(args); err != nil { if err := flags.Parse(args); err != nil { return 2 }
return 2
}
if flags.NArg() > 0 { if flags.NArg() > 0 {
_, _ = fmt.Fprintf(stderr, "dibs: unknown command %q\n\n%s", flags.Arg(0), usage) _, _ = fmt.Fprintf(stderr, "dibs: unknown command %q\n\n%s", flags.Arg(0), usage)
return 2 return 2
} }
if _, ok := loadConfig(*configPath, stderr); !ok { if _, ok := loadConfig(*configPath, stderr); !ok { return 1 }
return 1
}
_, _ = fmt.Fprintln(stderr, "dibs: watching is not implemented yet") _, _ = fmt.Fprintln(stderr, "dibs: watching is not implemented yet")
return 1 return 1
@@ -76,14 +72,10 @@ func runConfig(args []string, stdout, stderr io.Writer) int {
} }
flags, configPath := newFlagSet("dibs config validate", stderr) flags, configPath := newFlagSet("dibs config validate", stderr)
if err := flags.Parse(args[1:]); err != nil { if err := flags.Parse(args[1:]); err != nil { return 2 }
return 2
}
cfg, ok := loadConfig(*configPath, stderr) cfg, ok := loadConfig(*configPath, stderr)
if !ok { if !ok { return 1 }
return 1
}
urls := 0 urls := 0
for _, it := range cfg.Items { for _, it := range cfg.Items {
@@ -98,9 +90,7 @@ func runConfig(args []string, stdout, stderr io.Writer) int {
} }
func plural(n int, noun string) string { func plural(n int, noun string) string {
if n == 1 { if n == 1 { return "1 " + noun }
return "1 " + noun
}
return fmt.Sprintf("%d %ss", n, noun) return fmt.Sprintf("%d %ss", n, noun)
} }
@@ -126,13 +116,13 @@ func loadConfig(path string, stderr io.Writer) (*config.Config, bool) {
if err != nil { if err != nil {
var errs config.Errors var errs config.Errors
switch { switch {
case errors.As(err, &errs): case errors.As(err, &errs):
_, _ = fmt.Fprintln(stderr, errs) _, _ = fmt.Fprintln(stderr, errs)
_, _ = fmt.Fprintf(stderr, "%s in config\n", plural(len(errs), "problem")) _, _ = fmt.Fprintf(stderr, "%s in config\n", plural(len(errs), "problem"))
case errors.Is(err, fs.ErrNotExist): case errors.Is(err, fs.ErrNotExist):
_, _ = fmt.Fprintf(stderr, "dibs: no config at %s: create it or pass --config\n", path) _, _ = fmt.Fprintf(stderr, "dibs: no config at %s: create it or pass --config\n", path)
default: default:
_, _ = fmt.Fprintf(stderr, "dibs: %v\n", err) _, _ = fmt.Fprintf(stderr, "dibs: %v\n", err)
} }
return nil, false return nil, false
+23 -31
View File
@@ -29,10 +29,10 @@ const (
// Defaults for keys that may be omitted. // Defaults for keys that may be omitted.
const ( const (
DefaultInterval = 3 * time.Minute DefaultInterval = 3 * time.Minute
DefaultCooldown = 30 * time.Minute DefaultCooldown = 30 * time.Minute
DefaultSandboxTimeout = 2 * time.Second DefaultSandboxTimeout = 2 * time.Second
DefaultSessionTimeout = 5 * time.Minute DefaultSessionTimeout = 5 * time.Minute
DefaultMemoryMB = 64 DefaultMemoryMB = 64
DefaultCallStack = 200 DefaultCallStack = 200
) )
@@ -130,9 +130,7 @@ type Options struct {
// DefaultPath returns dibs.toml in the user config dir. // DefaultPath returns dibs.toml in the user config dir.
func DefaultPath() (string, error) { func DefaultPath() (string, error) {
dir, err := os.UserConfigDir() dir, err := os.UserConfigDir()
if err != nil { if err != nil { return "", err }
return "", err
}
return filepath.Join(dir, "dibs", "dibs.toml"), nil return filepath.Join(dir, "dibs", "dibs.toml"), nil
} }
@@ -140,22 +138,18 @@ func DefaultPath() (string, error) {
// are returned together as Errors. // are returned together as Errors.
func Load(path string, opts Options) (*Config, error) { func Load(path string, opts Options) (*Config, error) {
data, err := os.ReadFile(path) data, err := os.ReadFile(path)
if err != nil { if err != nil { return nil, err }
return nil, err
}
abs, err := filepath.Abs(path) abs, err := filepath.Abs(path)
if err != nil { if err != nil { return nil, err }
return nil, err
}
if opts.LookupEnv == nil { if opts.LookupEnv == nil {
opts.LookupEnv = os.LookupEnv opts.LookupEnv = os.LookupEnv
} }
cfg := &Config{ cfg := &Config{
Path: abs, Path: abs,
Notify: Notify{ Notify: Notify{
Desktop: true, Desktop: true,
Cooldown: Duration{Duration: DefaultCooldown}, Cooldown: Duration{Duration: DefaultCooldown},
}, },
@@ -177,27 +171,25 @@ func Load(path string, opts Options) (*Config, error) {
var decErr *toml.DecodeError var decErr *toml.DecodeError
switch { switch {
case err == nil: case err == nil:
case errors.As(err, &strict): case errors.As(err, &strict):
// The rest of the document was decoded, so keep validating it. // The rest of the document was decoded, so keep validating it.
for _, e := range strict.Errors { for _, e := range strict.Errors {
msg := "unknown key" msg := "unknown key"
if k := e.Key(); len(k) > 0 && k[len(k)-1] == "quantity" { if k := e.Key(); len(k) > 0 && k[len(k)-1] == "quantity" {
msg = "unknown key: quantity is always 1 and cannot be configured" msg = "unknown key: quantity is always 1 and cannot be configured"
}
v.decodeError(&e, msg)
} }
v.decodeError(&e, msg) case errors.As(err, &decErr):
} v.decodeError(decErr, "")
case errors.As(err, &decErr): return nil, v.errs
v.decodeError(decErr, "") default:
return nil, v.errs return nil, err
default:
return nil, err
} }
v.validate(cfg, opts) v.validate(cfg, opts)
if len(v.errs) > 0 { if len(v.errs) > 0 { return nil, v.errs }
return nil, v.errs
}
return cfg, nil return cfg, nil
} }
+15 -19
View File
@@ -24,18 +24,18 @@ func indexPositions(doc []byte) positions {
e := p.Expression() e := p.Expression()
switch e.Kind { switch e.Kind {
case unstable.Table, unstable.ArrayTable: case unstable.Table, unstable.ArrayTable:
keys, first := keyParts(e.Key()) keys, first := keyParts(e.Key())
path := strings.Join(keys, ".") path := strings.Join(keys, ".")
if e.Kind == unstable.ArrayTable { if e.Kind == unstable.ArrayTable {
n := arrays[path] n := arrays[path]
arrays[path]++ arrays[path]++
path = fmt.Sprintf("%s[%d]", path, n) path = fmt.Sprintf("%s[%d]", path, n)
} }
prefix = path prefix = path
ps.add(&p, path, first) ps.add(&p, path, first)
case unstable.KeyValue: case unstable.KeyValue:
ps.keyValue(&p, prefix, e) ps.keyValue(&p, prefix, e)
} }
} }
@@ -44,7 +44,7 @@ func indexPositions(doc []byte) positions {
func (ps positions) keyValue(p *unstable.Parser, prefix string, kv *unstable.Node) { func (ps positions) keyValue(p *unstable.Parser, prefix string, kv *unstable.Node) {
keys, first := keyParts(kv.Key()) keys, first := keyParts(kv.Key())
path := strings.Join(keys, ".") path := strings.Join(keys, ".")
if prefix != "" { if prefix != "" {
path = prefix + "." + path path = prefix + "." + path
@@ -84,9 +84,7 @@ func (ps positions) add(p *unstable.Parser, path string, n *unstable.Node) {
// that a missing key points at the table it belongs in. // that a missing key points at the table it belongs in.
func (ps positions) find(path string) (unstable.Position, bool) { func (ps positions) find(path string) (unstable.Position, bool) {
for path != "" { for path != "" {
if pos, ok := ps[path]; ok { if pos, ok := ps[path]; ok { return pos, true }
return pos, true
}
i := strings.LastIndexAny(path, ".[") i := strings.LastIndexAny(path, ".[")
if i < 0 { if i < 0 {
@@ -123,9 +121,7 @@ func keyParts(it unstable.Iterator) ([]string, *unstable.Node) {
for it.Next() { for it.Next() {
n := it.Node() n := it.Node()
if first == nil { if first == nil { first = n }
first = n
}
keys = append(keys, string(n.Data)) keys = append(keys, string(n.Data))
} }
+57 -73
View File
@@ -19,9 +19,9 @@ import (
// Ranges for the [sandbox] limits. // Ranges for the [sandbox] limits.
const ( const (
minSandboxTimeout = 100 * time.Millisecond minSandboxTimeout = 100 * time.Millisecond
maxSandboxTimeout = 30 * time.Second maxSandboxTimeout = 30 * time.Second
minSessionTimeout = 10 * time.Second minSessionTimeout = 10 * time.Second
maxSessionTimeout = 30 * time.Minute maxSessionTimeout = 30 * time.Minute
minMemoryMB = 4 minMemoryMB = 4
maxMemoryMB = 1024 maxMemoryMB = 1024
minCallStack = 50 minCallStack = 50
@@ -50,7 +50,7 @@ var goTypeNames = map[string]string{
// Error is one problem in the config file. // Error is one problem in the config file.
type Error struct { type Error struct {
File string File string
Line int // 1-based; 0 if unknown Line int // 1-based; 0 if unknown
Col int Col int
Key string // e.g. "item[1].interval"; empty for file-level problems Key string // e.g. "item[1].interval"; empty for file-level problems
Msg string Msg string
@@ -59,9 +59,7 @@ type Error struct {
func (e Error) Error() string { func (e Error) Error() string {
var b strings.Builder var b strings.Builder
b.WriteString(e.File) b.WriteString(e.File)
if e.Line > 0 { if e.Line > 0 { _, _ = fmt.Fprintf(&b, ":%d:%d", e.Line, e.Col) }
_, _ = fmt.Fprintf(&b, ":%d:%d", e.Line, e.Col)
}
b.WriteString(": ") b.WriteString(": ")
if e.Key != "" { if e.Key != "" {
@@ -78,9 +76,7 @@ type Errors []Error
func (es Errors) Error() string { func (es Errors) Error() string {
lines := make([]string, len(es)) lines := make([]string, len(es))
for i, e := range es { for i, e := range es { lines[i] = e.Error() }
lines[i] = e.Error()
}
return strings.Join(lines, "\n") return strings.Join(lines, "\n")
} }
@@ -93,9 +89,7 @@ type validator struct {
func (v *validator) errorf(key, format string, args ...any) { func (v *validator) errorf(key, format string, args ...any) {
e := Error{File: v.file, Key: key, Msg: fmt.Sprintf(format, args...)} e := Error{File: v.file, Key: key, Msg: fmt.Sprintf(format, args...)}
if p, ok := v.pos.find(key); ok { if p, ok := v.pos.find(key); ok { e.Line, e.Col = p.Line, p.Column }
e.Line, e.Col = p.Line, p.Column
}
v.errs = append(v.errs, e) v.errs = append(v.errs, e)
} }
@@ -119,17 +113,11 @@ func (v *validator) decodeError(de *toml.DecodeError, msg string) {
// types, into TOML terms. // types, into TOML terms.
func friendlyDecodeMsg(msg string) string { func friendlyDecodeMsg(msg string) string {
m := typeErrRe.FindStringSubmatch(msg) m := typeErrRe.FindStringSubmatch(msg)
if m == nil { if m == nil { return msg }
return msg
}
want, ok := goTypeNames[m[2]] want, ok := goTypeNames[m[2]]
if !ok { if !ok {
if strings.HasPrefix(m[2], "map[") { if strings.HasPrefix(m[2], "map[") { want = "a table" } else { return msg }
want = "a table"
} else {
return msg
}
} }
return fmt.Sprintf("expected %s, got a TOML %s", want, strings.ToLower(m[1])) return fmt.Sprintf("expected %s, got a TOML %s", want, strings.ToLower(m[1]))
@@ -137,9 +125,7 @@ func friendlyDecodeMsg(msg string) string {
func (v *validator) validate(cfg *Config, opts Options) { func (v *validator) validate(cfg *Config, opts Options) {
shops := map[string]bool{} shops := map[string]bool{}
for _, b := range opts.Builtins { for _, b := range opts.Builtins { shops[b] = true }
shops[b] = true
}
v.plugins(cfg, shops) v.plugins(cfg, shops)
v.items(cfg, shops, opts.Builtins) v.items(cfg, shops, opts.Builtins)
@@ -180,10 +166,10 @@ func (v *validator) plugins(cfg *Config, shops map[string]bool) {
info, err := os.Stat(path) info, err := os.Stat(path)
switch { switch {
case err != nil: case err != nil:
v.errorf(key, "cannot read plugin: %v", err) v.errorf(key, "cannot read plugin: %v", err)
case !info.Mode().IsRegular(): case !info.Mode().IsRegular():
v.errorf(key, "%s is not a regular file", path) v.errorf(key, "%s is not a regular file", path)
} }
} }
} }
@@ -195,27 +181,27 @@ func (v *validator) items(cfg *Config, shops map[string]bool, builtins []string)
} }
names := map[string]int{} names := map[string]int{}
urls := map[string]string{} urls := map[string]string{}
for i := range cfg.Items { for i := range cfg.Items {
it := &cfg.Items[i] it := &cfg.Items[i]
key := fmt.Sprintf("item[%d]", i) key := fmt.Sprintf("item[%d]", i)
switch { switch {
case it.Name == "": case it.Name == "":
v.errorf(key+".name", "missing required key") v.errorf(key+".name", "missing required key")
case names[it.Name] > 0: case names[it.Name] > 0:
v.errorf(key+".name", "duplicate item name %q (also item[%d])", it.Name, names[it.Name]-1) v.errorf(key+".name", "duplicate item name %q (also item[%d])", it.Name, names[it.Name]-1)
default: default:
names[it.Name] = i + 1 names[it.Name] = i + 1
} }
switch { switch {
case it.Shop == "": case it.Shop == "":
v.errorf(key+".shop", "missing required key") v.errorf(key+".shop", "missing required key")
case !shops[it.Shop]: case !shops[it.Shop]:
v.errorf(key+".shop", "unknown shop %q: built-in plugins are %s, others must be listed under [plugins]", v.errorf(key+".shop", "unknown shop %q: built-in plugins are %s, others must be listed under [plugins]",
it.Shop, strings.Join(builtins, ", ")) it.Shop, strings.Join(builtins, ", "))
} }
if len(it.URLs) == 0 { if len(it.URLs) == 0 {
@@ -252,26 +238,26 @@ func (v *validator) items(cfg *Config, shops map[string]bool, builtins []string)
if it.FXMargin != 0 { if it.FXMargin != 0 {
switch { switch {
case it.FXMargin < 0 || it.FXMargin > 1: case it.FXMargin < 0 || it.FXMargin > 1:
v.errorf(key+".fx_margin", "must be between 0 and 1, e.g. 0.1 for 10%% (got %v)", it.FXMargin) v.errorf(key+".fx_margin", "must be between 0 and 1, e.g. 0.1 for 10%% (got %v)", it.FXMargin)
case it.Currency == "" || it.MaxPrice == nil: case it.Currency == "" || it.MaxPrice == nil:
v.errorf(key+".fx_margin", "needs both currency and max_price to have an effect") v.errorf(key+".fx_margin", "needs both currency and max_price to have an effect")
} }
} }
switch it.Seller { switch it.Seller {
case "": case "":
it.Seller = SellerFirstParty it.Seller = SellerFirstParty
case SellerFirstParty, SellerAny: case SellerFirstParty, SellerAny:
default: default:
v.errorf(key+".seller", "must be %q or %q (got %q)", SellerFirstParty, SellerAny, it.Seller) v.errorf(key+".seller", "must be %q or %q (got %q)", SellerFirstParty, SellerAny, it.Seller)
} }
switch { switch {
case !it.Interval.IsSet(): case !it.Interval.IsSet():
it.Interval.Duration = DefaultInterval it.Interval.Duration = DefaultInterval
case it.Interval.Duration < MinInterval: case it.Interval.Duration < MinInterval:
v.errorf(key+".interval", "must be at least %s (got %s)", MinInterval, it.Interval) v.errorf(key+".interval", "must be at least %s (got %s)", MinInterval, it.Interval)
} }
} }
} }
@@ -286,11 +272,11 @@ func (v *validator) accounts(cfg *Config, shops map[string]bool, lookupEnv func(
} }
switch acc.CartMode { switch acc.CartMode {
case "": case "":
acc.CartMode = CartModeDeeplink acc.CartMode = CartModeDeeplink
case CartModeDeeplink, CartModeSession: case CartModeDeeplink, CartModeSession:
default: default:
v.errorf(key+".cart_mode", "must be %q or %q (got %q)", CartModeDeeplink, CartModeSession, acc.CartMode) v.errorf(key+".cart_mode", "must be %q or %q (got %q)", CartModeDeeplink, CartModeSession, acc.CartMode)
} }
if acc.PasswordEnv != "" { if acc.PasswordEnv != "" {
@@ -300,9 +286,7 @@ func (v *validator) accounts(cfg *Config, shops map[string]bool, lookupEnv func(
} }
for _, f := range []struct{ name, raw string }{{"login_url", acc.LoginURL}, {"cart_url", acc.CartURL}} { for _, f := range []struct{ name, raw string }{{"login_url", acc.LoginURL}, {"cart_url", acc.CartURL}} {
if f.raw == "" { if f.raw == "" { continue }
continue
}
if msg := checkURL(f.raw); msg != "" { if msg := checkURL(f.raw); msg != "" {
v.errorf(key+"."+f.name, "%s", msg) v.errorf(key+"."+f.name, "%s", msg)
@@ -324,11 +308,11 @@ func (v *validator) notify(n *Notify) {
} }
switch wh.Format { switch wh.Format {
case FormatDiscord, FormatNtfy, FormatJSON: case FormatDiscord, FormatNtfy, FormatJSON:
case "": case "":
v.errorf(key+".format", "missing required key (%q, %q or %q)", FormatDiscord, FormatNtfy, FormatJSON) v.errorf(key+".format", "missing required key (%q, %q or %q)", FormatDiscord, FormatNtfy, FormatJSON)
default: default:
v.errorf(key+".format", "must be %q, %q or %q (got %q)", FormatDiscord, FormatNtfy, FormatJSON, wh.Format) v.errorf(key+".format", "must be %q, %q or %q (got %q)", FormatDiscord, FormatNtfy, FormatJSON, wh.Format)
} }
} }
@@ -360,12 +344,12 @@ func durationRange(v *validator, key string, d, lo, hi time.Duration) {
func checkURL(raw string) string { func checkURL(raw string) string {
u, err := url.Parse(raw) u, err := url.Parse(raw)
switch { switch {
case err != nil: case err != nil:
return fmt.Sprintf("invalid URL: %v", err) return fmt.Sprintf("invalid URL: %v", err)
case u.Scheme != "http" && u.Scheme != "https": case u.Scheme != "http" && u.Scheme != "https":
return fmt.Sprintf("URL must start with http:// or https:// (got %q)", raw) return fmt.Sprintf("URL must start with http:// or https:// (got %q)", raw)
case u.Host == "": case u.Host == "":
return fmt.Sprintf("URL has no host (got %q)", raw) return fmt.Sprintf("URL has no host (got %q)", raw)
} }
return "" return ""