<commit_before>'use strict';

var Generator = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var path = require('path');
var _ = require('lodash');

var gadget = require('../lib/util');
var drupalOrgApi = require('../lib/drupalProjectVersion');

var options = {};

module.exports = Generator.extend({
  initializing: function () {
    this.pkg = require('../../package.json');

    if (!this.options.skipWelcome) {
      this.log(yosay(
        'Welcome to ' + chalk.red.bold('Gadget ' + this.pkg.version)
        + ', the gnarly generator for Grunt Drupal Tasks!'
      ));
    }
  },

  prompting: function () {
    var self = this;

    if (this.options.hasOwnProperty('drupalDistro') && typeof self.options.drupalDistro === 'string') {
      var distros = require('../lib/distros');
      self.options.drupalDistro = distros[self.options.drupalDistro];
    }

    if (this.options.hasOwnProperty('drupal-distro') && typeof self.options['drupal-distro'] === 'string') {
      var distros = require('../lib/distros');
      self.options['drupalDistro'] = distros[self.options['drupal-distro']];
    }

    var prompts = require('../lib/prompts');
    prompts = _.filter(prompts, function (item) {
      return _.isUndefined(self.options[item.name]);
    });

    if (!self.options['cacheInternal']) {
      self.options.cacheInternal = 'database';
    }
    // The generator uses a separate options object, let's make sure it is not
    // dependent on prompt processing.
    options = self.options;

    return this.prompt(prompts).then(function (props) {
      options = _.assign(props, self.options);
      this.log("\nOk, I'm going to start assembling this project...");
    }.bind(self));
  },

  configuring: {
    // Determine the latest stable release for the requested Drupal core version.
    getDistroRelease: function () {
      if (options['offline']) {
        options.drupalDistroRelease = '0.0.0';
      }
      else {
        // Find the latest stable release for the Drupal distro version.
        var done = this.async();
        options.drupalDistro.releaseVersion(options.drupalDistroVersion, done, function(err, version, done) {
          if (err) {
            this.log.error(err);
            return done(err);
          }
          options.drupalDistroRelease = version;
          done();
        }.bind(this));
      }
    },

    cacheVersion: function() {
      if (options.cacheInternal != 'database') {
        if (options['offline']) {
          options.cacheVersion = 0;
        }
        else {
          var done = this.async();
          // the other options for cache are redis and memcache, which happen
          // to be the names of the contrib modules that integrate with them.
          drupalOrgApi.latestRelease(options.cacheInternal, options.drupalDistroVersion, done,
            function(err, version, done) {
              if (err) {
                this.log.error(err);
                return done(err);
              }
              options.cacheVersion = version.substr(4);
              done();
            }.bind(this)
          );
        }
      }
    },

    smtpVersion: function() {
      if (options.mail == 'mailhog') {
        if (options['offline']) {
          options.smtpVersion = 0;
        }
        else {
          var done = this.async();
          drupalOrgApi.latestRelease('smtp', options.drupalDistroVersion, done,
            function(err, version, done) {
              if (err) {
                this.log.error(err);
                return done(err);
              }
              options.smtpVersion = version.substr(4);

              done();
            }.bind(this)
          );
        }
      }
    },

    gdtBase: function() {
      // Load any existing composer.json now before it is overridden by template.
      this.composerOrig = this.fs.readJSON('composer.json');
      this.fs.copy(
        path.resolve(this.templatePath('gdt'), '**', '*'),
        this.destinationRoot(),
        {
          globOptions: { dot: true }
        }
      );
      this.fs.copyTpl(
        path.resolve(this.templatePath('gdt'), 'test', 'behat.yml'),
        path.resolve(this.destinationRoot(), 'test', 'behat.yml'),
        options
      );
    },

    // This has been moved up from writing because the details of some of these
    // files may need to be loaded as part of configuring other write operations,
    // and the parallelization model for generator composition requires
    // dependencies to be handled in an earlier priority context.
    distroAdditions: function () {
      var srcFiles = path.resolve(
        this.templatePath('drupal'),
        options.drupalDistro.id,
        options.drupalDistroVersion
      );

      if (gadget.fsExistsSync(srcFiles)) {
        this.fs.copy(
          path.resolve(srcFiles),
          this.destinationRoot(),
          {
            globOptions: { dot: true }
          }
        );
      }

      this.composer = options.drupalDistro.loadComposer(this, options);
    },

    // While there are write operations in this, other write operations may need
    // to examine the composer.json to determine their own configuration.
    prepareComposerJson: function () {
      var isNewProject = (this.composerOrig == undefined);
      if (!isNewProject) {
        // Use original composer file if project already generated.
        this.composer = this.composerOrig;
      }

      this.composer.name = options.projectName;
      this.composer.description = options.projectDescription;
      // Allow distros to modify the composer.json.
      if (typeof options.drupalDistro.modifyComposer == 'function') {
        var done = this.async();
        options.drupalDistro.modifyComposer(options, this.composer, isNewProject, done, function(err, result, done) {
          if (!err && result) {
            this.composer = result;
          }
          else {
            this.log.warning("Could not retrieve Octane's composer.json: "  + err);
            return done(err);
          }
          done();
        }.bind(this));
      }

      // Overwrite new project composer.json with a new core version.
      // This needs to go down here to give distros a chance to preemptively
      // modify the version of drupal/core.
      if (isNewProject) {
        // drupal/core is set, it is a real version or range and we have a
        // release version to derive something better.
        if (this.composer.require['drupal/core'] && !_.isString(this.composer.require['drupal/core']) && options.drupalDistroRelease) {
          this.composer.require['drupal/core'] = drupalOrgApi.toMinorRange(options.drupalDistroRelease);
        }
      }

      this.fs.writeJSON('composer.json', this.composer);
    }
  },

  writing: {
    projectResources: function () {
      this.fs.copy(
        this.templatePath('project/gitignore'),
        this.destinationPath('.gitignore')
      );
      this.fs.copy(
        this.templatePath('project/editorconfig'),
        this.destinationPath('.editorconfig')
      );
    },

    packageJson: function () {
      var pkg = this.fs.readJSON('package.json');

      // Inject grunt-drupal-tasks into the dependency list.
      pkg.dependencies['grunt-drupal-tasks'] = gadget.npmVersion(
        'grunt-drupal-tasks',
        '//github.com/phase2/grunt-drupal-tasks.git',
        this.options['use-master'] || this.options['offline']
      );

      pkg.name = options.projectName;
      pkg.description = options.projectDescription;

      if (!pkg['scripts']) {
        pkg.scripts = {};
      }
      if (!pkg.scripts['postinstall'] && options['themePath']) {
        pkg.scripts['postinstall'] = 'cd ' + options.themePath + ' && npm install';
      }

      this.fs.writeJSON('package.json', pkg);
    },

    gruntConfig: function () {
      var gcfg = this.fs.readJSON('Gruntconfig.json');

      if (!gcfg) {
        //TODO: throw error
      }

      // Process theme options and insert into Gruntconfig.json.
      if (options.themeName && options.themePath) {
        var themeOpts = {
          path: "<%= config.srcPaths.drupal %>/themes/" + options.themeName
        };

        if (options.themeType === 'compass') {
          themeOpts.compass = true;
        }
        else if (options.themeType === 'grunt' && options.themeGruntTask) {
          themeOpts.grunt = true;
          themeOpts.gruntTask = options.themeGruntTask;
        }

        if (options.themeScripts) {
          themeOpts.scripts = options.themeScripts;
        }

        if (!gcfg.hasOwnProperty('themes')) {
          gcfg.themes = {};
        }
        gcfg.themes[options.themeName] = themeOpts;
      }

      gcfg.project = { 'profile': options.drupalDistro.profile };
      gcfg.generated = { name: this.pkg.name, version: this.pkg.version };

      this.fs.writeJSON('Gruntconfig.json', gcfg);
    },

    readme: function () {
      if (!options['skip-readme']) {
        this.fs.copyTpl(
          this.templatePath('README.md'),
          this.destinationPath('README.md'),
          // Extracted to facilitate parallel README generation by a parent.
          gadget.tokens(options)
        );
      }
    },

    composerJson: function() {
      this.fs.writeJSON('composer.json', this.composer);
    },

    drushMakefile: function () {
      // Make files only for 7.x and less.
      var coreVersion = drupalOrgApi.numericCoreVersion(options.drupalDistroVersion);
      if (coreVersion < 8) {
        this.log('Setting up Drush makefile to install Drupal Distribution '
          + options.drupalDistro.option.name + ' version '
          + chalk.red(options.drupalDistroRelease) + '.\n');
        var done = this.async();
        options.drupalDistro.drushMakeFile(this, options, done);
      }
    }
  },

  install: function () {
    if (!options['skip-install'] && !options['offline']) {
      this.npmInstall();
    }
  },

  end: function () {
    if (!options['skipGoodbye']) {
      this.log('\nGadget has ' + chalk.red('finished')
        + ' setting up the Drupal project scaffold with Grunt Drupal Tasks!\n');
      this.log('Run `' + chalk.red('grunt')
        + '` to start the first build of this project.\n');
    }
  }
});
<commit_msg>Remove drupal/core massaging and add an organization name.<commit_after>'use strict';

var Generator = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var path = require('path');
var _ = require('lodash');

var gadget = require('../lib/util');
var drupalOrgApi = require('../lib/drupalProjectVersion');

var options = {};

