7

我的目标是将一组由模式指定的文件复制到目标目录。源目录中的文件可以有子目录。

我试过了:

cp_r(Dir.glob('**/*.html'), @target_dir):

cp_r(FileList['**/*.html'], @target_dir):

但两者都不起作用。

它仅在我执行以下操作时才有效:

cp_r(Dir['.'], @target_dir):

但我只需要复制 *.html 文件而不是其他任何东西。

我需要什么

cp --parents

命令确实

使用现有的 Ruby/Rake 方法有什么建议吗?

更新看起来用 Ant 更容易做的事情,用 Ruby/Rake 堆栈是不可能的——可能我需要研究别的东西。我不想编写自定义代码以使其在 Ruby 中工作。我只是认为 Ruby/Rake 是合适的解决方案。

更新 2这就是我使用 Ant 的方式

<target name="buildeweb" description="Builds web site" depends="clean">
    <mkdir dir="${build.dir.web}" />

    <copy todir="${build.dir.web}" verbose="true">
        <fileset dir="${source.dir.web}">
            <include name="**/*.html" />
            <include name="**/*.htm" />
        </fileset>
    </copy>

    <chmod perm="a+x">
        <fileset dir="${build.dir.web}">
            <include name="**/*.html" />
            <include name="**/*.htm" />
        </fileset>
    </chmod>
</target>
4

3 回答 3

7

如果你想要纯 Ruby,你可以这样做(在标准库中 FileUtils 的帮助下)。

require 'fileutils'

Dir.glob('**/*.html').each do |file|
  dir, filename = File.dirname(file), File.basename(file)
  dest = File.join(@target_dir, dir)
  FileUtils.mkdir_p(dest)
  FileUtils.copy_file(file, File.join(dest,filename))
end
于 2012-10-01T00:05:31.240 回答
3

我没听说过cp --parents,但是如果它可以满足您的要求,那么从您的 Rakefile 中使用它就不会感到羞耻,如下所示:

system("cp --parents #{your} #{args}")
于 2012-09-30T23:49:01.720 回答
0

这可能很有用:

# copy "files" to "dest" with any sub-folders after "src_root". 
def copy_and_preserve files, dest, src_root
  files.each {|f|
    f.slice! src_root # the files without src_root dir
    dest_dir = File.dirname(File.join(dest, f))
    FileUtils.mkdir_p dest_dir # make dest dir
    FileUtils.cp(File.join(src_root, f), dest_dir, {:verbose => true})
  }
end
于 2013-07-04T02:16:46.870 回答