diff --git a/internal/transfer/atomic.go b/internal/transfer/atomic.go
new file mode 100644
index 0000000..499f70b
--- /dev/null
+++ b/internal/transfer/atomic.go
@@ -0,0 +1,5 @@
+package transfer
+
+// oldPrefix names the aside copy of a replaced file on FSes without atomic
+// replace:
/.vcom-old-<8hex>-.
+const oldPrefix = ".vcom-old-"
diff --git a/internal/transfer/errors.go b/internal/transfer/errors.go
new file mode 100644
index 0000000..5c3ccb7
--- /dev/null
+++ b/internal/transfer/errors.go
@@ -0,0 +1,13 @@
+package transfer
+
+import "errors"
+
+// Prepare refuses a request with one of these (wrapped with the path).
+var (
+ ErrSameFile = errors.New("source and target are the same file")
+ ErrIntoItself = errors.New("cannot copy a directory into itself")
+ ErrTargetNotDir = errors.New("target is not a directory")
+ ErrDuplicateName = errors.New("two sources have the same name")
+ ErrReadOnly = errors.New("read-only file system")
+ ErrAborted = errors.New("transfer aborted")
+)
diff --git a/internal/transfer/helpers_test.go b/internal/transfer/helpers_test.go
new file mode 100644
index 0000000..898545f
--- /dev/null
+++ b/internal/transfer/helpers_test.go
@@ -0,0 +1,99 @@
+package transfer
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+
+ "vcom/internal/testutil/fstree"
+ "vcom/internal/vfs"
+ "vcom/internal/vfs/localfs"
+ "vcom/internal/vfs/vfstest"
+)
+
+var bg = context.Background()
+
+var local = localfs.New()
+
+// counter is a FaultFS hook that counts operations (and optionally fails).
+type counter struct {
+ mu sync.Mutex
+ n map[vfstest.Op]int
+}
+
+func (c *counter) hook(op vfstest.Op, _ string) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.n == nil {
+ c.n = map[vfstest.Op]int{}
+ }
+ c.n[op]++
+ return nil
+}
+
+func (c *counter) get(op vfstest.Op) int {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.n[op]
+}
+
+// otherVolume makes a local FS look like a different volume (as a remote
+// would): no SameConn, no identity checks.
+type otherVolume struct{ vfs.FS }
+
+func (otherVolume) Volume() vfs.VolumeID { return "other" }
+func (otherVolume) Kind() vfs.Kind { return vfs.KindSFTP }
+
+// layout builds /src and /dst from specs and returns their paths.
+func layout(t *testing.T, src, dst fstree.Spec) (string, string) {
+ t.Helper()
+ d := t.TempDir()
+ s, ds := filepath.Join(d, "src"), filepath.Join(d, "dst")
+ for _, p := range []string{s, ds} {
+ if err := os.MkdirAll(p, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ fstree.Build(t, s, src)
+ fstree.Build(t, ds, dst)
+ return s, ds
+}
+
+func req(op Op, from vfs.FS, paths []string, to vfs.FS, toDir string, mut ...func(*Options)) Request {
+ o := DefaultOptions()
+ for _, f := range mut {
+ f(&o)
+ }
+ return Request{Op: op, From: FSSource(from, paths, o.Symlinks), To: to, ToDir: toDir, Opts: o}
+}
+
+func join(dir string, names ...string) []string {
+ out := make([]string, len(names))
+ for i, n := range names {
+ out[i] = filepath.Join(dir, n)
+ }
+ return out
+}
+
+// noLeftovers fails if any .vcom-part-* / .vcom-old-* remains under dir.
+func noLeftovers(t *testing.T, dir string) {
+ t.Helper()
+ _ = filepath.Walk(dir, func(p string, fi os.FileInfo, err error) error {
+ if err == nil && (strings.HasPrefix(fi.Name(), partPrefix) || strings.HasPrefix(fi.Name(), oldPrefix)) {
+ t.Errorf("temp file left behind: %s", p)
+ }
+ return nil
+ })
+}
+
+func read(t *testing.T, p string) string {
+ t.Helper()
+ b, err := os.ReadFile(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(b)
+}
diff --git a/internal/transfer/prepare.go b/internal/transfer/prepare.go
new file mode 100644
index 0000000..851c7ab
--- /dev/null
+++ b/internal/transfer/prepare.go
@@ -0,0 +1,232 @@
+package transfer
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strings"
+
+ "vcom/internal/vfs"
+)
+
+// partPrefix names temp files of WriteAtomic: /.vcom-part-<8hex>-.
+const partPrefix = ".vcom-part-"
+
+// rootLstatMax: with more roots than this, the target directory is listed
+// once instead of one Lstat per root.
+const rootLstatMax = 4
+
+// Prepare validates req and builds the plan (design §4.2): the target is
+// writable and a directory; no root is the same file as its target and no
+// directory is copied into itself (SameFile/Within, through symlinks); the
+// source is walked once; every target directory that already exists is
+// listed once (not one call per file) to find Existing and the Conflicts;
+// totals are exact. progress, if non-nil, receives Scanning snapshots.
+func Prepare(ctx context.Context, req Request, progress func(Progress)) (*Plan, error) {
+ if req.To == nil || req.From == nil {
+ return nil, errors.New("transfer: incomplete request")
+ }
+ if req.Op == Move {
+ req.Opts.Symlinks = CopyLinks // a move never follows links
+ }
+ if req.To.Caps().ReadOnly {
+ return nil, fmt.Errorf("%w: %s", ErrReadOnly, req.To.Label())
+ }
+ toOps := req.To.Paths()
+ req.ToDir = toOps.Clean(req.ToDir)
+ if fi, err := req.To.Stat(ctx, req.ToDir); err != nil {
+ return nil, err
+ } else if !fi.IsDir() {
+ return nil, fmt.Errorf("%w: %s", ErrTargetNotDir, req.ToDir)
+ }
+
+ if fb, ok := req.From.(FSBacked); ok {
+ if req.Op == Move && fb.FS().Caps().ReadOnly {
+ return nil, fmt.Errorf("%w: cannot move from %s", ErrReadOnly, fb.FS().Label())
+ }
+ if err := checkRoots(ctx, fb, req); err != nil {
+ return nil, err
+ }
+ if fs, ok := fb.(*fsSource); ok && fs.sym != req.Opts.Symlinks {
+ cp := *fs
+ cp.sym = req.Opts.Symlinks
+ req.From = &cp
+ }
+ }
+
+ plan := &Plan{Req: req}
+ report := func() {
+ if progress != nil {
+ progress(Progress{Phase: Scanning, FilesTotal: plan.TotalFiles, BytesTotal: plan.TotalBytes})
+ }
+ }
+ err := req.From.Walk(ctx, func(it Item) error {
+ if it.Warning != "" {
+ plan.Warnings = append(plan.Warnings, it.Rel+": "+it.Warning)
+ }
+ switch it.Kind {
+ case File:
+ plan.TotalFiles++
+ plan.TotalBytes += it.Size
+ case Symlink:
+ plan.TotalFiles++
+ case Special:
+ plan.Warnings = append(plan.Warnings, it.Rel+": special file skipped")
+ }
+ plan.Items = append(plan.Items, it)
+ if len(plan.Items)%256 == 0 {
+ report()
+ }
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ seen := map[string]bool{}
+ for _, it := range plan.Items {
+ if !strings.Contains(it.Rel, "/") {
+ if seen[it.Rel] {
+ return nil, fmt.Errorf("%w: %s", ErrDuplicateName, it.Rel)
+ }
+ seen[it.Rel] = true
+ }
+ }
+ if err := findExisting(ctx, plan); err != nil {
+ return nil, err
+ }
+ report()
+
+ if fb, ok := req.From.(FSBacked); ok {
+ a, b := fb.FS(), req.To
+ plan.SameConn = (a.Kind() == vfs.KindLocal && b.Kind() == vfs.KindLocal) ||
+ (a == b && a.Volume() == b.Volume())
+ }
+ return plan, nil
+}
+
+// checkRoots refuses roots that are their own target or contain ToDir.
+func checkRoots(ctx context.Context, fb FSBacked, req Request) error {
+ src := fb.FS()
+ for _, root := range fb.Roots() {
+ dst := req.To.Paths().Join(req.ToDir, src.Paths().Base(root))
+ same, err := vfs.SameFile(ctx, src, root, req.To, dst)
+ if err != nil {
+ return err
+ }
+ if same {
+ return fmt.Errorf("%w: %s", ErrSameFile, root)
+ }
+ if src.Volume() != req.To.Volume() {
+ continue
+ }
+ fi, err := src.Lstat(ctx, root)
+ if err != nil {
+ return err
+ }
+ isDir := fi.IsDir() || (req.Opts.Symlinks == FollowLinks && fi.NavigableDir())
+ if !isDir {
+ continue
+ }
+ in, err := vfs.Within(ctx, req.To, req.ToDir, root)
+ if err != nil {
+ return err
+ }
+ if in {
+ return fmt.Errorf("%w: %s → %s", ErrIntoItself, root, req.ToDir)
+ }
+ }
+ return nil
+}
+
+// dstPath maps an item's Rel onto the target FS.
+func dstPath(to vfs.FS, toDir, rel string) string {
+ return to.Paths().Join(append([]string{toDir}, strings.Split(rel, "/")...)...)
+}
+
+func splitRel(rel string) (parent, name string) {
+ i := strings.LastIndexByte(rel, '/')
+ if i < 0 {
+ return "", rel
+ }
+ return rel[:i], rel[i+1:]
+}
+
+// findExisting fills Existing and Conflicts. Target directories are listed
+// only when they exist as real directories that a source directory merges
+// into — one ReadDir per directory (N-P2-4/5).
+func findExisting(ctx context.Context, plan *Plan) error {
+ to, toDir := plan.Req.To, plan.Req.ToDir
+ listings := map[string]map[string]vfs.FileInfo{}
+
+ list := func(rel, p string) error {
+ ents, err := to.ReadDir(ctx, p)
+ if err != nil {
+ return err
+ }
+ m := make(map[string]vfs.FileInfo, len(ents))
+ for _, e := range ents {
+ m[e.Name] = e
+ if strings.HasPrefix(e.Name, partPrefix) {
+ plan.Warnings = append(plan.Warnings, fmt.Sprintf("%s: leftover of an interrupted transfer",
+ to.Paths().Join(p, e.Name)))
+ }
+ }
+ listings[rel] = m
+ return nil
+ }
+
+ roots := 0
+ for _, it := range plan.Items {
+ if !strings.Contains(it.Rel, "/") {
+ roots++
+ }
+ }
+ if roots > rootLstatMax {
+ if err := list("", toDir); err != nil {
+ return err
+ }
+ }
+
+ for i := range plan.Items {
+ if i%256 == 0 {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ }
+ it := &plan.Items[i]
+ parent, name := splitRel(it.Rel)
+ var existing *vfs.FileInfo
+ if l, ok := listings[parent]; ok {
+ if fi, ok := l[name]; ok {
+ existing = &fi
+ }
+ } else if parent == "" {
+ fi, err := to.Lstat(ctx, dstPath(to, toDir, it.Rel))
+ switch {
+ case err == nil:
+ existing = &fi
+ case !errors.Is(err, vfs.ErrNotExist):
+ return err
+ }
+ }
+ it.Existing = existing
+ if existing == nil {
+ continue
+ }
+ switch {
+ case it.Kind == Dir && existing.IsDir():
+ if err := list(it.Rel, dstPath(to, toDir, it.Rel)); err != nil {
+ return err
+ }
+ case it.Kind == Dir || existing.IsDir():
+ plan.Conflicts = append(plan.Conflicts, Conflict{Item: *it, Kind: TypeMismatch})
+ case it.Kind == Special:
+ default:
+ plan.Conflicts = append(plan.Conflicts, Conflict{Item: *it, Kind: FileFile})
+ }
+ }
+ return nil
+}
diff --git a/internal/transfer/prepare_test.go b/internal/transfer/prepare_test.go
new file mode 100644
index 0000000..5c99b61
--- /dev/null
+++ b/internal/transfer/prepare_test.go
@@ -0,0 +1,214 @@
+package transfer
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "path/filepath"
+ "testing"
+
+ "vcom/internal/testutil/fstree"
+ "vcom/internal/vfs"
+ "vcom/internal/vfs/vfstest"
+)
+
+func TestPrepareCountsBytes(t *testing.T) {
+ src, dst := layout(t, fstree.Spec{
+ fstree.File("dir/a", "1234567890"),
+ fstree.File("dir/sub/b", "").WithSize(1000),
+ fstree.Symlink("dir/ln", "a"),
+ fstree.FIFO("dir/fifo"),
+ fstree.File("top.txt", "abc"),
+ }, nil)
+ var last Progress
+ plan, err := Prepare(bg, req(Copy, local, join(src, "dir", "top.txt"), local, dst), func(p Progress) { last = p })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if plan.TotalBytes != 10+1000+3 || plan.TotalFiles != 4 {
+ t.Fatalf("totals: files=%d bytes=%d (N-P1-13: dir bytes must be counted)", plan.TotalFiles, plan.TotalBytes)
+ }
+ if last.Phase != Scanning || last.BytesTotal != plan.TotalBytes {
+ t.Fatalf("final scanning progress %+v", last)
+ }
+ if len(plan.Warnings) != 1 || plan.Warnings[0] != "dir/fifo: special file skipped" {
+ t.Fatalf("warnings %v", plan.Warnings)
+ }
+ var rels []string
+ for _, it := range plan.Items {
+ rels = append(rels, it.Rel+":"+it.Kind.String())
+ }
+ want := "[dir:dir dir/a:file dir/fifo:special dir/ln:symlink dir/sub:dir dir/sub/b:file top.txt:file]"
+ if fmt.Sprint(rels) != want {
+ t.Fatalf("items %v", rels)
+ }
+ if !plan.SameConn {
+ t.Fatal("local→local is SameConn")
+ }
+}
+
+func TestPrepareRejectsSameFile(t *testing.T) {
+ src, _ := layout(t, fstree.Spec{fstree.File("real/f.txt", "ONLY COPY"), fstree.Symlink("alias", "real")}, nil)
+ cases := map[string]Request{
+ "same dir": req(Copy, local, join(src, "real/f.txt"), local, filepath.Join(src, "real")),
+ "via dir alias": req(Copy, local, join(src, "real/f.txt"), local, filepath.Join(src, "alias")),
+ "dir onto alias": req(Move, local, join(src, "real"), local, src),
+ }
+ for name, r := range cases {
+ if _, err := Prepare(bg, r, nil); !errors.Is(err, ErrSameFile) {
+ t.Errorf("%s: err = %v, want ErrSameFile (N-P0-6)", name, err)
+ }
+ }
+ if read(t, filepath.Join(src, "real", "f.txt")) != "ONLY COPY" {
+ t.Fatal("source touched")
+ }
+}
+
+func TestPrepareRejectsIntoItself(t *testing.T) {
+ src, _ := layout(t, fstree.Spec{fstree.Dir("proj/sub/deep"), fstree.Symlink("plink", "proj/sub")}, nil)
+ for _, to := range []string{
+ filepath.Join(src, "proj"),
+ filepath.Join(src, "proj", "sub", "deep"),
+ filepath.Join(src, "plink"), // inside through a symlink
+ } {
+ if _, err := Prepare(bg, req(Copy, local, join(src, "proj"), local, to), nil); !errors.Is(err, ErrIntoItself) {
+ t.Errorf("to %s: err = %v, want ErrIntoItself", to, err)
+ }
+ }
+ // A sibling with a common prefix is fine.
+ fstree.Build(t, src, fstree.Spec{fstree.Dir("project")})
+ if _, err := Prepare(bg, req(Copy, local, join(src, "proj"), local, filepath.Join(src, "project")), nil); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestPrepareConflictsPerFile(t *testing.T) {
+ src, dst := layout(t, fstree.Spec{
+ fstree.File("proj/same.txt", "new"),
+ fstree.File("proj/new.txt", "n"),
+ fstree.File("proj/isdir", "file in src"),
+ fstree.Dir("proj/isfile"),
+ fstree.File("proj/isfile/x", ""),
+ fstree.File("proj/sub/deeper.txt", "d"),
+ }, fstree.Spec{
+ fstree.File("proj/same.txt", "old"),
+ fstree.Dir("proj/isdir"),
+ fstree.File("proj/isfile", "file in dst"),
+ fstree.File("proj/sub/deeper.txt", "old"),
+ fstree.File("proj/only-in-dst", ""),
+ fstree.File("proj/.vcom-part-deadbeef-x", ""),
+ })
+ plan, err := Prepare(bg, req(Copy, local, join(src, "proj"), local, dst), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got := map[string]ConflictKind{}
+ for _, c := range plan.Conflicts {
+ got[c.Item.Rel] = c.Kind
+ }
+ want := map[string]ConflictKind{
+ "proj/same.txt": FileFile,
+ "proj/isdir": TypeMismatch,
+ "proj/isfile": TypeMismatch,
+ "proj/sub/deeper.txt": FileFile,
+ }
+ if fmt.Sprint(got) != fmt.Sprint(want) {
+ t.Fatalf("conflicts %v, want %v", got, want)
+ }
+ for _, it := range plan.Items {
+ if (it.Rel == "proj/new.txt" || it.Rel == "proj/isfile/x") && it.Existing != nil {
+ t.Errorf("%s has Existing", it.Rel)
+ }
+ if it.Rel == "proj" && (it.Existing == nil || !it.Existing.IsDir()) {
+ t.Error("root dir merge target not found")
+ }
+ }
+ if len(plan.Warnings) != 1 {
+ t.Fatalf("leftover warning expected: %v", plan.Warnings)
+ }
+}
+
+func TestPrepareReadDirPerDirNotPerFile(t *testing.T) {
+ var spec, dspec fstree.Spec
+ for i := range 1000 {
+ spec = append(spec, fstree.File(fmt.Sprintf("d/f%04d", i), ""))
+ if i%2 == 0 {
+ dspec = append(dspec, fstree.File(fmt.Sprintf("d/f%04d", i), ""))
+ }
+ }
+ src, dst := layout(t, spec, dspec)
+ c := &counter{}
+ to := &vfstest.FaultFS{FS: local, Hook: c.hook}
+ plan, err := Prepare(bg, req(Copy, local, join(src, "d"), to, dst), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(plan.Conflicts) != 500 {
+ t.Fatalf("%d conflicts", len(plan.Conflicts))
+ }
+ if n := c.get(vfstest.OpReadDir); n != 1 {
+ t.Fatalf("%d ReadDir calls on the target, want 1 (N-P2-4/5)", n)
+ }
+ if n := c.get(vfstest.OpLstat) + c.get(vfstest.OpStat); n > 4 {
+ t.Fatalf("%d stat calls on the target", n)
+ }
+
+ // Many roots: one listing of ToDir instead of a Lstat per root.
+ var roots fstree.Spec
+ var names []string
+ for i := range 50 {
+ n := fmt.Sprintf("r%02d", i)
+ roots = append(roots, fstree.File(n, ""))
+ names = append(names, n)
+ }
+ src, dst = layout(t, roots, nil)
+ c = &counter{}
+ to = &vfstest.FaultFS{FS: local, Hook: c.hook}
+ if _, err := Prepare(bg, req(Copy, local, join(src, names...), to, dst), nil); err != nil {
+ t.Fatal(err)
+ }
+ if c.get(vfstest.OpReadDir) != 1 || c.get(vfstest.OpLstat) > 2 {
+ t.Fatalf("many roots: readdir=%d lstat=%d", c.get(vfstest.OpReadDir), c.get(vfstest.OpLstat))
+ }
+}
+
+func TestPrepareCancel(t *testing.T) {
+ var spec fstree.Spec
+ for i := range 50 {
+ spec = append(spec, fstree.File(fmt.Sprintf("d/s%02d/f", i), ""))
+ }
+ src, dst := layout(t, spec, nil)
+ ctx, cancel := context.WithCancel(bg)
+ n := 0
+ from := &vfstest.FaultFS{FS: local, Hook: func(op vfstest.Op, _ string) error {
+ if op == vfstest.OpReadDir {
+ if n++; n == 5 {
+ cancel()
+ }
+ }
+ return nil
+ }}
+ _, err := Prepare(ctx, req(Copy, from, join(src, "d"), local, dst), nil)
+ if !errors.Is(err, vfs.ErrCancelled) {
+ t.Fatalf("err = %v, want cancelled", err)
+ }
+ if n > 6 {
+ t.Fatalf("walk continued after cancel: %d ReadDirs", n)
+ }
+}
+
+func TestPrepareRejectsBadTargets(t *testing.T) {
+ src, dst := layout(t, fstree.Spec{fstree.File("a", ""), fstree.File("x/a", "")}, fstree.Spec{fstree.File("file", "")})
+ if _, err := Prepare(bg, req(Copy, local, join(src, "a"), vfs.ReadOnly(local), dst), nil); !errors.Is(err, ErrReadOnly) {
+ t.Fatalf("read-only target: %v", err)
+ }
+ if _, err := Prepare(bg, req(Copy, local, join(src, "a"), local, filepath.Join(dst, "file")), nil); !errors.Is(err, ErrTargetNotDir) {
+ t.Fatalf("file target: %v", err)
+ }
+ if _, err := Prepare(bg, req(Copy, local, join(src, "a", "x/a"), local, dst), nil); !errors.Is(err, ErrDuplicateName) {
+ t.Fatalf("duplicate names: %v", err)
+ }
+ if _, err := Prepare(bg, req(Move, vfs.ReadOnly(local), join(src, "a"), local, dst), nil); !errors.Is(err, ErrReadOnly) {
+ t.Fatalf("move from read-only: %v", err)
+ }
+}
diff --git a/internal/transfer/source.go b/internal/transfer/source.go
new file mode 100644
index 0000000..1c2b375
--- /dev/null
+++ b/internal/transfer/source.go
@@ -0,0 +1,190 @@
+package transfer
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "sort"
+ "strings"
+
+ "vcom/internal/vfs"
+)
+
+// Source yields the items of a transfer.
+type Source interface {
+ Label() string
+ // Walk emits every item once, parents before children (plan phase).
+ Walk(ctx context.Context, fn func(Item) error) error
+ // Stream calls fn for items in source order; r is the content of File
+ // items and nil otherwise (execute phase).
+ Stream(ctx context.Context, items []Item, fn func(Item, io.Reader) error) error
+}
+
+// Opener is a Source with random access: Execute reopens an item for every
+// attempt, so Retry after a read error works.
+type Opener interface {
+ Open(ctx context.Context, it Item) (io.ReadCloser, error)
+}
+
+// FSBacked is a Source over a vfs.FS (FSSource): Prepare checks identity
+// against the target and Move can rename and remove source items.
+type FSBacked interface {
+ Source
+ FS() vfs.FS
+ Roots() []string
+}
+
+// FSSource reads the given paths (files, directories, links) from fsys.
+func FSSource(fsys vfs.FS, paths []string, sym SymlinkPolicy) Source {
+ roots := make([]string, len(paths))
+ for i, p := range paths {
+ roots[i] = fsys.Paths().Clean(p)
+ }
+ return &fsSource{fs: fsys, roots: roots, sym: sym}
+}
+
+type fsSource struct {
+ fs vfs.FS
+ roots []string
+ sym SymlinkPolicy
+}
+
+func (s *fsSource) Label() string { return s.fs.Label() }
+func (s *fsSource) FS() vfs.FS { return s.fs }
+func (s *fsSource) Roots() []string { return s.roots }
+
+// maxFollowDepth bounds FollowLinks recursion (design §4.3).
+const maxFollowDepth = 40
+
+func (s *fsSource) Walk(ctx context.Context, fn func(Item) error) error {
+ ops := s.fs.Paths()
+ for i, root := range s.roots {
+ base := ops.Base(root)
+ if base == "" || base == "." || base == ".." || base == string(ops.Sep()) {
+ return fmt.Errorf("transfer: cannot use %q as a source", root)
+ }
+ fi, err := s.fs.Lstat(ctx, root)
+ if err != nil {
+ return err
+ }
+ if err := s.walk(ctx, i, root, base, fi, 0, map[string]bool{}, fn); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (s *fsSource) walk(ctx context.Context, root int, p, rel string, fi vfs.FileInfo, depth int,
+ ancestors map[string]bool, fn func(Item) error) error {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ it := Item{Rel: rel, Root: root, Src: p, Mode: fi.Mode, ModTime: fi.ModTime, Size: fi.Size}
+ follow := s.sym == FollowLinks && fi.IsSymlink()
+ var real string
+ if follow {
+ switch {
+ case fi.Target == nil:
+ it.Warning = "broken symlink copied as a link"
+ follow = false
+ case fi.Target.IsDir():
+ rp, err := s.fs.RealPath(ctx, p)
+ if err != nil || ancestors[rp] || depth >= maxFollowDepth {
+ it.Warning = "symlink loop copied as a link"
+ follow = false
+ } else {
+ real = rp
+ }
+ }
+ if follow {
+ t := *fi.Target
+ it.Mode, it.ModTime, it.Size = t.Mode, t.ModTime, t.Size
+ }
+ }
+ switch {
+ case it.Mode.IsDir():
+ it.Kind, it.Size = Dir, 0
+ case it.Mode.IsRegular():
+ it.Kind = File
+ case fi.IsSymlink() && !follow:
+ it.Kind, it.Size = Symlink, 0
+ t, err := s.fs.ReadLink(ctx, p)
+ if err != nil {
+ return err
+ }
+ it.LinkTarget = t
+ default:
+ it.Kind, it.Size = Special, 0
+ }
+ if it.Kind != Dir {
+ return fn(it)
+ }
+
+ ents, err := s.fs.ReadDir(ctx, p)
+ if err != nil {
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+ it.ScanErr = err
+ return fn(it)
+ }
+ if err := fn(it); err != nil {
+ return err
+ }
+ if s.sym == FollowLinks {
+ if real == "" {
+ if real, err = s.fs.RealPath(ctx, p); err != nil {
+ return err
+ }
+ }
+ ancestors[real] = true
+ defer delete(ancestors, real)
+ }
+ sort.Slice(ents, func(i, j int) bool { return ents[i].Name < ents[j].Name })
+ ops := s.fs.Paths()
+ for _, e := range ents {
+ if strings.HasPrefix(e.Name, partPrefix) {
+ continue // leftovers of an interrupted transfer are never copied
+ }
+ if err := s.walk(ctx, root, ops.Join(p, e.Name), rel+"/"+e.Name, e, depth+1, ancestors, fn); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (s *fsSource) Open(ctx context.Context, it Item) (io.ReadCloser, error) {
+ return s.fs.Open(ctx, it.Src)
+}
+
+func (s *fsSource) Stream(ctx context.Context, items []Item, fn func(Item, io.Reader) error) error {
+ for _, it := range items {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ if it.Kind != File {
+ if err := fn(it, nil); err != nil {
+ return err
+ }
+ continue
+ }
+ f, err := s.Open(ctx, it)
+ if err != nil {
+ if err := fn(it, errReader{err}); err != nil {
+ return err
+ }
+ continue
+ }
+ err = fn(it, f)
+ f.Close()
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// errReader reports an open error through the first Read.
+type errReader struct{ err error }
+
+func (r errReader) Read([]byte) (int, error) { return 0, r.err }
diff --git a/internal/transfer/types.go b/internal/transfer/types.go
new file mode 100644
index 0000000..cdd2577
--- /dev/null
+++ b/internal/transfer/types.go
@@ -0,0 +1,238 @@
+// Package transfer is the one engine for copy, move and unpack (design §4):
+// Prepare walks the source once and plans every item, Execute writes each file
+// through WriteAtomic (temp name + rename), merges directories, copies
+// symlinks as links and asks the caller about conflicts and errors through
+// Hooks. It works over any pair of vfs.FS.
+//
+// Invariants: the source is never modified by a copy; an existing target is
+// replaced only by the final rename of a fully written temp file; after an
+// error or cancellation no partial file is left under a target name; a move
+// removes a source item only after it was copied; directories are never
+// deleted to make room for a file.
+package transfer
+
+import (
+ "context"
+ "io/fs"
+ "time"
+
+ "vcom/internal/vfs"
+)
+
+// Op is what Execute does with the source.
+type Op uint8
+
+const (
+ Copy Op = iota
+ Move
+)
+
+// ConflictPolicy decides what happens when a target already exists.
+type ConflictPolicy uint8
+
+const (
+ Ask ConflictPolicy = iota // Hooks.Resolve decides (Skip if nil)
+ Overwrite // replace files (never directories)
+ Skip // keep the target
+ OverwriteOlder // replace only if the source is newer
+ KeepBoth // write under a free "name (1).ext"
+)
+
+// SymlinkPolicy: copy links as links (default) or copy what they point to.
+type SymlinkPolicy uint8
+
+const (
+ CopyLinks SymlinkPolicy = iota
+ FollowLinks
+)
+
+// ErrorPolicy decides what happens on an item error.
+type ErrorPolicy uint8
+
+const (
+ ErrorAsk ErrorPolicy = iota // Hooks.OnError decides (Skip if nil)
+ ErrorSkipAll // record and continue
+ ErrorAbort // stop at the first error
+)
+
+// FsyncPolicy decides when a written file is fsync'ed before its rename.
+type FsyncPolicy uint8
+
+const (
+ FsyncReplace FsyncPolicy = iota // only when replacing an existing file
+ FsyncAlways
+ FsyncNever
+)
+
+// Options tune a request. Use DefaultOptions for the defaults.
+type Options struct {
+ Conflict ConflictPolicy
+ Symlinks SymlinkPolicy
+ OnError ErrorPolicy
+ Fsync FsyncPolicy
+ PreserveMode bool
+ PreserveTimes bool
+}
+
+// DefaultOptions: ask on conflicts and errors, copy links as links, fsync
+// before replacing, keep mode and mtime.
+func DefaultOptions() Options {
+ return Options{PreserveMode: true, PreserveTimes: true}
+}
+
+// ItemKind classifies a source item.
+type ItemKind uint8
+
+const (
+ File ItemKind = iota
+ Dir
+ Symlink
+ Special // FIFO, socket, device: skipped with a warning
+)
+
+func (k ItemKind) String() string {
+ switch k {
+ case File:
+ return "file"
+ case Dir:
+ return "dir"
+ case Symlink:
+ return "symlink"
+ }
+ return "special"
+}
+
+// Item is one node of the plan.
+type Item struct {
+ Rel string // path relative to ToDir, slash-separated; first element is the root's name
+ Kind ItemKind
+ Size int64
+ Mode fs.FileMode
+ ModTime time.Time
+ LinkTarget string
+ Existing *vfs.FileInfo // what is at the target (Lstat); nil — nothing
+ Root int // index of the top-level source
+
+ // Src is the item's path on the source FS (FSSource); empty for
+ // sources without one (archives).
+ Src string
+ // Warning is set by the source when the item is degraded, e.g. a
+ // symlink loop under FollowLinks copied as a link.
+ Warning string
+ // ScanErr: the directory could not be listed during Prepare; Execute
+ // reports it as the item's error.
+ ScanErr error
+}
+
+// Request describes one transfer.
+type Request struct {
+ Op Op
+ From Source
+ To vfs.FS
+ ToDir string
+ Opts Options
+}
+
+// ConflictKind: same type on both sides, or file↔dir / link↔dir.
+type ConflictKind uint8
+
+const (
+ FileFile ConflictKind = iota
+ TypeMismatch
+)
+
+// Conflict is an item whose target exists.
+type Conflict struct {
+ Item Item
+ Kind ConflictKind
+}
+
+// ResolveAction answers a conflict.
+type ResolveAction uint8
+
+const (
+ ResolveOverwrite ResolveAction = iota
+ ResolveSkip
+ ResolveKeepBoth
+ ResolveAbort
+)
+
+// Resolution is the caller's answer to a conflict; ApplyToAll reuses it for
+// every later conflict of the same ConflictKind.
+type Resolution struct {
+ Action ResolveAction
+ ApplyToAll bool
+}
+
+// Plan is the result of Prepare.
+type Plan struct {
+ Req Request
+ Items []Item
+ TotalFiles int // files and symlinks
+ TotalBytes int64
+ Conflicts []Conflict
+ Warnings []string
+ SameConn bool // From and To are the same connection (or both local)
+}
+
+// Phase of a running transfer.
+type Phase uint8
+
+const (
+ Scanning Phase = iota
+ Copying
+ Removing
+ Finishing
+)
+
+// Progress is a snapshot; BytesTotal comes from Prepare, BytesDone counts
+// processed bytes (copied plus skipped), so it reaches BytesTotal.
+type Progress struct {
+ Phase Phase
+ FilesDone, FilesTotal int
+ BytesDone, BytesTotal int64
+ Current string
+ CurrentDone int64
+ CurrentSize int64
+}
+
+// ErrorAction answers an item error.
+type ErrorAction uint8
+
+const (
+ ErrorRetry ErrorAction = iota
+ ErrorSkip
+ ErrorSkipRest // skip this and every later error
+ ErrorStop // abort the transfer
+)
+
+// Hooks connect Execute to its caller (the jobs manager).
+type Hooks struct {
+ // Progress is called after every chunk and item, at most once per
+ // ProgressInterval (default 50 ms), plus a final call per phase.
+ Progress func(Progress)
+ ProgressInterval time.Duration
+ Resolve func(ctx context.Context, c Conflict) (Resolution, error)
+ OnError func(ctx context.Context, e ItemError) (ErrorAction, error)
+}
+
+// ItemError is a failed item.
+type ItemError struct {
+ Item Item
+ Op string // "read", "write", "mkdir", "symlink", "rename", "remove", "scan", ...
+ Err error
+}
+
+func (e ItemError) Error() string { return e.Op + " " + e.Item.Rel + ": " + e.Err.Error() }
+func (e ItemError) Unwrap() error { return e.Err }
+
+// Report is the outcome of Execute.
+type Report struct {
+ Done, Skipped, Failed int
+ Bytes int64 // bytes actually written
+ Errors []ItemError
+ Warnings []string
+ Cancelled bool
+ Affected []vfs.Location // directories that changed (to reload panels)
+ Err error // fatal: aborted, invalid plan
+}