module.exports = Generator.extend({
  initializing: function () {
    this.pkg = require('../../package.json');

    if (!this.options.skipWelcome) {
      this.log(yosay(
        'Welcome to ' + chalk.red.bold('Gadget ' + this.pkg.version)
        + ', the gnarly generator for Grunt Drupal Tasks!'
      ));
    }
  },

  prompting: function () {
    var self = this;

    if (this.options.hasOwnProperty('drupalDistro') && typeof self.options.drupalDistro === 'string') {
      var distros = require('../lib/distros');
      self.options.drupalDistro = distros[self.options.drupalDistro];
    }

    if (this.options.hasOwnProperty('drupal-distro') && typeof self.options['drupal-distro'] === 'string') {
      var distros = require('../lib/distros');
      self.options['drupalDistro'] = distros[self.options['drupal-distro']];
    }

    var prompts = require('../lib/prompts');
    prompts = _.filter(prompts, function (item) {
      return _.isUndefined(self.options[item.name]);
    });

    if (!self.options['cacheInternal']) {
      self.options.cacheInternal = 'database';
    }
    // The generator uses a separate options object, let's make sure it is not
    // dependent on prompt processing.
    options = self.options;

    return this.prompt(prompts).then(function (props) {
      options = _.assign(props, self.options);
      this.log("\nOk, I'm going to start assembling this project...");
    }.bind(self));
  },

  configuring: {
    // Determine the latest stable release for the requested Drupal core version.
    getDistroRelease: function () {
      if (options['offline']) {
        options.drupalDistroRelease = '0.0.0';
      }
      else {
        // Find the latest stable release for the Drupal distro version.
        var done = this.async();
        options.drupalDistro.releaseVersion(options.drupalDistroVersion, done, function(err, version, done) {
          if (err) {
            this.log.error(err);
            return done(err);
          }
          options.drupalDistroRelease = version;
          done();
        }.bind(this));
      }
    },

    cacheVersion: function() {
      if (options.cacheInternal != 'database') {
        if (options['offline']) {
          options.cacheVersion = 0;
        }
        else {
          var done = this.async();
          // the other options for cache are redis and memcache, which happen
          // to be the names of the contrib modules that integrate with them.
          drupalOrgApi.latestRelease(options.cacheInternal, options.drupalDistroVersion, done,
            function(err, version, done) {
              if (err) {
                this.log.error(err);
                return done(err);
              }
              options.cacheVersion = version.substr(4);
              done();
            }.bind(this)
          );
        }
      }
    },

    smtpVersion: function() {
      if (options.mail == 'mailhog') {
        if (options['offline']) {
          options.smtpVersion = 0;
        }
        else {
          var done = this.async();
          drupalOrgApi.latestRelease('smtp', options.drupalDistroVersion, done,
            function(err, version, done) {
              if (err) {
                this.log.error(err);
                return done(err);
              }
              options.smtpVersion = version.substr(4);

              done();
            }.bind(this)
          );
        }
      }
    },

    gdtBase: function() {
      // Load any existing composer.json now before it is overridden by template.
      this.composerOrig = this.fs.readJSON('composer.json');
      this.fs.copy(
        path.resolve(this.templatePath('gdt'), '**', '*'),
        this.destinationRoot(),
        {
          globOptions: { dot: true }
        }
      );
      this.fs.copyTpl(
        path.resolve(this.templatePath('gdt'), 'test', 'behat.yml'),
        path.resolve(this.destinationRoot(), 'test', 'behat.yml'),
        options
      );
    },

    // This has been moved up from writing because the details of some of these
    // files may need to be loaded as part of configuring other write operations,
    // and the parallelization model for generator composition requires
    // dependencies to be handled in an earlier priority context.
    distroAdditions: function () {
      var srcFiles = path.resolve(
        this.templatePath('drupal'),
        options.drupalDistro.id,
        options.drupalDistroVersion
      );

      if (gadget.fsExistsSync(srcFiles)) {
        this.fs.copy(
          path.resolve(srcFiles),
          this.destinationRoot(),
          {
            globOptions: { dot: true }
          }
        );
      }

      this.composer = options.drupalDistro.loadComposer(this, options);
    },

    // While there are write operations in this, other write operations may need
    // to examine the composer.json to determine their own configuration.
    prepareComposerJson: function () {
      var isNewProject = (this.composerOrig == undefined);
      if (!isNewProject) {
        // Use original composer file if project already generated.
        this.composer = this.composerOrig;
      }

      this.composer.name = 'organization/' + options.projectName;
      this.composer.description = options.projectDescription;
      // Allow distros to modify the composer.json.
      if (typeof options.drupalDistro.modifyComposer == 'function') {
        var done = this.async();
        options.drupalDistro.modifyComposer(options, this.composer, isNewProject, done, function(err, result, done) {
          if (!err && result) {
            this.composer = result;
          }
          else {
            this.log.warning("Could not retrieve Octane's composer.json: "  + err);
            return done(err);
          }
          done();
        }.bind(this));
      }
    }
  },

  writing: {
    projectResources: function () {
      this.fs.copy(
        this.templatePath('project/gitignore'),
        this.destinationPath('.gitignore')
      );
      this.fs.copy(
        this.templatePath('project/editorconfig'),
        this.destinationPath('.editorconfig')
      );
    },

    packageJson: function () {
      var pkg = this.fs.readJSON('package.json');

      // Inject grunt-drupal-tasks into the dependency list.
      pkg.dependencies['grunt-drupal-tasks'] = gadget.npmVersion(
        'grunt-drupal-tasks',
        '//github.com/phase2/grunt-drupal-tasks.git',
        this.options['use-master'] || this.options['offline']
      );

      pkg.name = options.projectName;
      pkg.description = options.projectDescription;

      if (!pkg['scripts']) {
        pkg.scripts = {};
      }
      if (!pkg.scripts['postinstall'] && options['themePath']) {
        pkg.scripts['postinstall'] = 'cd ' + options.themePath + ' && npm install';
      }

      this.fs.writeJSON('package.json', pkg);
    },

    gruntConfig: function () {
      var gcfg = this.fs.readJSON('Gruntconfig.json');

      if (!gcfg) {
        //TODO: throw error
      }

      // Process theme options and insert into Gruntconfig.json.
      if (options.themeName && options.themePath) {
        var themeOpts = {
          path: "<%= config.srcPaths.drupal %>/themes/" + options.themeName
        };

        if (options.themeType === 'compass') {
          themeOpts.compass = true;
        }
        else if (options.themeType === 'grunt' && options.themeGruntTask) {
          themeOpts.grunt = true;
          themeOpts.gruntTask = options.themeGruntTask;
        }

        if (options.themeScripts) {
          themeOpts.scripts = options.themeScripts;
        }

        if (!gcfg.hasOwnProperty('themes')) {
          gcfg.themes = {};
        }
        gcfg.themes[options.themeName] = themeOpts;
      }

      gcfg.project = { 'profile': options.drupalDistro.profile };
      gcfg.generated = { name: this.pkg.name, version: this.pkg.version };

      this.fs.writeJSON('Gruntconfig.json', gcfg);
    },

    readme: function () {
      if (!options['skip-readme']) {
        this.fs.copyTpl(
          this.templatePath('README.md'),
          this.destinationPath('README.md'),
          // Extracted to facilitate parallel README generation by a parent.
          gadget.tokens(options)
        );
      }
    },

    composerJson: function() {
      this.fs.writeJSON('composer.json', this.composer);
    },

    drushMakefile: function () {
      // Make files only for 7.x and less.
      var coreVersion = drupalOrgApi.numericCoreVersion(options.drupalDistroVersion);
      if (coreVersion < 8) {
        this.log('Setting up Drush makefile to install Drupal Distribution '
          + options.drupalDistro.option.name + ' version '
          + chalk.red(options.drupalDistroRelease) + '.\n');
        var done = this.async();
        options.drupalDistro.drushMakeFile(this, options, done);
      }
    }
  },

  install: function () {
    if (!options['skip-install'] && !options['offline']) {
      this.npmInstall();
    }
  },

  end: function () {
    if (!options['skipGoodbye']) {
      this.log('\nGadget has ' + chalk.red('finished')
        + ' setting up the Drupal project scaffold with Grunt Drupal Tasks!\n');
      this.log('Run `' + chalk.red('grunt')
        + '` to start the first build of this project.\n');
    }
  }
});
<|endoftext|>


<commit_before>'use strict';

const yeoman = require('yeoman-generator');

module.exports = yeoman.Base.extend({
  prompting() {
    const done = this.async();
    this.prompt([
      {
        type: 'input',
        name: 'name',
        message: 'Your project name',
        // Defaults to the project's folder name if not specified
        default: this.appname,
      },
      {
        type: 'input',
        name: 'description',
        message: 'Please enter a description for your project',
        default: 'mobx is the best!',
      },
      {
        type: 'list',
        name: 'language',
        message: 'Which language would you like to use?',
        default: 'es2015',
        choices: [
          {
            name: 'ES2015',
            value: 'es2015',
            short: 'es2015',
          },
          {
            name: 'TypeScript',
            value: 'ts',
            short: 'ts',
          },
        ],
      },
      {
        type: 'confirm',
        name: 'installDeps',
        message: 'Would you like to install all dependencies now?',
        default: false,
      },
    ], (answers) => {
      this.props = answers;
      done();
    });
  },

  writing() {
    const baseDevDeps = [
      /* eslint-disable quotes */
      `"clean-webpack-plugin": "^0.1.8"`,
      `"css-loader": "^0.23.0"`,
      `"eslint": "^2.5.0"`,
      `"eslint-plugin-react": "^4.2.0"`,
      `"extract-text-webpack-plugin": "^1.0.0"`,
      `"file-loader": "^0.8.5"`,
      `"html-webpack-plugin": "^2.15.0"`,
      `"npm-install-webpack-plugin": "^3.0.0"`,
      `"rimraf": "^2.5.0"`,
      `"style-loader": "^0.13.0"`,
      `"url-loader": "^0.5.0"`,
      `"webpack": "^1.12.0"`,
      `"webpack-dev-server": "^1.14.1"`,
      `"webpack-merge": "^0.8.4"`,
      /* eslint-enable quotes */
    ];

    const devDeps = (function buildPackageDeps(commonDeps, language) {
      let fullDeps;
      if (language === 'es2015') {
        fullDeps = commonDeps.concat(
          [
            /* eslint-disable quotes */
            `"babel-cli": "^6.0.0"`,
            `"babel-eslint": "^6.0.0"`,
            `"babel-loader": "^6.0.0"`,
            `"babel-plugin-array-includes": "^2.0.0"`,
            `"babel-plugin-transform-decorators-legacy": "^1.0.0"`,
            `"babel-plugin-transform-object-assign": "^6.0.0"`,
            `"babel-preset-es2015": "^6.0.0"`,
            `"babel-preset-react": "^6.0.0"`,
            `"babel-preset-react-hmre": "^1.0.0"`,
            `"babel-preset-stage-1": "^6.0.0"`,
            `"eslint-config-airbnb": "^6.0.0"`,
            /* eslint-enable quotes */
          ]
        );
      } else if (language === 'ts') {
        fullDeps = commonDeps.concat(
          [
            /* eslint-disable quotes */
            `"ts-loader": "^0.8.0"`,
            `"typescript": "^1.8.0"`,
            `"typings": "^0.7.0"`,
            /* eslint-enable quotes */
          ]
        );
      } else {
        throw new Error('No language was specified!');
      }

      // sort in alphabetical order and then join into a JSON-friendly string to be inserted
      // in `package.json`
      return fullDeps.sort().join(`,\n    `);
    }(baseDevDeps, this.props.language));

    // Package.json
    this.fs.copyTpl(
      this.templatePath('_package.json'),
      this.destinationPath('package.json'), {
        name: this.props.name,
        description: this.props.description,
        devDeps,
      }
    );

    // .gitignore
    this.fs.copy(
      this.templatePath('_gitignore'),
      this.destinationPath('.gitignore')
    );

    // set up eslint if using es2015
    if (this.props.language === 'es2015') {
      this.fs.copy(
        this.templatePath('_eslintrc.js'),
        this.destinationPath('.eslintrc.js')
      );
    }

    // webpack config
    this.fs.copyTpl(
      this.templatePath('_webpack.config.js'),
      this.destinationPath('webpack.config.js'),
      {
        name: this.props.name,
        language: this.props.language,
      }
    );

    // copy app src, dependent on language choice
    this.fs.copyTpl(
      this.templatePath(`src_${this.props.language === 'es2015' ? 'es2015' : 'ts'}`),
      this.destinationPath('src'),
      {
        name: this.props.name,
        description: this.props.description,
      }
    );

    if (this.props.language === 'ts') {
      // basic tsconfig.json
      this.fs.copy(
        this.templatePath('_tsconfig.json'),
        this.destinationPath('tsconfig.json')
      );
    }
  },

  install() {
    if (this.props.installDeps) {
      this.npmInstall(null, null, () => {
        if (this.props.language === 'ts') {
          this.spawnCommandSync('./node_modules/.bin/typings', ['init']);
          this.spawnCommandSync('./node_modules/.bin/typings',
            ['install', 'react', '--ambient', '--save']
          );
          this.spawnCommandSync('./node_modules/.bin/typings',
            ['install', 'react-dom', '--ambient', '--save']
          );
        }
      });
    } else {
      this.log(`Skipping the install step. Run \`npm install\` inside the project root when
        you're ready.`);
    }
  },
});
<commit_msg>Roll back `npm-install-webpack-plugin` version<commit_after>'use strict';

