gpt4 book ai didi

Rubyzip 无法从另一个文件夹添加同名文件 [Zip::EntryExistsError]

转载 作者:行者123 更新时间:2023-12-05 07:44:01 35 4
gpt4 key购买 nike

例如使用以下测试树文件夹:

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

并从 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

失败是因为有两个文件具有相同的名称,即使它们不在同一目录中(在我的示例中为 test1)。

有什么我想念的吗?

最佳答案

感谢@simonoff ( here ),我不应该使用基本名称,而是使用完整的相对路径,这样 Rubyzip 就可以区分 test1folder2/test1.

这是修复它的代码:

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

肯定有更简洁的方法来做到这一点。

关于Rubyzip 无法从另一个文件夹添加同名文件 [Zip::EntryExistsError],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43234973/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com