Search code examples
yeomanboweryeoman-generator

Yeoman custom generator - how to access the generated project in the dependencies callback


In my custom Yeoman generator I want to do some file copying only after all the Bower components have been installed. Currently, in index.js the callback looks like this:

var SiteGenerator = module.exports = function SiteGenerator(args, options, config) {
    yeoman.generators.Base.apply(this, arguments);
    this.on('end', function () {
        this.installDependencies({
            skipInstall: options['skip-install'],
            callback: function () {
                this.copy('assets/bower_components/wordpress/index.php', 'app/index.php');
            }.bind(this)
        });
    });
    this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

However, obviously this is referencing the original generator, not the site that has just been generated. The generator function in which the directory creating and copying is done is SiteGenerator.prototype.app = function app() therefore, in the installDependencies callback I have tried:

SiteGenerator.prototype.app.copy()

But this is clearly producing an error.

How can I access my newly-genetated directory after the Bower components have installed?


Solution

  • I have found that the way to access the project directory is with: process.cwd()

    Therefore, the callback function should look like:

    var fs = require('fs');
    var SiteGenerator = module.exports = function SiteGenerator(args, options, config) {
        yeoman.generators.Base.apply(this, arguments);
        this.on('end', function () {
            this.installDependencies({
                skipInstall: options['skip-install'],
                callback: function () {
                    var projectDir = process.cwd();
                    fs.createReadStream(projectDir + '/bower_components/wordpress/index.php').pipe(fs.createWriteStream(projectDir + '/app/index.php'));
                }.bind(this)
            });
        });
        this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
    };