const yeoman = require('yeoman-generator');

module.exports = yeoman.Base.extend({
  prompting() {
    const done = this.async();
    this.prompt([
      {
        type: 'input',
        name: 'name',
        message: 'Your project name',
        // Defaults to the project's folder name if not specified
        default: this.appname,
      },
      {
        type: 'input',
        name: 'description',
        message: 'Please enter a description for your project',
        default: 'mobx is the best!',
      },
      {
        type: 'list',
        name: 'language',
        message: 'Which language would you like to use?',
        default: 'es2015',
        choices: [
          {
            name: 'ES2015',
            value: 'es2015',
            short: 'es2015',
          },
          {
            name: 'TypeScript',
            value: 'ts',
            short: 'ts',
          },
        ],
      },
      {
        type: 'confirm',
        name: 'installDeps',
        message: 'Would you like to install all dependencies now?',
        default: false,
      },
    ], (answers) => {
      this.props = answers;
      done();
    });
  },

  writing() {
    const baseDevDeps = [
      /* eslint-disable quotes */
      `"clean-webpack-plugin": "^0.1.8"`,
      `"css-loader": "^0.23.0"`,
      `"eslint": "^2.5.0"`,
      `"eslint-plugin-react": "^4.2.0"`,
      `"extract-text-webpack-plugin": "^1.0.0"`,
      `"file-loader": "^0.8.5"`,
      `"html-webpack-plugin": "^2.15.0"`,
      `"npm-install-webpack-plugin": "3.0.0"`,
      `"rimraf": "^2.5.0"`,
      `"style-loader": "^0.13.0"`,
      `"url-loader": "^0.5.0"`,
      `"webpack": "^1.12.0"`,
      `"webpack-dev-server": "^1.14.1"`,
      `"webpack-merge": "^0.8.4"`,
      /* eslint-enable quotes */
    ];

    const devDeps = (function buildPackageDeps(commonDeps, language) {
      let fullDeps;
      if (language === 'es2015') {
        fullDeps = commonDeps.concat(
          [
            /* eslint-disable quotes */
            `"babel-cli": "^6.0.0"`,
            `"babel-eslint": "^6.0.0"`,
            `"babel-loader": "^6.0.0"`,
            `"babel-plugin-array-includes": "^2.0.0"`,
            `"babel-plugin-transform-decorators-legacy": "^1.0.0"`,
            `"babel-plugin-transform-object-assign": "^6.0.0"`,
            `"babel-preset-es2015": "^6.0.0"`,
            `"babel-preset-react": "^6.0.0"`,
            `"babel-preset-react-hmre": "^1.0.0"`,
            `"babel-preset-stage-1": "^6.0.0"`,
            `"eslint-config-airbnb": "^6.0.0"`,
            /* eslint-enable quotes */
          ]
        );
      } else if (language === 'ts') {
        fullDeps = commonDeps.concat(
          [
            /* eslint-disable quotes */
            `"ts-loader": "^0.8.0"`,
            `"typescript": "^1.8.0"`,
            `"typings": "^0.7.0"`,
            /* eslint-enable quotes */
          ]
        );
      } else {
        throw new Error('No language was specified!');
      }

      // sort in alphabetical order and then join into a JSON-friendly string to be inserted
      // in `package.json`
      return fullDeps.sort().join(`,\n    `);
    }(baseDevDeps, this.props.language));

    // Package.json
    this.fs.copyTpl(
      this.templatePath('_package.json'),
      this.destinationPath('package.json'), {
        name: this.props.name,
        description: this.props.description,
        devDeps,
      }
    );

    // .gitignore
    this.fs.copy(
      this.templatePath('_gitignore'),
      this.destinationPath('.gitignore')
    );

    // set up eslint if using es2015
    if (this.props.language === 'es2015') {
      this.fs.copy(
        this.templatePath('_eslintrc.js'),
        this.destinationPath('.eslintrc.js')
      );
    }

    // webpack config
    this.fs.copyTpl(
      this.templatePath('_webpack.config.js'),
      this.destinationPath('webpack.config.js'),
      {
        name: this.props.name,
        language: this.props.language,
      }
    );

    // copy app src, dependent on language choice
    this.fs.copyTpl(
      this.templatePath(`src_${this.props.language === 'es2015' ? 'es2015' : 'ts'}`),
      this.destinationPath('src'),
      {
        name: this.props.name,
        description: this.props.description,
      }
    );

    if (this.props.language === 'ts') {
      // basic tsconfig.json
      this.fs.copy(
        this.templatePath('_tsconfig.json'),
        this.destinationPath('tsconfig.json')
      );
    }
  },

  install() {
    if (this.props.installDeps) {
      this.npmInstall(null, null, () => {
        if (this.props.language === 'ts') {
          this.spawnCommandSync('./node_modules/.bin/typings', ['init']);
          this.spawnCommandSync('./node_modules/.bin/typings',
            ['install', 'react', '--ambient', '--save']
          );
          this.spawnCommandSync('./node_modules/.bin/typings',
            ['install', 'react-dom', '--ambient', '--save']
          );
        }
      });
    } else {
      this.log(`Skipping the install step. Run \`npm install\` inside the project root when
        you're ready.`);
    }
  },
});
<|endoftext|>


<commit_before>'use strict';

var Generator = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var path = require('path');
var _ = require('lodash');

var gadget = require('../lib/util');
var drupalOrgApi = require('../lib/drupalProjectVersion');

var options = {};

