53 lines
1.0 KiB
Go
Executable File
53 lines
1.0 KiB
Go
Executable File
package files
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"io/fs"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
func TreeSize(root string) (int64, error) {
|
|
var total int64
|
|
err := filepath.WalkDir(root, func(_ string, entry fs.DirEntry, walkErr error) error {
|
|
if walkErr != nil {
|
|
return walkErr
|
|
}
|
|
if !entry.Type().IsRegular() {
|
|
return nil
|
|
}
|
|
info, err := entry.Info()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
total += info.Size()
|
|
return nil
|
|
})
|
|
return total, err
|
|
}
|
|
|
|
func UniquePath(candidate string) string {
|
|
if !exists(candidate) {
|
|
return candidate
|
|
}
|
|
|
|
directory, name := filepath.Split(candidate)
|
|
extension := filepath.Ext(name)
|
|
base := strings.TrimSuffix(name, extension)
|
|
for index := 1; index < 1000; index++ {
|
|
next := filepath.Join(directory, fmt.Sprintf("%s (%d)%s", base, index, extension))
|
|
if !exists(next) {
|
|
return next
|
|
}
|
|
}
|
|
return filepath.Join(directory, fmt.Sprintf("%s-%d%s", base, time.Now().UnixNano(), extension))
|
|
}
|
|
|
|
func exists(path string) bool {
|
|
_, err := os.Lstat(path)
|
|
return !errors.Is(err, fs.ErrNotExist)
|
|
}
|