Last active
August 29, 2015 14:16
-
-
Save lesleh/90a9cd49e035cf92fe81 to your computer and use it in GitHub Desktop.
Add a music file to your music library, with the format {artist}/{album}/{track} {title}.{ext}. Automatically removes illegal filename characters.
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
| #!/usr/bin/env ruby | |
| # Ubuntu: apt-get install libtagc0-dev | |
| # gem install taglib-ruby | |
| require 'taglib' | |
| require 'fileutils' | |
| #------------------------------------------------ | |
| # Configuration | |
| #------------------------------------------------ | |
| MUSIC_DIR = File.join(ENV['HOME'], 'Music') | |
| ILLEGAL_CHARS = '\\/:*?"<>|' # Linux actually only disallows NUL and /, this is the Windows list | |
| REPLACEMENT_CHAR = '_' | |
| #------------------------------------------------ | |
| # End Configuration | |
| #------------------------------------------------ | |
| if ARGV.length == 0 | |
| STDERR.puts "No filenames specified." | |
| exit 1 | |
| end | |
| def sanitize(input) | |
| input.tr ILLEGAL_CHARS, REPLACEMENT_CHAR | |
| end | |
| ARGV.each do |filename| | |
| TagLib::FileRef.open(filename) do |fileref| | |
| if fileref.null? | |
| STDERR.puts "Skipping #{filename} due to error." | |
| next | |
| end | |
| puts "Adding #{filename}" | |
| tag = fileref.tag | |
| new_dir = File.join(MUSIC_DIR, sanitize(tag.artist), sanitize(tag.album)) | |
| new_filename = ('%02d' % tag.track) + ' ' + sanitize(tag.title) + File.extname(filename) | |
| FileUtils.mkdir_p(new_dir) unless Dir.exists?(new_dir) | |
| FileUtils.mv filename, File.join(new_dir, new_filename) | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment