How can I call grunt prompt task from copy task?

425 Views Asked by At

I am using load-grunt-config and I have a simple copy task setup like this inside my Gruntfile.js,

grunt.registerTask('copy-css', 'Blah.', ['copy:css'])

And then inside my copy.js file I have this (ignore the invalid code. The copy task is working fine, I am just setting up this example).

'use strict';

module.exports = function(grunt, options) {
    if(!grunt.file.exists(foldername)) { 
        //I NEED TO RUN A PROMPT HERE BUT THIS IS NOT WORKING
        grunt.task.run('prompt:directory-exists');
    }

    return {
        'css': {
            'files': [{
            }]
        }
    };
};

My prompt task looks something like this,

'use strict';

module.exports = {
    'directory-exists': {
        'options': {
            'questions': [{
                'type': 'confirm',
                'message': 'That folder already exists. Are you sure you want to continue?',
                'choices': ['Yes (overwrite my project files)', 'No (do nothing)']
            }]
        }
    }
};

Grunt is not finding this task though, which I think has to do with how I am calling it considering I am using load-grunt-config.

2

There are 2 best solutions below

0
On BEST ANSWER

I ended up going about this differenlty. Instead of checking to see if the directory exists, I am just getting a list of the directories, passing that to the prompt question and forcing the user to choose a directory before it ever gets to the copy task.

//Get directories
var projects = grunt.file.expand({filter: "isDirectory", cwd: "project"}, ["*"]);

//Format these for grunt-prompt
grunt.option('global.project.list', projects.map(function (proj_name) { return { 'value': proj_name, 'name': proj_name}; }));

//Prompt.js
return {
    //Prompt the user to choose their directory
    'project-name': {
        'options': {
            'questions': [{
                config: 'my.selection', 
                type: 'list',
                message: 'Choose directory to copy to?', 
                choices: grunt.option('global.project.list')
            }]
        }
    }
};
0
On

If you register a task, you will have access to the tasks in grunt config (like prompt).

Here is an example of a task you can create in your Gruntfile.js:

grunt.registerTask('myowntask', 'My precious, my own task...', function(){
    // init
    var runCopy = true;

    // You'll need to retrieve or define foldername somewhere before...
    if( grunt.file.exists( foldername )) {
        // If your file exists, you call the prompt task, with the specific 'directory-exists' configuration you put in your prompt.js file
        grunt.task.call('prompt:directory-exists');
    }

}

Then, you run grunt myowntask.