diff --git a/cmd/devbox/main.go b/cmd/devbox/main.go index 223856e..21e59a1 100644 --- a/cmd/devbox/main.go +++ b/cmd/devbox/main.go @@ -7,6 +7,7 @@ import ( "os" "os/signal" "path/filepath" + "strings" "syscall" "time" @@ -132,7 +133,7 @@ func publishCmd() *cobra.Command { if err != nil { return err } - res, err := syncer.Push(c, root, share, ig, guard, head) + res, err := syncer.Push(c, root, share, "", ig, guard, head) if err != nil { return err } @@ -155,11 +156,11 @@ func publishCmd() *cobra.Command { func mountCmd() *cobra.Command { var ro bool cmd := &cobra.Command{ - Use: "mount ", - Short: "🔗 mount a hub share into a local directory (clone + sync)", + Use: "mount ", + Short: "🔗 mount a hub share (or sub-path) into a local directory (clone + sync)", Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - share := args[0] + share, subpath := splitShare(args[0]) local, err := filepath.Abs(args[1]) if err != nil { return err @@ -178,7 +179,7 @@ func mountCmd() *cobra.Command { if err := os.MkdirAll(local, 0o755); err != nil { return err } - d.Mounts = upsertMount(d.Mounts, config.Mount{Share: share, Local: local, Hub: d.Hub, ReadOnly: ro}) + d.Mounts = upsertMount(d.Mounts, config.Mount{Share: share, Subpath: subpath, Local: local, Hub: d.Hub, ReadOnly: ro}) if err := config.SaveDaemon(dir, d); err != nil { return err } @@ -198,15 +199,15 @@ func mountCmd() *cobra.Command { if err != nil { return err } - key := share + "\x00" + local + key := share + "\x00" + subpath + "\x00" + local var pr syncer.PullResult var newBase string if ro { - pr, err = syncer.Pull(c, local, share, st[key], host, time.Now().Unix(), ig, guard) + pr, err = syncer.Pull(c, local, share, subpath, st[key], host, time.Now().UnixNano(), ig, guard) newBase = pr.Base } else { - newBase, pr, err = syncer.Sync(c, local, share, st[key], host, time.Now().Unix(), ig, guard) + newBase, pr, err = syncer.Sync(c, local, share, subpath, st[key], host, time.Now().UnixNano(), ig, guard) } if err != nil { return err @@ -221,7 +222,7 @@ func mountCmd() *cobra.Command { if ro { mode = "ro" } - fmt.Fprintf(out, "🔗 mounted %q -> %s [%s]\n", share, local, mode) + fmt.Fprintf(out, "🔗 mounted %q -> %s [%s]\n", args[0], local, mode) fmt.Fprintf(out, "📥 %d files, %d conflicts\n", len(pr.Written), len(pr.Conflicts)) fmt.Fprintln(out, "▶️ run 'devbox start' to keep it live-synced") return nil @@ -231,6 +232,15 @@ func mountCmd() *cobra.Command { return cmd } +// splitShare splits "share/sub/path" into ("share", "sub/path"); a bare "share" +// yields an empty sub-path. +func splitShare(arg string) (share, subpath string) { + if i := strings.IndexByte(arg, '/'); i >= 0 { + return arg[:i], arg[i+1:] + } + return arg, "" +} + func upsertMount(mounts []config.Mount, m config.Mount) []config.Mount { for i, x := range mounts { if x.Share == m.Share && x.Local == m.Local { diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index b6b7ece..da903e3 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -69,7 +69,7 @@ func (d *Daemon) Run(ctx context.Context) error { return nil } -func mountKey(m config.Mount) string { return m.Share + "\x00" + m.Local } +func mountKey(m config.Mount) string { return m.Share + "\x00" + m.Subpath + "\x00" + m.Local } func (d *Daemon) getBase(m config.Mount) string { d.mu.Lock() @@ -157,7 +157,7 @@ func (d *Daemon) syncMount(c *transport.Client, m config.Mount) { now := time.Now().UnixNano() // nanoseconds so conflict-copy names don't collide if m.ReadOnly { - pr, err := syncer.Pull(c, m.Local, m.Share, base, d.host, now, ig, d.guard) + pr, err := syncer.Pull(c, m.Local, m.Share, m.Subpath, base, d.host, now, ig, d.guard) if err != nil { d.logf("pull %s: %v", m.Share, err) return @@ -167,7 +167,7 @@ func (d *Daemon) syncMount(c *transport.Client, m config.Mount) { return } - newBase, pr, err := syncer.Sync(c, m.Local, m.Share, base, d.host, now, ig, d.guard) + newBase, pr, err := syncer.Sync(c, m.Local, m.Share, m.Subpath, base, d.host, now, ig, d.guard) if err != nil { d.logf("sync %s: %v", m.Share, err) return diff --git a/internal/syncer/pull.go b/internal/syncer/pull.go index ba9a862..1d9dc45 100644 --- a/internal/syncer/pull.go +++ b/internal/syncer/pull.go @@ -30,7 +30,7 @@ type PullResult struct { // - delete-vs-edit never loses the edit (the edit always survives). // // Never destroys a byte: every losing local edit becomes a conflict copy. -func Pull(c *transport.Client, root, share, base, host string, now int64, ig *ignore.Matcher, guard *secret.Guard) (PullResult, error) { +func Pull(c *transport.Client, root, share, subpath, base, host string, now int64, ig *ignore.Matcher, guard *secret.Guard) (PullResult, error) { head, err := c.Head(share) if err != nil { return PullResult{}, err @@ -40,15 +40,18 @@ func Pull(c *transport.Client, root, share, base, host string, now int64, ig *ig return res, nil // nothing on the hub, or already up to date } - theirs, err := fetchManifest(c, head) + theirsFull, err := fetchManifest(c, head) if err != nil { return PullResult{}, err } + theirs := filterStrip(theirsFull, subpath) var baseM manifest.Manifest if base != "" { - if baseM, err = fetchManifest(c, base); err != nil { + baseFull, err := fetchManifest(c, base) + if err != nil { return PullResult{}, err } + baseM = filterStrip(baseFull, subpath) } ours, _, err := manifest.Build(root, ig, guard) if err != nil { @@ -129,14 +132,14 @@ func Pull(c *transport.Client, root, share, base, host string, now int64, ig *ig // Sync brings a mount into agreement with the hub: pull+merge to head, then push // the merged local state; retries if the hub advanced underneath. Returns the new // base snapshot and the pull result. -func Sync(c *transport.Client, root, share, base, host string, now int64, ig *ignore.Matcher, guard *secret.Guard) (string, PullResult, error) { +func Sync(c *transport.Client, root, share, subpath, base, host string, now int64, ig *ignore.Matcher, guard *secret.Guard) (string, PullResult, error) { for attempt := 0; attempt < 5; attempt++ { - pr, err := Pull(c, root, share, base, host, now, ig, guard) + pr, err := Pull(c, root, share, subpath, base, host, now, ig, guard) if err != nil { return base, pr, err } base = pr.Base - push, err := Push(c, root, share, ig, guard, base) + push, err := Push(c, root, share, subpath, ig, guard, base) if err != nil { return base, pr, err } @@ -149,6 +152,48 @@ func Sync(c *transport.Client, root, share, base, host string, now int64, ig *ig return base, PullResult{}, fmt.Errorf("sync: too many conflict retries") } +// --- sub-path helpers: a mount's local root maps to share/subpath/ --- + +// under reports whether a share-relative path lives within subpath ("" = whole share). +func under(path, subpath string) bool { + if subpath == "" { + return true + } + return path == subpath || strings.HasPrefix(path, subpath+"/") +} + +// strip removes the subpath prefix, yielding a local-relative path. +func strip(path, subpath string) string { + if subpath == "" { + return path + } + return strings.TrimPrefix(path, subpath+"/") +} + +// prefixPath adds the subpath prefix to a local-relative path. +func prefixPath(path, subpath string) string { + if subpath == "" { + return path + } + return subpath + "/" + path +} + +// filterStrip keeps only the entries of a full share manifest that live under +// subpath, with the prefix stripped (so they're local-relative). +func filterStrip(m manifest.Manifest, subpath string) manifest.Manifest { + if subpath == "" { + return m + } + var out []manifest.Entry + for _, e := range m.Entries { + if under(e.Path, subpath) { + e.Path = strip(e.Path, subpath) + out = append(out, e) + } + } + return manifest.Manifest{Entries: out} +} + func fetchManifest(c *transport.Client, id string) (manifest.Manifest, error) { b, err := c.GetBlob(id) if err != nil { diff --git a/internal/syncer/pull_test.go b/internal/syncer/pull_test.go index f6afefa..e39464b 100644 --- a/internal/syncer/pull_test.go +++ b/internal/syncer/pull_test.go @@ -56,13 +56,13 @@ func TestTwoWayConvergeAndConflict(t *testing.T) { // A creates foo + bar and syncs them up. writeFile(t, rootA, "foo.txt", "A1\n") writeFile(t, rootA, "bar.txt", "shared\n") - baseA, _, err := Sync(A, rootA, "s", "", "alice", 1000, ig, guard) + baseA, _, err := Sync(A, rootA, "s", "", "", "alice", 1000, ig, guard) if err != nil { t.Fatalf("A sync: %v", err) } // B clones the share into an empty dir. - baseB, _, err := Sync(B, rootB, "s", "", "bob", 1001, ig, guard) + baseB, _, err := Sync(B, rootB, "s", "", "", "bob", 1001, ig, guard) if err != nil { t.Fatalf("B sync: %v", err) } @@ -72,14 +72,14 @@ func TestTwoWayConvergeAndConflict(t *testing.T) { // A edits foo.txt; it becomes the hub head. writeFile(t, rootA, "foo.txt", "A2\n") - baseA, _, err = Sync(A, rootA, "s", baseA, "alice", 1002, ig, guard) + baseA, _, err = Sync(A, rootA, "s", "", baseA, "alice", 1002, ig, guard) if err != nil { t.Fatalf("A sync 2: %v", err) } // B edits the SAME file (still on the old base) and syncs -> conflict. writeFile(t, rootB, "foo.txt", "B2\n") - _, prB2, err := Sync(B, rootB, "s", baseB, "bob", 1003, ig, guard) + _, prB2, err := Sync(B, rootB, "s", "", baseB, "bob", 1003, ig, guard) if err != nil { t.Fatalf("B sync 2: %v", err) } @@ -94,7 +94,7 @@ func TestTwoWayConvergeAndConflict(t *testing.T) { } // A syncs again and must receive B's conflict copy — full convergence. - if _, _, err = Sync(A, rootA, "s", baseA, "alice", 1004, ig, guard); err != nil { + if _, _, err = Sync(A, rootA, "s", "", baseA, "alice", 1004, ig, guard); err != nil { t.Fatalf("A sync 3: %v", err) } if read(t, rootA, "foo.txt") != "A2\n" { @@ -126,13 +126,13 @@ func TestPullDeleteAndEditBeatsDelete(t *testing.T) { writeFile(t, rootA, "keep.txt", "k\n") writeFile(t, rootA, "gone.txt", "g\n") - baseA, _, _ := Sync(A, rootA, "s", "", "alice", 1, ig, guard) - baseB, _, _ := Sync(B, rootB, "s", "", "bob", 2, ig, guard) + baseA, _, _ := Sync(A, rootA, "s", "", "", "alice", 1, ig, guard) + baseB, _, _ := Sync(B, rootB, "s", "", "", "bob", 2, ig, guard) // A deletes gone.txt; B (clone) should drop it on next sync. os.Remove(filepath.Join(rootA, "gone.txt")) - baseA, _, _ = Sync(A, rootA, "s", baseA, "alice", 3, ig, guard) - if _, _, err := Sync(B, rootB, "s", baseB, "bob", 4, ig, guard); err != nil { + baseA, _, _ = Sync(A, rootA, "s", "", baseA, "alice", 3, ig, guard) + if _, _, err := Sync(B, rootB, "s", "", baseB, "bob", 4, ig, guard); err != nil { t.Fatal(err) } if exists(rootB, "gone.txt") { @@ -158,7 +158,7 @@ func TestPullSkipsFileDirClash(t *testing.T) { rootA := t.TempDir() writeFile(t, rootA, "data", "hello\n") writeFile(t, rootA, "ok.txt", "fine\n") - if _, _, err := Sync(A, rootA, "s", "", "alice", 1, ig, guard); err != nil { + if _, _, err := Sync(A, rootA, "s", "", "", "alice", 1, ig, guard); err != nil { t.Fatal(err) } @@ -167,7 +167,7 @@ func TestPullSkipsFileDirClash(t *testing.T) { if err := os.MkdirAll(filepath.Join(rootB, "data", "child"), 0o755); err != nil { t.Fatal(err) } - pr, err := Pull(B, rootB, "s", "", "bob", 2, ig, guard) + pr, err := Pull(B, rootB, "s", "", "", "bob", 2, ig, guard) if err != nil { t.Fatalf("pull must not abort on a file/dir clash: %v", err) } @@ -179,3 +179,63 @@ func TestPullSkipsFileDirClash(t *testing.T) { t.Fatal("ok.txt should have been written despite the data/ clash") } } + +// TestSubPathMount: a device mounts only proj/app, sees just that subtree +// (stripped), and editing+pushing from it must NOT drop the rest of the share. +func TestSubPathMount(t *testing.T) { + db, _ := meta.Open(":memory:") + defer db.Close() + store, _ := blobstore.NewDisk(t.TempDir()) + srv := httptest.NewServer(hub.NewServer(db, store).Handler()) + defer srv.Close() + guard, _ := secret.New(nil) + ig, _ := LoadIgnore(t.TempDir()) + + A := joinDevice(t, db, srv.URL, "alice") + B := joinDevice(t, db, srv.URL, "bob") + _ = A.Publish("proj") + + // A: whole-share mount with a nested tree. + rootA := t.TempDir() + writeFile(t, rootA, "app/main.go", "package main // v1\n") + writeFile(t, rootA, "app/util.go", "package app\n") + writeFile(t, rootA, "docs/readme.md", "# docs\n") + writeFile(t, rootA, "root.txt", "top\n") + baseA, _, err := Sync(A, rootA, "proj", "", "", "alice", 1, ig, guard) + if err != nil { + t.Fatal(err) + } + + // B: SUB-PATH mount of proj/app -> empty dir; sees only app/, stripped. + rootB := t.TempDir() + baseB, _, err := Sync(B, rootB, "proj", "app", "", "bob", 2, ig, guard) + if err != nil { + t.Fatalf("B subpath sync: %v", err) + } + if !exists(rootB, "main.go") || !exists(rootB, "util.go") { + t.Fatal("B did not clone the app/ subtree (stripped)") + } + if exists(rootB, "docs/readme.md") || exists(rootB, "root.txt") || exists(rootB, "app") { + t.Fatal("B's sub-path mount leaked files from outside app/") + } + + // B edits main.go and pushes: the splice must preserve docs/ and root.txt. + writeFile(t, rootB, "main.go", "package main // B-edit\n") + if _, _, err = Sync(B, rootB, "proj", "app", baseB, "bob", 3, ig, guard); err != nil { + t.Fatalf("B subpath push: %v", err) + } + + // A (whole share) gets B's edit AND still has docs/ + root.txt intact. + if _, _, err = Sync(A, rootA, "proj", "", baseA, "alice", 4, ig, guard); err != nil { + t.Fatal(err) + } + if read(t, rootA, "app/main.go") != "package main // B-edit\n" { + t.Fatalf("A did not receive B's sub-path edit: %q", read(t, rootA, "app/main.go")) + } + if !exists(rootA, "docs/readme.md") || !exists(rootA, "root.txt") { + t.Fatal("B's sub-path push DROPPED files outside the sub-path!") + } + if read(t, rootA, "docs/readme.md") != "# docs\n" { + t.Fatal("docs/readme.md was corrupted by the sub-path push") + } +} diff --git a/internal/syncer/syncer.go b/internal/syncer/syncer.go index c48d4ea..6568be7 100644 --- a/internal/syncer/syncer.go +++ b/internal/syncer/syncer.go @@ -6,6 +6,7 @@ package syncer import ( "os" "path/filepath" + "sort" "strings" "git.shoemoney.ai/shoemoney/devbox/internal/chunk" @@ -28,17 +29,20 @@ type Result struct { // Push builds a manifest of root (filtered by ig + guard), uploads any blobs the // hub is missing (chunks + the manifest blob), then commits a snapshot on share. +// For a sub-path mount (subpath != "") root maps to share/subpath/: the local +// subtree is spliced into the share head (entries outside subpath are preserved) +// so a partial mount can push without dropping the rest of the share. // parent is the device's last-known head ("" if none). -func Push(c *transport.Client, root, share string, ig *ignore.Matcher, guard *secret.Guard, parent string) (Result, error) { - m, blocked, err := manifest.Build(root, ig, guard) +func Push(c *transport.Client, root, share, subpath string, ig *ignore.Matcher, guard *secret.Guard, parent string) (Result, error) { + localM, blocked, err := manifest.Build(root, ig, guard) if err != nil { return Result{}, err } - // Gather the bytes of every distinct chunk, plus the manifest blob itself. + // Gather the bytes of every distinct local chunk (with sizes). blobs := map[string][]byte{} - refs := map[string]int64{} // distinct chunk hash -> size - for _, e := range m.Entries { + refs := map[string]int64{} // local chunk hash -> size + for _, e := range localM.Entries { data, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(e.Path))) if err != nil { return Result{}, err @@ -54,11 +58,17 @@ func Push(c *transport.Client, root, share string, ig *ignore.Matcher, guard *se } } } - manBytes, err := m.Marshal() + + // Splice the local subtree into the full share manifest (no-op when subpath == ""). + fullM, err := splice(c, localM, subpath, parent) if err != nil { return Result{}, err } - manHash := m.ID() + manBytes, err := fullM.Marshal() + if err != nil { + return Result{}, err + } + manHash := fullM.ID() blobs[manHash] = manBytes // Upload only what the hub lacks. @@ -76,10 +86,22 @@ func Push(c *transport.Client, root, share string, ig *ignore.Matcher, guard *se } } - chunks := make([]proto.ChunkRef, 0, len(refs)) - for h, sz := range refs { - chunks = append(chunks, proto.ChunkRef{Hash: h, Size: sz}) + // Declare every distinct chunk the full manifest references so the hub's + // refcounts stay correct. Local chunks carry their size; chunks already on + // the hub (outside the subpath) carry 0 — the hub keeps the size it recorded + // on first upload and just bumps the refcount. + seen := map[string]bool{} + var chunks []proto.ChunkRef + for _, e := range fullM.Entries { + for _, h := range e.Chunks { + if seen[h] { + continue + } + seen[h] = true + chunks = append(chunks, proto.ChunkRef{Hash: h, Size: refs[h]}) + } } + resp, err := c.Push(proto.PushRequest{ Share: share, Parent: parent, @@ -94,11 +116,38 @@ func Push(c *transport.Client, root, share string, ig *ignore.Matcher, guard *se Head: resp.Head, Blocked: blocked, Uploaded: len(missing), - Files: len(m.Entries), + Files: len(localM.Entries), Conflict: resp.Conflict, }, nil } +// splice builds the full share manifest from a sub-path mount's local manifest: +// it re-prefixes local entries with subpath and keeps the parent snapshot's +// entries outside subpath. For a whole-share mount it returns localM unchanged. +func splice(c *transport.Client, localM manifest.Manifest, subpath, parent string) (manifest.Manifest, error) { + if subpath == "" { + return localM, nil + } + entries := make([]manifest.Entry, 0, len(localM.Entries)) + if parent != "" { + base, err := fetchManifest(c, parent) + if err != nil { + return manifest.Manifest{}, err + } + for _, e := range base.Entries { + if !under(e.Path, subpath) { + entries = append(entries, e) + } + } + } + for _, e := range localM.Entries { + e.Path = prefixPath(e.Path, subpath) + entries = append(entries, e) + } + sort.Slice(entries, func(i, j int) bool { return entries[i].Path < entries[j].Path }) + return manifest.Manifest{Entries: entries}, nil +} + // LoadIgnore compiles root/.devignore (an empty matcher if the file is absent). func LoadIgnore(root string) (*ignore.Matcher, error) { b, err := os.ReadFile(filepath.Join(root, ".devignore")) diff --git a/internal/syncer/syncer_test.go b/internal/syncer/syncer_test.go index c64ad68..bef2467 100644 --- a/internal/syncer/syncer_test.go +++ b/internal/syncer/syncer_test.go @@ -98,7 +98,7 @@ func TestPushEndToEnd(t *testing.T) { t.Fatal(err) } - res, err := Push(c, root, "projects", ig, guard, "") + res, err := Push(c, root, "projects", "", ig, guard, "") if err != nil { t.Fatalf("push: %v", err) } @@ -136,7 +136,7 @@ func TestPushEndToEnd(t *testing.T) { // Second push of the unchanged tree: dedup means zero blobs uploaded and the // same content-addressed snapshot id. - res2, err := Push(c, root, "projects", ig, guard, res.Head) + res2, err := Push(c, root, "projects", "", ig, guard, res.Head) if err != nil { t.Fatalf("second push: %v", err) } @@ -173,7 +173,7 @@ func TestPushConflictWhenBehind(t *testing.T) { } rootA := t.TempDir() writeFile(t, rootA, "a.txt", "from alice\n") - resA, err := Push(a, rootA, "shared", ig, guard, "") + resA, err := Push(a, rootA, "shared", "", ig, guard, "") if err != nil { t.Fatalf("A push: %v", err) } @@ -185,7 +185,7 @@ func TestPushConflictWhenBehind(t *testing.T) { b := joinDevice(t, db, srv.URL, "bob") rootB := t.TempDir() writeFile(t, rootB, "b.txt", "from bob\n") - resB, err := Push(b, rootB, "shared", ig, guard, "") + resB, err := Push(b, rootB, "shared", "", ig, guard, "") if err != nil { t.Fatalf("B push: %v", err) }