module.exports = Generator.extend({
  initializing: function () {
    this.pkg = require('../../package.json');

    if (!this.options.skipWelcome) {
      this.log(yosay(
        'Welcome to ' + chalk.red.bold('Gadget ' + this.pkg.version)
        + ', the gnarly generator for Grunt Drupal Tasks!'
      ));
    }
  },

  prompting: function () {
    var self = this;

    if (this.options.hasOwnProperty('drupalDistro') && typeof self.options.drupalDistro === 'string') {
      var distros = require('../lib/distros');
      self.options.drupalDistro = distros[self.options.drupalDistro];
    }

    if (this.options.hasOwnProperty('drupal-distro') && typeof self.options['drupal-distro'] === 'string') {
      var distros = require('../lib/distros');
      self.options['drupalDistro'] = distros[self.options['drupal-distro']];
    }

    var prompts = require('../lib/prompts');
    prompts = _.filter(prompts, function (item) {
      return _.isUndefined(self.options[item.name]);
    });

    if (!self.options['cacheInternal']) {
      self.options.cacheInternal = 'database';
    }
    // The generator uses a separate options object, let's make sure it is not
    // dependent on prompt processing.
    options = self.options;

    return this.prompt(prompts).then(function (props) {
      options = _.assign(props, self.options);
      this.log("\nOk, I'm going to start assembling this project...");
    }.bind(self));
  },

  configuring: {
    // Determine the latest stable release for the requested Drupal core version.
    getDistroRelease: function () {
      if (options['offline']) {
        options.drupalDistroRelease = '0.0.0';
      }
      else {
        // Find the latest stable release for the Drupal distro version.
        var done = this.async();
        options.drupalDistro.releaseVersion(options.drupalDistroVersion, done, function(err, version, done) {
          if (err) {
            this.log.error(err);
            return done(err);
          }
          options.drupalDistroRelease = version;
          done();
        }.bind(this));
      }
    },

    cacheVersion: function() {
      if (options.cacheInternal != 'database') {
        if (options['offline']) {
          options.cacheVersion = 0;
        }
        else {
          var done = this.async();
          // the other options for cache are redis and memcache, which happen
          // to be the names of the contrib modules that integrate with them.
          drupalOrgApi.latestRelease(options.cacheInternal, options.drupalDistroVersion, done,
            function(err, version, done) {
              if (err) {
                this.log.error(err);
                return done(err);
              }
              options.cacheVersion = version.substr(4);
              done();
            }.bind(this)
          );
        }
      }
    },

    smtpVersion: function() {
      if (options.mail == 'mailhog') {
        if (options['offline']) {
          options.smtpVersion = 0;
        }
        else {
          var done = this.async();
          drupalOrgApi.latestRelease('smtp', options.drupalDistroVersion, done,
            function(err, version, done) {
              if (err) {
                this.log.error(err);
                return done(err);
              }
              options.smtpVersion = version.substr(4);

              done();
            }.bind(this)
          );
        }
      }
    },

    gdtBase: function() {
      // Load any existing composer.json now before it is overridden by template.
      this.composerOrig = this.fs.readJSON('composer.json');
      this.fs.copy(
        path.resolve(this.templatePath('gdt'), '**', '*'),
        this.destinationRoot(),
        {
          globOptions: { dot: true }
        }
      );
      this.fs.copyTpl(
        path.resolve(this.templatePath('gdt'), 'test', 'behat.yml'),
        path.resolve(this.destinationRoot(), 'test', 'behat.yml'),
        options
      );
    },

    // This has been moved up from writing because the details of some of these
    // files may need to be loaded as part of configuring other write operations,
    // and the parallelization model for generator composition requires
    // dependencies to be handled in an earlier priority context.
    distroAdditions: function () {
      var srcFiles = path.resolve(
        this.templatePath('drupal'),
        options.drupalDistro.id,
        options.drupalDistroVersion
      );

      if (gadget.fsExistsSync(srcFiles)) {
        this.fs.copy(
          path.resolve(srcFiles),
          this.destinationRoot(),
          {
            globOptions: { dot: true }
          }
        );
      }

      this.composer = options.drupalDistro.loadComposer(this, options);
    },

    // While there are write operations in this, other write operations may need
    // to examine the composer.json to determine their own configuration.
    prepareComposerJson: function () {
      var isNewProject = (this.composerOrig == undefined);
      if (!isNewProject) {
        // Use original composer file if project already generated.
        this.composer = this.composerOrig;
      }

      this.composer.name = 'organization/' + options.projectName;
      this.composer.description = options.projectDescription;
      // Allow distros to modify the composer.json.
      if (typeof options.drupalDistro.modifyComposer == 'function') {
        var done = this.async();
        options.drupalDistro.modifyComposer(options, this.composer, isNewProject, done, function(err, result, done) {
          if (!err && result) {
            this.composer = result;
          }
          else {
            this.log.warning("Could not retrieve Octane's composer.json: "  + err);
            return done(err);
          }
          done();
        }.bind(this));
      }
    }
  },

  writing: {
    projectResources: function () {
      this.fs.copy(
        this.templatePath('project/gitignore'),
        this.destinationPath('.gitignore')
      );
      this.fs.copy(
        this.templatePath('project/editorconfig'),
        this.destinationPath('.editorconfig')
      );
    },

    packageJson: function () {
      var pkg = this.fs.readJSON('package.json');

      // Inject grunt-drupal-tasks into the dependency list.
      pkg.dependencies['grunt-drupal-tasks'] = gadget.npmVersion(
        'grunt-drupal-tasks',
        '//github.com/phase2/grunt-drupal-tasks.git',
        this.options['use-master'] || this.options['offline']
      );

      pkg.name = options.projectName;
      pkg.description = options.projectDescription;

      if (!pkg['scripts']) {
        pkg.scripts = {};
      }
      if (!pkg.scripts['postinstall'] && options['themePath']) {
        pkg.scripts['postinstall'] = 'cd ' + options.themePath + ' && npm install';
      }

      this.fs.writeJSON('package.json', pkg);
    },

    gruntConfig: function () {
      var gcfg = this.fs.readJSON('Gruntconfig.json');

      if (!gcfg) {
        //TODO: throw error
      }

      // Process theme options and insert into Gruntconfig.json.
      if (options.themeName && options.themePath) {
        var themeOpts = {
          path: "<%= config.srcPaths.drupal %>/themes/" + options.themeName
        };

        if (options.themeType === 'compass') {
          themeOpts.compass = true;
        }
        else if (options.themeType === 'grunt' && options.themeGruntTask) {
          themeOpts.grunt = true;
          themeOpts.gruntTask = options.themeGruntTask;
        }

        if (options.themeScripts) {
          themeOpts.scripts = options.themeScripts;
        }

        if (!gcfg.hasOwnProperty('themes')) {
          gcfg.themes = {};
        }
        gcfg.themes[options.themeName] = themeOpts;
      }

      gcfg.project = { 'profile': options.drupalDistro.profile };
      gcfg.generated = { name: this.pkg.name, version: this.pkg.version };

      this.fs.writeJSON('Gruntconfig.json', gcfg);
    },

    readme: function () {
      if (!options['skip-readme']) {
        this.fs.copyTpl(
          this.templatePath('README.md'),
          this.destinationPath('README.md'),
          // Extracted to facilitate parallel README generation by a parent.
          gadget.tokens(options)
        );
      }
    },

    composerJson: function() {
      this.fs.writeJSON('composer.json', this.composer);
    },

    drushMakefile: function () {
      // Make files only for 7.x and less.
      var coreVersion = drupalOrgApi.numericCoreVersion(options.drupalDistroVersion);
      if (coreVersion < 8) {
        this.log('Setting up Drush makefile to install Drupal Distribution '
          + options.drupalDistro.option.name + ' version '
          + chalk.red(options.drupalDistroRelease) + '.\n');
        var done = this.async();
        options.drupalDistro.drushMakeFile(this, options, done);
      }
    }
  },

  install: function () {
    if (!options['skip-install'] && !options['offline']) {
      this.npmInstall();
    }
  },

  end: function () {
    if (!options['skipGoodbye']) {
      this.log('\nGadget has ' + chalk.red('finished')
        + ' setting up the Drupal project scaffold with Grunt Drupal Tasks!\n');
      this.log('Run `' + chalk.red('grunt')
        + '` to start the first build of this project.\n');
    }
  }
});
<commit_msg>Standardize path to theme for Gruntconfig.json and package.json<commit_after>'use strict';

var Generator = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var path = require('path');
var _ = require('lodash');

var gadget = require('../lib/util');
var drupalOrgApi = require('../lib/drupalProjectVersion');

var options = {};

module.exports = Generator.extend({
  initializing: function () {
    this.pkg = require('../../package.json');

    if (!this.options.skipWelcome) {
      this.log(yosay(
        'Welcome to ' + chalk.red.bold('Gadget ' + this.pkg.version)
        + ', the gnarly generator for Grunt Drupal Tasks!'
      ));
    }
  },

  prompting: function () {
    var self = this;

    if (this.options.hasOwnProperty('drupalDistro') && typeof self.options.drupalDistro === 'string') {
      var distros = require('../lib/distros');
      self.options.drupalDistro = distros[self.options.drupalDistro];
    }

    if (this.options.hasOwnProperty('drupal-distro') && typeof self.options['drupal-distro'] === 'string') {
      var distros = require('../lib/distros');
      self.options['drupalDistro'] = distros[self.options['drupal-distro']];
    }

    var prompts = require('../lib/prompts');
    prompts = _.filter(prompts, function (item) {
      return _.isUndefined(self.options[item.name]);
    });

    if (!self.options['cacheInternal']) {
      self.options.cacheInternal = 'database';
    }
    // The generator uses a separate options object, let's make sure it is not
    // dependent on prompt processing.
    options = self.options;

    return this.prompt(prompts).then(function (props) {
      options = _.assign(props, self.options);
      this.log("\nOk, I'm going to start assembling this project...");
    }.bind(self));
  },

  configuring: {
    // Determine the latest stable release for the requested Drupal core version.
    getDistroRelease: function () {
      if (options['offline']) {
        options.drupalDistroRelease = '0.0.0';
      }
      else {
        // Find the latest stable release for the Drupal distro version.
        var done = this.async();
        options.drupalDistro.releaseVersion(options.drupalDistroVersion, done, function(err, version, done) {
          if (err) {
            this.log.error(err);
            return done(err);
          }
          options.drupalDistroRelease = version;
          done();
        }.bind(this));
      }
    },

    cacheVersion: function() {
      if (options.cacheInternal != 'database') {
        if (options['offline']) {
          options.cacheVersion = 0;
        }
        else {
          var done = this.async();
          // the other options for cache are redis and memcache, which happen
          // to be the names of the contrib modules that integrate with them.
          drupalOrgApi.latestRelease(options.cacheInternal, options.drupalDistroVersion, done,
            function(err, version, done) {
              if (err) {
                this.log.error(err);
                return done(err);
              }
              options.cacheVersion = version.substr(4);
              done();
            }.bind(this)
          );
        }
      }
    },

    smtpVersion: function() {
      if (options.mail == 'mailhog') {
        if (options['offline']) {
          options.smtpVersion = 0;
        }
        else {
          var done = this.async();
          drupalOrgApi.latestRelease('smtp', options.drupalDistroVersion, done,
            function(err, version, done) {
              if (err) {
                this.log.error(err);
                return done(err);
              }
              options.smtpVersion = version.substr(4);

              done();
            }.bind(this)
          );
        }
      }
    },

    gdtBase: function() {
      // Load any existing composer.json now before it is overridden by template.
      this.composerOrig = this.fs.readJSON('composer.json');
      this.fs.copy(
        path.resolve(this.templatePath('gdt'), '**', '*'),
        this.destinationRoot(),
        {
          globOptions: { dot: true }
        }
      );
      this.fs.copyTpl(
        path.resolve(this.templatePath('gdt'), 'test', 'behat.yml'),
        path.resolve(this.destinationRoot(), 'test', 'behat.yml'),
        options
      );
    },

    // This has been moved up from writing because the details of some of these
    // files may need to be loaded as part of configuring other write operations,
    // and the parallelization model for generator composition requires
    // dependencies to be handled in an earlier priority context.
    distroAdditions: function () {
      var srcFiles = path.resolve(
        this.templatePath('drupal'),
        options.drupalDistro.id,
        options.drupalDistroVersion
      );

      if (gadget.fsExistsSync(srcFiles)) {
        this.fs.copy(
          path.resolve(srcFiles),
          this.destinationRoot(),
          {
            globOptions: { dot: true }
          }
        );
      }

      this.composer = options.drupalDistro.loadComposer(this, options);
    },

    // While there are write operations in this, other write operations may need
    // to examine the composer.json to determine their own configuration.
    prepareComposerJson: function () {
      var isNewProject = (this.composerOrig == undefined);
      if (!isNewProject) {
        // Use original composer file if project already generated.
        this.composer = this.composerOrig;
      }

      this.composer.name = 'organization/' + options.projectName;
      this.composer.description = options.projectDescription;
      // Allow distros to modify the composer.json.
      if (typeof options.drupalDistro.modifyComposer == 'function') {
        var done = this.async();
        options.drupalDistro.modifyComposer(options, this.composer, isNewProject, done, function(err, result, done) {
          if (!err && result) {
            this.composer = result;
          }
          else {
            this.log.warning("Could not retrieve Octane's composer.json: "  + err);
            return done(err);
          }
          done();
        }.bind(this));
      }
    }
  },

  writing: {
    projectResources: function () {
      this.fs.copy(
        this.templatePath('project/gitignore'),
        this.destinationPath('.gitignore')
      );
      this.fs.copy(
        this.templatePath('project/editorconfig'),
        this.destinationPath('.editorconfig')
      );
    },

    packageJson: function () {
      var pkg = this.fs.readJSON('package.json');

      // Inject grunt-drupal-tasks into the dependency list.
      pkg.dependencies['grunt-drupal-tasks'] = gadget.npmVersion(
        'grunt-drupal-tasks',
        '//github.com/phase2/grunt-drupal-tasks.git',
        this.options['use-master'] || this.options['offline']
      );

      pkg.name = options.projectName;
      pkg.description = options.projectDescription;

      if (!pkg['scripts']) {
        pkg.scripts = {};
      }
      if (!pkg.scripts['postinstall'] && options['themePath']) {
        pkg.scripts['postinstall'] = 'cd ' + path.join(options.themePath, options.themeName) + ' && npm install';
      }

      this.fs.writeJSON('package.json', pkg);
    },

    gruntConfig: function () {
      var gcfg = this.fs.readJSON('Gruntconfig.json');

      if (!gcfg) {
        //TODO: throw error
      }

      // Process theme options and insert into Gruntconfig.json.
      if (options.themeName && options.themePath) {
        var themeOpts = {
          path: path.join(options.themePath, options.themeName)
        };

        if (options.themeType === 'compass') {
          themeOpts.compass = true;
        }
        else if (options.themeType === 'grunt' && options.themeGruntTask) {
          themeOpts.grunt = true;
          themeOpts.gruntTask = options.themeGruntTask;
        }

        if (options.themeScripts) {
          themeOpts.scripts = options.themeScripts;
        }

        if (!gcfg.hasOwnProperty('themes')) {
          gcfg.themes = {};
        }
        gcfg.themes[options.themeName] = themeOpts;
      }

      gcfg.project = { 'profile': options.drupalDistro.profile };
      gcfg.generated = { name: this.pkg.name, version: this.pkg.version };

      this.fs.writeJSON('Gruntconfig.json', gcfg);
    },

    readme: function () {
      if (!options['skip-readme']) {
        this.fs.copyTpl(
          this.templatePath('README.md'),
          this.destinationPath('README.md'),
          // Extracted to facilitate parallel README generation by a parent.
          gadget.tokens(options)
        );
      }
    },

    composerJson: function() {
      this.fs.writeJSON('composer.json', this.composer);
    },

    drushMakefile: function () {
      // Make files only for 7.x and less.
      var coreVersion = drupalOrgApi.numericCoreVersion(options.drupalDistroVersion);
      if (coreVersion < 8) {
        this.log('Setting up Drush makefile to install Drupal Distribution '
          + options.drupalDistro.option.name + ' version '
          + chalk.red(options.drupalDistroRelease) + '.\n');
        var done = this.async();
        options.drupalDistro.drushMakeFile(this, options, done);
      }
    }
  },

  install: function () {
    if (!options['skip-install'] && !options['offline']) {
      this.npmInstall();
    }
  },

  end: function () {
    if (!options['skipGoodbye']) {
      this.log('\nGadget has ' + chalk.red('finished')
        + ' setting up the Drupal project scaffold with Grunt Drupal Tasks!\n');
      this.log('Run `' + chalk.red('grunt')
        + '` to start the first build of this project.\n');
    }
  }
});
<|endoftext|>


<commit_before>import { peerSocket } from 'messaging'
import { readFileSync, writeFileSync } from 'fs'
export { Conditions } from './common'

let weather = undefined

const WEATHER_DATA_FILE = "276e3d15-ffae-4a07-bda5-f1851e68cc77" // should be a unique name

const promises = {}
const requests = []

const readWeatherFile = () => {
  try {
    weather = readFileSync(WEATHER_DATA_FILE, 'cbor')
  } catch (n) {
    weather = undefined
  }
}

const writeWeatherFile = () => {
  try {
    writeFileSync(WEATHER_DATA_FILE, weather, 'cbor')
  } catch (n) {
  }
}

const sendRequest = (r) => {
  if (peerSocket.readyState === peerSocket.OPEN) {
    peerSocket.send(r);
  } else {
    requests.push(r);
  }
}

peerSocket.addEventListener('message', (evt) => {
  const { weather_message_id, data, error } = evt.data
  if (weather_message_id) {
    const promise = promises[weather_message_id]
    if (error) {
      promise.reject(error)
    }
    else {
      weather = data
      weather.timestamp = Date.now()
      writeWeatherFile()
      promise.resolve(weather)
    }
    delete promises[weather_message_id]
  }
})

peerSocket.addEventListener('open', (evt) => {
  setTimeout(() => {
    requests.forEach(r => sendRequest(r))
    requests.length = 0
  }, 500);
})

peerSocket.addEventListener('error', (err) => {
  console.log("Connection error: " + err.message)
  // I don't know what to do in this case yet... Notify every promises object ?
})

export const fetch = (maximumAge = 0) => {

  if (weather === undefined) {
    readWeatherFile()
  }

  return new Promise((resolve, reject) => {
    const now = Date.now()
    if (weather && (now - weather.timestamp < maximumAge)) {
      resolve(weather)
    }
    else {
      promises[now] = { resolve, reject }
      sendRequest({ weather_message_id : now })
    }
  })
}

export const get = () => {
  if(weather === undefined) {
    readWeatherFile()
  }
  return weather
}<commit_msg>init weather with empty data if the file is not found<commit_after>import { peerSocket } from 'messaging'
import { readFileSync, writeFileSync } from 'fs'
export { Conditions } from './common'

let weather = undefined

const WEATHER_DATA_FILE = "276e3d15-ffae-4a07-bda5-f1851e68cc77" // should be a unique name

const promises = {}
const requests = []

const readWeatherFile = () => {
  try {
    weather = readFileSync(WEATHER_DATA_FILE, 'cbor')
  } catch (n) {
    weather = { now : 0 }
  }
}

const writeWeatherFile = () => {
  try {
    writeFileSync(WEATHER_DATA_FILE, weather, 'cbor')
  } catch (n) {
  }
}

const sendRequest = (r) => {
  if (peerSocket.readyState === peerSocket.OPEN) {
    peerSocket.send(r);
  } else {
    requests.push(r);
  }
}

peerSocket.addEventListener('message', (evt) => {
  const { weather_message_id, data, error } = evt.data
  if (weather_message_id) {
    const promise = promises[weather_message_id]
    if (error) {
      promise.reject(error)
    }
    else {
      weather = data
      weather.timestamp = Date.now()
      writeWeatherFile()
      promise.resolve(weather)
    }
    delete promises[weather_message_id]
  }
})

peerSocket.addEventListener('open', (evt) => {
  setTimeout(() => {
    requests.forEach(r => sendRequest(r))
    requests.length = 0
  }, 500);
})

peerSocket.addEventListener('error', (err) => {
  console.log("Connection error: " + err.message)
  // I don't know what to do in this case yet... Notify every promises object ?
})

export const fetch = (maximumAge = 0) => {

  if (weather === undefined) {
    readWeatherFile()
  }

  return new Promise((resolve, reject) => {
    const now = Date.now()
    if (weather && (now - weather.timestamp < maximumAge)) {
      resolve(weather)
    }
    else {
      promises[now] = { resolve, reject }
      sendRequest({ weather_message_id : now })
    }
  })
}

export const get = () => {
  if(weather === undefined) {
    readWeatherFile()
  }
  return weather
}<|endoftext|>


<commit_before>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');

module.exports = yeoman.Base.extend({

    prompting: function () {
        var done = this.async();

        // Have Yeoman greet the user.
        this.log(yosay(
            'Welcome to the glorious ' + chalk.red('generator-react-typescript-immutable') + ' generator!'
        ));

        var prompts = [
            {
                type: 'input',
                name: 'name',
                message: 'Component name',
                default: this.appname
            },
            {
                type: 'input',
                name: 'description',
                message: 'Description',
                default: ""
            }
        ];

        this.prompt(prompts, function (props) {
            this.props = props;
            this.props.capName = this.props.name.charAt(0).toUpperCase() + this.props.name.slice(1);
            this.props.model = this.props.name + "Props";
            this.props.capModel = this.props.capName + "Props";
            done();
        }.bind(this));
    },

    writing: {
        config: function () {
            this.fs.copyTpl(
                this.templatePath('_package.json'),
                this.destinationPath('package.json'),
                this.props
            );
            this.fs.copyTpl(
                this.templatePath('_readme.md'),
                this.destinationPath('readme.md'),
                this.props
            );
            this.fs.copy(
                this.templatePath('_tsd.json'),
                this.destinationPath('tsd.json')
            );
            this.fs.copy(
                this.templatePath('_karma.conf.js'),
                this.destinationPath('karma.conf.js')
            );
            this.fs.copy(
                this.templatePath('_tsconfig.json'),
                this.destinationPath('tsconfig.json')
            );
        },
        src: function () {
            this.fs.copyTpl(
                this.templatePath('_src/_app/_components/_component.tsx'),
                this.destinationPath('src/app/components/' + this.props.name + '.tsx'),
                this.props
            );
            this.fs.copyTpl(
            this.templatePath('_src/_app/_models/_model.ts'),
            this.destinationPath('src/app/models/' + this.props.model + '.ts'),
            this.props
          );
        },
        test: function () {
            this.fs.copyTpl(
                this.templatePath('_src/_test/_index.html'),
                this.destinationPath('src/test/index.html'),
                this.props
            );
            this.fs.copyTpl(
                this.templatePath('_src/_test/_main.ts'),
                this.destinationPath('src/test/main.ts'),
                this.props
            );
            this.fs.copyTpl(
                this.templatePath('_src/_test/_spec/_modelSpec.ts'),
                this.destinationPath('src/test/spec/' + this.props.model + 'Spec.ts'),
                this.props
            );
        }
    },

    install: function () {
        this.installDependencies();
    }
});
<commit_msg>Adds template copy for tsconfig<commit_after>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');

