Created
February 10, 2009 14:43
-
-
Save takuma104/61408 to your computer and use it in GitHub Desktop.
This file contains 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 -wKU | |
# Pure Ruby minimal .tar file un-archiver | |
class Untar | |
def initialize(file, root_directory) | |
@root = root_directory | |
@f = file | |
loop do | |
name, size = read_header | |
break if name.nil? or name.length == 0 | |
if name =~ /.*\/$/ | |
create_directory(name) | |
else | |
save_file(name, size) | |
end | |
end | |
end | |
private | |
def read_header | |
name = @f.read(100).unpack('A*')[0] | |
@f.seek(8*3, IO::SEEK_CUR) | |
size = @f.read(12).unpack('A*')[0].oct | |
@f.seek(512-100-8*3-12, IO::SEEK_CUR) | |
[name, size] | |
end | |
def create_directory(name) | |
fn = File.join(@root, name) | |
p fn | |
begin | |
Dir.mkdir(fn) | |
rescue | |
end | |
end | |
def save_file(name, size) | |
fn = File.join(@root, name) | |
p fn | |
File.open(fn, 'w') {|f| f.write(@f.read(size)) } | |
# @f.seek(size, IO::SEEK_CUR) | |
m = size % 512 | |
if m != 0 | |
@f.seek(512-m, IO::SEEK_CUR) | |
end | |
end | |
end | |
if $0 == __FILE__ | |
tar = ARGV[0] | |
dir = ARGV[1] || '/tmp' | |
File.open(tar) do |f| | |
Untar.new(f, dir) | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment