unzip (zip, tar, tag.gz) files with ruby

前端 未结 4 1911
长发绾君心
长发绾君心 2020-12-01 00:30

I want to unzip a lot of zip files. Is there a module or script that checks which format the zip file is and decompresses it? This should work on Linux, I don\'t care about

4条回答
  •  粉色の甜心
    2020-12-01 01:00

    Draco, thx for you snippet. Some TARs encode directories as paths ending with '/' - see this Wiki. Examlple tar is Oracle Server JRE 7u80 for Windows. This will work for them:

    require 'fileutils'
    require 'rubygems/package'
    require 'zlib'
    
    TAR_LONGLINK = '././@LongLink'
    
    Gem::Package::TarReader.new( Zlib::GzipReader.open tar_gz_archive ) do |tar|
            dest = nil
            tar.each do |entry|
                if entry.full_name == TAR_LONGLINK
                    dest = File.join destination, entry.read.strip
                    next
                end
                dest ||= File.join destination, entry.full_name
                if entry.directory? || (entry.header.typeflag == '' && entry.full_name.end_with?('/'))
                    File.delete dest if File.file? dest
                    FileUtils.mkdir_p dest, :mode => entry.header.mode, :verbose => false
                elsif entry.file? || (entry.header.typeflag == '' && !entry.full_name.end_with?('/'))
                    FileUtils.rm_rf dest if File.directory? dest
                    File.open dest, "wb" do |f|
                        f.print entry.read
                    end
                    FileUtils.chmod entry.header.mode, dest, :verbose => false
                elsif entry.header.typeflag == '2' #Symlink!
                    File.symlink entry.header.linkname, dest
                else
                    puts "Unkown tar entry: #{entry.full_name} type: #{entry.header.typeflag}."
                end
                dest = nil
            end
        end
    end
    

提交回复
热议问题