clonetool/util.go
2026-09-05 23:02:29 +02:00

50 lines
1.0 KiB
Go

package main
import (
"fmt"
"sync"
)
// limitedBuffer keeps only the last maxLen bytes written to it — used to
// capture a bounded tail of a subprocess's stderr for error messages
// without risking unbounded memory growth from a noisy remote command.
type limitedBuffer struct {
mu sync.Mutex
buf []byte
maxLen int
}
func newLimitedBuffer(maxLen int) *limitedBuffer {
return &limitedBuffer{maxLen: maxLen}
}
func (b *limitedBuffer) Write(p []byte) (int, error) {
b.mu.Lock()
defer b.mu.Unlock()
b.buf = append(b.buf, p...)
if len(b.buf) > b.maxLen {
b.buf = b.buf[len(b.buf)-b.maxLen:]
}
return len(p), nil
}
func (b *limitedBuffer) String() string {
b.mu.Lock()
defer b.mu.Unlock()
return string(b.buf)
}
func humanBytes(n int64) string {
const unit = 1024
if n < unit {
return fmt.Sprintf("%d B", n)
}
div, exp := int64(unit), 0
for m := n / unit; m >= unit; m /= unit {
div *= unit
exp++
}
units := "KMGTPE"
return fmt.Sprintf("%.1f%ciB", float64(n)/float64(div), units[exp])
}