Search code examples
rubyrake

Copy Folder Contents to Parent Directory in Rake (on Windows)


I have a set of files in a folder ../SomeFolder/AndAnother/dist

the dist folder contains a bunch of files and folders that I want to move up a level in a Rake task.

So

../SomeFolder/AndAnother/dist/subFolder/a.txt becomes ../SomeFolder/AndAnother/subFolder/a.txt

I can do this on linux by

task :lift_to_parent do
  sh('mv', '../SomeFolder/AndAnother/dist/*', '../SomeFolder/AndAnother')
end

but this Rake task also runs on Windows and on that OS i get Errno::EACCES: Permission denied @ unlink_internal

I'm hoping that FileUtils.mv will work on both linux and windows...

but if I

task :lift_to_parent do
  FileUtils.mv '../SomeFolder/AndAnother/dist', '../SomeFolder/AndAnother', :force => true
end

I get ArgumentError: same file: ../SomeFolder/AndAnother/dist and ../SomeFolder/AndAnother/dist so I'm clearly missing something to allow FileUtils.mv to copy up a level (or going about this the wrong way)

So, how do I fix my FileUtils version or otherwise use a Rake task to copy a folder structure to its parent?


Solution

  • I've ended up doing this

    task : lift_to_parent do
      copied_by_jenkins = '../SomeFolder/AndAnother/dist'
      copy_pattern = "#{copied_by_jenkins}/**/*"
      target_directory = '../SomeFolder/AndAnother/Public'
    
      next unless File.exists? copied_by_jenkins
    
      FileList[copy_pattern].each do |file|
        file_path = File.dirname(file).sub! copied_by_jenkins, ''
        file_name = File.basename(file)
        target_directory = File.join(target_directory, file_path)
        destination = File.join(target_directory, file_name)
    
        FileUtils.mkdir_p target_directory
        FileUtils.copy_file(file, destination) unless File.directory? file
      end
    
      FileUtils.remove copied_by_jenkins
    end
    

    but that seems like a lot of the typing to achieve my goal