Skip to content

Instantly share code, notes, and snippets.

@hatyuki
Last active December 5, 2016 15:29
Show Gist options
  • Save hatyuki/911568e45033902e5537 to your computer and use it in GitHub Desktop.
Save hatyuki/911568e45033902e5537 to your computer and use it in GitHub Desktop.
ファイルパスから MP3 に適切な ID3 Tag を設定する
source 'http://rubygems.org'
gem 'mercenary'
gem 'taglib-ruby'
#!/usr/bin/env ruby
require 'bundler/setup'
require 'mercenary'
require 'taglib'
def fix (basedir, options = { })
Dir.glob(File.join(basedir, '**/*.mp3')).each do |path|
regexp = Regexp.new('^(\d+)(:?\s|-)+')
attrs = { }
%i{ title album artist }.inject(path) do |memo, key|
value = File.basename(memo, '.mp3')
if key == :title && match = regexp.match(value)
attrs[:track] = match[0].to_i
value.gsub!(regexp, '')
end
attrs[key] = value
File.dirname(memo)
end
puts "Artist: #{attrs[:artist]}"
puts " Album: #{attrs[:album]}"
puts " Title: #{attrs[:title]}"
puts " Track: #{attrs[:track]}"
puts '--------------------------------------------------------------------------------'
next if options[:dryrun]
TagLib::MPEG::File.open(path) do |mp3|
tag = mp3.tag
attrs.each { |key, value| tag.send(:"#{key}=", value) }
mp3.save
end
end
end
Mercenary.program :updid3 do |program|
program.version '0.0.1'
program.description 'Update ID3 tag from file path'
program.syntax "#{$0} directory [directory ...]"
program.option :dryrun, '-n', '--dry-run', 'Perform a trial run with no changes made'
program.action do |directories, options|
if directories.empty?
puts program
else
directories.each { |directory| fix(directory, options) }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment