class ExtensionFixer
A ruby gem to fix file extensions
Public Instance Methods
check()
click to toggle source
# File lib/extension_fixer.rb, line 7 def check # Check all files for the correct extension type walk_args do |file, right_ext| p "#{file} should have a #{right_ext} extension." end end
fix()
click to toggle source
# File lib/extension_fixer.rb, line 14 def fix # Change all files to the correct extension types walk_args do |file, right_extension| p "$ mv #{file.gsub(File.extname(file), '{\0,.' + right_extension + '}')}" File.rename file, file.ext(right_extension) end end
Private Instance Methods
correct_extension?(file)
click to toggle source
Check if the file has one of the possible extensions from mime/type
# File lib/extension_fixer.rb, line 37 def correct_extension?(file) extension = File.extname(file).delete('.') extension_by_file(file).any? do |possible_extensions| possible_extensions.extensions.include? extension end end
extension_by_file(file)
click to toggle source
Extracts the MIME::Type of a file using unix `file` command. Then reverses the mime/type to a list of possible extensions
# File lib/extension_fixer.rb, line 26 def extension_by_file(file) command = ['file', '--brief', '--mime-type', file] mimetype = IO.popen(command, in: :close, err: :close).read.chomp unless MIME::Types[mimetype].is_a? Array p "File #{file} doesn't have any setted mime/type." return [] end MIME::Types[mimetype] end
scan(path) { |path, preferred_extension| ... }
click to toggle source
Scans each file and calls `walk_directory` when presented with a directory.
# File lib/extension_fixer.rb, line 52 def scan(path, &block) if File.file?(path) && !correct_extension?(path) correct_extension = extension_by_file(path).first if correct_extension.nil? p "Skipping #{path}, unknown mimetype" else yield path, correct_extension.preferred_extension end elsif File.directory?(path) walk_directory(path, &block) end end
walk_args(&block)
click to toggle source
Calls `scan` for every argument
# File lib/extension_fixer.rb, line 45 def walk_args(&block) ARGV.each do |path_or_file| scan(path_or_file, &block) end end
walk_directory(path, &block)
click to toggle source
For each file call `scan`
# File lib/extension_fixer.rb, line 66 def walk_directory(path, &block) Dir.foreach(path) do |file| filename = File.join(path, file) next if ['.', '..'].include?(file) scan(filename, &block) end end