Skip to content

Instantly share code, notes, and snippets.

@IceDragon200
Last active August 29, 2015 14:11
Show Gist options
  • Save IceDragon200/5ae6dd4892f8f4c40391 to your computer and use it in GitHub Desktop.
Save IceDragon200/5ae6dd4892f8f4c40391 to your computer and use it in GitHub Desktop.
Multi-archive extractor (shells out)
#!/usr/bin/env ruby
# extractall
# Because sometimes I don't feel like typing unzip or tar and just want
# to extract multiple acrhives of varying type, or I dont feel like
# mkdir-ing && doing the previous thing.
# I just wanna "Do the thing" as varrick would say ;3
require 'fileutils'
require 'optparse'
module ExtractAll
module Version
MAJOR, MINOR, TEENY, PATCH = 2, 0, 0, nil
STRING = [MAJOR, MINOR, TEENY, PATCH].compact.join('.').freeze
end
VERSION = Version::STRING
class Instance
# Controls whether this Instance is in verbose mode, which it will
# print out all debug information.
# @return [Boolean]
attr_accessor :verbose
def initialize(options = {})
@verbose = options.fetch(:verbose, false)
end
def sh(command)
puts command if @verbose
system(command)
end
end
end
options = {
verbose: false
}
argv = OptionParser.new do |opts|
opts.banner = "Usage: #{File.basename(__FILE__)} [options] [<filename>...]"
opts.on '-d', '--directory DIRNAME', String, 'set extraction directory' do |v|
options[:directory] = v
end
opts.on '-v', '--[no-]verbose', 'verbose mode' do |v|
options[:verbose] = v
end
opts.on '', '--version', 'displays version' do
puts "extractall v#{ExtractAll::VERSION}"
puts 'by IceDragon'
end
opts.on '-h', '--help', 'Display this help' do |v|
puts opts
exit
end
end.parse!
exts_ary = ['tar.gz', 'tar', 'zip', 'rar', '7z', 'iso', 'ISO']
files = argv.empty? ? Dir.glob("*.{#{exts_ary.join(",")}}") : argv.dup
exts = exts_ary.join('|').gsub('.', '\.')
FileUtils.mkdir_p(options[:directory]) if options.key?(:directory)
inst = ExtractAll::Instance.new(options)
files.each do |filename|
extname = filename.scan(/(\.(?:#{exts}))\z/).first.first
dirname = filename.gsub(/\.(?:#{exts})\z/, '')
if d = options[:directory]
dirname = File.join(d, dirname)
end
if Dir.exists?(dirname)
STDERR.puts "directory #{dirname} already exists"
else
case extname.downcase
when '.iso', '.7z'
inst.sh("7za x -o\"#{dirname}\" \"#{filename}\"", filename)
when '.tar.gz', '.tar'
FileUtils::Verbose.mkdir_p(dirname)
unless inst.sh("tar -xf \"#{filename}\" --directory=\"#{dirname}\"", filename)
FileUtils::Verbose.rm_rf(dirname)
end
when '.zip'
inst.sh("unzip -q -d \"#{dirname}\" \"#{filename}\"", filename)
when '.rar'
FileUtils::Verbose.mkdir_p(dirname)
unless inst.sh("unrar -inul x \"#{filename}\" \"#{dirname}\"", filename)
FileUtils::Verbose.rm_rf(dirname)
end
else
STDERR.puts "unhandled archive extension: #{extension}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment