Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grunt - Can you call grunt-contrib-copy from within a custom registered task and customize the copy on the fly?

I know I can setup a task in grunt.config that will grunt-contrib-copy files from src to dest, and looking through Grunt docs I know I can copy single files using grunt.file.copy.

But, is it possible to create grunt-contrib-copy tasks on the fly in a custom registered task to accommodate arguments being sent from the bash? I want to create a new directory grunt.file.mkdir("some/path/appfoldername") and then copy files to that folder from another destination, but I won't know the folder name until after the custom task is run. So something like:

grunt create_app:appfoldername

So I could copy single files over one at a time, but the files will change so want the power of grunt-contrib-copy, but with the flexibility of a custom registered task.

I imagine something like this if my explanation isn't clear enough:

grunt.registerTask('createCopy', 'Create a copy', function(folderName) {

    var cwd = grunt.template.process("some/path/to/app");
    var src = grunt.template.process("some/path/to/src");
    var dest = grunt.template.process("some/path/to/dest") + folderName;

    grunt.task.run('copy: {  
       files: { 
          cwd: cwd,
          src: src,
          dest: dest
       }           
    }');
}

UPDATE

grunt.registerTask('mkapp', 'Create Application', function(appName) {

    // Check appName is not empty or undefined
    if(appName !== "" && appName !== undefined) { 

        // Require node path module, since not a global
        var path = require("path");

        // Resolve directory path using templates
        var relPath = grunt.template.process("<%= root %>/<%= dirs.src %>/application/");
        var srcPath = relPath + "default_install";
        var destPath = relPath + appName;

        // Create new application folder
        grunt.file.mkdir(destPath, 0444);

        // Return unique array of all file paths which match globbing pattern
        var options = { cwd: srcPath, filter: 'isFile' };
        var globPattern = "**/*"

        grunt.file.expand(options, globPattern).forEach(function(srcPathRelCwd) {

            // Copy a source file to a destination path, creating directories if necessary
            grunt.file.copy(
                path.join(srcPath, srcPathRelCwd), 
                path.join(destPath, srcPathRelCwd)
            );
        });
    }
});
like image 238
mtpultz Avatar asked Oct 31 '22 19:10

mtpultz


1 Answers

Yes. Just call grunt.file.expand on the file specs and then loop over the resulting array, copying them however you like.

grunt.file.expand(specs).forEach(function(src) {
  grunt.file.copy(src, dest);
});
like image 102
ryanb Avatar answered Nov 12 '22 12:11

ryanb