module.exports = yeoman.Base.extend({

    prompting: function () {
        var done = this.async();

        // Have Yeoman greet the user.
        this.log(yosay(
            'Welcome to the glorious ' + chalk.red('generator-react-typescript-immutable') + ' generator!'
        ));

        var prompts = [
            {
                type: 'input',
                name: 'name',
                message: 'Component name',
                default: this.appname
            },
            {
                type: 'input',
                name: 'description',
                message: 'Description',
                default: ""
            }
        ];

        this.prompt(prompts, function (props) {
            this.props = props;
            this.props.capName = this.props.name.charAt(0).toUpperCase() + this.props.name.slice(1);
            this.props.model = this.props.name + "Props";
            this.props.capModel = this.props.capName + "Props";
            done();
        }.bind(this));
    },

    writing: {
        config: function () {
            this.fs.copyTpl(
                this.templatePath('_package.json'),
                this.destinationPath('package.json'),
                this.props
            );
            this.fs.copyTpl(
                this.templatePath('_readme.md'),
                this.destinationPath('readme.md'),
                this.props
            );
            this.fs.copy(
                this.templatePath('_tsd.json'),
                this.destinationPath('tsd.json')
            );
            this.fs.copy(
                this.templatePath('_karma.conf.js'),
                this.destinationPath('karma.conf.js')
            );
            this.fs.copyTpl(
                this.templatePath('_tsconfig.json'),
                this.destinationPath('tsconfig.json'),
                this.props
            );
        },
        src: function () {
            this.fs.copyTpl(
                this.templatePath('_src/_app/_components/_component.tsx'),
                this.destinationPath('src/app/components/' + this.props.name + '.tsx'),
                this.props
            );
            this.fs.copyTpl(
            this.templatePath('_src/_app/_models/_model.ts'),
            this.destinationPath('src/app/models/' + this.props.model + '.ts'),
            this.props
          );
        },
        test: function () {
            this.fs.copyTpl(
                this.templatePath('_src/_test/_index.html'),
                this.destinationPath('src/test/index.html'),
                this.props
            );
            this.fs.copyTpl(
                this.templatePath('_src/_test/_main.ts'),
                this.destinationPath('src/test/main.ts'),
                this.props
            );
            this.fs.copyTpl(
                this.templatePath('_src/_test/_spec/_modelSpec.ts'),
                this.destinationPath('src/test/spec/' + this.props.model + 'Spec.ts'),
                this.props
            );
        }
    },

    install: function () {
        this.installDependencies();
    }
});
<|endoftext|>


<commit_before>'use strict';
const Generator = require('yeoman-generator');
const chalk = require('chalk');
const commandExists = require('command-exists').sync;
const cowsay = require('cowsay');
const updateNotifier = require('update-notifier');
const pkg = require('../../package.json');
const stripIndent = require('strip-indent');
const yosay = require('yosay');

module.exports = class extends Generator {
    /**
     * Constructor
     * @param {String|Array} args
     * @param {Object} opts
     */
    constructor(args, opts) {
        // Noinspection JSAnnotator
        super(args, opts);

        // Check for newer versions of this generator and notify
        updateNotifier({pkg}).notify();

        this.argument('name', {
            type: String,
            required: false,
            description: 'The name of the project. If not set then you will be prompted.'
        });
    }

    /**
     * Sets the app name
     * @param {string} name
     * @private
     */
    _setAppName(name) {
        this.appName = name.replace(/\s+/g, '-').toLowerCase();
    }

    /**
     * Initialization
     */
    initializing() {
        // Initialize configuration
        this.appName = 'Website';

        // If the app name was passed as an argument then set it here
        if (typeof this.options.name !== 'undefined') {
            this._setAppName(this.options.name);
        }
    }

    /**
     * Questions
     * @returns {Promise.<TResult>|Promise}
     */
    prompting() {
        // Have Yeoman greet the user.
        this.log(yosay('Starting the ' + chalk.red('Cacao BranchCMS') + ' website generator!'));

        var prompts = [];

        // Ask for the website project name if it's not already set
        if (typeof this.options.name === 'undefined') {
            prompts.push({
                type: 'input',
                name: 'name',
                message: 'What is the name of the website project?'
            });
        }

        // Is this a theme website for BranchCMS?
        prompts.push({
            type: 'list',
            name: 'istheme',
            message: 'Is this a new theme website?',
            choices: ['Yes', 'No'],
            default: 'No'
        });

        // Front-end libraries to include
        prompts.push({
            type: 'checkbox',
            name: 'libraries',
            message: 'Check which libraries to include',
            choices: [
                {name: 'Magnific Popup', value: 'magnific', checked: true},
                {name: 'Slick slider', value: 'slick', checked: true},
                {name: 'Drift image zoom', value: 'driftzoom'}
            ]
        });

        // BranchCMS App templates to include
        prompts.push({
            type: 'checkbox',
            name: 'apps',
            message: 'Check which BranchCMS apps you will use for this website',
            choices: [
                {name: 'Blog', value: 'blog'},
                {name: 'Store', value: 'store'}
            ]
        });

        return this.prompt(prompts).then(answers => {
            // Set the app name if it was asked
            if (typeof answers.name !== 'undefined') {
                this._setAppName(answers.name);
            }

            // Tests to see if a value was selected in an answer
            const hasAnswer = (val, test) => val && val.indexOf(test) !== -1;

            this.isThemeWebsite = answers.istheme.toLowerCase() === 'yes';

            this.includeMagnific = hasAnswer(answers.libraries, 'magnific');
            this.includeSlick = hasAnswer(answers.libraries, 'slick');
            this.includeDrift = hasAnswer(answers.libraries, 'driftzoom');

            this.appBlog = hasAnswer(answers.apps, 'blog');
            this.appStore = hasAnswer(answers.apps, 'store');
        });
    }

    /**
     * Create the source files
     */
    writing() {
        this.log('\n' + chalk.bold('Writing files') + '\n');

        this._setupConfigFiles();
        this._copySourceFiles();
        this._copyTemplateFiles();
    }

    /**
     * Sets up the package.json and other config files
     * @private
     */
    _setupConfigFiles() {
        // Editor Config
        this.fs.copy(
            this.templatePath('_editorconfig'),
            this.destinationPath('.editorconfig')
        );

        // Gitignore
        this.fs.copy(
            this.templatePath('_gitignore'),
            this.destinationPath('.gitignore')
        );

        // Package.json
        this.fs.copyTpl(
            this.templatePath('_package.json'),
            this.destinationPath('package.json'),
            {
                name: this.appName,
                includeDriftZoom: this.includeDrift,
                includeMagnific: this.includeMagnific,
                includeSlick: this.includeSlick
            }
        );

        // Stylelint
        this.fs.copy(
            this.templatePath('_stylelintrc'),
            this.destinationPath('.stylelintrc'),
        );

        this.fs.copyTpl(
            this.templatePath() + '/gulp/**/*',
            this.destinationPath() + '/gulp',
            {
                includeDriftZoom: this.includeDrift,
                includeMagnific: this.includeMagnific,
                includeSlick: this.includeSlick,
                isThemeWebsite: this.isThemeWebsite
            }
        );

        // Gulpfile.js
        this.fs.copyTpl(
            this.templatePath('gulpfile.js'),
            this.destinationPath('gulpfile.js'),
            {
                isThemeWebsite: this.isThemeWebsite
            }
        );
    }

    /**
     * Copies the boilerplate images, CSS and Javascript files
     */
    _copySourceFiles() {
        this.fs.copy(
            this.templatePath() + '/src/**/*',
            this.destinationPath() + '/src'
        );

        if (this.isThemeWebsite) {
            // Include the theme files in the main css file
            let themeInclude = `
                    /**
                     * Theme configuration
                     */

                    @import './theme';`;
            this.fs.append(this.destinationPath() + '/src/css/main.css', stripIndent(themeInclude));

            // Include the theme config files
            this.fs.copy(
                this.templatePath() + '/theme-starter/css/**/*',
                this.destinationPath() + '/src/css'
            );
        }
    }

    /**
     * Copy the BranchCMS template files
     * @private
     */
    _copyTemplateFiles() {
        const src = this.templatePath() + '/theme/';
        const dest = this.destinationPath() + '/src/theme/';

        // Copy the theme.json file
        this.fs.copy(
            src + 'theme.json',
            this.destinationPath() + '/src/theme.json'
        );

        // Copy the default site template
        this.fs.copy(
            src + 'default.twig',
            dest + 'default.twig'
        );

        // Copy the app templates
        let apps = [
            'content-builder',
            'forms',
            'navigation',
            'search',
            'snippets'
        ];
        if (this.appBlog) {
            apps.push('blog');
        }
        if (this.appStore) {
            apps.push('store');
        }
        for (let app of apps) {
            this.fs.copy(
                src + app + '/**/*',
                dest + app
            );
        }
    }

    /**
     * Installation via yarn or npm
     */
    install() {
        this.log('\n');
        if (commandExists('yarn')) {
            this.yarnInstall();
        } else {
            this.npmInstall();
        }
    }

    /**
     * Finish
     */
    end() {
        this._build();
    }

    /**
     * Runs the gulp build
     * @private
     */
    _build() {
        this.log('\n\n' + chalk.bold('Running ' + chalk.yellow('gulp `build`') + ' task'));
        this.spawnCommand('gulp', ['build']).on('close', () => {
            this._done();
        });
    }

    /**
     * Output the closing message
     * @private
     */
    _done() {
        const cows = [
            'default',
            'cheese',
            'dragon-and-cow',
            'dragon',
            'elephant',
            'eyes',
            'ghostbusters',
            'goat',
            'hedgehog',
            'kitty',
            'koala',
            'luke-koala',
            'mech-and-cow',
            'meow',
            'milk',
            'moofasa',
            'moose',
            'sheep',
            'small',
            'squirrel',
            'stegosaurus',
            'turtle',
            'tux',
            'vader-koala',
            'vader',
            'whale',
            'www'
        ];
        const cow = cows[Math.floor(Math.random() * cows.length)];
        this.log(cowsay.say({
            text: '\nAll Done! Now go and build something great!\n',
            f: cow
        }) + '\n');
    }
};
<commit_msg>Changed the default template<commit_after>'use strict';
const Generator = require('yeoman-generator');
const chalk = require('chalk');
const commandExists = require('command-exists').sync;
const cowsay = require('cowsay');
const updateNotifier = require('update-notifier');
const pkg = require('../../package.json');
const stripIndent = require('strip-indent');
const yosay = require('yosay');

