简体   繁体   English

Rubyzip无法从另一个文件夹添加具有相同名称的文件[Zip :: EntryExistsError]

[英]Rubyzip fail to add a file with a same name from another folder [Zip::EntryExistsError]

Using the following test tree folder for example: 例如,使用以下测试树文件夹:

- test1
- folder2
  - test1 # This is the file rubyzip will break on.
  - test2

And copied this code from here : 并从这里复制此代码:

path = File.expand_path path
archive = File.join(__dir__, File.basename(path)) + '.zip'
FileUtils.rm archive, force: true

Zip::File.open(archive, Zip::File::CREATE) do | zipfile |
  Dir["#{path}/**/**"].reject{|f|f==archive}.each do | item |
    basename = File.basename(item)
    zipfile.add(basename, item)
  end
end

It fails because there is two files having the same name even if their are not in the same directory ( test1 in my example). 它失败是因为有两个文件具有相同的名称,即使它们不在同一目录中(在我的示例中为test1 )。

Is there something I am missing ? 有什么我想念的吗?

Thanks to @simonoff ( here ), I shouldn't use the basename but the full relative path so Rubyzip could make the difference between test1 and folder2/test1 . 感谢@simonoff( 这里 ),我不应该使用基本名称而是使用完整的相对路径,因此Rubyzip可以区分test1folder2/test1

Here is a code fixing it: 这是修复它的代码:

basename = File.basename path
dirname = File.dirname path
internal_path = path.sub %r[^#{__dir__}/], ''

archive = File.join(dirname, basename) + '.zip'
FileUtils.rm archive, force: true

Zip::File.open(archive, Zip::File::CREATE) do | zipfile |
  Dir["#{internal_path}/**/**"].map{|e|e.sub %r[^#{internal_path}/],''}.reject{|f|f==archive}.each do | item |
    zipfile.add(item, File.join(internal_path, item))
  end
end

There is certainly a much cleaner way to do it. 肯定有一个更清洁的方法来做到这一点。

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

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