package worktree import ( "context" "errors" "fmt" "os" "path/filepath" "syscall" "time" ) // ErrDiskLow means the work volume stayed below the free-space floor. var ErrDiskLow = errors.New("disk low") // FreeBytes reports the space available to unprivileged writers on the volume // holding the work directory, which may not exist yet. func (m *Manager) FreeBytes() (uint64, error) { path := m.WorkDir for { var st syscall.Statfs_t err := syscall.Statfs(path, &st) if err == nil { return st.Bavail * uint64(st.Bsize), nil //nolint:gosec // Bsize is positive } parent := filepath.Dir(path) if !errors.Is(err, os.ErrNotExist) || parent == path { return 0, err } path = parent } } // AwaitSpace blocks until free reports at least floor bytes, checking every // interval for up to wait, so a full volume delays a clone instead of failing // it half-written. A volume that cannot be measured does not block the clone. func AwaitSpace(ctx context.Context, free func() (uint64, error), floor uint64, interval, wait time.Duration) error { deadline := time.Now().Add(wait) for { have, err := free() if err == nil && have < floor { if !time.Now().Add(interval).Before(deadline) { return fmt.Errorf("%w: %d MiB free on the work volume, %d MiB needed to clone", ErrDiskLow, have>>20, floor>>20) } select { case <-ctx.Done(): return ctx.Err() case <-time.After(interval): } continue } return nil } }