vcom/internal/transfer/reader.go
vrubelroman 86c110f0b1 feat(transfer): WriteAtomic and Execute for files, dirs and links (3.2)
Every file is written to .vcom-part-<rand>-<name>, closed (a Close error
fails the item: N-P2-6), chmod/chtimes'ed and only then renamed over the
target, so a failed or cancelled overwrite keeps the old file (N-P0-4) and
leaves no temp. Without atomic replace the old file is renamed aside and
restored on failure. Directories are merged, never replaced (N-P0-7), and
get their real mode/mtime post-order (N-P1-17); symlinks are copied as
links, broken ones too (N-P1-8); mode and mtime are preserved (N-P1-9);
FIFOs and devices are skipped with a warning. The copy loop goes through a
ctx-aware reader with Size() and throttled byte progress. Conflict and
error policies are wired in here; their tests follow in 3.3.

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

65 lines
1.3 KiB
Go

package transfer
import (
"context"
"io"
"time"
)
// progressReader checks ctx before every chunk (cancellation inside a file:
// N-P1-7) and reports bytes read. Size lets pkg/sftp pick its concurrent
// ReadFrom path.
type progressReader struct {
ctx context.Context
r io.Reader
size int64
n int64
onRead func(total int64)
}
func (r *progressReader) Read(p []byte) (int, error) {
if err := r.ctx.Err(); err != nil {
return 0, err
}
n, err := r.r.Read(p)
if n > 0 {
r.n += int64(n)
if r.onRead != nil {
r.onRead(r.n)
}
}
return n, err
}
func (r *progressReader) Size() int64 { return r.size }
// defaultProgressInterval bounds how often Hooks.Progress is called.
const defaultProgressInterval = 50 * time.Millisecond
// emitter throttles progress callbacks.
type emitter struct {
fn func(Progress)
every time.Duration
last time.Time
p Progress
}
func newEmitter(fn func(Progress), every time.Duration) *emitter {
if every <= 0 {
every = defaultProgressInterval
}
return &emitter{fn: fn, every: every}
}
// emit calls fn if the interval has passed or force is set.
func (e *emitter) emit(force bool) {
if e.fn == nil {
return
}
now := time.Now()
if !force && now.Sub(e.last) < e.every {
return
}
e.last = now
e.fn(e.p)
}