Files

90 lines
2.1 KiB
Go
Raw Permalink Normal View History

package main
import (
"fmt"
"log"
"os"
"path/filepath"
"sort"
"strings"
"text/tabwriter"
"mcquay.me/arrange"
)
// bigVideo is the size past which a video is more likely a ripped movie than
// a home video.
const bigVideo = 1 << 30
type group struct {
dir string
images, raws, videos int
big int
bytes, videoBytes int64
}
// survey tallies media under dir by directory, *depth levels down, so ripped
// movies and other things to keep out of a store stand out. It only stats
// files, and prints directory names, so its output is for the person running
// it.
func survey(dir string, f arrange.Filter) error {
if _, err := os.Stat(dir); err != nil {
return err
}
groups := map[string]*group{}
for path := range arrange.SourceFiltered(dir, f) {
fi, err := os.Stat(path)
if err != nil {
log.Printf("%v", err)
continue
}
key := groupKey(dir, path, *depth)
g := groups[key]
if g == nil {
g = &group{dir: key}
groups[key] = g
}
g.bytes += fi.Size()
c, _ := arrange.ClassOf(path)
switch c {
case arrange.Image:
g.images++
case arrange.Raw:
g.raws++
case arrange.Video:
g.videos++
g.videoBytes += fi.Size()
if fi.Size() >= bigVideo {
g.big++
}
}
}
gs := make([]*group, 0, len(groups))
for _, g := range groups {
gs = append(gs, g)
}
sort.Slice(gs, func(i, j int) bool { return gs[i].bytes > gs[j].bytes })
tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', tabwriter.AlignRight)
fmt.Fprintln(tw, "size\timages\traw\tvideos\tvideos>1G\tvideo size\t\tdir")
for _, g := range gs {
fmt.Fprintf(tw, "%s\t%d\t%d\t%d\t%d\t%s\t\t%s\n",
human(g.bytes), g.images, g.raws, g.videos, g.big, human(g.videoBytes), g.dir)
}
return tw.Flush()
}
// groupKey is the directory of path relative to root, cut to depth levels.
func groupKey(root, path string, depth int) string {
rel, err := filepath.Rel(root, filepath.Dir(path))
if err != nil || rel == "." {
return "."
}
parts := strings.Split(rel, string(filepath.Separator))
if depth > 0 && len(parts) > depth {
parts = parts[:depth]
}
return filepath.Join(parts...)
}