module.exports = class extends Generator {
    /**
     * Constructor
     * @param {String|Array} args
     * @param {Object} opts
     */
    constructor(args, opts) {
        // Noinspection JSAnnotator
        super(args, opts);

        // Check for newer versions of this generator and notify
        updateNotifier({pkg}).notify();

        this.argument('name', {
            type: String,
            required: false,
            description: 'The name of the project. If not set then you will be prompted.'
        });
    }

    /**
     * Sets the app name
     * @param {string} name
     * @private
     */
    _setAppName(name) {
        this.appName = name.replace(/\s+/g, '-').toLowerCase();
    }

    /**
     * Initialization
     */
    initializing() {
        // Initialize configuration
        this.appName = 'Website';

        // If the app name was passed as an argument then set it here
        if (typeof this.options.name !== 'undefined') {
            this._setAppName(this.options.name);
        }
    }

    /**
     * Questions
     * @returns {Promise.<TResult>|Promise}
     */
    prompting() {
        // Have Yeoman greet the user.
        this.log(yosay('Starting the ' + chalk.red('Cacao BranchCMS') + ' website generator!'));

        var prompts = [];

        // Ask for the website project name if it's not already set
        if (typeof this.options.name === 'undefined') {
            prompts.push({
                type: 'input',
                name: 'name',
                message: 'What is the name of the website project?'
            });
        }

        // Is this a theme website for BranchCMS?
        prompts.push({
            type: 'list',
            name: 'istheme',
            message: 'Is this a new theme website?',
            choices: ['Yes', 'No'],
            default: 'No'
        });

        // Front-end libraries to include
        prompts.push({
            type: 'checkbox',
            name: 'libraries',
            message: 'Check which libraries to include',
            choices: [
                {name: 'Magnific Popup', value: 'magnific', checked: true},
                {name: 'Slick slider', value: 'slick', checked: true},
                {name: 'Drift image zoom', value: 'driftzoom'}
            ]
        });

        // BranchCMS App templates to include
        prompts.push({
            type: 'checkbox',
            name: 'apps',
            message: 'Check which BranchCMS apps you will use for this website',
            choices: [
                {name: 'Blog', value: 'blog'},
                {name: 'Store', value: 'store'}
            ]
        });

        return this.prompt(prompts).then(answers => {
            // Set the app name if it was asked
            if (typeof answers.name !== 'undefined') {
                this._setAppName(answers.name);
            }

            // Tests to see if a value was selected in an answer
            const hasAnswer = (val, test) => val && val.indexOf(test) !== -1;

            this.isThemeWebsite = answers.istheme.toLowerCase() === 'yes';

            this.includeMagnific = hasAnswer(answers.libraries, 'magnific');
            this.includeSlick = hasAnswer(answers.libraries, 'slick');
            this.includeDrift = hasAnswer(answers.libraries, 'driftzoom');

            this.appBlog = hasAnswer(answers.apps, 'blog');
            this.appStore = hasAnswer(answers.apps, 'store');
        });
    }

    /**
     * Create the source files
     */
    writing() {
        this.log('\n' + chalk.bold('Writing files') + '\n');

        this._setupConfigFiles();
        this._copySourceFiles();
        this._copyTemplateFiles();
    }

    /**
     * Sets up the package.json and other config files
     * @private
     */
    _setupConfigFiles() {
        // Editor Config
        this.fs.copy(
            this.templatePath('_editorconfig'),
            this.destinationPath('.editorconfig')
        );

        // Gitignore
        this.fs.copy(
            this.templatePath('_gitignore'),
            this.destinationPath('.gitignore')
        );

        // Package.json
        this.fs.copyTpl(
            this.templatePath('_package.json'),
            this.destinationPath('package.json'),
            {
                name: this.appName,
                includeDriftZoom: this.includeDrift,
                includeMagnific: this.includeMagnific,
                includeSlick: this.includeSlick
            }
        );

        // Stylelint
        this.fs.copy(
            this.templatePath('_stylelintrc'),
            this.destinationPath('.stylelintrc'),
        );

        this.fs.copyTpl(
            this.templatePath() + '/gulp/**/*',
            this.destinationPath() + '/gulp',
            {
                includeDriftZoom: this.includeDrift,
                includeMagnific: this.includeMagnific,
                includeSlick: this.includeSlick,
                isThemeWebsite: this.isThemeWebsite
            }
        );

        // Gulpfile.js
        this.fs.copyTpl(
            this.templatePath('gulpfile.js'),
            this.destinationPath('gulpfile.js'),
            {
                isThemeWebsite: this.isThemeWebsite
            }
        );
    }

    /**
     * Copies the boilerplate images, CSS and Javascript files
     */
    _copySourceFiles() {
        this.fs.copy(
            this.templatePath() + '/src/**/*',
            this.destinationPath() + '/src'
        );

        if (this.isThemeWebsite) {
            // Include the theme files in the main css file
            let themeInclude = `
                    /**
                     * Theme configuration
                     */

                    @import './theme';`;
            this.fs.append(this.destinationPath() + '/src/css/main.css', stripIndent(themeInclude));

            // Include the theme config files
            this.fs.copy(
                this.templatePath() + '/theme-starter/css/**/*',
                this.destinationPath() + '/src/css'
            );
        }
    }

    /**
     * Copy the BranchCMS template files
     * @private
     */
    _copyTemplateFiles() {
        const src = this.templatePath() + '/theme/';
        const dest = this.destinationPath() + '/src/theme/';

        // Copy the theme.json file
        this.fs.copy(
            src + 'theme.json',
            this.destinationPath() + '/src/theme.json'
        );

        // Copy the default site template
        this.fs.copy(
            src + 'one-column.twig',
            dest + 'one-column.twig'
        );
        this.fs.copy(
            src + 'two-column.twig',
            dest + 'two-column.twig'
        );

        // Copy the app templates
        let apps = [
            'content-builder',
            'forms',
            'navigation',
            'search',
            'snippets'
        ];
        if (this.appBlog) {
            apps.push('blog');
        }
        if (this.appStore) {
            apps.push('store');
        }
        for (let app of apps) {
            this.fs.copy(
                src + app + '/**/*',
                dest + app
            );
        }
    }

    /**
     * Installation via yarn or npm
     */
    install() {
        this.log('\n');
        if (commandExists('yarn')) {
            this.yarnInstall();
        } else {
            this.npmInstall();
        }
    }

    /**
     * Finish
     */
    end() {
        this._build();
    }

    /**
     * Runs the gulp build
     * @private
     */
    _build() {
        this.log('\n\n' + chalk.bold('Running ' + chalk.yellow('gulp `build`') + ' task'));
        this.spawnCommand('gulp', ['build']).on('close', () => {
            this._done();
        });
    }

    /**
     * Output the closing message
     * @private
     */
    _done() {
        const cows = [
            'default',
            'cheese',
            'dragon-and-cow',
            'dragon',
            'elephant',
            'eyes',
            'ghostbusters',
            'goat',
            'hedgehog',
            'kitty',
            'koala',
            'luke-koala',
            'mech-and-cow',
            'meow',
            'milk',
            'moofasa',
            'moose',
            'sheep',
            'small',
            'squirrel',
            'stegosaurus',
            'turtle',
            'tux',
            'vader-koala',
            'vader',
            'whale',
            'www'
        ];
        const cow = cows[Math.floor(Math.random() * cows.length)];
        this.log(cowsay.say({
            text: '\nAll Done! Now go and build something great!\n',
            f: cow
        }) + '\n');
    }
};
<|endoftext|>


<commit_before>'use strict';

var Generator = require('yeoman-generator');
var path = require('path');
var chalk = require('chalk');
var yosay = require('yosay');
var _ = require('lodash');
var options = {};

