gruntjsgrunt-contrib-copy

Adapt dest folder to ** globbing pattern


I'm working with grunt-contrib-copy. I have this file tree:

`-- src
    `-- model
        |-- a4
        |   `-- public
        |       |-- css
        |       |-- img
        |       `-- js
        |-- posters
        |   `-- public
        |       |-- css
        |       |-- img
        |       `-- js
        `-- prints
            `-- public
                |-- css
                |-- img
                `-- js

I would like to copy the files in src/model/**/public/img to dist/images/{1}/ where {1} is the folder name (a4, posters, prints... dynamic folders that are bound to change too), so:

src/model/a4/public/img/file.png -> dist/images/a4/file.png

Is there a way to specify that with grunt-contrib-copy (maybe the rename function?) or do I have to iterate manually over the files?

Right now this is what I have:

grunt.registerTask 'images-generate', ->
gruntCopyFiles.images = {
  expand: true,
  cwd: './src/model/',
  src: ["**/public/img/*.png", "**/public/img/*.jpg"],
  dest: "./dist/images/"
}

But this copies src/model/a4/public/img/file.png to dist/images/a4/public/img/file.png which is not what I want.

Any suggestion? Thanks!


Solution

  • Is there a way to specify that with grunt-contrib-copy (maybe the rename function?) or do I have to iterate manually over the files?

    Utilizing the rename function is the way to achieve this. Glob patterns alone cannot meet your requirement, nor can the flatten option.

    Something like the following also copies any subfolders which may potentially reside inside the source img folders:

    gruntCopyFiles.images = {
        expand: true,
        cwd: 'src/model',
        dest: 'dist/images',
        src: '**/public/img/**/*.{png,jpg,gif}',
        rename: function(dest, src) {
            var items = src.split('/'),
                baseIndex = items.indexOf('img') + 1,
                subPath = items.slice(baseIndex, items.length).join('/');
    
            return [dest, items[0], subPath].join('/');
        }
    }
    

    Example:

    src/model/a4/public/img/file.png --> dist/images/a4/file.png

    src/model/a4/public/img/quux/file.jpg --> dist/images/a4/quux/file.jpg