我正在处理a Ruby script,特别是一个名为copy2tmp
的方法(复制粘贴的方法定义)
define_singleton_method(:copy2tmp) do |files|
files.each do |f|
if File.symlink?(f)
# Avoid trouble with symlink loops
# Delete old symlink if there is one, because:
# If a proper file or directory has been replaced with a symlink,
# remove the obsolete stuff.
# If there already is a symlink, delete because it might have been
# relinked.
if File.exist?("#{PARAMS[:tmpdir]}/#{f}")
FileUtils.rm("#{PARAMS[:tmpdir]}/#{f}")
end
# Create new symlink instead of copying
File.symlink("#{PARAMS[:jobpath]}/#{f}", "#{PARAMS[:tmpdir]}/#{f}")
elsif File.directory?(f)
FileUtils.mkdir_p("#{PARAMS[:tmpdir]}/#{f}")
copy2tmp(Dir.entries(f)\
.delete_if do |s| ['.', '..', ]\
.include?(s) end.map { |s| "#{f}/#{s}" })
# TODO: Is this necessary? Why not just copy? (For now, safer and more adaptable.)
else
FileUtils.cp(f,"#{PARAMS[:tmpdir]}/#{f}")
end
end
end
这似乎会创建嵌套过深的目录,从而导致错误.该脚本用于处理使用ltx2any
的LaTeX文档.当脚本试图将文件复制到临时目录时,就会出现这个问题,但最终会创建一个像../folderName/folderName/folderName/...
这样的深度嵌套 struct .
copy2tmp(Dir.entries('.').delete_if { |f| exceptions.include?(f) })
我try 了以下几点:
-
Debugging with Recursion Depth:添加了调试语句以跟踪
copy2tmp
中的递归深度.这表明,随着每次递归调用,深度增加,目录路径变长(../folderName/...
).
define_singleton_method(:copy2tmp) do |files, depth = 0|
puts "Debug: Recursion depth #{depth}, files: #{files.inspect}"
# ...
copy2tmp(Dir.entries(f).delete_if do |s| ['.', '..', ].include?(s) end.map { |s| "#{f}/#{s}" }, depth + 1)
# ...
copy2tmp(Dir.entries('.').delete_if { |f| exceptions.include?(f) }, 0)
-
Manual Inspection:判断可能导致递归循环的符号链接或异常目录 struct .没有发现任何明显的问题.我已经try 在文件夹中运行脚本,在它们的名称中有空格和没有空格.
-
Checking 100 Calls:确保使用适当的参数调用
copy2tmp
,并判断其递归调用. -
Expectation vs. Reality:我希望该脚本将文件复制到临时目录,而不会创建不必要的嵌套 struct .相反,该脚本创建了一个深度嵌套的目录路径,从而导致"没有这样的文件或目录"错误.
问题:
我怀疑问题出在copy2tmp
方法中,无论是它的定义还是它的调用方式.该方法旨在将文件复制到临时目录中,但它似乎会导致目录创建的递归循环.有人能帮助找出导致这个问题的copy2tmp
方法或它的调用中的缺陷吗?任何关于阻止这种无意的递归的见解都将不胜感激.