module.exports = Generator.extend({
  initializing: function () {
    this.pkg = require('../../package.json');
    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the fantabulous ' + chalk.red('Phase2') + ' generator! ' + this.pkg.version
    ));
    options = _.assign({
      skipWelcome: true,
      skipGoodbye: true
    }, this.options);
  },

  prompting: function () {
    if (options['replay']) {
      options = _.assign(options, this.config.getAll());
      // Backwards compatibility for mail handling prompt config.
      options.mail = options.mailhog ? 'mailhog' : 'none';
    }

    // Ensure the drupalDistro plugin is loaded for this value when sidestepping
    // the prompt filter.
    if (options.hasOwnProperty('drupalDistro') && typeof options.drupalDistro === 'string') {
      var distros = require('generator-gadget/app/distros');
      options.drupalDistro = distros[options.drupalDistro];
    }

    var prompts = [];
    var gadgetPrompts = require('generator-gadget/lib/prompts');
    gadgetPrompts.forEach(function (item) {
      if (_.isUndefined(options[item.name])) {
        item.default = this.config.get(item.name) || item.default;
        prompts.push(item);
      }
    }.bind(this));

    if (_.isUndefined(options['useENV'])) {
      prompts.push({
        name: 'useENV',
        type: 'confirm',
        message: 'Use Phase2 DevTools/Docker Environment?'
      });
    }
    var envPrompts = require('../lib/prompts.js');
    envPrompts.forEach(function (item) {
      if (_.isUndefined(options[item.name])) {
        var validate = item.when;
        item.when = function(answers) {
          return answers['useENV'] && (!_.isFunction(validate) || validate(answers));
        };
        item.default = this.config.get(item.name) || item.default;

        prompts.push(item);
      }
    }.bind(this));

    if (_.isUndefined(options['usePLS'])) {
      prompts.push({
        name: 'usePLS',
        type: 'confirm',
        message: 'Use Pattern Lab Starter?'
      });
    }
    options['themePath'] = 'src/theme';  // Answer PLS question for theme location
    options['themeName'] = 'patternlab';  // This theme name is currently hardcoded in PLS
    var plPrompts = require('generator-pattern-lab-starter/generators/app/prompts.js');
    plPrompts.forEach(function (item) {
      if (_.isUndefined(options[item.name])) {
        var validate = item.when;
        item.when = function(answers) {
          return answers['usePLS'] && (!_.isFunction(validate) || validate(answers));
        };
        item.default = this.config.get(item.name) || item.default;

        prompts.push(item);
      }
    }.bind(this));

    // Minimally necessary prompt as a fallback if the other generators drop it.
    if (_.isUndefined(options.projectName)) {
      prompts.push({
        name: 'projectName',
        message: 'Machine name of project?',
        default: this.config.get('projectName') || _.last(this.env.cwd.split('/')), // parent folder
        validate: function (input) {
          return (input.search(' ') === -1) ? true : 'No spaces allowed.';
        }
      });
    }

    // ensuring we only ask questions with the same `name` value once; earlier questions take priority
    prompts = _.uniqBy(prompts, 'name');
    return this.prompt(prompts).then(function (props) {
      options = _.assign(options, props);
      // The complete distro includes callbacks that break when serialized to a file.
      options.drupalDistro = options.drupalDistro.id;
      if (options['themeName']) {
        options.themePath = 'src/themes/' + options.themeName;
      }

      var store = options;
      delete store['env'];
      delete store['resolved'];
      this.config.set(store);

      options['skip-readme'] = true;
      // If using Docker-based environment defer running install locally.
      if (options['useENV']) {
        options['skip-install'] = true;
        // The prompt key for the PLS npm install toggle.
        options['installDeps'] = true;
      }
    }.bind(this));
  },

  writing: {
    gadget: function () {
      var gadgetOptions = {}
      if (options['usePLS']) {
        gadgetOptions.themeScripts = {
          "compile-theme": "npm run setup --unsafe-perm && npm run compile --unsafe-perm",
          "validate": "npm run test --unsafe-perm"
        };
      }
      this.composeWith(require.resolve('generator-gadget'), _.assign(options, gadgetOptions));
    },

    env: function() {
      if (options['useENV']) {
        this.composeWith(require.resolve('../environment'), options);
      }
    },

    pls: function() {
      if (options['usePLS']) {
        this.composeWith(require.resolve('generator-pattern-lab-starter'), options);
      }
    },

    readme: function() {
      var tokens = require('../lib/tokens')(options);
      tokens.useENV = options['useENV'];
      this.fs.copyTpl(
        this.templatePath('README.md'),
        this.destinationPath('README.md'),
        tokens
      );
    }

  },

  install: function () {
    if (!options['skip-install']) {
      this.npmInstall();
    }
  },

  end: function() {
    var version = {
      gadget: require('generator-gadget/package.json').version,
      env: require('generator-p2/package.json').version,
      pls: require('generator-pattern-lab-starter/package.json').version,
    }

    this.log(yosay('Yo P2 has completed generation of your Drupal project.'));
    this.log('Primary scaffolding created by ' + chalk.red('generator-gadget v' + version.gadget) + '.');
    this.log('Check out your new READMEs to get oriented.');
    if (options['useENV']) {
      this.log('You have chosen a ' + chalk.bold('Docker-based development environment') + ' created by ' + chalk.red('generator-p2:environment v' + version.env) + '.');
      this.log(chalk.yellow('All tools and application code should be run via the Docker containers.'));
      this.log(chalk.green('A handy TODOS.md checklist has been created for your next steps.'));
      this.log('Want to see a running Drupal site without opening a text editor? Run ' + chalk.bold('bash bin/start.sh') + ' now.');
    }
    if (options['usePLS']) {
      this.log('You have created a new theme ' + chalk.green(options.themeName) + ' at ' + chalk.red(options.themePath) + ' with ' + chalk.red('generator-pattern-lab-starter v' + version.pls) + '.');
    }
  }

});
<commit_msg>Revise handling of theme option defaults.<commit_after>'use strict';

var Generator = require('yeoman-generator');
var path = require('path');
var chalk = require('chalk');
var yosay = require('yosay');
var _ = require('lodash');
var options = {};

module.exports = Generator.extend({
  initializing: function () {
    this.pkg = require('../../package.json');
    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the fantabulous ' + chalk.red('Phase2') + ' generator! ' + this.pkg.version
    ));
    options = _.assign({
      skipWelcome: true,
      skipGoodbye: true
    }, this.options);
  },

  prompting: function () {
    if (options['replay']) {
      options = _.assign(options, this.config.getAll());
      // Backwards compatibility for mail handling prompt config.
      options.mail = options.mailhog ? 'mailhog' : 'none';
    }

    // Ensure the drupalDistro plugin is loaded for this value when sidestepping
    // the prompt filter.
    if (options.hasOwnProperty('drupalDistro') && typeof options.drupalDistro === 'string') {
      var distros = require('generator-gadget/app/distros');
      options.drupalDistro = distros[options.drupalDistro];
    }

    var prompts = [];
    var gadgetPrompts = require('generator-gadget/lib/prompts');
    gadgetPrompts.forEach(function (item) {
      if (_.isUndefined(options[item.name])) {
        item.default = this.config.get(item.name) || item.default;
        prompts.push(item);
      }
    }.bind(this));

    if (_.isUndefined(options['useENV'])) {
      prompts.push({
        name: 'useENV',
        type: 'confirm',
        message: 'Use Phase2 DevTools/Docker Environment?'
      });
    }
    var envPrompts = require('../lib/prompts.js');
    envPrompts.forEach(function (item) {
      if (_.isUndefined(options[item.name])) {
        var validate = item.when;
        item.when = function(answers) {
          return answers['useENV'] && (!_.isFunction(validate) || validate(answers));
        };
        item.default = this.config.get(item.name) || item.default;

        prompts.push(item);
      }
    }.bind(this));

    if (_.isUndefined(options['usePLS'])) {
      prompts.push({
        name: 'usePLS',
        type: 'confirm',
        message: 'Use Pattern Lab Starter?'
      });
    }

    var plPrompts = require('generator-pattern-lab-starter/generators/app/prompts.js');
    plPrompts.forEach(function (item) {
      if (_.isUndefined(options[item.name])) {
        var validate = item.when;
        item.when = function(answers) {
          return answers['usePLS'] && (!_.isFunction(validate) || validate(answers));
        };
        item.default = this.config.get(item.name) || item.default;

        // These two need special-case defaulting.
        // @todo themePath emergent from generator-gadget usage.
        if (item.name == 'themePath') {
          item.default = 'src/theme';
        }

        prompts.push(item);
      }
    }.bind(this));

    // Minimally necessary prompt as a fallback if the other generators drop it.
    if (_.isUndefined(options.projectName)) {
      prompts.push({
        name: 'projectName',
        message: 'Machine name of project?',
        default: this.config.get('projectName') || _.last(this.env.cwd.split('/')), // parent folder
        validate: function (input) {
          return (input.search(' ') === -1) ? true : 'No spaces allowed.';
        }
      });
    }

    // ensuring we only ask questions with the same `name` value once; earlier questions take priority
    prompts = _.uniqBy(prompts, 'name');
    return this.prompt(prompts).then(function (props) {
      options = _.assign(options, props);
      // The complete distro includes callbacks that break when serialized to a file.
      options.drupalDistro = options.drupalDistro.id;
      if (options['themeName']) {
        options.themePath = 'src/themes/' + options.themeName;
      }

      var store = options;
      delete store['env'];
      delete store['resolved'];
      this.config.set(store);

      options['skip-readme'] = true;
      // If using Docker-based environment defer running install locally.
      if (options['useENV']) {
        // Suppress dependency install as part of dependency run.
        // --skip-install is used by this project and gadget.
        // --installDeps is the reverse and used by generator-pattern-lab-starter.
        options['skip-install'] = true;
        options['installDeps'] = false;
      }
      if (options['usePLS']) {
        // @todo remove when theme name prompting is explicitly in
        // generator-pattern-lab-starter. We need it here so the environment
        // generator can set up theme wiring. This is the hard-coded name.
        options['themeName'] = 'patternlab';
      }
    }.bind(this));
  },

  writing: {
    gadget: function () {
      var gadgetOptions = {}
      if (options['usePLS']) {
        gadgetOptions.themeScripts = {
          "compile-theme": "npm run setup --unsafe-perm && npm run compile --unsafe-perm",
          "validate": "npm run test --unsafe-perm"
        };
      }
      this.composeWith(require.resolve('generator-gadget'), _.assign(options, gadgetOptions));
    },

    env: function() {
      if (options['useENV']) {
        this.composeWith(require.resolve('../environment'), options);
      }
    },

    pls: function() {
      if (options['usePLS']) {
        this.composeWith(require.resolve('generator-pattern-lab-starter'), options);
      }
    },

    readme: function() {
      var tokens = require('../lib/tokens')(options);
      tokens.useENV = options['useENV'];
      this.fs.copyTpl(
        this.templatePath('README.md'),
        this.destinationPath('README.md'),
        tokens
      );
    }

  },

  install: function () {
    if (!options['skip-install']) {
      this.npmInstall();
    }
  },

  end: function() {
    var version = {
      gadget: require('generator-gadget/package.json').version,
      env: require('generator-p2/package.json').version,
      pls: require('generator-pattern-lab-starter/package.json').version,
    }

    this.log(yosay('Yo P2 has completed generation of your Drupal project.'));
    this.log('Primary scaffolding created by ' + chalk.red('generator-gadget v' + version.gadget) + '.');
    this.log('Check out your new READMEs to get oriented.');
    if (options['useENV']) {
      this.log('You have chosen a ' + chalk.bold('Docker-based development environment') + ' created by ' + chalk.red('generator-p2:environment v' + version.env) + '.');
      this.log(chalk.yellow('All tools and application code should be run via the Docker containers.'));
      this.log(chalk.green('A handy TODOS.md checklist has been created for your next steps.'));
      this.log('Want to see a running Drupal site without opening a text editor? Run ' + chalk.bold('bash bin/start.sh') + ' now.');
    }
    if (options['usePLS']) {
      this.log('You have created a new theme ' + chalk.green(options.themeName) + ' at ' + chalk.red(options.themePath) + ' with ' + chalk.red('generator-pattern-lab-starter v' + version.pls) + '.');
    }
  }

});
<|endoftext|>