feat(transfer): move by rename or copy+delete per item (3.5)

With SameConn a top-level item without a target is renamed whole
(NoReplace), and files merged into an existing directory are renamed one by
one; EXDEV or any rename failure falls back to copy. Otherwise each file or
link is copied, its size checked and only then removed from the source
(Remove never follows links: N-P0-3); source directories are removed
bottom-up only when empty, so skipped and failed items stay in place.
Links are always moved as links (FollowLinks is ignored for a move: N-P1-8).
Affected includes the source directories.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-11-01 04:04:31 +03:00
parent 058616de38
commit b3f9452a1d
6 changed files with 411 additions and 28 deletions

View file

@ -11,6 +11,3 @@ var (
ErrReadOnly = errors.New("read-only file system")
ErrAborted = errors.New("transfer aborted")
)
// ErrUnsupportedMove is temporary (task 3.5).
var ErrUnsupportedMove = errors.New("move is not implemented yet")

View file

@ -31,18 +31,19 @@ type executor struct {
opts Options
move bool
rep Report
prog *emitter
applyAll map[ConflictKind]ResolveAction
skipErrors bool
doneBytes int64 // processed bytes of finished items
renamed map[string]string // rel of a dir written under another name → its new rel
skipped map[string]bool // rel of dirs whose subtree is not written
incomplete map[string]bool // rel of source dirs that keep content (move)
dirFix []dirFix
affected map[string]bool
srcDirs []Item // move: source directories, removed post-order
crossVol bool
rep Report
prog *emitter
applyAll map[ConflictKind]ResolveAction
skipErrors bool
doneBytes int64 // processed bytes of finished items
renamed map[string]string // rel of a dir written under another name → its new rel
skipped map[string]bool // rel of dirs whose subtree is not written
incomplete map[string]bool // rel of source dirs that keep content (move)
dirFix []dirFix
affected map[string]bool
srcDirs []Item // move: source directories, removed post-order
srcDirsAffected map[string]bool
crossVol bool
}
type dirFix struct {
@ -135,12 +136,7 @@ func (e *executor) finish() {
if e.ctx.Err() != nil {
e.rep.Cancelled = true
}
dirs := make([]string, 0, len(e.affected))
for d := range e.affected {
dirs = append(dirs, d)
}
sort.Strings(dirs)
for _, d := range dirs {
for _, d := range sortedKeys(e.affected) {
e.rep.Affected = append(e.rep.Affected, vfs.Location{FS: e.to, Path: d})
}
if e.move {
@ -368,6 +364,11 @@ func (e *executor) doFile(it Item, open func() (io.ReadCloser, error)) error {
replace = true
}
}
if e.move && e.plan.SameConn {
if e.renameItem(it, rel, replace) {
return nil
}
}
for {
dst := dstPath(e.to, e.toDir, rel)
e.prog.p.CurrentSize = it.Size
@ -541,3 +542,12 @@ func (t readTracker) Size() int64 {
}
return 0
}
func sortedKeys(m map[string]bool) []string {
out := make([]string, 0, len(m))
for k := range m {
out = append(out, k)
}
sort.Strings(out)
return out
}

View file

@ -1,12 +1,158 @@
package transfer
// Move support lands in task 3.5; until then Execute refuses Op Move.
import (
"errors"
"fmt"
"strings"
"vcom/internal/vfs"
)
// renameWhole is the fast path of a move (design §4.3): with SameConn, a
// top-level item that has no target yet is renamed as a whole (NoReplace).
// Anything that cannot be renamed — EXDEV, a target that appeared, any
// other error — falls back to the per-item copy+delete path. It returns the
// items still to process.
func (e *executor) renameWhole(items []Item) []Item {
e.rep.Err = ErrUnsupportedMove
return nil
fb, ok := e.plan.Req.From.(FSBacked)
if !ok {
e.rep.Err = errors.New("transfer: move needs a file-system source")
return nil
}
if !e.plan.SameConn {
return items
}
src := fb.FS()
var rest []Item
for i := 0; i < len(items); {
root := items[i]
end := i + 1
for end < len(items) && strings.HasPrefix(items[end].Rel, root.Rel+"/") {
end++
}
if e.ctx.Err() != nil {
return append(rest, items[i:]...)
}
if root.Existing == nil && root.Src != "" && root.ScanErr == nil && !hasScanErr(items[i:end]) {
dst := dstPath(e.to, e.toDir, root.Rel)
if err := e.to.Rename(e.ctx, root.Src, dst, vfs.NoReplace); err == nil {
for _, it := range items[i:end] {
if it.Kind == File || it.Kind == Symlink {
e.prog.p.FilesDone++
e.doneBytes += it.Size
e.rep.Done++
}
}
e.prog.p.BytesDone = e.doneBytes
e.prog.emit(false)
e.parentAffected(root.Rel)
e.srcAffected(src.Paths().Dir(root.Src))
i = end
continue
}
// EXDEV (another device), ErrExist (appeared) or anything else:
// copy and delete item by item instead.
}
rest = append(rest, items[i:end]...)
i = end
}
return rest
}
func (e *executor) removeSource(Item) error { return nil }
func (e *executor) removeSourceDirs() {}
func (e *executor) addSourceAffected() {}
func hasScanErr(items []Item) bool {
for _, it := range items {
if it.ScanErr != nil {
return true
}
}
return false
}
func (e *executor) srcFS() vfs.FS { return e.plan.Req.From.(FSBacked).FS() }
func (e *executor) srcAffected(dir string) {
if e.srcDirsAffected == nil {
e.srcDirsAffected = map[string]bool{}
}
e.srcDirsAffected[dir] = true
}
// removeSource deletes a file or link from the source after it was copied.
// Remove never follows links (N-P0-3 for move).
func (e *executor) removeSource(it Item) error {
src := e.srcFS()
for {
err := src.Remove(e.ctx, it.Src)
if err == nil || errors.Is(err, vfs.ErrNotExist) {
e.srcAffected(src.Paths().Dir(it.Src))
return nil
}
switch r := e.handleError(it, "remove", err); r {
case errRetry:
continue
case nil:
return nil
default:
return r
}
}
}
// removeSourceDirs removes moved source directories bottom-up, only those
// with nothing left behind (skipped, failed or special items stay).
func (e *executor) removeSourceDirs() {
if len(e.srcDirs) == 0 {
return
}
src := e.srcFS()
e.prog.p.Phase = Removing
e.prog.emit(true)
for i := len(e.srcDirs) - 1; i >= 0; i-- {
it := e.srcDirs[i]
if e.incomplete[it.Rel] || e.skipped[it.Rel] || e.underSkipped(it.Rel) {
continue
}
err := src.Remove(e.ctx, it.Src)
if err == nil || errors.Is(err, vfs.ErrNotExist) {
e.srcAffected(src.Paths().Dir(it.Src))
continue
}
if e.ctx.Err() != nil {
return
}
e.rep.Errors = append(e.rep.Errors, ItemError{Item: it, Op: "remove",
Err: fmt.Errorf("source directory not removed: %w", err)})
e.rep.Failed++
e.markIncomplete(it.Rel)
}
}
func (e *executor) addSourceAffected() {
src := e.srcFS()
for _, d := range sortedKeys(e.srcDirsAffected) {
e.rep.Affected = append(e.rep.Affected, vfs.Location{FS: src, Path: d})
}
}
// renameItem moves one file or link inside a merged directory by rename
// when source and target share the namespace. It reports whether it did;
// on any failure (EXDEV, a target that appeared, ...) the caller copies.
func (e *executor) renameItem(it Item, rel string, replace bool) bool {
if it.Src == "" {
return false
}
mode := vfs.NoReplace
if replace {
if !e.to.Caps().AtomicReplace {
return false
}
mode = vfs.Replace
}
if err := e.to.Rename(e.ctx, it.Src, dstPath(e.to, e.toDir, rel), mode); err != nil {
return false
}
e.parentAffected(rel)
e.srcAffected(e.srcFS().Paths().Dir(it.Src))
e.finishFile(it, true)
return true
}

View file

@ -0,0 +1,227 @@
package transfer
import (
"context"
"errors"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
"syscall"
"testing"
"vcom/internal/testutil/fstree"
"vcom/internal/vfs"
"vcom/internal/vfs/vfstest"
)
func inode(t *testing.T, p string) uint64 {
t.Helper()
fi, err := os.Lstat(p)
if err != nil {
t.Fatal(err)
}
return fi.Sys().(*syscall.Stat_t).Ino
}
func gone(t *testing.T, p string) {
t.Helper()
if _, err := os.Lstat(p); !os.IsNotExist(err) {
t.Errorf("%s still exists", p)
}
}
func TestMoveSameVolumeIsRename(t *testing.T) {
src, dst := layout(t, fstree.Spec{fstree.File("proj/big", "").WithSize(1 << 20), fstree.File("f.txt", "f")},
fstree.Spec{fstree.File("merge/keep", "k")})
inoDir, inoFile := inode(t, filepath.Join(src, "proj")), inode(t, filepath.Join(src, "f.txt"))
c := &counter{}
to := &vfstest.FaultFS{FS: local, Hook: c.hook}
plan, rep := run(t, req(Move, local, join(src, "proj", "f.txt"), to, dst), Hooks{})
if !plan.SameConn || rep.Err != nil || rep.Done != 2 {
t.Fatalf("plan.SameConn=%v report %+v", plan.SameConn, rep)
}
if inode(t, filepath.Join(dst, "proj")) != inoDir || inode(t, filepath.Join(dst, "f.txt")) != inoFile {
t.Fatal("same-volume move copied instead of renaming (inode changed)")
}
if c.get(vfstest.OpCreate) != 0 || c.get(vfstest.OpWrite) != 0 {
t.Fatalf("data was written: create=%d write=%d", c.get(vfstest.OpCreate), c.get(vfstest.OpWrite))
}
gone(t, filepath.Join(src, "proj"))
gone(t, filepath.Join(src, "f.txt"))
// Merging into an existing directory renames file by file.
fstree.Build(t, src, fstree.Spec{fstree.File("merge/new", "n")})
ino := inode(t, filepath.Join(src, "merge", "new"))
if _, rep := run(t, req(Move, local, join(src, "merge"), local, dst), Hooks{}); rep.Done != 1 || rep.Err != nil {
t.Fatalf("%+v", rep)
}
if inode(t, filepath.Join(dst, "merge", "new")) != ino || read(t, filepath.Join(dst, "merge", "keep")) != "k" {
t.Fatal("merge move")
}
gone(t, filepath.Join(src, "merge"))
}
func TestMoveFallsBackOnEXDEV(t *testing.T) {
src, dst := layout(t, fstree.Spec{fstree.File("d/a", "aaa"), fstree.Symlink("d/l", "a")}, nil)
to := &vfstest.FaultFS{FS: local, Hook: func(op vfstest.Op, p string) error {
if op == vfstest.OpRename && strings.HasPrefix(p, src+"/") {
return &os.LinkError{Op: "rename", Old: p, Err: syscall.EXDEV}
}
return nil
}}
_, rep := run(t, req(Move, local, join(src, "d"), to, dst), Hooks{})
if rep.Err != nil || rep.Done != 2 || rep.Failed != 0 {
t.Fatalf("%+v", rep)
}
if read(t, filepath.Join(dst, "d", "a")) != "aaa" {
t.Fatal("not copied")
}
gone(t, filepath.Join(src, "d"))
noLeftovers(t, dst)
}
func TestMoveSkippedItemStaysInSource(t *testing.T) {
src, dst := layout(t, fstree.Spec{fstree.File("d/conflict", "mine"), fstree.File("d/free", "f"), fstree.File("d/sub/x", "x")},
fstree.Spec{fstree.File("d/conflict", "theirs")})
for _, to := range []vfs.FS{local, otherVolume{local}} {
_, rep := run(t, req(Move, local, join(src, "d"), to, dst, func(o *Options) { o.Conflict = Skip }), Hooks{})
if rep.Err != nil || rep.Skipped != 1 || rep.Done != 2 {
t.Fatalf("%T: %+v", to, rep)
}
fstree.Equal(t, fstree.FromSpec(fstree.Spec{fstree.File("d/conflict", "mine")}), fstree.Snapshot(t, src), fstree.Opts{})
if read(t, filepath.Join(dst, "d", "conflict")) != "theirs" || read(t, filepath.Join(dst, "d", "sub", "x")) != "x" {
t.Fatal("target wrong")
}
// Reset for the second (cross-volume) round.
fstree.Build(t, src, fstree.Spec{fstree.File("d/free", "f"), fstree.File("d/sub/x", "x")})
_ = os.RemoveAll(filepath.Join(dst, "d", "sub"))
_ = os.Remove(filepath.Join(dst, "d", "free"))
}
}
func TestMoveFailedItemStaysInSource(t *testing.T) {
src, dst := layout(t, fstree.Spec{fstree.File("d/bad", "b"), fstree.File("d/good", "g")}, nil)
to := &vfstest.FaultFS{FS: otherVolume{local}, Hook: func(op vfstest.Op, p string) error {
if op == vfstest.OpCreate && hasSuffixName(p, "bad") {
return syscall.EIO
}
return nil
}}
_, rep := run(t, req(Move, local, join(src, "d"), to, dst, skipAll), Hooks{})
if rep.Failed != 1 || rep.Done != 1 || rep.Errors[0].Item.Rel != "d/bad" {
t.Fatalf("%+v", rep)
}
if read(t, filepath.Join(src, "d", "bad")) != "b" {
t.Fatal("failed item removed from the source")
}
gone(t, filepath.Join(src, "d", "good"))
gone(t, filepath.Join(dst, "d", "bad"))
noLeftovers(t, dst)
// A failed removal of the source is reported, the copy stays.
src2, dst2 := layout(t, fstree.Spec{fstree.File("e/f", "f")}, nil)
from := &vfstest.FaultFS{FS: local, Hook: func(op vfstest.Op, _ string) error {
if op == vfstest.OpRemove {
return syscall.EACCES
}
return nil
}}
plan, err := Prepare(bg, Request{Op: Move, From: FSSource(from, join(src2, "e"), CopyLinks), To: otherVolume{local}, ToDir: dst2, Opts: DefaultOptions()}, nil)
if err != nil {
t.Fatal(err)
}
rep = Execute(bg, plan, Hooks{OnError: func(context.Context, ItemError) (ErrorAction, error) { return ErrorSkip, nil }})
if rep.Failed != 1 || rep.Errors[0].Op != "remove" || read(t, filepath.Join(dst2, "e", "f")) != "f" || read(t, filepath.Join(src2, "e", "f")) != "f" {
t.Fatalf("%+v", rep)
}
}
func TestMoveDirWithSymlinkKeepsLink(t *testing.T) {
src, dst := layout(t, fstree.Spec{
fstree.File("target/data", "precious"),
fstree.Symlink("d/link", "../target"),
fstree.Symlink("d/broken", "nowhere"),
fstree.File("d/f", "f"),
}, nil)
_, rep := run(t, req(Move, local, join(src, "d"), otherVolume{local}, dst, follow), Hooks{}) // follow is ignored for move
if rep.Err != nil || rep.Failed != 0 || rep.Done != 3 {
t.Fatalf("%+v", rep)
}
for name, want := range map[string]string{"link": "../target", "broken": "nowhere"} {
if tgt, err := os.Readlink(filepath.Join(dst, "d", name)); err != nil || tgt != want {
t.Fatalf("%s: %q %v (N-P1-8: link lost in move)", name, tgt, err)
}
}
gone(t, filepath.Join(src, "d"))
if read(t, filepath.Join(src, "target", "data")) != "precious" {
t.Fatal("link target damaged")
}
}
func TestMoveNeverFollowsSourceLinks(t *testing.T) {
src, dst := layout(t, fstree.Spec{
fstree.File("outside/keep1", "1"),
fstree.File("outside/sub/keep2", "2"),
fstree.Symlink("rootlink", "outside"),
fstree.Symlink("d/inner", "../outside"),
fstree.File("d/own", "o"),
}, nil)
for _, to := range []vfs.FS{otherVolume{local}, local} {
_, rep := run(t, req(Move, local, join(src, "rootlink", "d"), to, dst), Hooks{})
if rep.Err != nil || rep.Failed != 0 {
t.Fatalf("%T: %+v", to, rep)
}
fstree.Equal(t, fstree.FromSpec(fstree.Spec{fstree.File("outside/keep1", "1"), fstree.File("outside/sub/keep2", "2")}),
fstree.Snapshot(t, src), fstree.Opts{Links: true})
if fi, err := os.Lstat(filepath.Join(dst, "rootlink")); err != nil || fi.Mode()&fs.ModeSymlink == 0 {
t.Fatal("root link not moved as a link")
}
// Back for the second round.
_ = os.RemoveAll(filepath.Join(dst, "d"))
_ = os.Remove(filepath.Join(dst, "rootlink"))
fstree.Build(t, src, fstree.Spec{fstree.Symlink("rootlink", "outside"), fstree.Symlink("d/inner", "../outside"), fstree.File("d/own", "o")})
}
}
func TestMoveAffectedIncludesSource(t *testing.T) {
src, dst := layout(t, fstree.Spec{fstree.File("d/sub/f", "f"), fstree.File("top", "t")}, nil)
to := otherVolume{local}
_, rep := run(t, req(Move, local, join(src, "d", "top"), to, dst), Hooks{})
if rep.Err != nil {
t.Fatal(rep.Err)
}
var srcDirs, dstDirs []string
for _, l := range rep.Affected {
if l.FS == vfs.FS(local) {
srcDirs = append(srcDirs, l.Path)
} else {
dstDirs = append(dstDirs, l.Path)
}
}
sort.Strings(srcDirs)
if len(srcDirs) == 0 || srcDirs[0] != src {
t.Fatalf("source dir not affected: %v", srcDirs)
}
if len(dstDirs) == 0 || dstDirs[0] != dst {
t.Fatalf("target dir not affected: %v", dstDirs)
}
// Same-volume rename path too.
src, dst = layout(t, fstree.Spec{fstree.File("x", "x")}, nil)
_, rep = run(t, req(Move, local, join(src, "x"), local, dst), Hooks{})
found := false
for _, l := range rep.Affected {
found = found || l.Path == src
}
if !found {
t.Fatalf("rename move: source not in Affected %v", rep.Affected)
}
}
func TestMoveRejectsNonFSSourceAndSelf(t *testing.T) {
src, _ := layout(t, fstree.Spec{fstree.File("d/f", "")}, nil)
if _, err := Prepare(bg, req(Move, local, join(src, "d"), local, filepath.Join(src, "d")), nil); !errors.Is(err, ErrIntoItself) {
t.Fatalf("move into itself: %v", err)
}
}

View file

@ -40,6 +40,9 @@ func Prepare(ctx context.Context, req Request, progress func(Progress)) (*Plan,
return nil, fmt.Errorf("%w: %s", ErrTargetNotDir, req.ToDir)
}
if _, ok := req.From.(FSBacked); !ok && req.Op == Move {
return nil, errors.New("transfer: move needs a file-system source")
}
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())

View file

@ -229,7 +229,7 @@ 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
Bytes int64 // bytes of completed files (copied, or moved by rename)
Errors []ItemError
Warnings []string
Cancelled bool