feat(cli): doctor --json, conflicts --rm, status sync-age, opt-in default ignores 🧰🙈
- 🩺 `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.
This commit is contained in:
parent
4333bba55b
commit
84a4ff53e8
7 changed files with 202 additions and 23 deletions
|
|
@ -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
|
||||
}
|
||||
|
||||
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 <hub> <token>")
|
||||
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)
|
||||
}
|
||||
fmt.Fprintln(out, "🎉 all checks passed")
|
||||
return nil
|
||||
return finish(fmt.Errorf("doctor found problems (see ❌ above)"))
|
||||
}
|
||||
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.
|
||||
|
|
|
|||
|
|
@ -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())
|
||||
|
|
|
|||
|
|
@ -106,6 +106,7 @@ type Settings struct {
|
|||
} `toml:"secrets"`
|
||||
Sync struct {
|
||||
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"`
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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{},
|
||||
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)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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) }
|
||||
|
|
|
|||
|
|
@ -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/
|
||||
|
|
|
|||
Loading…
Reference in a new issue