Al Phaba
Al Phaba

Reputation: 6755

How to copy a folder with its content in ruby

I trying to copy a folder in ruby but receiving the error that "cannot copy directory to itself"

I dont understand why this happens, can someone please explain? And how can I achieve it to copy a complete folder with new name. Here is my code where i try to copy the source folder with a timestamp in its name.

$releaseFolder = 'D:\ruby_workspace\fpsupdater\release'
$frontendSubPath = '\server\pdixfrontend\tomcat\conf'
$backendSubPath = '\server\pdixbackend\tomcat\conf\Catalina'


def println(text)
  puts $timestamp.inspect + ': ' + text
end


def getFileTimestamp()
 stamp = $timestamp.inspect
 stamp.gsub!(/\s+|:|\++/,"_")
end

def backupContext()

target = @configHash["target"]

if (Dir.exists?(target))

  println("backup of target " + target)
  println("need to backup: " + target + $frontendSubPath)
  println("need to backup: " + target + $backendSubPath)
  source = "#{target}#{$frontendSubPath}"
  backup = "#{target}#{$frontendSubPath}\\" + getFileTimestamp + "_conf" 
  println(source)
  println(backup)

  FileUtils.cp_r source , backup

else
  puts "cannot backup because target does not exists"
end
end

Upvotes: 0

Views: 403

Answers (2)

lzap
lzap

Reputation: 17174

You cannot copy directory to the same directory, example:

FileUtils.cp_r "C:/TEST", "C:/TEST"

You cannot even make a recursive copy to the directory you are copying into, because then you can end up in a never ending loop!

FileUtils.cp_r "C:/TEST", "C:/TEST/SUBFOLDER"

If you need to do that, use a temporary directory and then move it back. Also optimize your code, getFileTimestamp can be much better :-)

Upvotes: 2

javier_domenech
javier_domenech

Reputation: 6253

backup = "#{target}#{$frontendSubPath}\\" + getFileTimestamp + "_conf" 

notice you r still using the frontedSubPath instead of the backendSubPath

Upvotes: 0

Related Questions