简体   繁体   English

如何使用Ruby gem'zip'或'rubyzip'删除zip文件中的非空文件夹?

[英]How to delete a non-empty folder in a zip file using Ruby gem 'zip' or 'rubyzip'?

I tried to remove a non-empty folder in a zip file. 我试图删除zip文件中的非空文件夹。 I am using ruby 1.8.7 in Ubuntu 10.10. 我在Ubuntu 10.10中使用ruby 1.8.7。 I tried rubyzip gem and zip gem 我尝试了rubyzip gem和zip gem

require 'zip/zipfilesystem'
Zip::ZipFile.open('apkfile.apk') { |zfile| zfile.dir.delete('META-INF') }

it reported following error 它报告了以下错误

Errno::ENOENT: No such file or directory Errno :: ENOENT:没有这样的文件或目录

Now I could only delete every entry in the directory and the directory would be deleted finally after last file in the directory being deleted. 现在,我只能删除目录中的每个条目,并且在删除目录中的最后一个文件之后,该目录最终将被删除。

require 'zip/zipfilesystem'
Zip::ZipFile.open('apkfile.apk') do |zfile|
    zfile.file.delete("META-INF/foo1.bar") 
    zfile.file.delete("META-INF/foo2.bar")
    zfile.file.delete("META-INF/foo3.bar")
end

Is it possible to use FileUtils.rm_rf method in fileutils gem in the zip file? 是否可以在zip文件的fileutils gem中使用FileUtils.rm_rf方法?

I was slightly aghast to find that rubyzip would not do this, confounded by the fact that the more promising zipruby also has no obvious way of removing a file at all. 令我有些震惊的是,rubyzip无法做到这一点,这是因为事实是,更有前途的zipruby也根本没有明显的删除文件的方法。

On trying to implement my own recursive delete it seems there is something seriously broken in the implementation of rubyzip; 在尝试实现自己的递归删除时,似乎在rubyzip的实现中存在一些严重问题; internally it stores an @entries object in which other code, most obviously Zip::ZipFileSystem::ZipFsDir , expects to find :directory type nodes, but there are none there so it throws the not found exception. 它在内部存储一个@entries对象,其中的其他代码(最明显的是Zip::ZipFileSystem::ZipFsDir )期望找到:directory类型的节点,但是那里没有节点,因此会引发未找到的异常。 I will try and get round to posting a bug report. 我将尽力发布错误报告。

Anyway the following hack will allow you to delete a directory from a zip file using rubyzip. 无论如何,以下破解将使您能够使用rubyzip从zip文件中删除目录。 Note that by emptying a directory this way it vanishes, if you just wanted to empty it you might need to use ZipFsDir mkdir to add it back. 请注意,通过这种方式清空目录会消失,如果您只想清空该目录,则可能需要使用ZipFsDir mkdir将该目录重新添加回去。

class Zip::ZipFile
  def rm_rf(dir)
    dir_entries = self.entries.select { |e| Regexp.new("^#{File.join(dir, '/')}.*") === e.name }
    dir_entries.each { |e| self.remove(e) }
    dir_entries
  end
end

Then use: 然后使用:

Zip::ZipFile.open(path) do |a|
  a.rm_rf('directory-name')
end

to remove a directory. 删除目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM