<commit_before>'use strict';
var path = require('path');
var yeoman = require('yeoman-generator');
var pluralize = require('pluralize');
var _ = require('lodash');
var recast = require('recast');
var reservedWords = require('reserved-words');

module.exports = yeoman.Base.extend({
  prompting: function () {
    var srcDir = this.config.get('srcDir') || 'src';
    var apiDir = this.config.get('apiDir') || 'api';
    var authMethods = this.config.get('authMethods') || [];

    var methods = [
      {name: 'Create (POST)', value: 'POST'},
      {name: 'Retrieve list (GET)', value: 'GET LIST'},
      {name: 'Retrieve one (GET)', value: 'GET ONE'},
      {name: 'Update (PUT)', value: 'PUT'},
      {name: 'Delete (DELETE)', value: 'DELETE'}
    ];

    var getSelectedMethods = function (props) {
      return methods.filter(function (method) {
        return props.methods.indexOf(method.value) !== -1;
      });
    };

    var prompts = [{
      type: 'input',
      name: 'kebab',
      message: 'What\'s the API name?',
      default: 'some-entity'
    }, {
      type: 'input',
      name: 'lowerSuffix',
      message: 'Name is a reserved word, add suffix for lowercase identifier',
      default: 'Obj',
      when: function (props) {
        return reservedWords.check(_.lowerCase(props.kebab), 6);
      }
    }, {
      type: 'input',
      name: 'kebabs',
      message: 'What\'s the endpoint name?',
      default: function (props) {
        return pluralize(props.kebab);
      }
    }, {
      type: 'input',
      name: 'dir',
      message: 'Where to put the code?',
      default: srcDir + '/' + apiDir
    }, {
      type: 'checkbox',
      name: 'methods',
      message: 'Which methods it will have?',
      default: methods.map(function (method) {
        return method.value;
      }),
      choices: methods.map(function (method) {
        return _.assign({}, method, {checked: true});
      })
    }, {
      type: 'checkbox',
      name: 'masterMethods',
      message: 'Which methods are protected by the master key?',
      choices: getSelectedMethods,
      default: [],
      when: function () {
        return authMethods.length;
      }
    }, {
      type: 'checkbox',
      name: 'adminMethods',
      message: 'Which methods are only accessible by authenticated admin users?',
      default: [],
      choices: function (props) {
        var choices = getSelectedMethods(props);
        return choices.map(function (choice) {
          if (props.masterMethods.indexOf(choice.value) !== -1) {
            return _.assign({}, choice, {disabled: 'Accessible only with master key'});
          }
          return choice;
        });
      },
      when: function () {
        return authMethods.length;
      }
    }, {
      type: 'checkbox',
      name: 'userMethods',
      message: 'Which methods are only accessible by authenticated users?',
      default: [],
      choices: function (props) {
        var choices = getSelectedMethods(props);
        return choices.map(function (choice) {
          if (props.masterMethods.indexOf(choice.value) !== -1) {
            return _.assign({}, choice, {disabled: 'Accessible only with master key'});
          } else if (props.adminMethods.indexOf(choice.value) !== -1) {
            return _.assign({}, choice, {disabled: 'Accessible only by admin users'});
          }
          return choice;
        });
      },
      when: function () {
        return authMethods.length;
      }
    }, {
      type: 'confirm',
      name: 'generateModel',
      message: 'Do you want to generate a model?',
      default: true
    }, {
      type: 'input',
      name: 'modelFields',
      message: 'Which fields the model will have? (comma separated)',
      when: function (props) {
        return props.generateModel;
      }
    }, {
      type: 'confirm',
      name: 'storeUser',
      default: true,
      message: function (props) {
        return 'Do you want to store in a field the user who created the ' + props.kebab + '?';
      },
      when: function (props) {
        return props.generateModel && props.userMethods && props.userMethods.indexOf('POST') !== -1;
      }
    }, {
      type: 'input',
      name: 'userField',
      message: 'What\'s the name of the field which will store the user?',
      default: 'user',
      when: function (props) {
        return props.storeUser;
      }
    }, {
      type: 'confirm',
      name: 'getList',
      message: 'Do you want the retrieve methods (GET) to have the form { rows, count } ?',
      default: false,
      when: function (props) {
        var methods = getSelectedMethods(props);
        return methods.find(function (method) {
          return method.value === 'GET LIST';
        }) && props.generateModel;
      }
    }];

    return this.prompt(prompts).then(function (props) {
      this.props = props;
      this.props.camel = _.camelCase(this.props.kebab);
      this.props.camels = pluralize(this.props.camel);
      this.props.pascal = _.upperFirst(this.props.camel);
      this.props.pascals = _.upperFirst(this.props.camels);
      this.props.lower = _.lowerCase(this.props.camel);
      this.props.lowers = _.lowerCase(this.props.camels);
      this.props.start = _.upperFirst(this.props.lower);
      this.props.starts = _.upperFirst(this.props.lowers);

      // append suffix so we don't get reserved word clashes
      if (this.props.lowerSuffix) {
        this.props.camel = _.lowerCase(this.props.camel) + this.props.lowerSuffix;
      }

      this.props.authMethods = authMethods;
      this.props.srcDir = srcDir;
      this.props.apiDir = apiDir;

      this.props.modelFields = this.props.modelFields || '';
      this.props.modelFields = this.props.modelFields ?
        this.props.modelFields.split(',').map(function (field) {
          return field.trim();
        }) : [];

      this.props.getList = props.getList || false;
      this.props.storeUser = this.props.storeUser || false;

      if (props.userField && this.props.modelFields.indexOf(props.userField) !== -1) {
        this.props.modelFields.splice(this.props.modelFields.indexOf(props.userField), 1);
      }
    }.bind(this));
  },

  writing: function () {
    var props = this.props;
    var routesFile = path.join(props.dir, 'index.js');
    var copyTpl = this.fs.copyTpl.bind(this.fs);
    var tPath = this.templatePath.bind(this);
    var dPath = this.destinationPath.bind(this);
    var filepath = function (filename) {
      return path.join(props.dir, props.kebab, filename);
    };

    copyTpl(tPath('controller.js'), dPath(filepath('controller.js')), props);
    copyTpl(tPath('index.js'), dPath(filepath('index.js')), props);
    copyTpl(tPath('index.test.js'), dPath(filepath('index.test.js')), props);

    if (props.generateModel) {
      copyTpl(tPath('model.js'), dPath(filepath('model.js')), props);
      copyTpl(tPath('model.test.js'), dPath(filepath('model.test.js')), props);
    }

    if (this.fs.exists(routesFile)) {
      var ast = recast.parse(this.fs.read(routesFile));
      var body = ast.program.body;
      var lastImportIndex = _.findLastIndex(body, function (statement) {
        return statement.type === 'ImportDeclaration';
      });
      var actualImportCode = recast.print(body[lastImportIndex]).code;
      var importString = ['import ', props.camel, ' from \'./', props.kebab, '\''].join('');
      body.splice(lastImportIndex, 1, importString);
      body.splice(lastImportIndex, 0, actualImportCode);

      var middlewareString = [
        'router.use(\'/', props.kebabs, '\', ', props.camel, ')'
      ].join('');
      var lastMiddlewareIndex = _.findLastIndex(body, function (statement) {
        if (!statement.expression || !statement.expression.callee) {
          return false;
        }
        var callee = statement.expression.callee;
        return callee.object.name === 'router' && callee.property.name === 'use';
      });

      if (lastMiddlewareIndex === -1) {
        var exportRouterIndex = _.findIndex(body, function (statement) {
          return statement.type === 'ExportDefaultDeclaration';
        });
        body.splice(exportRouterIndex, 0, middlewareString);
      } else {
        var actualMiddlewareCode = recast.print(body[lastMiddlewareIndex]).code;
        body.splice(lastMiddlewareIndex, 1, middlewareString);
        body.splice(lastMiddlewareIndex, 0, actualMiddlewareCode);
      }

      this.fs.write(routesFile, recast.print(ast).code);
    }
  },

  install: function () {

  }
});
<commit_msg>Warning: Do not include id in model (#129)<commit_after>'use strict';
var path = require('path');
var yeoman = require('yeoman-generator');
var pluralize = require('pluralize');
var _ = require('lodash');
var recast = require('recast');
var reservedWords = require('reserved-words');

module.exports = yeoman.Base.extend({
  prompting: function () {
    var srcDir = this.config.get('srcDir') || 'src';
    var apiDir = this.config.get('apiDir') || 'api';
    var authMethods = this.config.get('authMethods') || [];

    var methods = [
      {name: 'Create (POST)', value: 'POST'},
      {name: 'Retrieve list (GET)', value: 'GET LIST'},
      {name: 'Retrieve one (GET)', value: 'GET ONE'},
      {name: 'Update (PUT)', value: 'PUT'},
      {name: 'Delete (DELETE)', value: 'DELETE'}
    ];

    var getSelectedMethods = function (props) {
      return methods.filter(function (method) {
        return props.methods.indexOf(method.value) !== -1;
      });
    };

    var prompts = [{
      type: 'input',
      name: 'kebab',
      message: 'What\'s the API name?',
      default: 'some-entity'
    }, {
      type: 'input',
      name: 'lowerSuffix',
      message: 'Name is a reserved word, add suffix for lowercase identifier',
      default: 'Obj',
      when: function (props) {
        return reservedWords.check(_.lowerCase(props.kebab), 6);
      }
    }, {
      type: 'input',
      name: 'kebabs',
      message: 'What\'s the endpoint name?',
      default: function (props) {
        return pluralize(props.kebab);
      }
    }, {
      type: 'input',
      name: 'dir',
      message: 'Where to put the code?',
      default: srcDir + '/' + apiDir
    }, {
      type: 'checkbox',
      name: 'methods',
      message: 'Which methods it will have?',
      default: methods.map(function (method) {
        return method.value;
      }),
      choices: methods.map(function (method) {
        return _.assign({}, method, {checked: true});
      })
    }, {
      type: 'checkbox',
      name: 'masterMethods',
      message: 'Which methods are protected by the master key?',
      choices: getSelectedMethods,
      default: [],
      when: function () {
        return authMethods.length;
      }
    }, {
      type: 'checkbox',
      name: 'adminMethods',
      message: 'Which methods are only accessible by authenticated admin users?',
      default: [],
      choices: function (props) {
        var choices = getSelectedMethods(props);
        return choices.map(function (choice) {
          if (props.masterMethods.indexOf(choice.value) !== -1) {
            return _.assign({}, choice, {disabled: 'Accessible only with master key'});
          }
          return choice;
        });
      },
      when: function () {
        return authMethods.length;
      }
    }, {
      type: 'checkbox',
      name: 'userMethods',
      message: 'Which methods are only accessible by authenticated users?',
      default: [],
      choices: function (props) {
        var choices = getSelectedMethods(props);
        return choices.map(function (choice) {
          if (props.masterMethods.indexOf(choice.value) !== -1) {
            return _.assign({}, choice, {disabled: 'Accessible only with master key'});
          } else if (props.adminMethods.indexOf(choice.value) !== -1) {
            return _.assign({}, choice, {disabled: 'Accessible only by admin users'});
          }
          return choice;
        });
      },
      when: function () {
        return authMethods.length;
      }
    }, {
      type: 'confirm',
      name: 'generateModel',
      message: 'Do you want to generate a model?',
      default: true
    }, {
      type: 'input',
      name: 'modelFields',
      message: 'Which fields the model will have? (comma separated, do not include id)',
      when: function (props) {
        return props.generateModel;
      }
    }, {
      type: 'confirm',
      name: 'storeUser',
      default: true,
      message: function (props) {
        return 'Do you want to store in a field the user who created the ' + props.kebab + '?';
      },
      when: function (props) {
        return props.generateModel && props.userMethods && props.userMethods.indexOf('POST') !== -1;
      }
    }, {
      type: 'input',
      name: 'userField',
      message: 'What\'s the name of the field which will store the user?',
      default: 'user',
      when: function (props) {
        return props.storeUser;
      }
    }, {
      type: 'confirm',
      name: 'getList',
      message: 'Do you want the retrieve methods (GET) to have the form { rows, count } ?',
      default: false,
      when: function (props) {
        var methods = getSelectedMethods(props);
        return methods.find(function (method) {
          return method.value === 'GET LIST';
        }) && props.generateModel;
      }
    }];

    return this.prompt(prompts).then(function (props) {
      this.props = props;
      this.props.camel = _.camelCase(this.props.kebab);
      this.props.camels = pluralize(this.props.camel);
      this.props.pascal = _.upperFirst(this.props.camel);
      this.props.pascals = _.upperFirst(this.props.camels);
      this.props.lower = _.lowerCase(this.props.camel);
      this.props.lowers = _.lowerCase(this.props.camels);
      this.props.start = _.upperFirst(this.props.lower);
      this.props.starts = _.upperFirst(this.props.lowers);

      // append suffix so we don't get reserved word clashes
      if (this.props.lowerSuffix) {
        this.props.camel = _.lowerCase(this.props.camel) + this.props.lowerSuffix;
      }

      this.props.authMethods = authMethods;
      this.props.srcDir = srcDir;
      this.props.apiDir = apiDir;

      this.props.modelFields = this.props.modelFields || '';
      this.props.modelFields = this.props.modelFields ?
        this.props.modelFields.split(',').map(function (field) {
          return field.trim();
        }) : [];

      this.props.getList = props.getList || false;
      this.props.storeUser = this.props.storeUser || false;

      if (props.userField && this.props.modelFields.indexOf(props.userField) !== -1) {
        this.props.modelFields.splice(this.props.modelFields.indexOf(props.userField), 1);
      }
    }.bind(this));
  },

  writing: function () {
    var props = this.props;
    var routesFile = path.join(props.dir, 'index.js');
    var copyTpl = this.fs.copyTpl.bind(this.fs);
    var tPath = this.templatePath.bind(this);
    var dPath = this.destinationPath.bind(this);
    var filepath = function (filename) {
      return path.join(props.dir, props.kebab, filename);
    };

    copyTpl(tPath('controller.js'), dPath(filepath('controller.js')), props);
    copyTpl(tPath('index.js'), dPath(filepath('index.js')), props);
    copyTpl(tPath('index.test.js'), dPath(filepath('index.test.js')), props);

    if (props.generateModel) {
      copyTpl(tPath('model.js'), dPath(filepath('model.js')), props);
      copyTpl(tPath('model.test.js'), dPath(filepath('model.test.js')), props);
    }

    if (this.fs.exists(routesFile)) {
      var ast = recast.parse(this.fs.read(routesFile));
      var body = ast.program.body;
      var lastImportIndex = _.findLastIndex(body, function (statement) {
        return statement.type === 'ImportDeclaration';
      });
      var actualImportCode = recast.print(body[lastImportIndex]).code;
      var importString = ['import ', props.camel, ' from \'./', props.kebab, '\''].join('');
      body.splice(lastImportIndex, 1, importString);
      body.splice(lastImportIndex, 0, actualImportCode);

      var middlewareString = [
        'router.use(\'/', props.kebabs, '\', ', props.camel, ')'
      ].join('');
      var lastMiddlewareIndex = _.findLastIndex(body, function (statement) {
        if (!statement.expression || !statement.expression.callee) {
          return false;
        }
        var callee = statement.expression.callee;
        return callee.object.name === 'router' && callee.property.name === 'use';
      });

      if (lastMiddlewareIndex === -1) {
        var exportRouterIndex = _.findIndex(body, function (statement) {
          return statement.type === 'ExportDefaultDeclaration';
        });
        body.splice(exportRouterIndex, 0, middlewareString);
      } else {
        var actualMiddlewareCode = recast.print(body[lastMiddlewareIndex]).code;
        body.splice(lastMiddlewareIndex, 1, middlewareString);
        body.splice(lastMiddlewareIndex, 0, actualMiddlewareCode);
      }

      this.fs.write(routesFile, recast.print(ast).code);
    }
  },

  install: function () {

  }
});
<|endoftext|>


<commit_before>/* eslint-env worker */
/* eslint no-var: off, strict: off */
/* globals prettier prettierPlugins */

// this is required to only load parsers when we need them
var parsers = {
  // JS - Babylon
  get babylon() {
    importScripts("lib/parser-babylon.js");
    return prettierPlugins.babylon.parsers.babylon;
  },
  get json() {
    importScripts("lib/parser-babylon.js");
    return prettierPlugins.babylon.parsers.json;
  },
  get json5() {
    importScripts("lib/parser-babylon.js");
    return prettierPlugins.babylon.parsers.json5;
  },
  get "json-stringify"() {
    importScripts("lib/parser-babylon.js");
    return prettierPlugins.babylon.parsers["json-stringify"];
  },
  // JS - Flow
  get flow() {
    importScripts("lib/parser-flow.js");
    return prettierPlugins.flow.parsers.flow;
  },
  // JS - TypeScript
  get typescript() {
    importScripts("lib/parser-typescript.js");
    return prettierPlugins.typescript.parsers.typescript;
  },

  // CSS
  get css() {
    importScripts("lib/parser-postcss.js");
    return prettierPlugins.postcss.parsers.css;
  },
  get less() {
    importScripts("lib/parser-postcss.js");
    return prettierPlugins.postcss.parsers.css;
  },
  get scss() {
    importScripts("lib/parser-postcss.js");
    return prettierPlugins.postcss.parsers.css;
  },

  // GraphQL
  get graphql() {
    importScripts("lib/parser-graphql.js");
    return prettierPlugins.graphql.parsers.graphql;
  },

  // Markdown
  get markdown() {
    importScripts("lib/parser-markdown.js");
    return prettierPlugins.markdown.parsers.remark;
  },

  // Vue
  get vue() {
    importScripts("lib/parser-vue.js");
    return prettierPlugins.vue.parsers.vue;
  }
};

importScripts("lib/standalone.js");
// eslint-disable-next-line no-unused-vars
var PRETTIER_DEBUG = true;

self.onmessage = function(event) {
  self.postMessage({
    uid: event.data.uid,
    message: handleMessage(event.data.message)
  });
};

function handleMessage(message) {
  if (message.type === "meta") {
    return {
      type: "meta",
      supportInfo: JSON.parse(JSON.stringify(prettier.getSupportInfo())),
      version: prettier.version
    };
  }

  if (message.type === "format") {
    var options = message.options || {};

    delete options.ast;
    delete options.doc;
    delete options.output2;

    var plugins = [{ parsers: parsers }];
    options.plugins = plugins;

    var response = {
      formatted: formatCode(message.code, options),
      debug: {
        ast: null,
        doc: null,
        reformatted: null
      }
    };

    if (message.debug.ast) {
      var ast;
      var errored = false;
      try {
        ast = JSON.stringify(prettier.__debug.parse(message.code, options).ast);
      } catch (e) {
        errored = true;
        ast = String(e);
      }

      if (!errored) {
        try {
          ast = formatCode(ast, { parser: "json", plugins: plugins });
        } catch (e) {
          ast = JSON.stringify(ast, null, 2);
        }
      }
      response.debug.ast = ast;
    }

    if (message.debug.doc) {
      try {
        response.debug.doc = prettier.__debug.formatDoc(
          prettier.__debug.printToDoc(message.code, options),
          { parser: "babylon", plugins: plugins }
        );
      } catch (e) {
        response.debug.doc = String(e);
      }
    }

    if (message.debug.reformat) {
      response.debug.reformatted = formatCode(response.formatted, options);
    }

    return response;
  }
}

function formatCode(text, options) {
  try {
    return prettier.format(text, options);
  } catch (e) {
    if (e.constructor && e.constructor.name === "SyntaxError") {
      // Likely something wrong with the user's code
      return String(e);
    }
    // Likely a bug in Prettier
    // Provide the whole stack for debugging
    return e.stack || String(e);
  }
}
<commit_msg>fix(playground): no unnecessary import (#4653)<commit_after>/* eslint-env worker */
/* eslint no-var: off, strict: off */
/* globals prettier prettierPlugins */

var imported = Object.create(null);
function importScriptOnce(url) {
  if (!imported[url]) {
    imported[url] = true;
    importScripts(url);
  }
}

// this is required to only load parsers when we need them
var parsers = {
  // JS - Babylon
  get babylon() {
    importScriptOnce("lib/parser-babylon.js");
    return prettierPlugins.babylon.parsers.babylon;
  },
  get json() {
    importScriptOnce("lib/parser-babylon.js");
    return prettierPlugins.babylon.parsers.json;
  },
  get json5() {
    importScriptOnce("lib/parser-babylon.js");
    return prettierPlugins.babylon.parsers.json5;
  },
  get "json-stringify"() {
    importScriptOnce("lib/parser-babylon.js");
    return prettierPlugins.babylon.parsers["json-stringify"];
  },
  // JS - Flow
  get flow() {
    importScriptOnce("lib/parser-flow.js");
    return prettierPlugins.flow.parsers.flow;
  },
  // JS - TypeScript
  get typescript() {
    importScriptOnce("lib/parser-typescript.js");
    return prettierPlugins.typescript.parsers.typescript;
  },

  // CSS
  get css() {
    importScriptOnce("lib/parser-postcss.js");
    return prettierPlugins.postcss.parsers.css;
  },
  get less() {
    importScriptOnce("lib/parser-postcss.js");
    return prettierPlugins.postcss.parsers.css;
  },
  get scss() {
    importScriptOnce("lib/parser-postcss.js");
    return prettierPlugins.postcss.parsers.css;
  },

  // GraphQL
  get graphql() {
    importScriptOnce("lib/parser-graphql.js");
    return prettierPlugins.graphql.parsers.graphql;
  },

  // Markdown
  get markdown() {
    importScriptOnce("lib/parser-markdown.js");
    return prettierPlugins.markdown.parsers.remark;
  },

  // Vue
  get vue() {
    importScriptOnce("lib/parser-vue.js");
    return prettierPlugins.vue.parsers.vue;
  }
};

importScripts("lib/standalone.js");
// eslint-disable-next-line no-unused-vars
var PRETTIER_DEBUG = true;

self.onmessage = function(event) {
  self.postMessage({
    uid: event.data.uid,
    message: handleMessage(event.data.message)
  });
};

function handleMessage(message) {
  if (message.type === "meta") {
    return {
      type: "meta",
      supportInfo: JSON.parse(JSON.stringify(prettier.getSupportInfo())),
      version: prettier.version
    };
  }

  if (message.type === "format") {
    var options = message.options || {};

    delete options.ast;
    delete options.doc;
    delete options.output2;

    var plugins = [{ parsers: parsers }];
    options.plugins = plugins;

    var response = {
      formatted: formatCode(message.code, options),
      debug: {
        ast: null,
        doc: null,
        reformatted: null
      }
    };

    if (message.debug.ast) {
      var ast;
      var errored = false;
      try {
        ast = JSON.stringify(prettier.__debug.parse(message.code, options).ast);
      } catch (e) {
        errored = true;
        ast = String(e);
      }

      if (!errored) {
        try {
          ast = formatCode(ast, { parser: "json", plugins: plugins });
        } catch (e) {
          ast = JSON.stringify(ast, null, 2);
        }
      }
      response.debug.ast = ast;
    }

    if (message.debug.doc) {
      try {
        response.debug.doc = prettier.__debug.formatDoc(
          prettier.__debug.printToDoc(message.code, options),
          { parser: "babylon", plugins: plugins }
        );
      } catch (e) {
        response.debug.doc = String(e);
      }
    }

    if (message.debug.reformat) {
      response.debug.reformatted = formatCode(response.formatted, options);
    }

    return response;
  }
}

function formatCode(text, options) {
  try {
    return prettier.format(text, options);
  } catch (e) {
    if (e.constructor && e.constructor.name === "SyntaxError") {
      // Likely something wrong with the user's code
      return String(e);
    }
    // Likely a bug in Prettier
    // Provide the whole stack for debugging
    return e.stack || String(e);
  }
}
<|endoftext|>


<commit_before>'use strict';
var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var _ = require('lodash');
var extend = _.merge;
var parseAuthor = require('parse-author');
var path = require('path');
var githubUsername = require('github-username');
var askName = require('inquirer-npm-name');
var chalk = require('chalk');
var message = require('../message');

module.exports = yeoman.Base.extend({
  constructor: function () {
    yeoman.Base.apply(this, arguments);

    this.option('travis', {
      type: Boolean,
      required: false,
      defaults: true,
      desc: message.travis
    });

    this.option('boilerplate', {
      type: Boolean,
      required: false,
      defaults: true,
      desc: message.boilerplate
    });

    this.option('gulp', {
      type: Boolean,
      required: false,
      defaults: true,
      desc: message.gulp
    });

    this.option('license', {
      type: Boolean,
      required: false,
      defaults: true,
      desc: message.license
    });

    this.option('name', {
      type: String,
      required: false,
      desc: message.name
    });

    this.option('githubAccount', {
      type: String,
      required: false,
      desc: message.githubAccount
    });

    this.option('projectRoot', {
      type: String,
      required: false,
      defaults: 'lib',
      desc: message.projectRoot
    });

    this.option('readme', {
      type: String,
      required: false,
      desc: message.readme
    });

    this.option('browser', {
      type: Boolean,
      required: false,
      defaults: true,
      desc: message.browser
    });

    this.option('styles', {
      type: Boolean,
      required: false,
      defaults: false,
      desc: message.styles
    });

    this.option('scss', {
      type: Boolean,
      required: false,
      defaults: true,
      desc: message.scss
    });

    this.option('bower', {
      type: Boolean,
      required: false,
      defaults: true,
      desc: message.browser
    });

    this.option('testFramework', {
      type: String,
      required: false,
      defaults: 'jasmine',
      desc: message.testFramework
    });
  },

  initializing: function () {
    this.pkg = this.fs.readJSON(this.destinationPath('package.json'), {});

    // Pre set the default props from the information we have at this point
    this.props = {
      name: this.pkg.name,
      description: this.pkg.description,
      version: this.pkg.version,
      homepage: this.pkg.homepage
    };

    if (_.isObject(this.pkg.author)) {
      this.props.authorName = this.pkg.author.name;
      this.props.authorEmail = this.pkg.author.email;
      this.props.authorUrl = this.pkg.author.url;
    } else if (_.isString(this.pkg.author)) {
      var info = parseAuthor(this.pkg.author);
      this.props.authorName = info.name;
      this.props.authorEmail = info.email;
      this.props.authorUrl = info.url;
    }
  },

  prompting: {
    showWelcome: function() {
      this.log(yosay(message.welcome));
      this.log(chalk.magenta(message.generator));
    },

    askForModuleName: function () {
      if (this.pkg.name || this.options.name) {
        this.props.name = this.pkg.name || _.kebabCase(this.options.name);
        return;
      }

      var done = this.async();

      askName({
        name: 'name',
        message: message.name,
        default: path.basename(process.cwd()),
        filter: _.kebabCase,
        validate: function (str) {
          return str.length > 0;
        }
      }, this, function (name) {
        this.props.name = name;
        done();
      }.bind(this));
    },

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

      var prompts = [{
        name: 'description',
        message: message.description,
        when: !this.props.description
      }, {
        name: 'homepage',
        message: message.homepage,
        when: !this.props.homepage
      }, {
        name: 'authorName',
        message: message.authorName,
        when: !this.props.authorName,
        default: this.user.git.name(),
        store: true
      }, {
        name: 'authorEmail',
        message: message.authorEmail,
        when: !this.props.authorEmail,
        default: this.user.git.email(),
        store: true
      }, {
        name: 'authorUrl',
        message: message.authorUrl,
        when: !this.props.authorUrl,
        store: true
      }, {
        name: 'keywords',
        message: message.keywords,
        when: !this.pkg.keywords,
        filter: function (words) {
          return words.split(/\s*,\s*/g);
        }
      }, {
        type: 'confirm',
        name: 'browser',
        message: message.browser,
        default: true
      }, {
        type: 'confirm',
        name: 'bower',
        message: message.bower,
        default: true,
        when: function (props) {
          return props.browser;
        }
      }, {
        type: 'confirm',
        name: 'styles',
        message: message.styles,
        default: false,
        when: function (props) {
          return props.browser;
        }
      }, {
        type: 'confirm',
        name: 'scss',
        message: message.scss,
        default: true,
        when: function (props) {
          return props.browser && props.styles;
        }
      }, {
        type: 'list',
        name: 'testFramework',
        message: message.testFramework,
        when: function (props) {
          return props.browser;
        },
        choices: [
          {
            name: "Jasmine",
            value: "jasmine"
          },
          {
            name: "Mocha",
            value: "mocha"
          }
        ],
        default: 0
      }];

      this.prompt(prompts, function (props) {
        this.props = extend(this.props, props);
        done();
      }.bind(this));
    },

    askForGithubAccount: function () {
      if (this.options.githubAccount) {
        this.props.githubAccount = this.options.githubAccount;
      } else {
        var done = this.async();

        githubUsername(this.props.authorEmail, function (err, username) {
          if (err) {
            username = username || '';
          }
          this.prompt({
            name: 'githubAccount',
            message: message.githubAccount,
            default: username
          }, function (prompt) {
            this.props.githubAccount = prompt.githubAccount;
            done();
          }.bind(this));
        }.bind(this));
      }
    }
  },

  writing: function () {
    // Re-read the content at this point because a composed generator might modify it.
    var currentPkg = this.fs.readJSON(this.destinationPath('package.json'), {});

    var pkg = extend({
      name: _.kebabCase(this.props.name),
      version: '0.0.0',
      description: this.props.description,
      homepage: this.props.homepage,
      author: {
        name: this.props.authorName,
        email: this.props.authorEmail,
        url: this.props.authorUrl
      },
      files: [
        'lib'
      ],
      main: this.props.styles ? ['lib/index.js', 'lib/' + this.props.name + '.css']: 'lib/index.js',
      keywords: [],
      typings: 'lib/index.d.ts'
    }, currentPkg);

    // Combine the keywords
    if (this.props.keywords) {
      pkg.keywords = _.uniq(this.props.keywords.concat(pkg.keywords));
    }

    // Let's extend package.json so we're not overwriting user previous fields
    this.fs.writeJSON(this.destinationPath('package.json'), pkg);

    if (this.props.browser && this.options.bower && this.props.bower) {
      var bower = {
        name: pkg.name,
        version: '0.0.0',
        description: this.props.description,
        main: this.props.styles ? ['bower/' + this.props.name + '.js', 'bower/' + this.props.name + '.css'] : 'bower/' + this.props.name + '.js',
        dependencies: {},
        devDependencies: {},
        moduleType: [
          'global'
        ],
        keywords: pkg.keywords,
        authors: [ this.props.authorName ],
        license: '',
        ignore: [
          'gulp',
          'lib',
          'node_modules',
          'src',
          'docs',
          'test',
          'coverage',
          'typings',
          '.gulp-scss-cache',
          '.sass-cache',
          '.tmp',
          '.idea',
          '.editorconfig',
          '.gitignore',
          '.jshintrc',
          '.npmignore',
          '.npmrc',
          'gulpfile.js',
          'karma.conf.js',
          'karma-coverage.conf.js',
          'package.json',
          'tsconfig.json',
          'tslint.json',
          'npm-debug.log'
        ]
      };

      this.fs.writeJSON(this.destinationPath('bower.json'), bower);
    }
  },

  default: function () {
    if (this.options.travis) {
      this.composeWith('travis', {}, {
        local: require.resolve('generator-travis/generators/app')
      });
    }

    this.composeWith('typescript-npm-bower:editor-conf', {}, {
      local: require.resolve('../editor-conf')
    });

    this.composeWith('typescript-npm-bower:lint', {}, {
      local: require.resolve('../lint')
    });

    this.composeWith('typescript-npm-bower:npm-conf', {}, {
      local: require.resolve('../npm-conf')
    });

    if (this.props.browser && this.options.bower && this.props.bower) {
      this.composeWith('typescript-npm-bower:bower-conf', {}, {
        local: require.resolve('../bower-conf')
      });
    }

    this.composeWith('typescript-npm-bower:typescript-conf', {
        options: {
          name: _.kebabCase(this.props.name),
          browser: this.props.browser,
          testFramework: this.props.testFramework
        }
      }, {
        local: require.resolve('../typescript-conf')
    });

    if (this.props.browser) {
      this.composeWith('typescript-npm-bower:karma-conf', {
        options: {
          testFramework: this.props.testFramework
        }
      }, {
        local: require.resolve('../karma-conf')
      });
    }

    this.composeWith('typescript-npm-bower:git', {
      options: {
        name: this.props.name,
        githubAccount: this.props.githubAccount
      }
    }, {
      local: require.resolve('../git')
    });

    if (this.options.gulp) {
      this.composeWith('typescript-npm-bower:gulp', {
        options: {
          name: _.kebabCase(this.props.name),
          browser: this.props.browser,
          styles: this.props.styles,
          scss: this.props.scss,
          bower: this.props.bower,
          testFramework: this.props.testFramework
        }
      },  {
        local: require.resolve('../gulp')
      });
    }

    if (this.options.boilerplate) {
      this.composeWith('typescript-npm-bower:boilerplate', {
        options: {
          browser: this.props.browser,
          styles: this.props.styles,
          scss: this.props.scss,
          bower: this.props.bower,
          testFramework: this.props.testFramework
        }
      }, {
        local: require.resolve('../boilerplate')
      });
    }

    if (this.options.license && !this.pkg.license) {
      this.composeWith('typescript-npm-bower:license', {
        options: {
          name: this.props.authorName,
          email: this.props.authorEmail,
          website: this.props.authorUrl
        }
      }, {
        local: require.resolve('generator-license/app')
      });
    }

    if (!this.fs.exists(this.destinationPath('README.md'))) {
      this.composeWith('typescript-npm-bower:readme', {
        options: {
          name: this.props.name,
          description: this.props.description,
          githubAccount: this.props.githubAccount,
          authorName: this.props.authorName,
          browser: this.props.browser,
          styles: this.props.styles,
          scss: this.props.scss,
          bower: this.props.bower,
          testFramework: this.props.testFramework
        }

      }, {
        local: require.resolve('../readme')
      });
    }
  },

  install: function () {
    this.npmInstall();
  }
});
<commit_msg>Add git account prompt check.<commit_after>'use strict';
var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var _ = require('lodash');
var extend = _.merge;
var parseAuthor = require('parse-author');
var path = require('path');
var githubUsername = require('github-username');
var askName = require('inquirer-npm-name');
var chalk = require('chalk');
var message = require('../message');

module.exports = yeoman.Base.extend({
  constructor: function () {
    yeoman.Base.apply(this, arguments);

    this.option('travis', {
      type: Boolean,
      required: false,
      defaults: true,
      desc: message.travis
    });

    this.option('boilerplate', {
      type: Boolean,
      required: false,
      defaults: true,
      desc: message.boilerplate
    });

    this.option('gulp', {
      type: Boolean,
      required: false,
      defaults: true,
      desc: message.gulp
    });

    this.option('license', {
      type: Boolean,
      required: false,
      defaults: true,
      desc: message.license
    });

    this.option('name', {
      type: String,
      required: false,
      desc: message.name
    });

    this.option('githubAccount', {
      type: String,
      required: false,
      desc: message.githubAccount
    });

    this.option('projectRoot', {
      type: String,
      required: false,
      defaults: 'lib',
      desc: message.projectRoot
    });

    this.option('readme', {
      type: String,
      required: false,
      desc: message.readme
    });

    this.option('browser', {
      type: Boolean,
      required: false,
      defaults: true,
      desc: message.browser
    });

    this.option('styles', {
      type: Boolean,
      required: false,
      defaults: false,
      desc: message.styles
    });

    this.option('scss', {
      type: Boolean,
      required: false,
      defaults: true,
      desc: message.scss
    });

    this.option('bower', {
      type: Boolean,
      required: false,
      defaults: true,
      desc: message.browser
    });

    this.option('testFramework', {
      type: String,
      required: false,
      defaults: 'jasmine',
      desc: message.testFramework
    });
  },

  initializing: function () {
    this.pkg = this.fs.readJSON(this.destinationPath('package.json'), {});

    // Pre set the default props from the information we have at this point
    this.props = {
      name: this.pkg.name,
      description: this.pkg.description,
      version: this.pkg.version,
      homepage: this.pkg.homepage
    };

    if (_.isObject(this.pkg.author)) {
      this.props.authorName = this.pkg.author.name;
      this.props.authorEmail = this.pkg.author.email;
      this.props.authorUrl = this.pkg.author.url;
    } else if (_.isString(this.pkg.author)) {
      var info = parseAuthor(this.pkg.author);
      this.props.authorName = info.name;
      this.props.authorEmail = info.email;
      this.props.authorUrl = info.url;
    }
  },

  prompting: {
    showWelcome: function() {
      this.log(yosay(message.welcome));
      this.log(chalk.magenta(message.generator));
    },

    askForModuleName: function () {
      if (this.pkg.name || this.options.name) {
        this.props.name = this.pkg.name || _.kebabCase(this.options.name);
        return;
      }

      var done = this.async();

      askName({
        name: 'name',
        message: message.name,
        default: path.basename(process.cwd()),
        filter: _.kebabCase,
        validate: function (str) {
          return str.length > 0;
        }
      }, this, function (name) {
        this.props.name = name;
        done();
      }.bind(this));
    },

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

      var prompts = [{
        name: 'description',
        message: message.description,
        when: !this.props.description
      }, {
        name: 'homepage',
        message: message.homepage,
        when: !this.props.homepage
      }, {
        name: 'authorName',
        message: message.authorName,
        when: !this.props.authorName,
        default: this.user.git.name(),
        store: true
      }, {
        name: 'authorEmail',
        message: message.authorEmail,
        when: !this.props.authorEmail,
        default: this.user.git.email(),
        store: true
      }, {
        name: 'authorUrl',
        message: message.authorUrl,
        when: !this.props.authorUrl,
        store: true
      }, {
        name: 'keywords',
        message: message.keywords,
        when: !this.pkg.keywords,
        filter: function (words) {
          return words.split(/\s*,\s*/g);
        }
      }, {
        type: 'confirm',
        name: 'browser',
        message: message.browser,
        default: true
      }, {
        type: 'confirm',
        name: 'bower',
        message: message.bower,
        default: true,
        when: function (props) {
          return props.browser;
        }
      }, {
        type: 'confirm',
        name: 'styles',
        message: message.styles,
        default: false,
        when: function (props) {
          return props.browser;
        }
      }, {
        type: 'confirm',
        name: 'scss',
        message: message.scss,
        default: true,
        when: function (props) {
          return props.browser && props.styles;
        }
      }, {
        type: 'list',
        name: 'testFramework',
        message: message.testFramework,
        when: function (props) {
          return props.browser;
        },
        choices: [
          {
            name: "Jasmine",
            value: "jasmine"
          },
          {
            name: "Mocha",
            value: "mocha"
          }
        ],
        default: 0
      }];

      this.prompt(prompts, function (props) {
        this.props = extend(this.props, props);
        done();
      }.bind(this));
    },

    askForGithubAccount: function () {
      if (this.options.githubAccount) {
        this.props.githubAccount = this.options.githubAccount;
      } else {
        if (this.props.authorEmail) {
          var done = this.async();

          githubUsername(this.props.authorEmail, function (err, username) {
            if (err) {
              username = username || '';
            }
            this.prompt({
              name: 'githubAccount',
              message: message.githubAccount,
              default: username
            }, function (prompt) {
              this.props.githubAccount = prompt.githubAccount;
              done();
            }.bind(this));
          }.bind(this));
        }
      }
    }
  },

  writing: function () {
    // Re-read the content at this point because a composed generator might modify it.
    var currentPkg = this.fs.readJSON(this.destinationPath('package.json'), {});

    var pkg = extend({
      name: _.kebabCase(this.props.name),
      version: '0.0.0',
      description: this.props.description,
      homepage: this.props.homepage,
      author: {
        name: this.props.authorName,
        email: this.props.authorEmail,
        url: this.props.authorUrl
      },
      files: [
        'lib'
      ],
      main: this.props.styles ? ['lib/index.js', 'lib/' + this.props.name + '.css']: 'lib/index.js',
      keywords: [],
      typings: 'lib/index.d.ts'
    }, currentPkg);

    // Combine the keywords
    if (this.props.keywords) {
      pkg.keywords = _.uniq(this.props.keywords.concat(pkg.keywords));
    }

    // Let's extend package.json so we're not overwriting user previous fields
    this.fs.writeJSON(this.destinationPath('package.json'), pkg);

    if (this.props.browser && this.options.bower && this.props.bower) {
      var bower = {
        name: pkg.name,
        version: '0.0.0',
        description: this.props.description,
        main: this.props.styles ? ['bower/' + this.props.name + '.js', 'bower/' + this.props.name + '.css'] : 'bower/' + this.props.name + '.js',
        dependencies: {},
        devDependencies: {},
        moduleType: [
          'global'
        ],
        keywords: pkg.keywords,
        authors: [ this.props.authorName ],
        license: '',
        ignore: [
          'gulp',
          'lib',
          'node_modules',
          'src',
          'docs',
          'test',
          'coverage',
          'typings',
          '.gulp-scss-cache',
          '.sass-cache',
          '.tmp',
          '.idea',
          '.editorconfig',
          '.gitignore',
          '.jshintrc',
          '.npmignore',
          '.npmrc',
          'gulpfile.js',
          'karma.conf.js',
          'karma-coverage.conf.js',
          'package.json',
          'tsconfig.json',
          'tslint.json',
          'npm-debug.log'
        ]
      };

      this.fs.writeJSON(this.destinationPath('bower.json'), bower);
    }
  },

  default: function () {
    if (this.options.travis) {
      this.composeWith('travis', {}, {
        local: require.resolve('generator-travis/generators/app')
      });
    }

    this.composeWith('typescript-npm-bower:editor-conf', {}, {
      local: require.resolve('../editor-conf')
    });

    this.composeWith('typescript-npm-bower:lint', {}, {
      local: require.resolve('../lint')
    });

    this.composeWith('typescript-npm-bower:npm-conf', {}, {
      local: require.resolve('../npm-conf')
    });

    if (this.props.browser && this.options.bower && this.props.bower) {
      this.composeWith('typescript-npm-bower:bower-conf', {}, {
        local: require.resolve('../bower-conf')
      });
    }

    this.composeWith('typescript-npm-bower:typescript-conf', {
        options: {
          name: _.kebabCase(this.props.name),
          browser: this.props.browser,
          testFramework: this.props.testFramework
        }
      }, {
        local: require.resolve('../typescript-conf')
    });

    if (this.props.browser) {
      this.composeWith('typescript-npm-bower:karma-conf', {
        options: {
          testFramework: this.props.testFramework
        }
      }, {
        local: require.resolve('../karma-conf')
      });
    }

    this.composeWith('typescript-npm-bower:git', {
      options: {
        name: this.props.name,
        githubAccount: this.props.githubAccount
      }
    }, {
      local: require.resolve('../git')
    });

    if (this.options.gulp) {
      this.composeWith('typescript-npm-bower:gulp', {
        options: {
          name: _.kebabCase(this.props.name),
          browser: this.props.browser,
          styles: this.props.styles,
          scss: this.props.scss,
          bower: this.props.bower,
          testFramework: this.props.testFramework
        }
      },  {
        local: require.resolve('../gulp')
      });
    }

    if (this.options.boilerplate) {
      this.composeWith('typescript-npm-bower:boilerplate', {
        options: {
          browser: this.props.browser,
          styles: this.props.styles,
          scss: this.props.scss,
          bower: this.props.bower,
          testFramework: this.props.testFramework
        }
      }, {
        local: require.resolve('../boilerplate')
      });
    }

    if (this.options.license && !this.pkg.license) {
      this.composeWith('typescript-npm-bower:license', {
        options: {
          name: this.props.authorName,
          email: this.props.authorEmail,
          website: this.props.authorUrl
        }
      }, {
        local: require.resolve('generator-license/app')
      });
    }

    if (!this.fs.exists(this.destinationPath('README.md'))) {
      this.composeWith('typescript-npm-bower:readme', {
        options: {
          name: this.props.name,
          description: this.props.description,
          githubAccount: this.props.githubAccount,
          authorName: this.props.authorName,
          browser: this.props.browser,
          styles: this.props.styles,
          scss: this.props.scss,
          bower: this.props.bower,
          testFramework: this.props.testFramework
        }

      }, {
        local: require.resolve('../readme')
      });
    }
  },

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


<commit_before>(function ($) {
    var itemTemplate = '

';
    var itemTemplateLabel = '';
    var itemTemplateCheckBox = '<input type="checkbox"  autocomplete="off" />';

    var box = '
' +
                '
' +
                    '' +
                 '
' +
                 '
' +
                    '

' +
                 '
' +
            '
';

    var index = 0;
    $.fn.parte = function (options) {
        debugger
        var settings = $.extend({
            // These are the defaults.
            saveOriginalData: true,
            backgroundColor: "white",
            top:'20px'
        }, options);

        if (this.length && !$('#parte-container').length) {
            $('body').append(box);
        }

        $('#parte-container').css('top', settings.top);

        $('#parte-btn').click(function () {
            if ($('#parte-box').length) {
                if ($('#parte-box').hasClass('open'))
                    $('#parte-box').removeClass('open');
                else
                    $('#parte-box').addClass('open');
            }

        });

        var elements = this.each(function (i, e) {
            var item = $(itemTemplate);
            var label = $(itemTemplateLabel);
            var checkbox = $(itemTemplateCheckBox);

            $(item).append(checkbox);
            $(item).append(label);

            $("#parte-container #parte-items").append(item);

            //set label name
            if (e.getAttribute('data-parte-name')) {
                label.html(e.getAttribute('data-parte-name'));
            } else {
                label.html('parte-label' + index);
            }

            //save data if saveOriginalData is true
            if (settings.saveOriginalData) {
                e.setAttribute("data-parte-value", e.value);
            }

            //set checkbox id, label for and related element id
            label.attr('for', 'parte-checkbox' + index);
            checkbox.attr('id', 'parte-checkbox' + index);
                       $(checkbox).change(function () {
                var cb = this;
                if (cb.checked) {
                    $(e).hide();
                } else {
                    $(e).show();
                }
            });

            index++;
        });

        return elements;
    };

    $.fn.parte.update = function (options) {
        var settings = $.extend({
            // These are the defaults.
            color: "#556b2f",
            backgroundColor: "white"
        }, options);

        return this.each(function () {
            // Do something to each element here.
        });

        return this;
    };

}(jQuery));
<commit_msg>Delete parte.js<commit_after><|endoftext|>


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

module.exports = yeoman.Base.extend({
  prompting: function () {
    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the first-rate ' + chalk.red('generator-trowel') + ' generator!'
    ));

    var prompts = [{
      type: 'confirm',
      name: 'someAnswer',
      message: 'Would you like to enable this option?',
      default: true
    }];

    return this.prompt(prompts).then(function (props) {
      // To access props later use this.props.someAnswer;
      this.props = props;
    }.bind(this));
  },

  writing: function () {
    this.fs.copy(
      this.templatePath('dummyfile.txt'),
      this.destinationPath('dummyfile.txt')
    );
  },

  install: function () {
    this.installDependencies();
  }
});
<commit_msg>add better hi to user<commit_after>/*jshint -W097 */
'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');

