KPthunder KPthunder - 6 months ago 7x
Ruby Question

Rake - Copy only changed files

So I have a rake file like the following:

require 'fileutils'

task :copy do
FileUtils.cp_r 'src', 'target'

How can I:

  1. Only copy the files that have changed?

  2. Make the
    task have a dependency on the
    directory so that it will only launch if it needs to?
    :copy => 'src'
    :copy => FileList['src/*'].to_a
    don't seem to work.

I can take care of the first question like this:

task :copy do
sh 'rsync -ru src/* target'

I would like to, if reasonably possible, do this with only ruby / rake. This also somewhat takes care of the second question because
won't do anything if no files have changed, but I would like for the rake task to not execute at all if possible.


To avoid executing the task, Rake needs to know both the target and source and the rule for determining whether to execute the task in order to create the target from the source.

Normally that is rule is "time modified", i.e. if source is newer than target then Rake will run the task. You can modify this by providing a Proc as the source dependency. See under "Advanced Rules" (but it does take some experimentation to get your head around what is happening!).

So your task must depend on the target. If you know the target does not exist it should be easy:

task :copy => 'target/' do
  sh 'rsync -ru src/ target'  # trailing slash is significant; target will be created

If target exists already it gets much more complicated. You could define a rule for each and every file but frankly I'd just run the rsync and be done with it. Rsync is very fast on local filesystems, running it everytime is just no big deal.