From 28fd86b8d5d01db11c6a0ecac63559a3127402bc Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sat, 31 Oct 2026 23:35:23 +0300 Subject: [PATCH] feat(config): non-fatal loading with warnings and in-place SetKey (2C.2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Load finds the file through paths (no ./vcom.toml), returns defaults plus an error for a broken file instead of exiting, warns about unknown and deprecated keys (strict second pass), resets invalid values with a warning, and aliases center_width_percent to ui.preview_width_percent. New keys from design §9.2 get defaults. SetKey edits one line keeping comments, order and unknown keys, appends missing keys/sections, creates the XDG file, refuses a file that does not parse and verifies the result before an atomic write. The old UI shows config errors in the status line and survives an unknown theme name; the reference vcom.toml is documented and current. Co-Authored-By: Claude Opus 5.5 --- README.md | 13 +- cmd/vcom/main.go | 26 ++- internal/config/config.go | 316 ++++++++++++++------------------- internal/config/config_test.go | 148 +++++++++++++++ internal/config/lookup.go | 133 ++++++++++++++ internal/config/setkey.go | 262 +++++++++++++++++++++++++++ internal/config/setkey_test.go | 152 ++++++++++++++++ internal/ui/model.go | 21 ++- vcom.toml | 37 ++-- 9 files changed, 905 insertions(+), 203 deletions(-) create mode 100644 internal/config/config_test.go create mode 100644 internal/config/lookup.go create mode 100644 internal/config/setkey.go create mode 100644 internal/config/setkey_test.go diff --git a/README.md b/README.md index 6cd5686..b57b7a7 100644 --- a/README.md +++ b/README.md @@ -176,12 +176,15 @@ Preview mode (`F9` / `i`) temporarily replaces the inactive pane and shows: Optional config lookup order: 1. `-config /path/to/vcom.toml` -2. `./vcom.toml` -3. `./config/vcom.toml` -4. `$XDG_CONFIG_HOME/vcom/vcom.toml` -5. `~/.config/vcom/vcom.toml` +2. `$VCOM_CONFIG` +3. `$XDG_CONFIG_HOME/vcom/vcom.toml` +4. `~/.config/vcom/vcom.toml` -Reference config: [vcom.toml](/home/vrubel/projects/vcom/vcom.toml) +A `vcom.toml` in the current directory is no longer loaded. A broken config does not stop vcom: it starts with +defaults and shows the error. Unknown keys are reported as warnings. Choosing a theme edits only the `theme = ...` +line of the config; comments and other keys are kept. + +Reference config: [vcom.toml](vcom.toml) Icon mode example: diff --git a/cmd/vcom/main.go b/cmd/vcom/main.go index 5927d03..c8627fd 100644 --- a/cmd/vcom/main.go +++ b/cmd/vcom/main.go @@ -18,10 +18,20 @@ func main() { configPath := flag.String("config", "", "path to vcom TOML config") flag.Parse() - cfg, resolvedPath, err := config.Load(*configPath) - if err != nil { - fmt.Fprintf(os.Stderr, "config error: %v\n", err) - os.Exit(1) + // A broken config is not fatal: defaults + a message in the status line. + cfg, info, cfgErr := config.Load(*configPath) + resolvedPath := "" + if info.Found && cfgErr == nil { + resolvedPath = info.Path + } + notice := "" + switch { + case cfgErr != nil: + notice = cfgErr.Error() + case len(info.Warnings) == 1: + notice = "config: " + info.Warnings[0] + case len(info.Warnings) > 1: + notice = fmt.Sprintf("config: %s (+%d more warnings in the log)", info.Warnings[0], len(info.Warnings)-1) } // Set up debug logging to a file in /tmp @@ -37,6 +47,12 @@ func main() { defer f.Close() log.Printf("[INIT] Logging to %s", logPath) log.Printf("[INIT] vcom starting — config: %s, resolved: %s", *configPath, resolvedPath) + if cfgErr != nil { + log.Printf("[WARN] %v", cfgErr) + } + for _, w := range info.Warnings { + log.Printf("[WARN] config: %s", w) + } } model, err := ui.NewModel(cfg, resolvedPath) @@ -46,6 +62,8 @@ func main() { os.Exit(1) } + model = model.WithStatus(notice) + program := tea.NewProgram(model, tea.WithAltScreen(), tea.WithMouseCellMotion()) log.Printf("[INIT] Bubble Tea program started") if _, err := program.Run(); err != nil { diff --git a/internal/config/config.go b/internal/config/config.go index 223cfd1..cbb3d8d 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -1,16 +1,15 @@ +// Package config holds the vcom.toml schema, loading and the in-place +// SetKey edit (design §9.2). +// +// Loading never aborts the program: a broken file yields Default() plus an +// error for the status line; unknown or deprecated keys yield warnings; an +// invalid value is replaced by its default with a warning. package config import ( - "errors" "fmt" - "os" - "path/filepath" "strings" - "syscall" - - toml "github.com/pelletier/go-toml/v2" - - "vcom/internal/homedir" + "time" ) type Config struct { @@ -19,6 +18,8 @@ type Config struct { Browser BrowserConfig `toml:"browser"` Preview PreviewConfig `toml:"preview"` Behavior BehaviorConfig `toml:"behavior"` + Transfer TransferConfig `toml:"transfer"` + SSH SSHConfig `toml:"ssh"` } type StartupConfig struct { @@ -27,15 +28,18 @@ type StartupConfig struct { } type UIConfig struct { - AppTitle string `toml:"app_title"` - Theme string `toml:"theme"` - IconMode string `toml:"icon_mode"` - ShowTitleBar bool `toml:"show_title_bar"` - ShowFooter bool `toml:"show_footer"` - Border string `toml:"border"` - PathDisplay string `toml:"path_display"` - PaneGap int `toml:"pane_gap"` - CenterWidthPercent int `toml:"center_width_percent"` + // AppTitle is deprecated (warning when set); only the old UI still shows + // it. It goes away with the old UI in stage 7. + AppTitle string `toml:"app_title"` + Theme string `toml:"theme"` + IconMode string `toml:"icon_mode"` + ShowFooter bool `toml:"show_footer"` + Border string `toml:"border"` + PathDisplay string `toml:"path_display"` + PaneGap int `toml:"pane_gap"` + // PreviewWidthPercent is the preview width in the Info screen. The old + // name center_width_percent is accepted as an alias with a warning. + PreviewWidthPercent int `toml:"preview_width_percent"` } type BrowserConfig struct { @@ -65,211 +69,159 @@ type PreviewConfig struct { WrapText bool `toml:"wrap_text"` MaxPreviewBytes int64 `toml:"max_preview_bytes"` DirectoryPreviewLimit int `toml:"directory_preview_limit"` + // ImageBackend: auto | kitty | ueberzugpp | none. + ImageBackend string `toml:"image_backend"` + // MaxRemoteImageBytes: larger remote images are not downloaded for preview. + MaxRemoteImageBytes int64 `toml:"max_remote_image_bytes"` } type BehaviorConfig struct { - ConfirmDelete bool `toml:"confirm_delete"` + ConfirmDelete bool `toml:"confirm_delete"` // asks before moving to the trash ConfirmOverwrite bool `toml:"confirm_overwrite"` CalculateDirSizeOnSpace bool `toml:"calculate_dir_size_on_space"` - FollowSymlinks bool `toml:"follow_symlinks"` + FollowSymlinks bool `toml:"follow_symlinks"` // default of the transfer dialog + ConfirmQuit bool `toml:"confirm_quit"` +} + +type TransferConfig struct { + OnConflict string `toml:"on_conflict"` // ask | overwrite | skip | newer | rename + Preserve bool `toml:"preserve"` // keep mode and mtime + Fsync string `toml:"fsync"` // replace | always | never + MaxParallelJobs int `toml:"max_parallel_jobs"` +} + +type SSHConfig struct { + KeepaliveInterval Duration `toml:"keepalive_interval"` + ConnectTimeout Duration `toml:"connect_timeout"` +} + +// Duration is a time.Duration written as a Go duration string ("15s"). +type Duration struct{ time.Duration } + +func (d Duration) MarshalText() ([]byte, error) { return []byte(d.String()), nil } + +func (d *Duration) UnmarshalText(b []byte) error { + v, err := time.ParseDuration(string(b)) + if err != nil { + return err + } + d.Duration = v + return nil } func Default() Config { return Config{ - Startup: StartupConfig{}, UI: UIConfig{ - AppTitle: "vcom", - Theme: "catppuccin-mocha", - IconMode: "auto", - ShowTitleBar: true, - ShowFooter: true, - Border: "rounded", - PathDisplay: "short", - PaneGap: 1, - CenterWidthPercent: 30, + AppTitle: "vcom", + Theme: "catppuccin-mocha", + IconMode: "auto", + ShowFooter: true, + Border: "rounded", + PathDisplay: "short", + PaneGap: 1, + PreviewWidthPercent: 50, }, Browser: BrowserConfig{ ShowHidden: true, DirsFirst: true, HumanReadableSize: true, - Sort: SortConfig{ - By: "name", - Reverse: false, - }, - Columns: BrowserColumnsConfig{ - Name: true, - Size: true, - Modified: true, - }, + Sort: SortConfig{By: "name"}, + Columns: BrowserColumnsConfig{Name: true, Size: true, Modified: true}, }, Preview: PreviewConfig{ ShowMetadata: true, - WrapText: false, MaxPreviewBytes: 64 * 1024, DirectoryPreviewLimit: 80, + ImageBackend: "auto", + MaxRemoteImageBytes: 20 << 20, }, Behavior: BehaviorConfig{ ConfirmDelete: true, ConfirmOverwrite: true, CalculateDirSizeOnSpace: true, - FollowSymlinks: false, + ConfirmQuit: true, + }, + Transfer: TransferConfig{ + OnConflict: "ask", + Preserve: true, + Fsync: "replace", + MaxParallelJobs: 2, + }, + SSH: SSHConfig{ + KeepaliveInterval: Duration{15 * time.Second}, + ConnectTimeout: Duration{20 * time.Second}, }, } } -func Load(explicitPath string) (Config, string, error) { - cfg := Default() - - path, found, err := resolvePath(explicitPath) - if err != nil { - return Config{}, "", err +// Validate normalises c and replaces invalid values with their defaults. It +// returns one warning per replaced value; it never fails. +func (c *Config) Validate() []string { + d := Default() + var warns []string + reset := func(key string, got any, fix func()) { + warns = append(warns, fmt.Sprintf("%s: invalid value %v, using the default", key, got)) + fix() } - if !found { - return cfg, "", nil - } - - data, err := os.ReadFile(path) - if err != nil { - return Config{}, "", fmt.Errorf("read %s: %w", path, err) - } - if err := toml.Unmarshal(data, &cfg); err != nil { - return Config{}, "", fmt.Errorf("parse %s: %w", path, err) - } - - if err := cfg.Validate(); err != nil { - return Config{}, "", fmt.Errorf("validate %s: %w", path, err) - } - - return cfg, path, nil -} - -func Save(cfg Config, path string) (string, error) { - if err := cfg.Validate(); err != nil { - return "", err - } - - targetPath := strings.TrimSpace(path) - if targetPath == "" { - var err error - targetPath, err = DefaultUserPath() - if err != nil { - return "", err + oneOf := func(key string, v *string, def string, allowed ...string) { + s := strings.ToLower(strings.TrimSpace(*v)) + if s == "" { + *v = def + return } + for _, a := range allowed { + if s == a { + *v = s + return + } + } + reset(key, *v, func() { *v = def }) } - absPath, err := filepath.Abs(targetPath) - if err != nil { - return "", fmt.Errorf("resolve %s: %w", targetPath, err) - } - if err := os.MkdirAll(filepath.Dir(absPath), 0o755); err != nil { - return "", fmt.Errorf("mkdir %s: %w", filepath.Dir(absPath), err) - } - - data, err := toml.Marshal(cfg) - if err != nil { - return "", fmt.Errorf("marshal config: %w", err) - } - if err := os.WriteFile(absPath, data, 0o644); err != nil { - return "", fmt.Errorf("write %s: %w", absPath, err) - } - return absPath, nil -} - -func (c *Config) Validate() error { - if c.UI.Theme == "" { - return errors.New("ui.theme must not be empty") - } - switch strings.ToLower(strings.TrimSpace(c.UI.IconMode)) { - case "", "auto": - c.UI.IconMode = "auto" - case "nerd", "ascii": - default: - return errors.New("ui.icon_mode must be one of: auto, nerd, ascii") + if strings.TrimSpace(c.UI.Theme) == "" { + c.UI.Theme = d.UI.Theme } if strings.TrimSpace(c.UI.AppTitle) == "" { - c.UI.AppTitle = "vcom" - } - if c.Preview.MaxPreviewBytes <= 0 { - return errors.New("preview.max_preview_bytes must be > 0") - } - if c.Preview.DirectoryPreviewLimit <= 0 { - return errors.New("preview.directory_preview_limit must be > 0") - } - if !c.Browser.Columns.Name { - return errors.New("browser.columns.name must stay enabled") + c.UI.AppTitle = d.UI.AppTitle } + oneOf("ui.icon_mode", &c.UI.IconMode, "auto", "auto", "nerd", "ascii") if strings.TrimSpace(c.UI.PathDisplay) == "" { - c.UI.PathDisplay = "short" + c.UI.PathDisplay = d.UI.PathDisplay } if c.UI.PaneGap < 0 || c.UI.PaneGap > 4 { - return errors.New("ui.pane_gap must be between 0 and 4") + reset("ui.pane_gap", c.UI.PaneGap, func() { c.UI.PaneGap = d.UI.PaneGap }) } - if c.UI.CenterWidthPercent < 20 || c.UI.CenterWidthPercent > 60 { - return errors.New("ui.center_width_percent must be between 20 and 60") + if c.UI.PreviewWidthPercent < 20 || c.UI.PreviewWidthPercent > 80 { + reset("ui.preview_width_percent", c.UI.PreviewWidthPercent, func() { c.UI.PreviewWidthPercent = d.UI.PreviewWidthPercent }) } - switch strings.ToLower(strings.TrimSpace(c.Browser.Sort.By)) { - case "", "name": - c.Browser.Sort.By = "name" - case "modified", "size", "created", "extension": - default: - return fmt.Errorf("browser.sort.by must be one of: name, modified, size, created, extension") + oneOf("browser.sort.by", &c.Browser.Sort.By, "name", "name", "modified", "size", "created", "extension") + if !c.Browser.Columns.Name { + reset("browser.columns.name", false, func() { c.Browser.Columns.Name = true }) } - return nil -} - -func resolvePath(explicitPath string) (string, bool, error) { - var candidates []string - - if explicitPath != "" { - candidates = append(candidates, explicitPath) - } else { - homeDir := homedir.Dir() - if homeDir == "" { - return "", false, fmt.Errorf("cannot determine home directory") - } - xdgDir := os.Getenv("XDG_CONFIG_HOME") - if xdgDir == "" { - xdgDir = filepath.Join(homeDir, ".config") - } - - candidates = append(candidates, - "vcom.toml", - filepath.Join("config", "vcom.toml"), - filepath.Join(xdgDir, "vcom", "vcom.toml"), - filepath.Join(homeDir, ".config", "vcom", "vcom.toml"), - ) - } - - for _, candidate := range candidates { - if candidate == "" { - continue - } - absPath, err := filepath.Abs(candidate) - if err != nil { - return "", false, fmt.Errorf("resolve %s: %w", candidate, err) - } - if _, err := os.Stat(absPath); err == nil { - return absPath, true, nil - } else if !isMissingPathError(err) { - return "", false, fmt.Errorf("stat %s: %w", absPath, err) - } - } - - return "", false, nil -} - -func isMissingPathError(err error) bool { - return errors.Is(err, os.ErrNotExist) || errors.Is(err, syscall.ENOTDIR) -} - -func DefaultUserPath() (string, error) { - homeDir := homedir.Dir() - if homeDir == "" { - return "", fmt.Errorf("cannot determine home directory") - } - xdgDir := os.Getenv("XDG_CONFIG_HOME") - if xdgDir == "" { - xdgDir = filepath.Join(homeDir, ".config") - } - return filepath.Join(xdgDir, "vcom", "vcom.toml"), nil + if c.Preview.MaxPreviewBytes <= 0 { + reset("preview.max_preview_bytes", c.Preview.MaxPreviewBytes, func() { c.Preview.MaxPreviewBytes = d.Preview.MaxPreviewBytes }) + } + if c.Preview.DirectoryPreviewLimit <= 0 { + reset("preview.directory_preview_limit", c.Preview.DirectoryPreviewLimit, func() { + c.Preview.DirectoryPreviewLimit = d.Preview.DirectoryPreviewLimit + }) + } + oneOf("preview.image_backend", &c.Preview.ImageBackend, "auto", "auto", "kitty", "ueberzugpp", "none") + if c.Preview.MaxRemoteImageBytes < 0 { + reset("preview.max_remote_image_bytes", c.Preview.MaxRemoteImageBytes, func() { + c.Preview.MaxRemoteImageBytes = d.Preview.MaxRemoteImageBytes + }) + } + oneOf("transfer.on_conflict", &c.Transfer.OnConflict, "ask", "ask", "overwrite", "skip", "newer", "rename") + oneOf("transfer.fsync", &c.Transfer.Fsync, "replace", "replace", "always", "never") + if c.Transfer.MaxParallelJobs < 1 || c.Transfer.MaxParallelJobs > 16 { + reset("transfer.max_parallel_jobs", c.Transfer.MaxParallelJobs, func() { c.Transfer.MaxParallelJobs = d.Transfer.MaxParallelJobs }) + } + if c.SSH.KeepaliveInterval.Duration < time.Second { + reset("ssh.keepalive_interval", c.SSH.KeepaliveInterval, func() { c.SSH.KeepaliveInterval = d.SSH.KeepaliveInterval }) + } + if c.SSH.ConnectTimeout.Duration < time.Second { + reset("ssh.connect_timeout", c.SSH.ConnectTimeout, func() { c.SSH.ConnectTimeout = d.SSH.ConnectTimeout }) + } + return warns } diff --git a/internal/config/config_test.go b/internal/config/config_test.go new file mode 100644 index 0000000..8604b89 --- /dev/null +++ b/internal/config/config_test.go @@ -0,0 +1,148 @@ +package config + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestDefaultsValid(t *testing.T) { + c := Default() + if w := c.Validate(); len(w) != 0 { + t.Fatalf("defaults produce warnings: %v", w) + } + // New keys from design §9.2. + if !c.Behavior.ConfirmQuit || c.Transfer.OnConflict != "ask" || !c.Transfer.Preserve || + c.Transfer.Fsync != "replace" || c.Transfer.MaxParallelJobs != 2 || c.Preview.ImageBackend != "auto" || + c.Preview.MaxRemoteImageBytes != 20<<20 || c.SSH.KeepaliveInterval.Duration != 15*time.Second || + c.SSH.ConnectTimeout.Duration != 20*time.Second || c.UI.PreviewWidthPercent != 50 { + t.Fatalf("defaults: %+v", c) + } +} + +func TestReferenceConfigParsesClean(t *testing.T) { + data, err := os.ReadFile("../../vcom.toml") + if err != nil { + t.Fatal(err) + } + c, warns, err := Parse(data) + if err != nil { + t.Fatal(err) + } + if len(warns) != 0 { + t.Fatalf("reference vcom.toml produces warnings: %v", warns) + } + if c.UI.Theme != "github-dark" || c.SSH.ConnectTimeout.Duration != 20*time.Second { + t.Fatalf("parsed %+v", c) + } +} + +func TestLoadUnknownKeysWarns(t *testing.T) { + data := []byte(` +[ui] +theme = "nord" +show_title_bar = true +app_title = "x" +center_width_percent = 40 +mystery = 1 + +[behavior] +auto_refresh = true +auto_refresh_interval = 5 + +[nosuchsection] +k = "v" + +[ssh] +connect_timeout = "7s" +`) + c, warns, err := Parse(data) + if err != nil { + t.Fatal(err) + } + joined := strings.Join(warns, "\n") + for _, want := range []string{ + "unknown key ui.mystery", + "unknown key nosuchsection", + "ui.show_title_bar", + "ui.app_title", + "ui.center_width_percent is renamed to ui.preview_width_percent", + "behavior.auto_refresh is not implemented", + "behavior.auto_refresh_interval", + } { + if !strings.Contains(joined, want) { + t.Errorf("missing warning %q in:\n%s", want, joined) + } + } + if c.UI.Theme != "nord" || c.SSH.ConnectTimeout.Duration != 7*time.Second { + t.Fatalf("known keys not applied: %+v", c) + } + if c.UI.PreviewWidthPercent != 40 { + t.Fatalf("alias center_width_percent not applied: %d", c.UI.PreviewWidthPercent) + } + // The new name wins over the alias. + c, _, _ = Parse([]byte("[ui]\ncenter_width_percent = 40\npreview_width_percent = 60\n")) + if c.UI.PreviewWidthPercent != 60 { + t.Fatalf("preview_width_percent = %d", c.UI.PreviewWidthPercent) + } +} + +func TestLoadInvalidValueUsesDefault(t *testing.T) { + c, warns, err := Parse([]byte("[ui]\npane_gap = 9\nicon_mode = 'weird'\n[transfer]\nfsync = 'sometimes'\n")) + if err != nil { + t.Fatal(err) + } + d := Default() + if c.UI.PaneGap != d.UI.PaneGap || c.UI.IconMode != "auto" || c.Transfer.Fsync != "replace" { + t.Fatalf("invalid values not reset: %+v", c) + } + if len(warns) != 3 { + t.Fatalf("warnings: %v", warns) + } +} + +func TestLoadBrokenConfigFallsBackToDefaults(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "vcom.toml") + if err := os.WriteFile(p, []byte("[ui]\ntheme = \"nord\"\nborder = \n"), 0o644); err != nil { + t.Fatal(err) + } + c, info, err := Load(p) + if err == nil { + t.Fatal("broken config must return an error") + } + if !strings.Contains(err.Error(), "line 3") { + t.Errorf("error should point at the line: %v", err) + } + if c != Default() { + t.Fatalf("got %+v, want defaults", c) + } + if !info.Found || info.Path != p { + t.Fatalf("info %+v", info) + } + // A missing explicit file: defaults, no error. + c, info, err = Load(filepath.Join(dir, "none.toml")) + if err != nil || info.Found || c != Default() { + t.Fatalf("missing file: %+v %+v %v", c, info, err) + } +} + +func TestLoadIgnoresCwdConfig(t *testing.T) { + cwd := t.TempDir() + if err := os.WriteFile(filepath.Join(cwd, "vcom.toml"), []byte("[ui]\ntheme = 'nord'\n"), 0o644); err != nil { + t.Fatal(err) + } + t.Chdir(cwd) + t.Setenv("HOME", t.TempDir()) + t.Setenv("XDG_CONFIG_HOME", "") + t.Setenv("VCOM_CONFIG", "") + c, info, err := Load("") + if err != nil || info.Found || c.UI.Theme == "nord" { + t.Fatalf("cwd config was used: %+v %+v %v", c.UI, info, err) + } + if len(info.Warnings) != 1 || !strings.Contains(info.Warnings[0], "not loaded") { + t.Fatalf("expected a hint about ./vcom.toml, got %v", info.Warnings) + } +} diff --git a/internal/config/lookup.go b/internal/config/lookup.go new file mode 100644 index 0000000..3b8a1c2 --- /dev/null +++ b/internal/config/lookup.go @@ -0,0 +1,133 @@ +package config + +import ( + "bytes" + "errors" + "fmt" + "os" + "sort" + "strings" + + toml "github.com/pelletier/go-toml/v2" + + "vcom/internal/paths" +) + +// LoadInfo describes where the config came from. +type LoadInfo struct { + // Path is the file that was read, or — when Found is false — where + // SetKey would create one. + Path string + Found bool + // Warnings: unknown/deprecated keys, replaced invalid values, a stray + // ./vcom.toml that is no longer loaded. + Warnings []string +} + +// deprecated keys: accepted, ignored (or aliased), reported. +var deprecated = map[string]string{ + "ui.show_title_bar": "ui.show_title_bar is no longer used and is ignored", + "ui.center_width_percent": "ui.center_width_percent is renamed to ui.preview_width_percent", + "behavior.auto_refresh": "behavior.auto_refresh is not implemented and is ignored", + "behavior.auto_refresh_interval": "behavior.auto_refresh_interval is not implemented and is ignored", +} + +// Load reads the config found by paths.ConfigFile(explicit). It never fails +// hard: on a read or parse error it returns Default() and the error, and the +// caller starts anyway and shows the error. +func Load(explicit string) (Config, LoadInfo, error) { + cfg := Default() + path, found, err := paths.ConfigFile(explicit) + info := LoadInfo{Path: path, Found: found} + if err != nil { + return cfg, info, fmt.Errorf("config: %w", err) + } + if !found { + if stray, ok := paths.StrayCwdConfig(); ok { + info.Warnings = append(info.Warnings, fmt.Sprintf( + "%s is not loaded any more; move it to %s or pass -config", stray, path)) + } + return cfg, info, nil + } + data, err := os.ReadFile(path) + if err != nil { + return cfg, info, fmt.Errorf("config: %w", err) + } + c, warns, err := Parse(data) + info.Warnings = append(info.Warnings, warns...) + if err != nil { + return cfg, info, fmt.Errorf("config %s: %w (using defaults)", path, err) + } + return c, info, nil +} + +// Parse decodes a config file on top of Default(), applies aliases, reports +// unknown and deprecated keys and validates values. +func Parse(data []byte) (Config, []string, error) { + cfg := Default() + if err := toml.Unmarshal(data, &cfg); err != nil { + return Default(), nil, describe(err) + } + var raw map[string]any + _ = toml.Unmarshal(data, &raw) // cannot fail after the decode above + + var warns []string + present := func(key string) (any, bool) { + var cur any = raw + for _, part := range strings.Split(key, ".") { + m, ok := cur.(map[string]any) + if !ok { + return nil, false + } + if cur, ok = m[part]; !ok { + return nil, false + } + } + return cur, true + } + if v, ok := present("ui.center_width_percent"); ok { + if _, set := present("ui.preview_width_percent"); !set { + if n, ok := v.(int64); ok { + cfg.UI.PreviewWidthPercent = int(n) + } + } + } + if _, ok := present("ui.app_title"); ok { + warns = append(warns, "ui.app_title is deprecated and will be ignored by the new UI") + } + + // Strict pass: only for the list of unknown keys. + var strict Config + dec := toml.NewDecoder(bytes.NewReader(data)).DisallowUnknownFields() + var sme *toml.StrictMissingError + if err := dec.Decode(&strict); errors.As(err, &sme) { + var unknown []string + for _, e := range sme.Errors { + key := strings.Join(e.Key(), ".") + if msg, ok := deprecated[key]; ok { + warns = append(warns, msg) + continue + } + unknown = append(unknown, key) + } + sort.Strings(unknown) + for _, k := range unknown { + warns = append(warns, fmt.Sprintf("unknown key %s (ignored)", k)) + } + } + warns = append(warns, cfg.Validate()...) + return cfg, warns, nil +} + +// describe adds the line/column go-toml knows to a decode error. +func describe(err error) error { + var de *toml.DecodeError + if errors.As(err, &de) { + row, col := de.Position() + return fmt.Errorf("line %d, column %d: %w", row, col, err) + } + return err +} + +// DefaultUserPath is where a new config file is created. +func DefaultUserPath() (string, error) { return paths.DefaultConfigFile() } diff --git a/internal/config/setkey.go b/internal/config/setkey.go new file mode 100644 index 0000000..a3550e3 --- /dev/null +++ b/internal/config/setkey.go @@ -0,0 +1,262 @@ +package config + +import ( + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "reflect" + "regexp" + "strconv" + "strings" + + toml "github.com/pelletier/go-toml/v2" + + "vcom/internal/atomicfile" +) + +// SetKey sets section.key = value in the config file at path by editing that +// one line: comments, order, formatting and unknown keys are kept (design +// §9.2). A missing key is appended to its section, a missing section to the +// end of the file, a missing file is created (path "" means the default XDG +// location). The file must parse before the edit — a broken config is never +// touched — and the result is parsed again before it is written atomically. +// +// value is a string, bool, integer or float. section may be dotted +// ("browser.sort"). +func SetKey(path, section, key string, value any) (string, error) { + if path == "" { + var err error + if path, err = DefaultUserPath(); err != nil { + return "", err + } + } + lit, err := tomlValue(value) + if err != nil { + return "", err + } + data, err := os.ReadFile(path) + if errors.Is(err, fs.ErrNotExist) { + out := []byte("[" + section + "]\n" + key + " = " + lit + "\n") + if err := verify(out, section, key, value); err != nil { + return "", err + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return "", err + } + return path, atomicfile.WriteFile(path, out, 0o644) + } + if err != nil { + return "", err + } + var probe map[string]any + if err := toml.Unmarshal(data, &probe); err != nil { + return "", fmt.Errorf("%s does not parse, not editing it: %w", path, describe(err)) + } + out, err := editTOML(data, section, key, lit) + if err != nil { + return "", fmt.Errorf("edit %s: %w", path, err) + } + if err := verify(out, section, key, value); err != nil { + return "", fmt.Errorf("edit %s: %w", path, err) + } + return path, atomicfile.WriteFile(path, out, 0o644) +} + +var ( + reHeader = regexp.MustCompile(`^\s*\[\s*([^\[\]]+?)\s*\]\s*(#.*)?$`) + reArray = regexp.MustCompile(`^\s*\[\[`) +) + +// normSection canonicalises a table name: `a . "b"` → `a.b`. +func normSection(s string) string { + parts := strings.Split(s, ".") + for i, p := range parts { + p = strings.TrimSpace(p) + if len(p) >= 2 && (p[0] == '"' && p[len(p)-1] == '"' || p[0] == '\'' && p[len(p)-1] == '\'') { + p = p[1 : len(p)-1] + } + parts[i] = p + } + return strings.Join(parts, ".") +} + +// editTOML returns data with section.key set to the TOML literal lit. +func editTOML(data []byte, section, key, lit string) ([]byte, error) { + text := string(data) + nl := "\n" + if strings.Contains(text, "\r\n") { + nl = "\r\n" + } + lines := strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n") + section = normSection(section) + reKey := regexp.MustCompile(`^(\s*(?:` + regexp.QuoteMeta(key) + `|"` + regexp.QuoteMeta(key) + `"|'` + + regexp.QuoteMeta(key) + `')\s*=\s*)(.*)$`) + + cur := "" // the root table + inTarget := section == "" + lastContent := -1 // last key/value line of the target section + headerAt := -1 + for i, line := range lines { + if reArray.MatchString(line) { + cur, inTarget = "\x00array", false + continue + } + if m := reHeader.FindStringSubmatch(line); m != nil { + cur = normSection(m[1]) + inTarget = cur == section + if inTarget { + headerAt = i + } + continue + } + if !inTarget { + continue + } + if m := reKey.FindStringSubmatch(line); m != nil { + val, rest, err := splitValue(m[2]) + if err != nil { + return nil, fmt.Errorf("%s.%s: %w", section, key, err) + } + if strings.HasPrefix(val, "'") && !strings.ContainsAny(lit, `'\`) && strings.HasPrefix(lit, `"`) { + // Keep the file's literal-string style when possible. + if s, err := strconv.Unquote(lit); err == nil && !strings.ContainsAny(s, "'\n") { + lit = "'" + s + "'" + } + } + lines[i] = m[1] + lit + rest + return []byte(strings.Join(lines, nl)), nil + } + if t := strings.TrimSpace(line); t != "" && !strings.HasPrefix(t, "#") { + lastContent = i + } + } + newLine := key + " = " + lit + switch { + case headerAt >= 0 || section == "": + at := lastContent + if at < 0 { + at = headerAt // empty section (or root): right after the header + } + lines = append(lines[:at+1], append([]string{newLine}, lines[at+1:]...)...) + default: + for len(lines) > 0 && lines[len(lines)-1] == "" { + lines = lines[:len(lines)-1] + } + if len(lines) > 0 { + lines = append(lines, "") + } + lines = append(lines, "["+section+"]", newLine, "") + } + return []byte(strings.Join(lines, nl)), nil +} + +// splitValue splits "value # comment" into the value token and the rest +// (whitespace and comment), respecting quoted strings. +func splitValue(s string) (val, rest string, err error) { + if strings.HasPrefix(s, `"""`) || strings.HasPrefix(s, `'''`) { + return "", "", errors.New("multi-line string values are not supported") + } + end := len(s) + switch { + case strings.HasPrefix(s, `"`): + end = -1 + for i := 1; i < len(s); i++ { + if s[i] == '\\' { + i++ + continue + } + if s[i] == '"' { + end = i + 1 + break + } + } + case strings.HasPrefix(s, `'`): + end = -1 + if j := strings.IndexByte(s[1:], '\''); j >= 0 { + end = j + 2 + } + case strings.HasPrefix(s, "[") || strings.HasPrefix(s, "{"): + return "", "", errors.New("array and inline-table values are not supported") + default: + if j := strings.IndexByte(s, '#'); j >= 0 { + end = j + } + end = len(strings.TrimRight(s[:end], " \t")) + } + if end < 0 { + return "", "", errors.New("unterminated string") + } + return s[:end], s[end:], nil +} + +// tomlValue renders value as a TOML literal. +func tomlValue(v any) (string, error) { + switch x := v.(type) { + case string: + var b strings.Builder + b.WriteByte('"') + for _, r := range x { + switch { + case r == '"': + b.WriteString(`\"`) + case r == '\\': + b.WriteString(`\\`) + case r == '\n': + b.WriteString(`\n`) + case r == '\t': + b.WriteString(`\t`) + case r < 0x20 || r == 0x7f: + fmt.Fprintf(&b, `\u%04X`, r) + default: + b.WriteRune(r) + } + } + b.WriteByte('"') + return b.String(), nil + case bool: + return strconv.FormatBool(x), nil + case int: + return strconv.Itoa(x), nil + case int64: + return strconv.FormatInt(x, 10), nil + case float64: + return strconv.FormatFloat(x, 'g', -1, 64), nil + } + return "", fmt.Errorf("config: unsupported value type %T", v) +} + +// verify parses out and checks that section.key now holds value. +func verify(out []byte, section, key string, value any) error { + var m map[string]any + if err := toml.Unmarshal(out, &m); err != nil { + return fmt.Errorf("result does not parse: %w", err) + } + var cur any = m + path := append(strings.Split(normSection(section), "."), key) + if section == "" { + path = []string{key} + } + for _, p := range path { + mm, ok := cur.(map[string]any) + if !ok { + return fmt.Errorf("result: %s.%s not found", section, key) + } + cur = mm[p] + } + want := value + if n, ok := value.(int); ok { + want = int64(n) + } + if !reflect.DeepEqual(cur, want) { + return fmt.Errorf("result: %s.%s = %v, want %v", section, key, cur, value) + } + return nil +} + +// Save persists the theme of cfg with SetKey. Deprecated: it exists only +// for the old UI and is removed in 2C.3; it no longer rewrites the file. +func Save(cfg Config, path string) (string, error) { + return SetKey(path, "ui", "theme", cfg.UI.Theme) +} diff --git a/internal/config/setkey_test.go b/internal/config/setkey_test.go new file mode 100644 index 0000000..c1b079a --- /dev/null +++ b/internal/config/setkey_test.go @@ -0,0 +1,152 @@ +package config + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func writeFile(t *testing.T, p, s string) { + t.Helper() + if err := os.WriteFile(p, []byte(s), 0o644); err != nil { + t.Fatal(err) + } +} + +func readFile(t *testing.T, p string) string { + t.Helper() + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +// diffLines returns the indexes of lines that differ (files of equal length). +func diffLines(t *testing.T, a, b string) []int { + t.Helper() + la, lb := strings.Split(a, "\n"), strings.Split(b, "\n") + if len(la) != len(lb) { + t.Fatalf("line count changed: %d -> %d\n%s", len(la), len(lb), b) + } + var d []int + for i := range la { + if la[i] != lb[i] { + d = append(d, i) + } + } + return d +} + +func TestSetKeyPreservesComments(t *testing.T) { + orig, err := os.ReadFile("../../vcom.toml") + if err != nil { + t.Fatal(err) + } + // Plus an unknown key and an extra comment the user added. + before := string(orig) + "\n# my own note\n[extra]\nmine = 1 # keep\n" + p := filepath.Join(t.TempDir(), "vcom.toml") + writeFile(t, p, before) + + if _, err := SetKey(p, "ui", "theme", "nord"); err != nil { + t.Fatal(err) + } + after := readFile(t, p) + d := diffLines(t, before, after) + if len(d) != 1 { + t.Fatalf("changed lines %v, want only the theme line:\n%s", d, after) + } + line := strings.Split(after, "\n")[d[0]] + if !strings.HasPrefix(line, "theme = 'nord'") { + t.Fatalf("theme line = %q (style of the original literal string expected)", line) + } + c, _, err := Parse([]byte(after)) + if err != nil || c.UI.Theme != "nord" { + t.Fatalf("result: %v %+v", err, c.UI) + } + + // A value with a trailing comment keeps the comment; a nested section works. + if _, err := SetKey(p, "browser.sort", "by", "size"); err != nil { + t.Fatal(err) + } + if !strings.Contains(readFile(t, p), "by = 'size' # name | modified") { + t.Fatalf("trailing comment lost:\n%s", readFile(t, p)) + } + if _, err := SetKey(p, "ui", "pane_gap", 2); err != nil { + t.Fatal(err) + } + if !strings.Contains(readFile(t, p), "pane_gap = 2 # 0..4") { + t.Fatalf("int edit:\n%s", readFile(t, p)) + } +} + +func TestSetKeyMissingSection(t *testing.T) { + p := filepath.Join(t.TempDir(), "vcom.toml") + before := "# top comment\n[browser]\nshow_hidden = false # mine\n" + writeFile(t, p, before) + if _, err := SetKey(p, "ui", "theme", "nord"); err != nil { + t.Fatal(err) + } + after := readFile(t, p) + if !strings.HasPrefix(after, before) { + t.Fatalf("existing content changed:\n%s", after) + } + if !strings.HasSuffix(after, "\n[ui]\ntheme = \"nord\"\n") { + t.Fatalf("section not appended:\n%q", after) + } + + // Missing key in an existing section: inserted after its last key. + writeFile(t, p, "[ui]\nborder = 'thin' # b\n\n# about browser\n[browser]\nshow_hidden = true\n") + if _, err := SetKey(p, "ui", "theme", "nord"); err != nil { + t.Fatal(err) + } + want := "[ui]\nborder = 'thin' # b\ntheme = \"nord\"\n\n# about browser\n[browser]\nshow_hidden = true\n" + if got := readFile(t, p); got != want { + t.Fatalf("got:\n%s\nwant:\n%s", got, want) + } +} + +func TestSetKeyNoFile(t *testing.T) { + xdg := t.TempDir() + t.Setenv("XDG_CONFIG_HOME", xdg) + t.Setenv("VCOM_CONFIG", "") + path, err := SetKey("", "ui", "theme", "nord") + if err != nil { + t.Fatal(err) + } + if want := filepath.Join(xdg, "vcom", "vcom.toml"); path != want { + t.Fatalf("created %s, want %s", path, want) + } + if got := readFile(t, path); got != "[ui]\ntheme = \"nord\"\n" { + t.Fatalf("content %q", got) + } +} + +func TestSetKeyRefusesBrokenFile(t *testing.T) { + p := filepath.Join(t.TempDir(), "vcom.toml") + broken := "[ui]\ntheme = \"nord\nborder = 'x'\n" + writeFile(t, p, broken) + if _, err := SetKey(p, "ui", "theme", "dracula"); err == nil { + t.Fatal("SetKey edited a file that does not parse") + } + if readFile(t, p) != broken { + t.Fatal("broken file was modified") + } + // Unsupported shapes are refused, not mangled. + writeFile(t, p, "[ui]\ntheme = \"\"\"\nnord\"\"\"\n") + if _, err := SetKey(p, "ui", "theme", "x"); err == nil { + t.Fatal("multi-line string must be refused") + } +} + +func TestSetKeyQuotingAndCRLF(t *testing.T) { + p := filepath.Join(t.TempDir(), "vcom.toml") + writeFile(t, p, "[ui]\r\ntheme = \"a#b\" # c\r\n") + if _, err := SetKey(p, "ui", "theme", `it's "q"`); err != nil { + t.Fatal(err) + } + if got := readFile(t, p); got != "[ui]\r\ntheme = \"it's \\\"q\\\"\" # c\r\n" { + t.Fatalf("got %q", got) + } +} diff --git a/internal/ui/model.go b/internal/ui/model.go index e828664..3f355f4 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -246,8 +246,14 @@ type Model struct { func NewModel(cfg config.Config, configPath string) (Model, error) { palette, err := theme.Resolve(cfg.UI.Theme) + themeErr := "" if err != nil { - return Model{}, err + // An unknown theme name in the config is not fatal. + themeErr = err.Error() + cfg.UI.Theme = config.Default().UI.Theme + if palette, err = theme.Resolve(cfg.UI.Theme); err != nil { + return Model{}, err + } } home := homedir.Dir() @@ -298,6 +304,10 @@ func NewModel(cfg config.Config, configPath string) (Model, error) { model.ssh = sshSt } + if themeErr != "" { + model.status = themeErr + } + // Apply saved session (overrides startup paths if a previous session exists) applySession(&model) @@ -312,6 +322,15 @@ func NewModel(cfg config.Config, configPath string) (Model, error) { return model, nil } +// WithStatus returns m with s in the status line (startup notices such as a +// broken config). An empty s changes nothing. +func (m Model) WithStatus(s string) Model { + if s != "" { + m.status = s + } + return m +} + func (m Model) Init() tea.Cmd { return m.loadPreviewCmd() } diff --git a/vcom.toml b/vcom.toml index ea51e44..5d2229d 100644 --- a/vcom.toml +++ b/vcom.toml @@ -1,17 +1,21 @@ +# vcom reference configuration. +# Copy to ~/.config/vcom/vcom.toml (or $XDG_CONFIG_HOME/vcom/vcom.toml) and edit. +# Every key is optional; missing keys keep their defaults. + [startup] +# Start directories; empty means the home directory (a saved session wins). left_path = '' right_path = '' [ui] -app_title = 'vcom' +# Theme name; `t` in vcom opens the selector and rewrites only this line. theme = 'github-dark' -icon_mode = 'auto' -show_title_bar = true +icon_mode = 'auto' # auto | nerd | ascii show_footer = true border = 'rounded' path_display = 'smart' -pane_gap = 1 -center_width_percent = 30 +pane_gap = 1 # 0..4 +preview_width_percent = 50 # preview width in the Info screen, 20..80 [browser] show_hidden = true @@ -19,14 +23,14 @@ dirs_first = true human_readable_size = true [browser.sort] -by = 'name' +by = 'name' # name | modified | size | created | extension reverse = false [browser.columns] name = true size = true modified = true -created = false +created = false # birth time; computed only when this column is on permissions = false extension = false @@ -35,11 +39,22 @@ show_metadata = true wrap_text = false max_preview_bytes = 65536 directory_preview_limit = 80 +image_backend = 'auto' # auto | kitty | ueberzugpp | none +max_remote_image_bytes = 20971520 [behavior] -confirm_delete = true +confirm_delete = true # ask before moving to the trash confirm_overwrite = true calculate_dir_size_on_space = true -follow_symlinks = false -auto_refresh = true -auto_refresh_interval = 5 +follow_symlinks = false # default of "follow links" in the copy dialog +confirm_quit = true + +[transfer] +on_conflict = 'ask' # ask | overwrite | skip | newer | rename +preserve = true # keep permissions and modification times +fsync = 'replace' # replace | always | never +max_parallel_jobs = 2 + +[ssh] +keepalive_interval = '15s' +connect_timeout = '20s'