Last active
January 19, 2017 00:35
-
-
Save gadtfly/69c809cf604844ef9b75c00c4c975d6c to your computer and use it in GitHub Desktop.
After the fact, realized that iTunes already does what I was starting to suspect I ultimately wanted out of this, so this probably won't be any further refined. But worked for task at hand.
This file contains hidden or 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 'optparse' | |
| require 'taglib' | |
| def parse_options(argv) | |
| {dry_run: false}.tap do |options| | |
| OptionParser.new do |parser| | |
| parser.banner = "Usage: tag_renamer.rb [options] FORMAT FILES" | |
| parser.separator "" | |
| parser.separator "Example:" | |
| parser.separator " ruby tag_renamer.rb -n \"artist - title\" \"Chapo Bonus Episodes\"/*.m*" | |
| parser.separator "" | |
| parser.separator "Options:" | |
| parser.on('-n', '--dry-run', "Dry Run") do | |
| options[:dry_run] = true | |
| end | |
| parser.on('-h', '--help', "Help") do | |
| puts parser | |
| exit | |
| end | |
| end.parse! | |
| end.merge(format: argv.shift, files: argv) | |
| end | |
| # Very much not generalized | |
| def sanitize_for_filesystem(file) | |
| file.gsub(':', ' - ').gsub('/', '_') | |
| end | |
| def derive_filename(file, format) | |
| TagLib::FileRef.open(file) do |file_ref| | |
| format.gsub(/\w+/) do |word| | |
| file_ref.tag.send(word) | |
| end | |
| end | |
| end | |
| def derive_path(file, format) | |
| File.join(File.dirname(file), sanitize_for_filesystem(derive_filename(file, format)) + File.extname(file)) | |
| end | |
| def process_file(file:, format:, dry_run: true) | |
| derive_path(file, format).tap do |new_file| | |
| puts "#{file.inspect} -> #{new_file.inspect}" | |
| File.rename(file, new_file) unless dry_run | |
| end | |
| end | |
| def process_files(files:, **options) | |
| files.each {|file| process_file(options.merge(file: file)) } | |
| end | |
| process_files(parse_options(ARGV)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment