diff --git a/internal/syncer/pull.go b/internal/syncer/pull.go index 8611dc6..39d48db 100644 --- a/internal/syncer/pull.go +++ b/internal/syncer/pull.go @@ -168,9 +168,22 @@ func Pull(c *transport.Client, root, share, subpath, base, host string, now int6 // snapshot doesn't contain is deleted. A bad onlyPath (not in the snapshot) errors // without touching the tree. func Restore(c *transport.Client, root, share, subpath, snapshot, onlyPath, host string, now int64, ig *ignore.Matcher, guard *secret.Guard, hk *hooks.Runner) (Result, error) { + // Never lose a byte, even on a deliberate revert: capture any uncommitted local + // edit this restore would overwrite or delete, then drop it back as a .conflict + // copy once the snapshot is applied (a clean restore — no uncommitted edits — + // captures nothing and reproduces the snapshot exactly). + endangered, err := captureUncommitted(c, root, share, subpath, snapshot, onlyPath, ig, guard) + if err != nil { + return Result{}, err + } if _, err := applySnapshot(c, root, subpath, snapshot, onlyPath, ig, guard); err != nil { return Result{}, err } + for path, data := range endangered { + if _, err := writeConflictCopy(root, path, data, host, now); err != nil { + return Result{}, err + } + } head, err := c.Head(share) if err != nil { return Result{}, err @@ -398,32 +411,113 @@ func safeJoin(root, relPath string) (string, error) { return filepath.Join(root, clean), nil } -// preserveAsConflict renames the current local file at relPath to a sibling named -// path.conflict--.ext, returning the conflict copy's relative path. -func preserveAsConflict(root, relPath, host string, ts int64) (string, error) { +// freeConflictName probes for an unused path.conflict--.ext sibling of +// relPath and returns its relative path (ts is nanoseconds, so collisions are +// already rare; the counter is belt-and-suspenders against overwriting a prior copy). +func freeConflictName(root, relPath, host string, ts int64) (string, error) { ext := filepath.Ext(relPath) stem := strings.TrimSuffix(relPath, ext) - src := filepath.Join(root, filepath.FromSlash(relPath)) - // Probe for a free name (ts is nanoseconds, so collisions are already rare; - // the counter is belt-and-suspenders against ever overwriting a prior copy). for n := 0; ; n++ { cp := fmt.Sprintf("%s.conflict-%s-%d%s", stem, host, ts, ext) if n > 0 { cp = fmt.Sprintf("%s.conflict-%s-%d-%d%s", stem, host, ts, n, ext) } - dst := filepath.Join(root, filepath.FromSlash(cp)) - if _, err := os.Stat(dst); err == nil { + if _, err := os.Stat(filepath.Join(root, filepath.FromSlash(cp))); err == nil { continue // taken } else if !os.IsNotExist(err) { return "", err } - if err := os.Rename(src, dst); err != nil { - return "", err - } return cp, nil } } +// preserveAsConflict renames the current local file at relPath to a sibling named +// path.conflict--.ext, returning the conflict copy's relative path. +func preserveAsConflict(root, relPath, host string, ts int64) (string, error) { + cp, err := freeConflictName(root, relPath, host, ts) + if err != nil { + return "", err + } + src := filepath.Join(root, filepath.FromSlash(relPath)) + if err := os.Rename(src, filepath.Join(root, filepath.FromSlash(cp))); err != nil { + return "", err + } + return cp, nil +} + +// writeConflictCopy writes captured bytes (a file's pre-restore local content) to +// a path.conflict-- sibling. Restore uses this to drop an uncommitted +// local edit beside the file AFTER the restore has overwritten/deleted the +// original — so the never-lose-a-byte guarantee holds even for a deliberate revert. +func writeConflictCopy(root, relPath string, data []byte, host string, ts int64) (string, error) { + cp, err := freeConflictName(root, relPath, host, ts) + if err != nil { + return "", err + } + dst := filepath.Join(root, filepath.FromSlash(cp)) + if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil { + return "", err + } + if err := atomicWrite(dst, data, 0o644); err != nil { + return "", err + } + return cp, nil +} + +// captureUncommitted reads the on-disk bytes of any local file an explicit restore +// is about to LOSE: one whose content differs from BOTH the snapshot being restored +// AND the current hub head. A file equal to the snapshot isn't changing; a file +// equal to head is safe in history. Everything else is an uncommitted local edit +// (or a file new since head) that restore would silently overwrite or delete — so +// grab its bytes now and (after restore applies) drop them as a .conflict copy. +// Honors onlyPath. Same ignore/secret filtering as the apply, so we never touch a +// .devignore'd or guarded file. +func captureUncommitted(c *transport.Client, root, share, subpath, snapshot, onlyPath string, ig *ignore.Matcher, guard *secret.Guard) (map[string][]byte, error) { + tgt, err := fetchManifest(c, snapshot) + if err != nil { + return nil, err + } + target := indexEntries(filterStrip(tgt, subpath)) + headIdx := map[string]manifest.Entry{} + head, err := c.Head(share) + if err != nil { + return nil, err + } + if head != "" { + hm, err := fetchManifest(c, head) + if err != nil { + return nil, err + } + headIdx = indexEntries(filterStrip(hm, subpath)) + } + local, _, err := manifest.Build(root, ig, guard) + if err != nil { + return nil, err + } + out := map[string][]byte{} + for _, oe := range local.Entries { + if onlyPath != "" && oe.Path != onlyPath { + continue + } + if te, ok := target[oe.Path]; ok && manifest.SameContent(oe, te) { + continue // unchanged by the restore + } + if he, ok := headIdx[oe.Path]; ok && manifest.SameContent(oe, he) { + continue // committed content, recoverable from history + } + dst, err := safeJoin(root, oe.Path) + if err != nil { + continue + } + data, err := os.ReadFile(dst) + if err != nil { + continue // already gone / unreadable; nothing to preserve + } + out[oe.Path] = data + } + return out, nil +} + // atomicWrite writes data to path via a temp file + rename (atomic on POSIX and // Windows; never leaves a half-written file in place). func atomicWrite(path string, data []byte, perm os.FileMode) error { diff --git a/internal/syncer/restore_test.go b/internal/syncer/restore_test.go index 425819f..40a6c5d 100644 --- a/internal/syncer/restore_test.go +++ b/internal/syncer/restore_test.go @@ -95,6 +95,62 @@ func TestRestoreWholeTree(t *testing.T) { } } +// TestRestorePreservesUncommittedEdit is the never-lose-a-byte guarantee on a +// deliberate revert: an UNCOMMITTED local edit (differs from both the snapshot +// being restored and the hub head) survives as a .conflict copy, while the file +// itself reverts. A clean restore (TestRestoreWholeTree) preserves nothing. +func TestRestorePreservesUncommittedEdit(t *testing.T) { + db, err := meta.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer db.Close() + store, err := blobstore.NewDisk(t.TempDir()) + if err != nil { + t.Fatal(err) + } + srv := httptest.NewServer(hub.NewServer(db, store).Handler()) + defer srv.Close() + + guard, _ := secret.New(nil) + ig, _ := LoadIgnore(t.TempDir()) + c := joinDevice(t, db, srv.URL, "alice") + if err := c.Publish("proj"); err != nil { + t.Fatal(err) + } + root := t.TempDir() + + writeFile(t, root, "main.go", "v1\n") + snap1, err := Push(c, root, "proj", "", ig, guard, "", nil) + if err != nil { + t.Fatal(err) + } + writeFile(t, root, "main.go", "v2\n") + if _, err := Push(c, root, "proj", "", ig, guard, snap1.Head, nil); err != nil { + t.Fatal(err) + } + + // Uncommitted local edit: v3 on disk, never pushed (head is still v2). + writeFile(t, root, "main.go", "v3 UNCOMMITTED\n") + + if _, err := Restore(c, root, "proj", "", snap1.Snapshot, "", "host", 1, ig, guard, nil); err != nil { + t.Fatalf("restore: %v", err) + } + + // The file reverted to v1... + if got := readFile(t, root, "main.go"); got != "v1\n" { + t.Fatalf("main.go = %q, want v1", got) + } + // ...and the uncommitted v3 survives as a conflict copy. + matches, _ := filepath.Glob(filepath.Join(root, "main.conflict-*")) + if len(matches) != 1 { + t.Fatalf("want exactly one conflict copy, got %v", matches) + } + if got, _ := os.ReadFile(matches[0]); string(got) != "v3 UNCOMMITTED\n" { + t.Fatalf("conflict copy = %q, want the uncommitted v3", got) + } +} + // TestRestoreSinglePath brings back just one file to its snapshot content without // touching the rest of the tree, and errors cleanly on a path not in the snapshot. func TestRestoreSinglePath(t *testing.T) {