From 84a4ff53e8558e8b23177b1c4ef0959f4341b388 Mon Sep 17 00:00:00 2001 From: shoemoney Date: Tue, 30 Jun 2026 13:26:24 -0500 Subject: [PATCH] =?UTF-8?q?feat(cli):=20doctor=20--json,=20conflicts=20--r?= =?UTF-8?q?m,=20status=20sync-age,=20opt-in=20default=20ignores=20?= =?UTF-8?q?=F0=9F=A7=B0=F0=9F=99=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - ๐Ÿฉบ `doctor --json`: structured check report for cron/monitoring; still exits non-zero on โŒ (collects checks into a slice, JSON path suppresses the human lines). - ๐Ÿ—‘๏ธ `conflicts --rm`: delete every `.conflict-` copy after review (lazy cleanup, not a resolver). Only touches conflict copies โ€” real files untouched. - โฑ๏ธ `status` shows per-mount last-sync age ("synced 12s ago" / "not synced yet") from a daemon-tracked timestamp (control.MountState.LastSyncUnix); also in --json. - ๐Ÿ™ˆ the reversed no-go: `settings.sync.ignore_defaults` (opt-in, default off) layers a built-in junk set (node_modules, .git, target, dist, build, .venv, __pycache__, .next, .DS_Store) onto the matcher โ€” don't ship gigabytes of regenerable junk over the now-live WAN. Reuses round-1 --exclude plumbing; honored by daemon + publish. Tests: doctor --json valid+exit-code, conflicts --rm deletes only conflicts, ignore.Defaults match. go test ./... -race + vet clean. --- cmd/devbox/main.go | 101 ++++++++++++++++++++++++++------- cmd/devbox/main_test.go | 62 ++++++++++++++++++++ internal/config/config.go | 3 +- internal/control/control.go | 1 + internal/daemon/daemon.go | 25 +++++++- internal/ignore/ignore.go | 16 ++++++ internal/ignore/ignore_test.go | 17 ++++++ 7 files changed, 202 insertions(+), 23 deletions(-) diff --git a/cmd/devbox/main.go b/cmd/devbox/main.go index adc7f29..59e7be4 100644 --- a/cmd/devbox/main.go +++ b/cmd/devbox/main.go @@ -25,6 +25,7 @@ import ( "github.com/shoemoney/devbox/internal/daemon" "github.com/shoemoney/devbox/internal/hooks" "github.com/shoemoney/devbox/internal/identity" + "github.com/shoemoney/devbox/internal/ignore" "github.com/shoemoney/devbox/internal/secret" "github.com/shoemoney/devbox/internal/syncer" "github.com/shoemoney/devbox/internal/transport" @@ -154,13 +155,17 @@ func publishCmd() *cobra.Command { c := transport.New(d.Hub) c.SetBearer(d.Bearer) + var extraIgnore []string if s, err := config.LoadSettings(dir); err == nil { c.SetCompress(s.Transfer.Compress) // big initial upload โ€” honor compress over WAN + if s.Sync.IgnoreDefaults { + extraIgnore = ignore.Defaults // don't upload node_modules/.git/โ€ฆ on publish + } } if err := c.Publish(share); err != nil { return err } - ig, err := syncer.LoadIgnore(root) + ig, err := syncer.LoadIgnoreWith(root, extraIgnore) if err != nil { return err } @@ -567,7 +572,7 @@ func ignoreCmd() *cobra.Command { } func conflictsCmd() *cobra.Command { - var asJSON bool + var asJSON, rm bool cmd := &cobra.Command{ Use: "conflicts", Short: "๐Ÿ’ฅ list conflict copies across all mounts", @@ -584,6 +589,7 @@ func conflictsCmd() *cobra.Command { type conflict struct { Share string `json:"share"` Path string `json:"path"` + abs string // absolute path on disk (for --rm); not serialized } found := []conflict{} for _, m := range d.Mounts { @@ -593,11 +599,24 @@ func conflictsCmd() *cobra.Command { } if strings.Contains(e.Name(), ".conflict-") { rel, _ := filepath.Rel(m.Local, p) - found = append(found, conflict{Share: m.Share, Path: filepath.ToSlash(rel)}) + found = append(found, conflict{Share: m.Share, Path: filepath.ToSlash(rel), abs: p}) } return nil }) } + if rm { + removed := 0 + for _, cf := range found { + if err := os.Remove(cf.abs); err != nil { + fmt.Fprintf(out, " โš ๏ธ could not remove %s/%s: %v\n", cf.Share, cf.Path, err) + continue + } + fmt.Fprintf(out, " ๐Ÿ—‘๏ธ removed %s/%s\n", cf.Share, cf.Path) + removed++ + } + fmt.Fprintf(out, "removed %d conflict copy(ies)\n", removed) + return nil + } if asJSON { return writeJSON(out, found) } @@ -607,12 +626,13 @@ func conflictsCmd() *cobra.Command { if len(found) == 0 { fmt.Fprintln(out, "โœ… no conflict copies") } else { - fmt.Fprintf(out, "%d conflict copy(ies) โ€” review, then delete the loser(s)\n", len(found)) + fmt.Fprintf(out, "%d conflict copy(ies) โ€” review, then delete the loser(s) (or `devbox conflicts --rm`)\n", len(found)) } return nil }, } cmd.Flags().BoolVar(&asJSON, "json", false, "emit machine-readable JSON") + cmd.Flags().BoolVar(&rm, "rm", false, "delete every conflict copy (review first!)") return cmd } @@ -754,6 +774,7 @@ type statusMount struct { ReadOnly bool `json:"readonly"` Pinned bool `json:"pinned"` BaseSnapshot string `json:"base_snapshot,omitempty"` + LastSyncUnix int64 `json:"last_sync_unix,omitempty"` } type statusJSON struct { @@ -797,6 +818,7 @@ func statusCmd() *cobra.Command { s.Mounts = append(s.Mounts, statusMount{ Share: m.Share, Subpath: m.Subpath, Local: m.Local, ReadOnly: m.ReadOnly, Pinned: m.Pinned, BaseSnapshot: m.BaseSnapshot, + LastSyncUnix: m.LastSyncUnix, }) } } else { @@ -832,8 +854,8 @@ func statusCmd() *cobra.Command { if m.Pinned { mode += ",pinned" } - fmt.Fprintf(out, " - %s/%s -> %s [%s] @%s\n", - m.Share, m.Subpath, m.Local, mode, short(orNone(m.BaseSnapshot))) + fmt.Fprintf(out, " - %s/%s -> %s [%s] @%s (%s)\n", + m.Share, m.Subpath, m.Local, mode, short(orNone(m.BaseSnapshot)), syncAge(m.LastSyncUnix)) } return nil } @@ -859,6 +881,22 @@ func statusCmd() *cobra.Command { return cmd } +// syncAge renders how long ago a mount last synced (for live status). +func syncAge(unix int64) string { + if unix == 0 { + return "not synced yet" + } + d := time.Since(time.Unix(unix, 0)).Round(time.Second) + switch { + case d < time.Minute: + return fmt.Sprintf("synced %ds ago", int(d.Seconds())) + case d < time.Hour: + return fmt.Sprintf("synced %dm ago", int(d.Minutes())) + default: + return fmt.Sprintf("synced %dh ago", int(d.Hours())) + } +} + func orNone(s string) string { if s == "" { return "(none)" @@ -907,7 +945,8 @@ func stopCmd() *cobra.Command { } func doctorCmd() *cobra.Command { - return &cobra.Command{ + var asJSON bool + cmd := &cobra.Command{ Use: "doctor", Short: "๐Ÿฉบ diagnose this device's devbox setup (config, hub, mounts, watcher)", RunE: func(cmd *cobra.Command, _ []string) error { @@ -916,38 +955,56 @@ func doctorCmd() *cobra.Command { if err != nil { return err } + type doctorCheck struct { + Name string `json:"name"` + Status string `json:"status"` // ok | warn | fail + Detail string `json:"detail,omitempty"` + } + var checks []doctorCheck var failed bool check := func(ok bool, warn bool, name, detail string) { - glyph := "โœ…" + glyph, status := "โœ…", "ok" if !ok { if warn { - glyph = "โš ๏ธ " + glyph, status = "โš ๏ธ ", "warn" } else { - glyph = "โŒ" - failed = true + glyph, status, failed = "โŒ", "fail", true } } + checks = append(checks, doctorCheck{Name: name, Status: status, Detail: detail}) + if asJSON { + return + } if detail != "" { fmt.Fprintf(out, "%s %s โ€” %s\n", glyph, name, detail) } else { fmt.Fprintf(out, "%s %s\n", glyph, name) } } + // finish emits the JSON report (when --json) and preserves the exit code. + finish := func(retErr error) error { + if asJSON { + _ = writeJSON(out, checks) + } + return retErr + } - fmt.Fprintf(out, "devbox %s ยท %s/%s\n", version, runtime.GOOS, runtime.GOARCH) - fmt.Fprintf(out, "config: %s\n\n", dir) + if !asJSON { + fmt.Fprintf(out, "devbox %s ยท %s/%s\n", version, runtime.GOOS, runtime.GOARCH) + fmt.Fprintf(out, "config: %s\n\n", dir) + } // Identity + join state. if _, err := identity.Load(dir); err != nil { check(false, false, "identity", "not joined โ€” run: devbox join ") - return fmt.Errorf("device is not joined") + return finish(fmt.Errorf("device is not joined")) } check(true, false, "identity", "device keypair present") d, err := config.LoadDaemon(dir) if err != nil { check(false, false, "config", err.Error()) - return err + return finish(err) } check(d.Hub != "", false, "hub configured", d.Hub) check(d.Bearer != "", false, "bearer token", "present") @@ -1023,14 +1080,20 @@ func doctorCmd() *cobra.Command { } } - fmt.Fprintln(out) if failed { - return fmt.Errorf("doctor found problems (see โŒ above)") + if !asJSON { + fmt.Fprintln(out) + } + return finish(fmt.Errorf("doctor found problems (see โŒ above)")) } - fmt.Fprintln(out, "๐ŸŽ‰ all checks passed") - return nil + if !asJSON { + fmt.Fprintln(out, "\n๐ŸŽ‰ all checks passed") + } + return finish(nil) }, } + cmd.Flags().BoolVar(&asJSON, "json", false, "emit machine-readable JSON (exit code still non-zero on failure)") + return cmd } // writable reports whether dir exists and we can create a file in it. diff --git a/cmd/devbox/main_test.go b/cmd/devbox/main_test.go index 223f0c6..87ed258 100644 --- a/cmd/devbox/main_test.go +++ b/cmd/devbox/main_test.go @@ -4,9 +4,12 @@ import ( "bytes" "encoding/json" "os" + "path/filepath" "strconv" "strings" "testing" + + "github.com/shoemoney/devbox/internal/config" ) // TestStatusJSON proves `status --json` emits valid JSON and reports not-joined @@ -30,6 +33,65 @@ func TestStatusJSON(t *testing.T) { } } +// TestDoctorJSON proves `doctor --json` emits valid JSON and still reports +// failure (non-zero exit) on an unjoined device. +func TestDoctorJSON(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) // unjoined + + var buf bytes.Buffer + cmd := doctorCmd() + cmd.SetOut(&buf) + cmd.SetErr(&buf) + cmd.SilenceUsage, cmd.SilenceErrors = true, true + cmd.SetArgs([]string{"--json"}) + err := cmd.Execute() + if err == nil { + t.Fatal("doctor on an unjoined device must return an error (non-zero exit)") + } + var checks []struct { + Name, Status, Detail string + } + if jerr := json.Unmarshal(buf.Bytes(), &checks); jerr != nil { + t.Fatalf("doctor --json emitted invalid JSON: %v\n%s", jerr, buf.String()) + } + if len(checks) == 0 || checks[0].Status != "fail" { + t.Fatalf("expected a failing identity check, got %+v", checks) + } +} + +// TestConflictsRm proves `conflicts --rm` deletes only .conflict- copies. +func TestConflictsRm(t *testing.T) { + cfg := t.TempDir() + t.Setenv("XDG_CONFIG_HOME", cfg) + mountDir := t.TempDir() + keep := filepath.Join(mountDir, "keep.txt") + conflictFile := filepath.Join(mountDir, "doc.conflict-host-123.txt") + if err := os.WriteFile(keep, []byte("real"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(conflictFile, []byte("loser"), 0o644); err != nil { + t.Fatal(err) + } + if err := config.SaveDaemon(filepath.Join(cfg, "devbox"), config.Daemon{ + Hub: "http://h", Mounts: []config.Mount{{Share: "proj", Local: mountDir, Hub: "http://h"}}, + }); err != nil { + t.Fatal(err) + } + + cmd := conflictsCmd() + cmd.SetOut(&bytes.Buffer{}) + cmd.SetArgs([]string{"--rm"}) + if err := cmd.Execute(); err != nil { + t.Fatalf("conflicts --rm: %v", err) + } + if _, err := os.Stat(conflictFile); !os.IsNotExist(err) { + t.Error("conflict copy should have been deleted") + } + if _, err := os.Stat(keep); err != nil { + t.Error("real file must NOT be deleted") + } +} + // TestConflictsJSON proves `conflicts --json` emits a JSON array (never null). func TestConflictsJSON(t *testing.T) { t.Setenv("XDG_CONFIG_HOME", t.TempDir()) diff --git a/internal/config/config.go b/internal/config/config.go index 8e89049..f0f4e68 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -105,7 +105,8 @@ type Settings struct { ExtraPatterns []string `toml:"extra_patterns"` } `toml:"secrets"` Sync struct { - RescanSeconds int `toml:"rescan_seconds"` // periodic rescan cadence; 0 = default (60s) + RescanSeconds int `toml:"rescan_seconds"` // periodic rescan cadence; 0 = default (60s) + IgnoreDefaults bool `toml:"ignore_defaults"` // also ignore common regenerable junk (node_modules, .git, โ€ฆ) } `toml:"sync"` } diff --git a/internal/control/control.go b/internal/control/control.go index cfcf0d5..4082e2f 100644 --- a/internal/control/control.go +++ b/internal/control/control.go @@ -40,6 +40,7 @@ type MountState struct { ReadOnly bool `json:"readonly"` Pinned bool `json:"pinned"` BaseSnapshot string `json:"base_snapshot"` + LastSyncUnix int64 `json:"last_sync_unix"` // 0 = not synced since daemon start } // Daemon is the slice of the running daemon the control server steers. The diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index f823eef..6d632a8 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -15,6 +15,7 @@ import ( "github.com/shoemoney/devbox/internal/config" "github.com/shoemoney/devbox/internal/control" "github.com/shoemoney/devbox/internal/hooks" + "github.com/shoemoney/devbox/internal/ignore" "github.com/shoemoney/devbox/internal/secret" "github.com/shoemoney/devbox/internal/syncer" "github.com/shoemoney/devbox/internal/transport" @@ -38,6 +39,7 @@ type Daemon struct { guard *secret.Guard maxBytesPerSec int compress bool // gzip blob uploads (settings.transfer.compress) + ignoreDefaults bool // also ignore common junk dirs (settings.sync.ignore_defaults) rescanInterval time.Duration // periodic safety-net cadence (settings.sync.rescan_seconds) logf func(string, ...any) @@ -47,6 +49,7 @@ type Daemon struct { state map[string]string // mountKey -> last-applied snapshot nudges map[string]func() // mountKey -> trigger a catch-up sync (for Resume) mounts map[string]config.Mount // mountKey -> mount config (for StateSnapshot) + lastSync map[string]int64 // mountKey -> unix secs of last successful sync (0 = never) resumeTimer *time.Timer // pending auto-resume from PauseFor; nil if none } @@ -75,13 +78,22 @@ func New(dir string, cfg config.Daemon, host string, logf func(string, ...any)) dir: dir, cfg: cfg, host: host, guard: guard, maxBytesPerSec: settings.Transfer.MaxKbps * 1024, compress: settings.Transfer.Compress, + ignoreDefaults: settings.Sync.IgnoreDefaults, rescanInterval: rescan, logf: logf, state: state, - nudges: map[string]func(){}, - mounts: map[string]config.Mount{}, + nudges: map[string]func(){}, + mounts: map[string]config.Mount{}, + lastSync: map[string]int64{}, }, nil } +// recordSync stamps a mount's last successful sync time (for StateSnapshot / status). +func (d *Daemon) recordSync(m config.Mount) { + d.mu.Lock() + d.lastSync[mountKey(m)] = time.Now().Unix() + d.mu.Unlock() +} + // Run syncs every mount until ctx is cancelled. func (d *Daemon) Run(ctx context.Context) error { // Start the control plane before mounts so `devbox status`/`pause` can reach @@ -315,13 +327,18 @@ func (d *Daemon) StateSnapshot() control.State { ReadOnly: m.ReadOnly, Pinned: m.Pinned, BaseSnapshot: d.state[k], + LastSyncUnix: d.lastSync[k], }) } return st } func (d *Daemon) syncMount(c *transport.Client, m config.Mount) { - ig, err := syncer.LoadIgnoreWith(m.Local, m.Exclude) + excludes := m.Exclude + if d.ignoreDefaults { + excludes = append(append([]string{}, m.Exclude...), ignore.Defaults...) + } + ig, err := syncer.LoadIgnoreWith(m.Local, excludes) if err != nil { d.logf("ignore %s: %v", m.Local, err) return @@ -337,6 +354,7 @@ func (d *Daemon) syncMount(c *transport.Client, m config.Mount) { return } d.setBase(m, pr.Base) + d.recordSync(m) d.report(m, pr) return } @@ -347,6 +365,7 @@ func (d *Daemon) syncMount(c *transport.Client, m config.Mount) { return } d.setBase(m, newBase) + d.recordSync(m) d.report(m, pr) } diff --git a/internal/ignore/ignore.go b/internal/ignore/ignore.go index ff5e1e0..c4bed03 100644 --- a/internal/ignore/ignore.go +++ b/internal/ignore/ignore.go @@ -19,6 +19,22 @@ type rule struct { dirOnly bool } +// Defaults are common regenerable / VCS directories that almost never belong in +// a sync share. Opt-in via settings.sync.ignore_defaults (off by default, so +// existing shares don't silently change what they sync). Gitignore syntax โ€” +// trailing slash = directory-only โ€” fed through the same --exclude layering. +var Defaults = []string{ + ".git/", + "node_modules/", + ".venv/", + "__pycache__/", + "target/", // rust/java build output + "dist/", + "build/", + ".next/", + ".DS_Store", +} + // Compile parses the lines of a .devignore file into a Matcher (case-sensitive, // matching gitignore semantics). func Compile(patterns []string) (*Matcher, error) { return compile(patterns, false) } diff --git a/internal/ignore/ignore_test.go b/internal/ignore/ignore_test.go index 5546f6e..e8fb83a 100644 --- a/internal/ignore/ignore_test.go +++ b/internal/ignore/ignore_test.go @@ -5,6 +5,23 @@ import ( "testing" ) +// TestDefaultsMatch proves the opt-in default-ignore set matches common junk +// dirs but leaves real source alone. +func TestDefaultsMatch(t *testing.T) { + m, err := Compile(Defaults) + if err != nil { + t.Fatal(err) + } + for _, dir := range []string{"node_modules", ".git", "__pycache__", "target", "dist"} { + if !m.Match(dir, true) { + t.Errorf("Defaults should ignore %q/", dir) + } + } + if m.Match("src", true) || m.Match("main.go", false) { + t.Error("Defaults must not ignore real source") + } +} + const devignore = ` node_modules/ dist/