choose what to arrange: -kinds, -exclude, am survey

-kinds picks any of image, raw, video (default all). -exclude skips
files and whole directories by name glob, and can be repeated. am
survey stats media per directory (counts by kind, videos over 1G,
sizes) so things like ripped DVDs stand out before arranging. It
never opens files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
sm
2026-10-26 15:57:23 -07:00
co-authored by Claude Opus 5.5
parent 6d971118b7
commit f63b855179
6 changed files with 270 additions and 15 deletions
+10
View File
@@ -13,6 +13,16 @@ header (mov, mp4, m4v, 3gp), or the file's mtime as a last resort.
go install mcquay.me/arrange/cmd/am@latest
# where's the media? per folder: images, raw, videos, videos over 1G
# (ripped movies stand out), sizes. Only stats files. Prints folder names.
am survey ~/Pictures
am survey -depth=2 ~/Pictures
# pick what to grab: -kinds is any of image,raw,video (default all), and
# -exclude skips matching file or folder names (repeatable)
am arr -n -kinds=image ~/Pictures /mnt/store
am arr -n -exclude=VIDEO_TS -exclude='*.vob' -exclude=DVDs ~/Pictures /mnt/store
# see what would happen; prints new/dup<TAB>src<TAB>content<TAB>date dir
am arr -n ~/Pictures /mnt/store > plan.tsv
+65 -10
View File
@@ -25,11 +25,39 @@ const (
kindJPEG kind = iota
kindPNG
kindGIF
kindStill // HEIC, camera RAW, etc.: dated by exif, no decode check
kindStill // HEIC, TIFF, etc.: dated by exif, no decode check
kindRaw // camera RAW: like kindStill, but its own Class
kindQuickTime // mov/mp4 family: dated by the mvhd atom
kindVideo // everything else: dated by mtime
)
// Class is the coarse sort of media a file is, for choosing what to arrange.
type Class string
// The classes of media.
const (
Image Class = "image"
Raw Class = "raw"
Video Class = "video"
)
func (k kind) class() Class {
switch k {
case kindRaw:
return Raw
case kindQuickTime, kindVideo:
return Video
}
return Image
}
// ClassOf reports the Class of path by its extension, and whether it is
// media at all.
func ClassOf(path string) (Class, bool) {
k, ok := exts[strings.ToLower(filepath.Ext(path))]
return k.class(), ok
}
var exts = map[string]kind{
// images
".jpg": kindJPEG,
@@ -41,11 +69,11 @@ var exts = map[string]kind{
".avif": kindStill,
".tif": kindStill,
".tiff": kindStill,
".dng": kindStill,
".cr2": kindStill,
".cr3": kindStill,
".nef": kindStill,
".arw": kindStill,
".dng": kindRaw,
".cr2": kindRaw,
".cr3": kindRaw,
".nef": kindRaw,
".arw": kindRaw,
// videos
".mov": kindQuickTime,
@@ -101,9 +129,36 @@ func PrepOutput(root string) error {
return nil
}
// Filter narrows what Source sends.
type Filter struct {
// Classes to include; empty means all.
Classes map[Class]bool
// Exclude skips files and whole directories whose name matches any of
// these filepath.Match patterns, e.g. "VIDEO_TS" or "*.vob".
Exclude []string
}
func (f Filter) excluded(name string) bool {
for _, p := range f.Exclude {
if ok, _ := filepath.Match(p, name); ok {
return true
}
}
return false
}
func (f Filter) wants(c Class) bool {
return len(f.Classes) == 0 || f.Classes[c]
}
// Source sends all files that match known extensions. Unreadable paths are
// logged and skipped rather than ending the crawl.
func Source(root string) <-chan string {
return SourceFiltered(root, Filter{})
}
// SourceFiltered is Source, sending only the files f lets through.
func SourceFiltered(root string, f Filter) <-chan string {
out := make(chan string)
go func() {
err := filepath.WalkDir(
@@ -119,16 +174,16 @@ func Source(root string) <-chan string {
name := d.Name()
if d.IsDir() {
// QNAP thumbnail caches
if name == ".@__thumb" {
if name == ".@__thumb" || (path != root && f.excluded(name)) {
return filepath.SkipDir
}
return nil
}
// AppleDouble resource forks
if strings.HasPrefix(name, "._") {
if strings.HasPrefix(name, "._") || f.excluded(name) {
return nil
}
if _, ok := exts[strings.ToLower(filepath.Ext(path))]; ok {
if c, ok := ClassOf(path); ok && f.wants(c) {
out <- path
}
return nil
@@ -261,7 +316,7 @@ func ParseFile(path string) (Media, error) {
// try a few things for a time value, falling back to mtime
var t time.Time
switch k {
case kindJPEG, kindPNG, kindStill:
case kindJPEG, kindPNG, kindStill, kindRaw:
t = exifTime(f, k == kindJPEG)
case kindQuickTime:
if _, err := f.Seek(0, io.SeekStart); err == nil {
+2 -2
View File
@@ -10,14 +10,14 @@ import (
"mcquay.me/arrange"
)
func arr(indir, outdir string) error {
func arr(indir, outdir string, f arrange.Filter) error {
if !*dryRun {
if err := arrange.PrepOutput(outdir); err != nil {
return fmt.Errorf("problem creating directory structure: %v", err)
}
}
work := arrange.Source(indir)
work := arrange.SourceFiltered(indir, f)
streams := []<-chan arrange.Media{}
workers := runtime.NumCPU()
+61 -3
View File
@@ -7,12 +7,15 @@ import (
"fmt"
"log"
"os"
"path/filepath"
"strings"
"mcquay.me/arrange"
)
const usage = "am <arr|clean|verify|meta> [flags]"
const arrUsage = "am arr [-h|-n|-hash=sha256|md5|-cores=N] <in> <out>"
const usage = "am <arr|survey|clean|verify|meta> [flags]"
const arrUsage = "am arr [-h|-n|-kinds=image,raw,video|-exclude=PATTERN...|-hash=sha256|md5|-cores=N] <in> <out>"
const surveyUsage = "am survey [-h|-depth=N|-kinds=...|-exclude=PATTERN...] <directory>"
const cleanUsage = "am clean [-h|-n|-cores=N] <directory>"
const verifyUsage = "am verify [-h|-cores=N] <directory>"
const metaUsage = "am meta [-h|-cores=N] <file0> <file1> ... <fileN>"
@@ -20,6 +23,45 @@ const metaUsage = "am meta [-h|-cores=N] <file0> <file1> ... <fileN>"
var cores = flag.Int("cores", 0, "how many threads to use")
var dryRun = flag.Bool("n", false, "dry run: print the plan as tab-separated lines, change nothing")
var hashName = flag.String("hash", "sha256", "content-address hash: sha256, or md5 to add to a store built by older versions")
var kinds = flag.String("kinds", "image,raw,video", "comma-separated kinds of media to include: image, raw, video")
var depth = flag.Int("depth", 1, "survey: how many directory levels to group by")
var excludes patterns
func init() {
flag.Var(&excludes, "exclude", "skip files and directories whose name matches this glob (repeatable), e.g. VIDEO_TS or '*.vob'")
}
// patterns collects a repeated flag.
type patterns []string
func (p *patterns) String() string { return strings.Join(*p, ",") }
func (p *patterns) Set(v string) error {
if _, err := filepath.Match(v, ""); err != nil {
return fmt.Errorf("bad pattern %q: %v", v, err)
}
*p = append(*p, v)
return nil
}
// filter builds the arrange.Filter from the -kinds and -exclude flags.
func filter() (arrange.Filter, error) {
f := arrange.Filter{Classes: map[arrange.Class]bool{}, Exclude: excludes}
for _, k := range strings.Split(*kinds, ",") {
c := arrange.Class(strings.TrimSpace(k))
switch c {
case arrange.Image, arrange.Raw, arrange.Video:
f.Classes[c] = true
case "":
default:
return f, fmt.Errorf("unknown kind %q (known: image, raw, video)", k)
}
}
if len(f.Classes) == 0 {
return f, fmt.Errorf("-kinds selects nothing")
}
return f, nil
}
func main() {
if len(os.Args) < 2 {
@@ -42,6 +84,12 @@ func main() {
os.Exit(1)
}
f, err := filter()
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
switch sub {
case "ar", "arr", "arrange":
args := flag.Args()
@@ -50,10 +98,20 @@ func main() {
os.Exit(1)
}
in, out := args[0], args[1]
if err := arr(in, out); err != nil {
if err := arr(in, out, f); err != nil {
fmt.Fprintf(os.Stderr, "problem arranging media: %v\n", err)
os.Exit(1)
}
case "s", "survey":
args := flag.Args()
if len(args) != 1 {
fmt.Fprintf(os.Stderr, "%s\n", surveyUsage)
os.Exit(1)
}
if err := survey(args[0], f); err != nil {
fmt.Fprintf(os.Stderr, "problem surveying: %v\n", err)
os.Exit(1)
}
case "c", "cl", "clean":
args := flag.Args()
if len(args) != 1 {
+89
View File
@@ -0,0 +1,89 @@
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...)
}
+43
View File
@@ -133,6 +133,49 @@ func TestSourceSkips(t *testing.T) {
}
}
func TestSourceFiltered(t *testing.T) {
root := t.TempDir()
for _, p := range []string{
"pics/a.jpg",
"pics/b.NEF",
"pics/clip.mov",
"rips/Movie/VIDEO_TS/VTS_01_1.mp4",
"rips/film.mkv",
"rips/cover.jpg",
} {
full := filepath.Join(root, p)
if err := os.MkdirAll(filepath.Dir(full), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(full, nil, 0644); err != nil {
t.Fatal(err)
}
}
tests := []struct {
name string
f Filter
want string
}{
{"everything", Filter{}, "pics/a.jpg pics/b.NEF pics/clip.mov rips/Movie/VIDEO_TS/VTS_01_1.mp4 rips/cover.jpg rips/film.mkv"},
{"images", Filter{Classes: map[Class]bool{Image: true}}, "pics/a.jpg rips/cover.jpg"},
{"no video", Filter{Classes: map[Class]bool{Image: true, Raw: true}}, "pics/a.jpg pics/b.NEF rips/cover.jpg"},
{"exclude dir", Filter{Exclude: []string{"VIDEO_TS"}}, "pics/a.jpg pics/b.NEF pics/clip.mov rips/cover.jpg rips/film.mkv"},
{"exclude glob", Filter{Exclude: []string{"*.mkv", "rip*"}}, "pics/a.jpg pics/b.NEF pics/clip.mov"},
{"root not excluded", Filter{Exclude: []string{filepath.Base(root)}}, "pics/a.jpg pics/b.NEF pics/clip.mov rips/Movie/VIDEO_TS/VTS_01_1.mp4 rips/cover.jpg rips/film.mkv"},
}
for _, test := range tests {
var got []string
for p := range SourceFiltered(root, test.f) {
rel, _ := filepath.Rel(root, p)
got = append(got, rel)
}
if g := strings.Join(got, " "); g != test.want {
t.Errorf("%s:\n got %s\nwant %s", test.name, g, test.want)
}
}
}
// arranged returns a store with one file arranged into it, and that Media.
func arranged(t *testing.T) (string, Media) {
t.Helper()