vcom/internal/transfer/prepare.go
vrubelroman 76ae6c3a87 feat(transfer): request/plan types, FSSource and Prepare (3.1)
Prepare refuses a read-only or non-directory target, a root that is the
same file as its target (also through a symlinked directory: N-P0-6) and a
directory copied into itself; walks the source once (links as links, or
followed with loop detection); lists each existing target directory once
instead of a stat per file (N-P2-4/5); fills Existing and the per-file
Conflicts and computes exact TotalFiles/TotalBytes (N-P1-13).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 03:56:21 +03:00

232 lines
6 KiB
Go

package transfer
import (
"context"
"errors"
"fmt"
"strings"
"vcom/internal/vfs"
)
// partPrefix names temp files of WriteAtomic: <dir>/.vcom-part-<8hex>-<name>.
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
}