module.exports = yeoman.Base.extend({
  prompting: function () {
    // Have Yeoman greet the user.
    this.log(yosay(
      'It\'s time to make some ' + chalk.red('trowel') + '!'
    ));

    var prompts = [{
      type: 'confirm',
      name: 'someAnswer',
      message: 'Would you like to enable this option?',
      default: true
    }];

    return this.prompt(prompts).then(function (props) {
      // To access props later use this.props.someAnswer;
      this.props = props;
    }.bind(this));
  },

  writing: function () {
    this.fs.copy(
      this.templatePath('dummyfile.txt'),
      this.destinationPath('dummyfile.txt')
    );
  },

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


<commit_before>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var mkdirp = require('mkdirp');
var path = require('path');
var _ = require('lodash');
var prompts = require('./prompts.json');

module.exports = yeoman.generators.Base.extend({
    prompting: function () {
        var done = this.async();
        this.pkg = {
            appVersion: '1.0.0'
        };
        this.log(yosay(
            'Welcome to the breathtaking ' + chalk.red('tssoft-aspnet-frontend') + ' generator!'));
        var index = _.findIndex(prompts, { name: 'appName' });
        prompts[index].default = process.cwd().split(path.sep).pop();
        this.prompt(prompts, function (answers) {
            var features = answers.features;
            var plugins = answers.plugins;
            var concatenatedSources = answers.concatenatedSources;

            function wasSelected(element, list) {
                return features && list.indexOf(element) !== -1;
            };

            this.pkg.appName = answers.appName;
            this.includeTwitterBootStrap = answers.includeTwitterBootStrap;
            this.includeModernizr = answers.includeModernizr;
            this.includeAngular = wasSelected('includeAngular', features);
            this.includeReact = wasSelected('includeReact', features);
            this.includeBackbone = wasSelected('includeBackbone', features);

            this.includeLess = wasSelected('includeLess', plugins);
            this.includeKarma = wasSelected('includeKarma', plugins);
            this.includeJscs = wasSelected('includeJscs', plugins);
            this.includeEslint = wasSelected('includeEslint', plugins);

            this.includeConcatCss = wasSelected('includeConcatCss', concatenatedSources);
            this.includeConcatJs = wasSelected('includeConcatJs', concatenatedSources);
            done();
        }.bind(this));
    },

    copyMainFiles: function () {
        mkdirp("src");
        mkdirp("test");
        this.copy("_gulpfile.js", "gulpfile.js");
        this.copy("_package.json", "package.json");
        this.copy("gulp/config.js", "gulp/config.js");
        this.copy(".gitignore", ".gitignore");
        this.copy("gulp/util/handleErrors.js", "gulp/util/handleErrors.js");
        this.copy("gulp/tasks/default.js", "gulp/tasks/default.js");
    },

    install: function () {
        this.npmInstall();
        this.npmInstall(['gulp'], { 'saveDev': true });
        if (this.includeTwitterBootStrap) {
            this.bowerInstall(['twitter'], { 'save': true })
        }
        if (this.includeAngular) {
            this.bowerInstall(['angular'], { 'save': true })
            this.bowerInstall(['angular-mocks'], { 'save': true })
        }
        if (this.includeReact) {
            this.bowerInstall(['react'], { 'save': true })
            this.npmInstall(['gulp-react'], { 'saveDev': true });
            this.copy("gulp/tasks/react.js", "gulp/tasks/react.js");
        }
        if (this.includeBackbone) {
            this.bowerInstall(['backbone'], { 'save': true })
        }
        if (this.includeModernizr) {
            this.npmInstall(['gulp-modernizr'], { 'saveDev': true })
            this.copy("gulp/tasks/modernizr.js", "gulp/tasks/modernizr.js");
        }
        if (this.includeConcatCss) {
            this.npmInstall(['gulp-concat-css'], { 'saveDev': true })
        }
        if (this.includeConcatJs) {
            this.npmInstall(['gulp-concat'], { 'saveDev': true })
        }
        if (this.includeLess) {
            this.copy("gulp/tasks/less.js", "gulp/tasks/less.js");
            this.npmInstall(['less'], { 'saveDev': true });
        }
        if (this.includeKarma) {
            this.copy("gulp/tasks/karma.js", "gulp/tasks/karma.js");
            this.copy("_karma.conf.js", "karma.conf.js");
            this.npmInstall(['karma'], { 'saveDev': true });
            this.npmInstall(['jasmine-core'], { 'saveDev': true });
            this.npmInstall(['phantomjs'], { 'saveDev': true });
        }
        if (this.includeJscs) {
            this.copy("gulp/tasks/jscs.js", "gulp/tasks/jscs.js");
            this.copy("_.jscsrc", ".jscsrc");
            this.npmInstall(['jscs'], { 'saveDev': true });
        }
        if (this.includeEslint) {
            this.copy("gulp/tasks/lint.js", "gulp/tasks/lint.js");
            this.copy("_eslint.config.json", "eslint.config.json");
            this.npmInstall(['eslint'], { 'saveDev': true });
        }
    }
});
<commit_msg>install karma-es5-shim for react testing<commit_after>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var mkdirp = require('mkdirp');
var path = require('path');
var _ = require('lodash');
var prompts = require('./prompts.json');

module.exports = yeoman.generators.Base.extend({
    prompting: function () {
        var done = this.async();
        this.pkg = {
            appVersion: '1.0.0'
        };
        this.log(yosay(
            'Welcome to the breathtaking ' + chalk.red('tssoft-aspnet-frontend') + ' generator!'));
        var index = _.findIndex(prompts, { name: 'appName' });
        prompts[index].default = process.cwd().split(path.sep).pop();
        this.prompt(prompts, function (answers) {
            var features = answers.features;
            var plugins = answers.plugins;
            var concatenatedSources = answers.concatenatedSources;

            function wasSelected(element, list) {
                return features && list.indexOf(element) !== -1;
            };

            this.pkg.appName = answers.appName;
            this.includeTwitterBootStrap = answers.includeTwitterBootStrap;
            this.includeModernizr = answers.includeModernizr;
            this.includeAngular = wasSelected('includeAngular', features);
            this.includeReact = wasSelected('includeReact', features);
            this.includeBackbone = wasSelected('includeBackbone', features);

            this.includeLess = wasSelected('includeLess', plugins);
            this.includeKarma = wasSelected('includeKarma', plugins);
            this.includeJscs = wasSelected('includeJscs', plugins);
            this.includeEslint = wasSelected('includeEslint', plugins);

            this.includeConcatCss = wasSelected('includeConcatCss', concatenatedSources);
            this.includeConcatJs = wasSelected('includeConcatJs', concatenatedSources);
            done();
        }.bind(this));
    },

    copyMainFiles: function () {
        mkdirp("src");
        mkdirp("test");
        this.copy("_gulpfile.js", "gulpfile.js");
        this.copy("_package.json", "package.json");
        this.copy("gulp/config.js", "gulp/config.js");
        this.copy(".gitignore", ".gitignore");
        this.copy("gulp/util/handleErrors.js", "gulp/util/handleErrors.js");
        this.copy("gulp/tasks/default.js", "gulp/tasks/default.js");
    },

    install: function () {
        this.npmInstall();
        this.npmInstall(['gulp'], { 'saveDev': true });
        if (this.includeTwitterBootStrap) {
            this.bowerInstall(['twitter'], { 'save': true })
        }
        if (this.includeAngular) {
            this.bowerInstall(['angular'], { 'save': true })
            this.bowerInstall(['angular-mocks'], { 'save': true })
        }
        if (this.includeReact) {
            this.bowerInstall(['react'], { 'save': true })
            this.npmInstall(['gulp-react'], { 'saveDev': true });
            this.npmInstall(['karma-es5-shim'], { 'saveDev': true });
            this.copy("gulp/tasks/react.js", "gulp/tasks/react.js");
        }
        if (this.includeBackbone) {
            this.bowerInstall(['backbone'], { 'save': true })
        }
        if (this.includeModernizr) {
            this.npmInstall(['gulp-modernizr'], { 'saveDev': true })
            this.copy("gulp/tasks/modernizr.js", "gulp/tasks/modernizr.js");
        }
        if (this.includeConcatCss) {
            this.npmInstall(['gulp-concat-css'], { 'saveDev': true })
        }
        if (this.includeConcatJs) {
            this.npmInstall(['gulp-concat'], { 'saveDev': true })
        }
        if (this.includeLess) {
            this.copy("gulp/tasks/less.js", "gulp/tasks/less.js");
            this.npmInstall(['less'], { 'saveDev': true });
        }
        if (this.includeKarma) {
            this.copy("gulp/tasks/karma.js", "gulp/tasks/karma.js");
            this.copy("_karma.conf.js", "karma.conf.js");
            this.npmInstall(['karma'], { 'saveDev': true });
            this.npmInstall(['jasmine-core'], { 'saveDev': true });
            this.npmInstall(['phantomjs'], { 'saveDev': true });
        }
        if (this.includeJscs) {
            this.copy("gulp/tasks/jscs.js", "gulp/tasks/jscs.js");
            this.copy("_.jscsrc", ".jscsrc");
            this.npmInstall(['jscs'], { 'saveDev': true });
        }
        if (this.includeEslint) {
            this.copy("gulp/tasks/lint.js", "gulp/tasks/lint.js");
            this.copy("_eslint.config.json", "eslint.config.json");
            this.npmInstall(['eslint'], { 'saveDev': true });
        }
    }
});
<|endoftext|>


<commit_before>var generators  = require('yeoman-generator');
var fs          = require('fs');
var colors      = require('colors');
var requestSync = require('sync-request');
var beautify    = require('js-beautify').js_beautify;

module.exports = generators.Base.extend({
	constructor: function() {
		generators.Base.apply(this, arguments);

		this.option('skip-install');
		this.option('skip-repo');
	},
	initializing: function() {
		// this.log('destinationRoot', this.destinationRoot());
		// this.log('sourceRoot', this.sourceRoot());
	},
	prompting: function() {
		var done = this.async();

		var questions = [{
			type: 'input',
			name: 'year',
			message: 'What year is it?',
			default: (new Date()).getFullYear()
		}, {
			type: 'input',
			name: 'teamName',
			message: 'What is your team name ' + 'exactly'.red + ' as it appears on the wiki? (Team:' + 'teamName'.magenta + ')',
			validate: function(input) {
				if (input === '') {
					return false;
				} else {
					return true;
				}
			}
		}, {
			type: 'input',
			name: 'author',
			message: 'Author? (optional) `Name <email>`'
		}];

		if (!this.options['skip-repo']) {
			questions.push({
				type: 'input',
				name: 'repo',
				message: 'What is the GitHub repository for this project? (Provided as ' + 'username/repo'.magenta + ')',
				validate: function(input) {
					var good = false
					for (var i = 0; i < input.length; i++) {
						if (input[i] === '/' && good === false) {
							good = true;
						} else if (input[i] === '/' && good === true) {
							good = false;
							return;
						}
					}

					if (!good)
						return 'Follow ' + 'username'.magenta + '/' + 'repo'.magenta + ' format.'

					base_url = 'https://github.com/'

					var httpResponse = requestSync('GET', base_url + input);

					if (httpResponse.statusCode === 200) {
						return true
					} else if (httpResponse.statusCode === 404) {
						return 'Nice try, the page ' + base_url.blue + input.blue + ' returned a ' + '404'.red
					} else {
						return false
					}
				}
			})
		}

		this.prompt(questions, function(answers) {
			this.config.set({
				year: answers.year,
				teamName: answers.teamName,
				repo: answers.repo ? 'https://github.com/' + answers.repo : '',
				author: answers.author
			})
			done();
		}.bind(this));
	},
	configuring: function() {
		// this.log('configuring');
	},
	default: function() {
		// this.log('default');
	},
	writing: function() {

		this.fs.copyTpl(
			this.templatePath('bower.json'),
			this.destinationPath('bower.json'),
			this.config.getAll()
		);
		this.fs.copyTpl(
			this.templatePath('gulpfile.coffee'),
			this.destinationPath('gulpfile.coffee'),
			this.config.getAll()
		);
		this.fs.copyTpl(
			this.templatePath('helpers.coffee'),
			this.destinationPath('helpers.coffee'),
			this.config.getAll()
		);
		this.fs.copyTpl(
			this.templatePath('package.json'),
			this.destinationPath('package.json'),
			this.config.getAll()
		);

		this.directory('src', './src');
		this.fs.copyTpl(
			this.templatePath('_template.json'),
			this.destinationPath('./src/template.json'),
			this.config.getAll()
		)
		this.directory('phantom', './phantom');
		this.directory('images', './images');
	},
	install: function() {
		pkg = JSON.parse(fs.readFileSync('package.json'))
		pkg.author = this.config.get('author')
		fs.writeFileSync('package.json', beautify(JSON.stringify(pkg)))

		if (this.options['skip-install']) {
			this.log('Skipping ' + 'npm install'.magenta + ' and ' + 'bower install'.magenta + '. Run these yourself.')
		} else {
			this.installDependencies()
		}
	},
	end: function() {
		this.log('Good Bye!');
	}
});
<commit_msg>Standard style'ify generators/app/index.js<commit_after>var generators = require('yeoman-generator')
var fs = require('fs')
var colors = require('colors')
var requestSync = require('sync-request')
var beautify = require('js-beautify').js_beautify

module.exports = generators.Base.extend({
  constructor: function () {
    generators.Base.apply(this, arguments)

    this.option('skip-install')
    this.option('skip-repo')
  },
  initializing: function () {
    // this.log('destinationRoot', this.destinationRoot())
    // this.log('sourceRoot', this.sourceRoot())
  },
  prompting: function () {
    var done = this.async()

    var questions = [{
      type: 'input',
      name: 'year',
      message: 'What year is it?',
      default: (new Date()).getFullYear()
    }, {
      type: 'input',
      name: 'teamName',
      message: 'What is your team name ' + 'exactly'.red + ' as it appears on the wiki? (Team:' + 'teamName'.magenta + ')',
      validate: function (input) {
        if (input === '') {
          return false
        } else {
          return true
        }
      }
    }, {
      type: 'input',
      name: 'author',
      message: 'Author? (optional) `Name <email>`'
    }]

    if (!this.options['skip-repo']) {
      questions.push({
        type: 'input',
        name: 'repo',
        message: 'What is the GitHub repository for this project? (Provided as ' + 'username/repo'.magenta + ')',
        validate: function (input) {
          var good = false
          for (var i = 0; i < input.length; i++) {
            if (input[i] === '/' && good === false) {
              good = true
            } else if (input[i] === '/' && good === true) {
              good = false
              return
            }
          }

          if (!good)
            return 'Follow ' + 'username'.magenta + '/' + 'repo'.magenta + ' format.'

          base_url = 'https://github.com/'

          var httpResponse = requestSync('GET', base_url + input)

          if (httpResponse.statusCode === 200) {
            return true
          } else if (httpResponse.statusCode === 404) {
            return 'Nice try, the page ' + base_url.blue + input.blue + ' returned a ' + '404'.red
          } else {
            return false
          }
        }
      })
    }

    this.prompt(questions, function (answers) {
      this.config.set({
        year: answers.year,
        teamName: answers.teamName,
        repo: answers.repo ? 'https://github.com/' + answers.repo : '',
        author: answers.author
      })
      done()
    }.bind(this))
  },
  configuring: function () {
    // this.log('configuring')
  },
  default: function () {
    // this.log('default')
  },
  writing: function () {

    this.fs.copyTpl(
      this.templatePath('bower.json'),
      this.destinationPath('bower.json'),
      this.config.getAll()
    )
    this.fs.copyTpl(
      this.templatePath('gulpfile.coffee'),
      this.destinationPath('gulpfile.coffee'),
      this.config.getAll()
    )
    this.fs.copyTpl(
      this.templatePath('helpers.coffee'),
      this.destinationPath('helpers.coffee'),
      this.config.getAll()
    )
    this.fs.copyTpl(
      this.templatePath('package.json'),
      this.destinationPath('package.json'),
      this.config.getAll()
    )

    this.directory('src', './src')
    this.fs.copyTpl(
      this.templatePath('_template.json'),
      this.destinationPath('./src/template.json'),
      this.config.getAll()
    )
    this.directory('phantom', './phantom')
    this.directory('images', './images')
  },
  install: function () {
    pkg = JSON.parse(fs.readFileSync('package.json'))
    pkg.author = this.config.get('author')
    fs.writeFileSync('package.json', beautify(JSON.stringify(pkg)))

    if (this.options['skip-install']) {
      this.log('Skipping ' + 'npm install'.magenta + ' and ' + 'bower install'.magenta + '. Run these yourself.')
    } else {
      this.installDependencies()
    }
  },
  end: function () {
    this.log('Good Bye!')
  }
})
<|endoftext|>


<commit_before>const Generator = require('yeoman-generator');
const path = require('path');
const utils = require('./utils');
const prompts = require('./prompts');
const which = require('which');

const OPTIONS = {
  // COMMIT: 'commit',
  INIT_GIT: 'git',
  LATEST: 'latest',
  // PUSH: 'push',
  YES: 'yes',
  YES_DEFAULT: 'yes-defaults'
};

// TODO replace file names with map
// const TEMPLATES = {
//   README: {
//     name: 'readme.md',
//     placeholders: []
//   }
// };

module.exports = class extends Generator {
  // get devDependencies() {
  //   // TODO add option to install latest versions or fixed
  //   return {
  //     "ava": "^0.18.2",
  //     "babel-loader": "^6.4.0",
  //     "babel-plugin-istanbul": "^4.0.0",
  //     "babel-preset-env": "^1.2.1",
  //     "babel-register": "^6.24.0",
  //     "codecov": "^2.0.1",
  //     "nyc": "^10.1.2",
  //     "webpack": "2.2.1",
  //     "xo": "^0.17.1"
  //   }
  // }

  constructor(args, opts) {
    super(args, opts);

    this.option('yes-default', {
      alias: 'd',
      default: false,
      description: `Ask only questions which don't have default or saved answer`,
      type: Boolean
    });

    this.option(OPTIONS.YES, {
      alias: 'y',
      default: false,
      description: `Agree on every question, don't ask anything`,
      type: Boolean
    });

    this.option(OPTIONS.INIT_GIT, {
      alias: 'g',
      default: true,
      description: `Init git repository`,
      type: Boolean
    });

    // this.option(OPTIONS.COMMIT, {
    //   alias: 'c',
    //   default: true,
    //   description: `Make initial commit`,
    //   type: Boolean
    // });

    // this.option(OPTIONS.PUSH, {
    //   alias: 'p',
    //   default: false,
    //   description: `Push commit`,
    //   type: Boolean
    // });

    this.option(OPTIONS.LATEST, {
      alias: 'l',
      default: false,
      description: `Install latest versions of dependencies. (!) Correct work is not guaranteed`,
      type: Boolean
    });

    this.storedPrompt = this.config.get('promptValues') || {};
    this.defaultAnswers = this._getDefaultAnswers(this.storedPrompt);
    this.answers = {};
  }

  // Lifecycle hook
  initializing() {
    return this._beforeInit()
      .then(() => this._afterInit());
  }

  // Lifecycle hook
  prompting() {
    return this._getAnswers()
      .then(answers => {
        this.answers = answers
      });
  }

  // Lifecycle hook
  configuring() {
    this._fastCopy('.babelrc');
    this._fastCopy('.editorconfig');
    this._fastCopy('.gitattributes');
    this._fastCopy('.gitignore');
    this._fastCopy('.travis.yml');
  }

  // Lifecycle hook
  // default() {}

  // Lifecycle hook
  writing() {
    this._fastCopy('index.js');
    this._fastCopy('LICENSE', this.answers);
    this._fastCopy('package.json', this.answers);
    this._fastCopy('README.md', this.answers);
    this._fastCopy('test.js');
    this._fastCopy('webpack.config.babel.js');
    this._fastCopy('yarn.lock');
  }

  // Lifecycle hook
  // conflicts() {}

  // Lifecycle hook
  install() {
    this._installDependencies({
      isYarn: which.sync('yarn')
    });

    if (which.sync('git')) {
      if (this.options[OPTIONS.INIT_GIT]) {
        this.spawnCommand('git', ['init']);
      }
    }
    // if git is available
      // init git

      // make commit

      // if github repo exists && user agreed
        // push
  }

  // Lifecycle hook
  // end() {}

  /**
   *
   * @param isYarn
   * @private
   */
  _installDependencies({isYarn}) {
    let dependencies = [];
    let devDependencies = [];

    if (this.options[OPTIONS.LATEST]) {
      const packageJson = require(this.templatePath('package.json'));
      const setLatest = dep => `${dep}@latest`;

      dependencies = Object.keys(packageJson.dependencies).map(setLatest);
      devDependencies = Object.keys(packageJson.devDependencies).map(setLatest);
    }

    isYarn
      ? this.yarnInstall(dependencies)
      : this.npmInstall(dependencies);

    if (devDependencies.length > 0) {
      isYarn
        ? this.yarnInstall(devDependencies, {dev: true})
        : this.npmInstall(devDependencies, {'save-dev': true});
    }
  }

  /**
   * Returns answers either after prompting or on
   * @return {Promise}
   * @private
   */
  _getAnswers() {
    return new Promise((resolve, reject) => {
      try {
        if (this.options[OPTIONS.YES_DEFAULT]) {
          // resolve questions that don't have default or stored answer
          const filtered = this.questions.ALL.filter(q => !this.defaultAnswers[q.name]);

          resolve(this.prompt(filtered).then(answers => {
            // combine answers with defaults
            return Object.assign({}, this.defaultAnswers, answers);
          }));
        } else if (this.options[OPTIONS.YES]) {
          // don't ask anything, just return answers
          resolve(Object.assign({}, this.defaultAnswers));
        } else {
          // ask all the questions
          resolve(this.prompt(this.questions.ALL));
        }
      } catch (e) {
        reject(e);
      }
    });
  }

  /**
   * Copies fileName to destination path with the same name
   * @param fileName
   * @param placeholders
   * @return {*}
   * @private
   */
  _fastCopy(fileName, placeholders) {
    return this.fs.copyTpl(
      this.templatePath(fileName),
      this.destinationPath(fileName),
      placeholders
    );
  }

  /**
   * Returns merged map of stored and default answers
   * @param config
   * @return {{name: *, email: *, website: null, moduleName: *, moduleDescription: *, githubUsername: null, camelModuleName: string, humanModuleName: string}}
   * @private
   */
  _getDefaultAnswers(config) {
    const name = config.name || this.user.git.name();
    const email = config.email || this.user.git.email();
    const website = config.website || null;
    const moduleName = path.basename(process.cwd());
    const moduleDescription = null;
    const githubUsername = config.githubUsername || null;
    const camelModuleName = utils.camelize(moduleName);
    const humanModuleName = utils.humanize(moduleName);
    // const gitRemote = githubUsername && `${githubUsername}/${moduleName}`;

    return {
      name, email, website, moduleName, moduleDescription, githubUsername, camelModuleName, humanModuleName
      // gitRemote
    };
  }

  /**
   * Async operations before initialing (load data, etc.)
   * @return {*}
   * @private
   */
  _beforeInit() {
    return this._initGithubUsername();
  }

  _initGithubUsername() {
    if (!this.defaultAnswers.githubUsername) {
      return this.user.github.username()
        .then(name => this.defaultAnswers.githubUsername = name);
    }

    return Promise.resolve(this.defaultAnswers.githubUsername);
  }

  _afterInit() {
    this.questions = prompts(this);
  }
};
<commit_msg>Add git commit and push options<commit_after>const Generator = require('yeoman-generator');
const path = require('path');
const utils = require('./utils');
const prompts = require('./prompts');
const which = require('which');

const OPTIONS = {
  COMMIT: 'commit',
  INIT_GIT: 'git',
  LATEST: 'latest',
  PUSH: 'push',
  YES: 'yes',
  YES_DEFAULT: 'yes-defaults'
};

// TODO replace file names with map
// const TEMPLATES = {
//   README: {
//     name: 'readme.md',
//     placeholders: []
//   }
// };

module.exports = class extends Generator {
  // get devDependencies() {
  //   // TODO add option to install latest versions or fixed
  //   return {
  //     "ava": "^0.18.2",
  //     "babel-loader": "^6.4.0",
  //     "babel-plugin-istanbul": "^4.0.0",
  //     "babel-preset-env": "^1.2.1",
  //     "babel-register": "^6.24.0",
  //     "codecov": "^2.0.1",
  //     "nyc": "^10.1.2",
  //     "webpack": "2.2.1",
  //     "xo": "^0.17.1"
  //   }
  // }
  get _remoteUrl() {
    if (this.answers.githubUsername && this.answers.moduleName) {
      return `https://github.com/${this.answers.githubUsername}/${this.answers.moduleName}`;
    }

    return null;
  }

  constructor(args, opts) {
    super(args, opts);

    this.option('yes-default', {
      alias: 'd',
      default: false,
      description: `Ask only questions which don't have default or saved answer`,
      type: Boolean
    });

    this.option(OPTIONS.YES, {
      alias: 'y',
      default: false,
      description: `Agree on every question, don't ask anything`,
      type: Boolean
    });

    this.option(OPTIONS.INIT_GIT, {
      alias: 'g',
      default: true,
      description: `Init git repository`,
      type: Boolean
    });

    this.option(OPTIONS.COMMIT, {
      alias: 'c',
      default: true,
      description: `Make initial commit`,
      type: Boolean
    });

    this.option(OPTIONS.PUSH, {
      alias: 'p',
      default: false,
      description: `Push commit`,
      type: Boolean
    });

    this.option(OPTIONS.LATEST, {
      alias: 'l',
      default: false,
      description: `Install latest versions of dependencies. (!) Correct work is not guaranteed`,
      type: Boolean
    });

    this.storedPrompt = this.config.get('promptValues') || {};
    this.defaultAnswers = this._getDefaultAnswers(this.storedPrompt);
    this.answers = {};
  }

  // Lifecycle hook
  initializing() {
    return this._beforeInit()
      .then(() => this._afterInit());
  }

  // Lifecycle hook
  prompting() {
    return this._getAnswers()
      .then(answers => {
        this.answers = answers
      });
  }

  // Lifecycle hook
  configuring() {
    this._fastCopy('.babelrc');
    this._fastCopy('.editorconfig');
    this._fastCopy('.gitattributes');
    this._fastCopy('.gitignore');
    this._fastCopy('.travis.yml');
  }

  // Lifecycle hook
  // default() {}

  // Lifecycle hook
  writing() {
    this._fastCopy('index.js');
    this._fastCopy('LICENSE', this.answers);
    this._fastCopy('package.json', this.answers);
    this._fastCopy('README.md', this.answers);
    this._fastCopy('test.js');
    this._fastCopy('webpack.config.babel.js');
    this._fastCopy('yarn.lock');
  }

  // Lifecycle hook
  // conflicts() {}

  // Lifecycle hook
  install() {
    this._installDependencies({
      isYarn: which.sync('yarn')
    });

    if (which.sync('git')) {
      if (this.options[OPTIONS.INIT_GIT]) {
        this.spawnCommandSync('git', ['init']);

        if (this.options[OPTIONS.COMMIT]) {
          this.spawnCommandSync('git', ['add', '.']);
          this.spawnCommandSync('git', ['commit', '-m', 'Initial']);

          const githubRepo = this._remoteUrl;

          if (this.options[OPTIONS.PUSH] && githubRepo) {
            this.spawnCommandSync('git', ['remote', 'add', 'origin', githubRepo]);
            this.spawnCommand('git', ['push', '-u', 'origin', 'master']);
          }
        }
      }
    }
    // if git is available
    // init git

    // make commit

    // if github repo exists && user agreed
    // push
  }

  // Lifecycle hook
  // end() {}

  /**
   *
   * @param isYarn
   * @private
   */
  _installDependencies({isYarn}) {
    let dependencies = [];
    let devDependencies = [];

    if (this.options[OPTIONS.LATEST]) {
      const packageJson = require(this.templatePath('package.json'));
      const setLatest = dep => `${dep}@latest`;

      dependencies = Object.keys(packageJson.dependencies).map(setLatest);
      devDependencies = Object.keys(packageJson.devDependencies).map(setLatest);
    }

    isYarn
      ? this.yarnInstall(dependencies)
      : this.npmInstall(dependencies);

    if (devDependencies.length > 0) {
      isYarn
        ? this.yarnInstall(devDependencies, {dev: true})
        : this.npmInstall(devDependencies, {'save-dev': true});
    }
  }

  /**
   * Returns answers either after prompting or on
   * @return {Promise}
   * @private
   */
  _getAnswers() {
    return new Promise((resolve, reject) => {
      try {
        if (this.options[OPTIONS.YES_DEFAULT]) {
          // resolve questions that don't have default or stored answer
          const filtered = this.questions.ALL.filter(q => !this.defaultAnswers[q.name]);

          resolve(this.prompt(filtered).then(answers => {
            // combine answers with defaults
            return Object.assign({}, this.defaultAnswers, answers);
          }));
        } else if (this.options[OPTIONS.YES]) {
          // don't ask anything, just return answers
          resolve(Object.assign({}, this.defaultAnswers));
        } else {
          // ask all the questions
          resolve(this.prompt(this.questions.ALL));
        }
      } catch (e) {
        reject(e);
      }
    });
  }

  /**
   * Copies fileName to destination path with the same name
   * @param fileName
   * @param placeholders
   * @return {*}
   * @private
   */
  _fastCopy(fileName, placeholders) {
    return this.fs.copyTpl(
      this.templatePath(fileName),
      this.destinationPath(fileName),
      placeholders
    );
  }

  /**
   * Returns merged map of stored and default answers
   * @param config
   * @return {{name: *, email: *, website: null, moduleName: *, moduleDescription: *, githubUsername: null, camelModuleName: string, humanModuleName: string}}
   * @private
   */
  _getDefaultAnswers(config) {
    const name = config.name || this.user.git.name();
    const email = config.email || this.user.git.email();
    const website = config.website || null;
    const moduleName = path.basename(process.cwd());
    const moduleDescription = null;
    const githubUsername = config.githubUsername || null;
    const camelModuleName = utils.camelize(moduleName);
    const humanModuleName = utils.humanize(moduleName);
    // const gitRemote = githubUsername && `${githubUsername}/${moduleName}`;

    return {
      name, email, website, moduleName, moduleDescription, githubUsername, camelModuleName, humanModuleName
      // gitRemote
    };
  }

  /**
   * Async operations before initialing (load data, etc.)
   * @return {*}
   * @private
   */
  _beforeInit() {
    return this._initGithubUsername();
  }

  _initGithubUsername() {
    if (!this.defaultAnswers.githubUsername) {
      return this.user.github.username()
        .then(name => this.defaultAnswers.githubUsername = name);
    }

    return Promise.resolve(this.defaultAnswers.githubUsername);
  }

  _afterInit() {
    this.questions = prompts(this);
  }
};
<|endoftext|>


<commit_before>const chalk = require('chalk');
const ora = require('ora');
const prettyMs = require('pretty-ms');
const print = console.log;
const printJson = require('jsome');
const logSymbols = require('log-symbols');
const emphasize = require('emphasize');
const map = require('lodash/map');

// json formatting
printJson.colors = {
  'num': 'cyan',
  'str': 'green',
  'bool': 'yellow',
  'regex': 'green',
  'undef': 'grey',
  'null': 'grey',
  'attr': ['white', 'bold'],
  'quot': 'green',
  'punc': 'grey',
  'brack': 'grey',
};

class DefaultFormatter {
  constructor(mode = 0) {
    this.spinner = null;
    this.mode = mode;
  }

  getRequestMessage(request) {
    return `${chalk.bgBlack.bold(request.method)} ${chalk.underline(request.url)}`;
  }

  startRequest(request) {
    let message = this.getRequestMessage(request);

    this.spinner = ora(message).start();
  }

  printResponse(response, ms) {
    let symbol, color;
    if (response.status >= 200 && response.status < 300) {
      symbol = logSymbols.success;
      color = chalk.green;
    } else if (response.status >= 400 && response.status < 500) {
      symbol = logSymbols.warning;
      color = chalk.yellow;
    } else if (response.status >= 500) {
      symbol = logSymbols.error;
      color = chalk.red;
    } else {
      symbol = chalk.cyan(process.platform === 'win32' ? 'i' : 'ℹ');
      color = chalk.cyan;
    }

    let requestMessage = this.getRequestMessage(response.config);
    let text = `${color.bold(response.status)} ${color(response.statusText)} `;

    if (this.mode >= 1) {
      text += requestMessage + ' ';
    }

    text += chalk.gray(`[${prettyMs(ms)}]`);
    text += '\n';

    this.spinner.stopAndPersist({symbol, text});

    // Print response headers in verbose mode.
    if (this.mode >= 1 && response.headers) {
      this.printHeaders(response);
    }
  }

  printHeaders(response) {
    map(response.headers, (value, key) => {
      print(`${chalk.bold(key)}${chalk.gray(':')} ${chalk.yellow(value)}`);
    });
    print();
  }

  printError(error, ms) {
    let requestMessage = this.getRequestMessage(error.config);
    let text = `${chalk.red.bold(error.code)} `;

    let details;
    switch (error.code) {
      case 'ENOTFOUND': details = 'The URL didn\'t resolve.'; break;
      default: details = 'An error occurred.';
    }

    text += chalk.red(details);

    if (this.mode >= 1) {
      text += ' ' + requestMessage;
    }

    text += chalk.gray(` [${prettyMs(ms)}]`);
    text += '\n';

    this.spinner.fail(text);

    // Print full error details in verbose mode.
    if (this.mode >= 1) {
      console.error(error.stack);
    }
  }

  printData(response) {
    if (! response.data) {
      return print(chalk.gray('<empty response>'));
    }

    // Handle pretty-printing common types of content (by header).
    if (response.headers && response.headers['content-type']) {
      let type = response.headers['content-type'];

      if (type.includes('application/json')) {
        return printJson(response.data);
      } else if (type.includes('text/html') || type.includes('application/xml')) {
        return print(emphasize.highlight('xml', response.data).value);
      } else if (type.includes('text/plain')) {
        return print(response.data);
      }
    }

    // ...or try to guess!
    return print(emphasize.highlightAuto(response.data).value);
  }
}

module.exports = DefaultFormatter;
<commit_msg>Output the spinner to stdout instead of stderr.<commit_after>const chalk = require('chalk');
const ora = require('ora');
const prettyMs = require('pretty-ms');
const print = console.log;
const printJson = require('jsome');
const logSymbols = require('log-symbols');
const emphasize = require('emphasize');
const map = require('lodash/map');

// json formatting
printJson.colors = {
  'num': 'cyan',
  'str': 'green',
  'bool': 'yellow',
  'regex': 'green',
  'undef': 'grey',
  'null': 'grey',
  'attr': ['white', 'bold'],
  'quot': 'green',
  'punc': 'grey',
  'brack': 'grey',
};

class DefaultFormatter {
  constructor(mode = 0) {
    this.spinner = null;
    this.mode = mode;
  }

  getRequestMessage(request) {
    return `${chalk.bgBlack.bold(request.method)} ${chalk.underline(request.url)}`;
  }

  startRequest(request) {
    let message = this.getRequestMessage(request);

    this.spinner = ora({message, stream: process.stdout});
    this.spinner.start();
  }

  printResponse(response, ms) {
    let symbol, color;
    if (response.status >= 200 && response.status < 300) {
      symbol = logSymbols.success;
      color = chalk.green;
    } else if (response.status >= 400 && response.status < 500) {
      symbol = logSymbols.warning;
      color = chalk.yellow;
    } else if (response.status >= 500) {
      symbol = logSymbols.error;
      color = chalk.red;
    } else {
      symbol = chalk.cyan(process.platform === 'win32' ? 'i' : 'ℹ');
      color = chalk.cyan;
    }

    let requestMessage = this.getRequestMessage(response.config);
    let text = `${color.bold(response.status)} ${color(response.statusText)} `;

    if (this.mode >= 1) {
      text += requestMessage + ' ';
    }

    text += chalk.gray(`[${prettyMs(ms)}]`);
    text += '\n';

    this.spinner.stopAndPersist({symbol, text});

    // Print response headers in verbose mode.
    if (this.mode >= 1 && response.headers) {
      this.printHeaders(response);
    }
  }

  printHeaders(response) {
    map(response.headers, (value, key) => {
      print(`${chalk.bold(key)}${chalk.gray(':')} ${chalk.yellow(value)}`);
    });
    print();
  }

  printError(error, ms) {
    let requestMessage = this.getRequestMessage(error.config);
    let text = `${chalk.red.bold(error.code)} `;

    let details;
    switch (error.code) {
      case 'ENOTFOUND': details = 'The URL didn\'t resolve.'; break;
      default: details = 'An error occurred.';
    }

    text += chalk.red(details);

    if (this.mode >= 1) {
      text += ' ' + requestMessage;
    }

    text += chalk.gray(` [${prettyMs(ms)}]`);
    text += '\n';

    this.spinner.fail(text);

    // Print full error details in verbose mode.
    if (this.mode >= 1) {
      console.error(error.stack);
    }
  }

  printData(response) {
    if (! response.data) {
      return print(chalk.gray('<empty response>'));
    }

    // Handle pretty-printing common types of content (by header).
    if (response.headers && response.headers['content-type']) {
      let type = response.headers['content-type'];

      if (type.includes('application/json')) {
        return printJson(response.data);
      } else if (type.includes('text/html') || type.includes('application/xml')) {
        return print(emphasize.highlight('xml', response.data).value);
      } else if (type.includes('text/plain')) {
        return print(response.data);
      }
    }

    // ...or try to guess!
    return print(emphasize.highlightAuto(response.data).value);
  }
}

module.exports = DefaultFormatter;
<|endoftext|>