Skip to content

Instantly share code, notes, and snippets.

@pcwalton
Created July 4, 2010 05:04
Show Gist options
  • Save pcwalton/463150 to your computer and use it in GitHub Desktop.
Save pcwalton/463150 to your computer and use it in GitHub Desktop.
(* organizemusic.ml *)
let process ~dryrun:dryrun dest_top (dirpath, _, filenames) =
Array.iter begin fun filename ->
let fullpath = Os.Path.join dirpath filename in
let tagfile =
try
Some (Taglib.open_file fullpath)
with Not_found -> None
in
Option.may begin fun tagfile ->
let artist, album, title =
Std.finally (fun() -> Taglib.close_file tagfile) begin fun() ->
Taglib.tag_artist tagfile, Taglib.tag_album tagfile,
Taglib.tag_title tagfile
end ()
in
let artist_dir = Os.Path.join dest_top artist in
let destdir = Os.Path.join artist_dir album in
try Os.makedirs destdir with Os.Io_error(Unix.EEXIST, _) -> ();
let basename = Os.Path.join destdir title in
let _, ext = Os.Path.splitext filename in
let destpath = Printf.sprintf "%s.%s" basename ext in
Printf.printf "copy %s -> %s\n" fullpath destpath;
flush stdout;
if not dryrun then Shutil.copyfile fullpath destpath
end tagfile
end filenames
in
let main() =
let op = OptParse.OptParser.make ~usage:"%prog [options] sourcedir" () in
let dryrun = OptParse.StdOpt.store_true() in
OptParse.OptParser.add op ~short_name:'d' ~long_name:"dryrun" dryrun;
let argv = OptParse.OptParser.parse_argv op in
let srcdir =
begin
if argv = [] then
OptParse.OptParser.error op "source dir must be specified"
end;
List.hd argv
in
let dryrun = OptParse.Opt.get dryrun in
Enum.iter (process ~dryrun:dryrun (Tempfile.mkdtemp())) (Os.walk srcdir)
in
main();;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment