Created
November 1, 2010 08:59
-
-
Save denisdefreyne/657855 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'mp3info' | |
require 'yaml' | |
rule %r{^dst/.*\.mp3$} => [proc { |tn| tn.sub(/^dst\//, 'src/') }] do |t| | |
puts "*** copying #{t.source}" | |
# Copy | |
FileUtils.mkdir_p(File.dirname(t.name)) | |
FileUtils.copy_file(t.source, t.name) | |
end | |
rule %r{^dst/.*\.yaml$} => [proc { |tn| tn.sub(/^dst\//, 'src/').sub(/\.yaml$/, '.mp3') }] do |t| | |
puts "*** extracting metadata from #{t.source}" | |
# Don’t overwrite already existing metadata | |
if File.file?(t.name) | |
puts " ... skipping ..." | |
FileUtils.touch(t.name) | |
next | |
end | |
# Extract metadata | |
metadata = {} | |
Mp3Info.open(t.source, :encoding => 'utf-8') do |mp3| | |
metadata['title'] = mp3.tag.title | |
metadata['artist'] = mp3.tag.artist | |
metadata['album'] = mp3.tag.album | |
end | |
# Write extracted metadata | |
FileUtils.mkdir_p(File.dirname(t.name)) | |
File.open(t.name, 'w') { |io| io.write(YAML.dump(metadata)) } | |
end | |
# Cleanup: remove stray files in dst directory | |
task :cleanup do | |
# For each file in the dst/ dir... | |
Dir['dst/**/*.{mp3,yaml}'].each do |dst_filename| | |
# Find a matching source file | |
matching_src_filename = dst_filename.sub(/^dst\//, 'src/').sub(/\.yaml$/, '.mp3') | |
# Remove dst file if there is no matching source file | |
if !File.file?(matching_src_filename) | |
puts "removing #{dst_filename}" | |
FileUtils.rm(dst_filename) | |
# Remove empty parent directories | |
last_dirname = File.dirname(dst_filename) | |
loop do | |
# Stop if directory is not empty | |
break if Dir.entries(last_dirname).any? { |e| e != '.' && e != '..' } | |
# Remove | |
puts "removing #{last_dirname}" | |
FileUtils.rmdir(last_dirname) | |
# Continue | |
last_dirname = File.dirname(last_dirname) | |
break if last_dirname == '.' | |
end | |
end | |
end | |
end | |
# Default: copy MP3s and extra metadata | |
src_files = Dir['src/**/*.mp3'] | |
dst_files_mp3 = src_files.map { |fn| fn.sub(/^src\//, 'dst/') } | |
dst_files_yaml = dst_files_mp3.map { |fn| fn.sub(/\.mp3$/, '.yaml') } | |
task :default => (dst_files_mp3 + dst_files_yaml) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment