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

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

    // add option to skip install
    this.option('skip-install');
  },
  initializing: function() {
    this.pkg = require('../../package.json');
  },
  prompting: {
    dirname: function () {
      this.log(yosay(
        'Welcome to the myun ' + chalk.red('generator-myun-vue ') + chalk.blue(this.pkg.version) + ' generator!'
      ));

      var done = this.async();
      var prompts = [
        {
          type: 'input',
          name: 'project',
          message: 'What is the project\'s name?',
          default: this.appname
        },
        {
          type: 'input',
          name: 'description',
          message: 'Enter project description'
        },
        {
          type: 'input',
          name: 'author',
          message: 'Enter project author name'
        },
        {
          type: 'input',
          name: 'version',
          message: 'Enter project version',
          default: 'v0.0.1'
        }
      ];

      this.prompt(prompts).then(function (answers) {
        this.projectName = answers.project;
        this.projectDes = answers.description;
        this.projectAuthor = answers.author;
        this.projectVersion = answers.version;

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

  writing: {
    packageJson: function () {
      this._copyTpl('_package.json', 'package.json', {
        projectName: this.projectName,
        projectDes: this.projectDes,
        projectAuthor: this.projectAuthor,
        projectVersion: this.projectVersion
      });
    },
    babel:function(){
      this._copy('_babelrc', '.babelrc');
    },
    editorconfig:function(){
      this._copy('_editorconfig', '.editorconfig');
    },
    eslint: function() {
      this._copy('_eslintrc.js', '.eslintrc.js');
    },
    gitattributes:function(){
      this._copy('_gitattributes', '.gitattributes');
    },
    gitignore: function() {
      this._copy('_gitignore', '.gitignore');
    },
    webpack: function() {
      mkdirp(this.destinationPath('./build'));
      this._copy('build/build.js', './build/build.js');
      this._copy('build/dev-client.js', './build/dev-client.js');
      this._copy('build/dev-server.js', './build/dev-server.js');
      this._copy('build/css-loaders.js', './build/css-loaders.js');
      this._copy('build/webpack.base.conf.js', './build/webpack.base.conf.js');
      this._copy('build/webpack.dev.conf.js', './build/webpack.dev.conf.js');
      this._copy('build/webpack.prod.conf.js', './build/webpack.prod.conf.js');
      mkdirp(this.destinationPath('./config'));
      this._copy('config/dev.env.js', './config/dev.env.js');
      this._copy('config/index.js', './config/index.js');
      this._copy('config/prod.env.js', './config/prod.env.js');
    },
    common: function() {
      mkdirp(this.destinationPath('./common'));
      this._copy('common/api.conf.js', './common/api.conf.js');
      this._copy('common/config.js', './common/config.js');
      this._copy('common/oss.conf.js', './common/oss.conf.js');
      this._copy('common/wx.conf.js', './common/wx.conf.js');
    },
    assets: function() {
      mkdirp(this.destinationPath('./src/assets'));
      this._copy('src/assets/pcd.js', './src/assets/pcd.js');
      this._copy('src/assets/config.js', './src/assets/config.js');
      this._copy('src/assets/function.js', './src/assets/function.js');
      this._copy('src/assets/lib.js', './src/assets/lib.js');
      this._copy('src/assets/myun.css', './src/assets/myun.css');
      mkdirp(this.destinationPath('./src/assets/font'));
      this._copy('src/assets/font/_gitkeep', './src/assets/font/.gitkeep');
      mkdirp(this.destinationPath('./src/assets/images'));
      this._copy('src/assets/images/_gitkeep', './src/assets/images/.gitkeep');
    },
    components: function() {
      mkdirp(this.destinationPath('./src/components'));
      this._copy('src/components/_gitkeep', './src/components/.gitkeep');
    },
    module: function() {
      mkdirp(this.destinationPath('./src/module/index'));
      this._copy('src/module/index/app.vue', './src/module/index/app.vue');
      this._copy('src/module/index/index.html', './src/module/index/index.html');
      this._copy('src/module/index/index.js', './src/module/index/index.js');
      mkdirp(this.destinationPath('./src/module/error'));
      this._copy('src/module/error/error.html', './src/module/error/error.html');
    },
    static: function() {
      mkdirp(this.destinationPath('./static'));
      this._copy('static/_gitkeep', './static/.gitkeep');
    },
    route: function() {
      mkdirp(this.destinationPath('./routes'));
      this._copy('routes/index.js', './routes/index.js');
    },
    bin: function() {
      mkdirp(this.destinationPath('./bin'));
      this._copy('bin/www', './bin/www');
    },
    app: function () {
      this._copy('_app.js', './app.js');
    },
    log: function () {
      mkdirp(this.destinationPath('./logs'));
      this._copy('logs/_gitkeep', './logs/.gitkeep');
      this._copy('_logger.js', './logger.js');
    }
  },
  _copy: function(from, to) {
    this.fs.copy(this.templatePath(from), this.destinationPath(to))
  },

  _copyTpl: function(from, to, params) {
    this.fs.copyTpl(this.templatePath(from), this.destinationPath(to), params)
  },
  install: function () {
    if (!this.options['skip-install']) this.installDependencies();
  }
});
<commit_msg>v1.0.6<commit_after>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var mkdirp = require('mkdirp');

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

    // add option to skip install
    this.option('skip-install');
  },
  initializing: function() {
    this.pkg = require('../../package.json');
    this.props = {};
  },
  prompting: {
    dirname: function () {
      this.log(yosay(
        'Welcome to the myun ' + chalk.red('generator-myun-vue ') + chalk.blue(this.pkg.version) + ' generator!'
      ));

      var done = this.async();
      var prompts = [
        {
          type: 'input',
          name: 'project',
          message: 'What is the project\'s name?'
        },
        {
          type: 'input',
          name: 'description',
          message: 'Enter project description'
        },
        {
          type: 'input',
          name: 'author',
          message: 'Enter project author name'
        },
        {
          type: 'input',
          name: 'version',
          message: 'Enter project version',
          default: 'v0.0.1'
        }
      ];

      this.prompt(prompts).then(function (answers) {
        this.projectName = answers.project;
        this.projectDes = answers.description;
        this.projectAuthor = answers.author;
        this.projectVersion = answers.version;
        this.props = props;
        done();
      }.bind(this));
    }
  },
  defaults: function () {
    if (path.basename(this.destinationPath()) !== this.props.projectName) {
      this.log(
        'Your generator must be inside a folder named ' + this.props.projectName + '\n' +
        'I\'ll automatically create this folder.'
      );
      mkdirp(this.props.projectName);
      this.destinationRoot(this.destinationPath(this.props.projectName));
    }
  },
  writing: {
    packageJson: function () {
      this._copyTpl('_package.json', 'package.json', {
        projectName: this.projectName,
        projectDes: this.projectDes,
        projectAuthor: this.projectAuthor,
        projectVersion: this.projectVersion
      });
    },
    babel:function(){
      this._copy('_babelrc', '.babelrc');
    },
    editorconfig:function(){
      this._copy('_editorconfig', '.editorconfig');
    },
    eslint: function() {
      this._copy('_eslintrc.js', '.eslintrc.js');
    },
    gitattributes:function(){
      this._copy('_gitattributes', '.gitattributes');
    },
    gitignore: function() {
      this._copy('_gitignore', '.gitignore');
    },
    webpack: function() {
      mkdirp(this.destinationPath('./build'));
      this._copy('build/build.js', './build/build.js');
      this._copy('build/dev-client.js', './build/dev-client.js');
      this._copy('build/dev-server.js', './build/dev-server.js');
      this._copy('build/css-loaders.js', './build/css-loaders.js');
      this._copy('build/webpack.base.conf.js', './build/webpack.base.conf.js');
      this._copy('build/webpack.dev.conf.js', './build/webpack.dev.conf.js');
      this._copy('build/webpack.prod.conf.js', './build/webpack.prod.conf.js');
      mkdirp(this.destinationPath('./config'));
      this._copy('config/dev.env.js', './config/dev.env.js');
      this._copy('config/index.js', './config/index.js');
      this._copy('config/prod.env.js', './config/prod.env.js');
    },
    common: function() {
      mkdirp(this.destinationPath('./common'));
      this._copy('common/api.conf.js', './common/api.conf.js');
      this._copy('common/config.js', './common/config.js');
      this._copy('common/oss.conf.js', './common/oss.conf.js');
      this._copy('common/wx.conf.js', './common/wx.conf.js');
    },
    assets: function() {
      mkdirp(this.destinationPath('./src/assets'));
      this._copy('src/assets/pcd.js', './src/assets/pcd.js');
      this._copy('src/assets/config.js', './src/assets/config.js');
      this._copy('src/assets/function.js', './src/assets/function.js');
      this._copy('src/assets/lib.js', './src/assets/lib.js');
      this._copy('src/assets/myun.css', './src/assets/myun.css');
      mkdirp(this.destinationPath('./src/assets/font'));
      this._copy('src/assets/font/_gitkeep', './src/assets/font/.gitkeep');
      mkdirp(this.destinationPath('./src/assets/images'));
      this._copy('src/assets/images/_gitkeep', './src/assets/images/.gitkeep');
    },
    components: function() {
      mkdirp(this.destinationPath('./src/components'));
      this._copy('src/components/_gitkeep', './src/components/.gitkeep');
    },
    module: function() {
      mkdirp(this.destinationPath('./src/module/index'));
      this._copy('src/module/index/app.vue', './src/module/index/app.vue');
      this._copy('src/module/index/index.html', './src/module/index/index.html');
      this._copy('src/module/index/index.js', './src/module/index/index.js');
      mkdirp(this.destinationPath('./src/module/error'));
      this._copy('src/module/error/error.html', './src/module/error/error.html');
    },
    static: function() {
      mkdirp(this.destinationPath('./static'));
      this._copy('static/_gitkeep', './static/.gitkeep');
    },
    route: function() {
      mkdirp(this.destinationPath('./routes'));
      this._copy('routes/index.js', './routes/index.js');
    },
    bin: function() {
      mkdirp(this.destinationPath('./bin'));
      this._copy('bin/www', './bin/www');
    },
    app: function () {
      this._copy('_app.js', './app.js');
    },
    log: function () {
      mkdirp(this.destinationPath('./logs'));
      this._copy('logs/_gitkeep', './logs/.gitkeep');
      this._copy('_logger.js', './logger.js');
    }
  },
  _copy: function(from, to) {
    this.fs.copy(this.templatePath(from), this.destinationPath(to))
  },

  _copyTpl: function(from, to, params) {
    this.fs.copyTpl(this.templatePath(from), this.destinationPath(to), params)
  },
  install: function () {
    if (!this.options['skip-install']) this.installDependencies();
  }
});
<|endoftext|>


<commit_before>const { Argument } = require('klasa');

module.exports = class extends Argument {

	run(arg, possible, message) {
		if (arg.toLowerCase() === possible.name.toLowerCase()) return arg.toLowerCase();
		throw (message.language || this.client.languages.default).get('RESOLVER_INVALID_LITERAL', possible.name);
	}

};
<commit_msg>fix literal to be returned in the case the dev defined it<commit_after>const { Argument } = require('klasa');

module.exports = class extends Argument {

	run(arg, possible, message) {
		if (arg.toLowerCase() === possible.name.toLowerCase()) return possible.name;
		throw (message.language || this.client.languages.default).get('RESOLVER_INVALID_LITERAL', possible.name);
	}

};
<|endoftext|>


<commit_before>var path = require("path");
var generators = require('yeoman-generator');

// 颜色
var chalk = require("chalk");

// yeoman的图标
var yosay = require("yosay");

// underscore 工具
var _ = require("underscore.string");

module.exports = generators.Base.extend({
    method1: function () {
        console.log('method 1 just ran');
    },
    constructor: function () {

        generators.Base.apply(this, arguments)

        //在这拿到传参和选项
    },

    initializing: function () {
        //默认配置，从环境变量中读取
        this.defaultOption = {
            user: process.env.USERNAME || 'nodefaultuser', // TODO windows下是USERNAME，USER貌似没起作用
            appname: this._getValidAppName(path.basename(process.cwd()))
        };

        //this.appPath = this.env.options.appPath;
        return this.pkg = require("../../package.json");
    },

    prompting: function () {

        // 异步调用
        var done = this.async();

        // 欢迎界面
        console.log(yosay("Welcome to the " + (chalk.red("MyTest")) + " generator"));

        var prompts = [{
            name: "appname", // 应用名称，最终会将生成小驼峰结果
            message: "What's the name of your app?",
            "default": this.defaultOption.appname
        }, {
            name: 'author', // 作者
            message: 'Author:',
            default: this.defaultOption.user
        }, {
            type: "list",
            name: "stylesheet", // 使用哪种stylesheet
            "default": 0,
            message: "What would you like to write stylesheets with?",
            choices: ["CSS", "Less"],
            filter: function (val) {
                return val.toLowerCase();
            }
        }, {
            type: "list",
            name: "cssdeploy", // 发布版本时，css以哪种方式引入
            "default": 1,
            message: "What would you like to deal html when deploy with css link?",
            choices: ["Suffix", "Embed", "Inline"],
            filter: function (val) {
                return val.toLowerCase();
            }
        }, {
            type: "list",
            name: "jsdeploy", // 发布版本时，js以哪种方式引入
            "default": 1,
            message: "What would you like to deal html when deploy with javaScript link?",
            choices: ["Suffix", "Embed", "Inline"],
            filter: function (val) {
                return val.toLowerCase();
            }
        }];

        // 所有的用户参数结果存储于此
        this.userOption = {};

        return this.prompt(prompts, function (answers) {
            this.userOption = answers;

            // 对appname进行处理，不能包括空格等
            this.userOption.appname = this._getValidAppName(this.userOption.appname);

            // 遍历展现用户选择的结果
            // for (var key in this.userOption) {
            //     this.log(this.userOption[key]);
            // }

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

    writing: function () {

        //生成 grunt 配置文件 Gruntfile.js
        this.fs.copyTpl(
            this.templatePath('_Gruntfile.js'),
            this.destinationPath('Gruntfile.js'),
            this.userOption
        );

        //生成 node 配置文件 package.json
        this.fs.copyTpl(
            this.templatePath('_package.json'),
            this.destinationPath('package.json'),
            this.userOption
        );

        //生成 html 页面
        this.fs.copyTpl(
            this.templatePath('html/index.html'),
            this.destinationPath('resource/html/index.html'),
            this.userOption
        );

        //拷贝js
        this.fs.copy(
            this.templatePath('js/**/*'),
            this.destinationPath('resource/js')
        );

        //拷贝css
        this.fs.copy(
            this.templatePath('css/**/*'),
            this.destinationPath('resource/css')
        );

        //拷贝less，只有在stylesheet=less时才拷贝
        if (this.userOption.stylesheet == "less") {
            this.fs.copy(
                this.templatePath('less/**/*'),
                this.destinationPath('resource/less')
            );
        }

        //拷贝img
        this.fs.copy(
            this.templatePath('img/**/*'),
            this.destinationPath('resource/img')
        );

    },

    install: function () {
        this.log('Install Grunt plugins ... ');

        // this.installDependencies({
        //     callback: function () {
        //         this.log('grunt 及其插件安装完毕。');

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

    end: function () {
        //存储用户默认配置
        this.config.set(this.userOption);

        return this.config.save(); // 此处调用可以省略
    },

    _getValidAppName: function (name) {
        return _.camelize(_.slugify(_.humanize(name)));
    }
});
<commit_msg>增加 --lazy 参数，可以不再自动运行npm install等<commit_after>var path = require("path");
var generators = require('yeoman-generator');

// 颜色
var chalk = require("chalk");

// yeoman的图标
var yosay = require("yosay");

// underscore 工具
var _ = require("underscore.string");

module.exports = generators.Base.extend({
    method1: function () {
        console.log('method 1 just ran');
    },
    constructor: function () {

        generators.Base.apply(this, arguments)

        // This method adds support for a `--coffee` flag
        this.option('lazy', {"desc": "Do not npm install or brower insall."});

        // And you can then access it later on this way; e.g.
        this.lazyInstall = !!this.options.lazy;
    },

    initializing: function () {
        //默认配置，从环境变量中读取
        this.defaultOption = {
            user: process.env.USERNAME || 'nodefaultuser', // TODO windows下是USERNAME，USER貌似没起作用
            appname: this._getValidAppName(path.basename(process.cwd()))
        };

        //this.appPath = this.env.options.appPath;
        return this.pkg = require("../../package.json");
    },

    prompting: function () {

        // 异步调用
        var done = this.async();

        // 欢迎界面
        console.log(yosay("Welcome to the " + chalk.red("GruntH5") + " generator"));

        var prompts = [{
            name: "appname", // 应用名称，最终会将生成小驼峰结果
            message: "What's the name of your app?",
            "default": this.defaultOption.appname
        }, {
            name: 'author', // 作者
            message: 'Author:',
            default: this.defaultOption.user
        }, {
            type: "list",
            name: "stylesheet", // 使用哪种stylesheet
            "default": 0,
            message: "What would you like to write stylesheets with?",
            choices: ["CSS", "Less"],
            filter: function (val) {
                return val.toLowerCase();
            }
        }, {
            type: "list",
            name: "cssdeploy", // 发布版本时，css以哪种方式引入
            "default": 1,
            message: "What would you like to deal html when deploy with css link?",
            choices: ["Suffix", "Embed", "Inline"],
            filter: function (val) {
                return val.toLowerCase();
            }
        }, {
            type: "list",
            name: "jsdeploy", // 发布版本时，js以哪种方式引入
            "default": 1,
            message: "What would you like to deal html when deploy with javaScript link?",
            choices: ["Suffix", "Embed", "Inline"],
            filter: function (val) {
                return val.toLowerCase();
            }
        }];

        // 所有的用户参数结果存储于此
        this.userOption = {};

        return this.prompt(prompts, function (answers) {
            this.userOption = answers;

            // 对appname进行处理，不能包括空格等
            this.userOption.appname = this._getValidAppName(this.userOption.appname);

            // 遍历展现用户选择的结果
            // for (var key in this.userOption) {
            //     this.log(this.userOption[key]);
            // }

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

    writing: function () {

        //生成 grunt 配置文件 Gruntfile.js
        this.fs.copyTpl(
            this.templatePath('_Gruntfile.js'),
            this.destinationPath('Gruntfile.js'),
            this.userOption
        );

        //生成 node 配置文件 package.json
        this.fs.copyTpl(
            this.templatePath('_package.json'),
            this.destinationPath('package.json'),
            this.userOption
        );

        //生成 html 页面
        this.fs.copyTpl(
            this.templatePath('html/index.html'),
            this.destinationPath('resource/html/index.html'),
            this.userOption
        );

        //拷贝js
        this.fs.copy(
            this.templatePath('js/**/*'),
            this.destinationPath('resource/js')
        );

        //拷贝css
        this.fs.copy(
            this.templatePath('css/**/*'),
            this.destinationPath('resource/css')
        );

        //拷贝less，只有在stylesheet=less时才拷贝
        if (this.userOption.stylesheet == "less") {
            this.fs.copy(
                this.templatePath('less/**/*'),
                this.destinationPath('resource/less')
            );
        }

        //拷贝img
        this.fs.copy(
            this.templatePath('img/**/*'),
            this.destinationPath('resource/img')
        );

    },

    install: function () {
        // 如果有--lazy选项，则不再自动运行 npm install & bower install
        if (this.lazyInstall) {
            this.log('You should run ' + chalk.blue('npm install & bower install') + ' yourself next!');
        } else {
            this.log('Install Grunt plugins ... ');

            // this.installDependencies({
            //     callback: function () {
            //         this.log('grunt 及其插件安装完毕。');
            //     }.bind(this)
            // });
        }
    },

    end: function () {
        //存储用户默认配置
        this.config.set(this.userOption);

        return this.config.save(); // 此处调用可以省略
    },

    _getValidAppName: function (name) {
        return _.camelize(_.slugify(_.humanize(name)));
    }
});
<|endoftext|>


<commit_before>/* eslint-disable no-extend-native */
import {ModifyCollectionObserver} from './collection-observation';
import * as LogManager from 'aurelia-logging';

const arrayProto = Array.prototype;
const pop = arrayProto.pop;
const push = arrayProto.push;
const reverse = arrayProto.reverse;
const shift = arrayProto.shift;
const sort = arrayProto.sort;
const splice = arrayProto.splice;
const unshift = arrayProto.unshift;

if (arrayProto.__au_patched__) {
  LogManager
    .getLogger('array-observation')
    .warn('Detected 2nd attempt of patching array from Aurelia binding.'
      + ' This is probably caused by dependency mismatch between core modules and a 3rd party plugin.'
      + ' Please see https://github.com/aurelia/cli/pull/906 if you are using webpack.'
    );
} else {
  arrayProto.__au_patched__ = 1;
  arrayProto.pop = function() {
    let notEmpty = this.length > 0;
    let methodCallResult = pop.apply(this, arguments);
    if (notEmpty && this.__array_observer__ !== undefined) {
      this.__array_observer__.addChangeRecord({
        type: 'delete',
        object: this,
        name: this.length,
        oldValue: methodCallResult
      });
    }
    return methodCallResult;
  };

  arrayProto.push = function() {
    let methodCallResult = push.apply(this, arguments);
    if (this.__array_observer__ !== undefined) {
      this.__array_observer__.addChangeRecord({
        type: 'splice',
        object: this,
        index: this.length - arguments.length,
        removed: [],
        addedCount: arguments.length
      });
    }
    return methodCallResult;
  };

  arrayProto.reverse = function() {
    let oldArray;
    if (this.__array_observer__ !== undefined) {
      this.__array_observer__.flushChangeRecords();
      oldArray = this.slice();
    }
    let methodCallResult = reverse.apply(this, arguments);
    if (this.__array_observer__ !== undefined) {
      this.__array_observer__.reset(oldArray);
    }
    return methodCallResult;
  };

  arrayProto.shift = function() {
    let notEmpty = this.length > 0;
    let methodCallResult = shift.apply(this, arguments);
    if (notEmpty && this.__array_observer__ !== undefined) {
      this.__array_observer__.addChangeRecord({
        type: 'delete',
        object: this,
        name: 0,
        oldValue: methodCallResult
      });
    }
    return methodCallResult;
  };

  arrayProto.sort = function() {
    let oldArray;
    if (this.__array_observer__ !== undefined) {
      this.__array_observer__.flushChangeRecords();
      oldArray = this.slice();
    }
    let methodCallResult = sort.apply(this, arguments);
    if (this.__array_observer__ !== undefined) {
      this.__array_observer__.reset(oldArray);
    }
    return methodCallResult;
  };

  arrayProto.splice = function() {
    let methodCallResult = splice.apply(this, arguments);
    if (this.__array_observer__ !== undefined) {
      this.__array_observer__.addChangeRecord({
        type: 'splice',
        object: this,
        index: +arguments[0],
        removed: methodCallResult,
        addedCount: arguments.length > 2 ? arguments.length - 2 : 0
      });
    }
    return methodCallResult;
  };

  arrayProto.unshift = function() {
    let methodCallResult = unshift.apply(this, arguments);
    if (this.__array_observer__ !== undefined) {
      this.__array_observer__.addChangeRecord({
        type: 'splice',
        object: this,
        index: 0,
        removed: [],
        addedCount: arguments.length
      });
    }
    return methodCallResult;
  };
}

export function getArrayObserver(taskQueue, array) {
  return ModifyArrayObserver.for(taskQueue, array);
}

class ModifyArrayObserver extends ModifyCollectionObserver {
  constructor(taskQueue, array) {
    super(taskQueue, array);
  }

  /**
   * Searches for observer or creates a new one associated with given array instance
   * @param taskQueue
   * @param array instance for which observer is searched
   * @returns ModifyArrayObserver always the same instance for any given array instance
   */
  static for(taskQueue, array) {
    if (!('__array_observer__' in array)) {
      Reflect.defineProperty(array, '__array_observer__', {
        value: ModifyArrayObserver.create(taskQueue, array),
        enumerable: false, configurable: false
      });
    }
    return array.__array_observer__;
  }

  static create(taskQueue, array) {
    return new ModifyArrayObserver(taskQueue, array);
  }
}
<commit_msg>fix(array-observation): make marker non enumerable<commit_after>/* eslint-disable no-extend-native */
import {ModifyCollectionObserver} from './collection-observation';
import * as LogManager from 'aurelia-logging';

const arrayProto = Array.prototype;
const pop = arrayProto.pop;
const push = arrayProto.push;
const reverse = arrayProto.reverse;
const shift = arrayProto.shift;
const sort = arrayProto.sort;
const splice = arrayProto.splice;
const unshift = arrayProto.unshift;

if (arrayProto.__au_patched__) {
  LogManager
    .getLogger('array-observation')
    .warn('Detected 2nd attempt of patching array from Aurelia binding.'
      + ' This is probably caused by dependency mismatch between core modules and a 3rd party plugin.'
      + ' Please see https://github.com/aurelia/cli/pull/906 if you are using webpack.'
    );
} else {
  Reflect.defineProperty(arrayProto, '__au_patched__', { value: 1 });
  arrayProto.pop = function() {
    let notEmpty = this.length > 0;
    let methodCallResult = pop.apply(this, arguments);
    if (notEmpty && this.__array_observer__ !== undefined) {
      this.__array_observer__.addChangeRecord({
        type: 'delete',
        object: this,
        name: this.length,
        oldValue: methodCallResult
      });
    }
    return methodCallResult;
  };

  arrayProto.push = function() {
    let methodCallResult = push.apply(this, arguments);
    if (this.__array_observer__ !== undefined) {
      this.__array_observer__.addChangeRecord({
        type: 'splice',
        object: this,
        index: this.length - arguments.length,
        removed: [],
        addedCount: arguments.length
      });
    }
    return methodCallResult;
  };

  arrayProto.reverse = function() {
    let oldArray;
    if (this.__array_observer__ !== undefined) {
      this.__array_observer__.flushChangeRecords();
      oldArray = this.slice();
    }
    let methodCallResult = reverse.apply(this, arguments);
    if (this.__array_observer__ !== undefined) {
      this.__array_observer__.reset(oldArray);
    }
    return methodCallResult;
  };

  arrayProto.shift = function() {
    let notEmpty = this.length > 0;
    let methodCallResult = shift.apply(this, arguments);
    if (notEmpty && this.__array_observer__ !== undefined) {
      this.__array_observer__.addChangeRecord({
        type: 'delete',
        object: this,
        name: 0,
        oldValue: methodCallResult
      });
    }
    return methodCallResult;
  };

  arrayProto.sort = function() {
    let oldArray;
    if (this.__array_observer__ !== undefined) {
      this.__array_observer__.flushChangeRecords();
      oldArray = this.slice();
    }
    let methodCallResult = sort.apply(this, arguments);
    if (this.__array_observer__ !== undefined) {
      this.__array_observer__.reset(oldArray);
    }
    return methodCallResult;
  };

  arrayProto.splice = function() {
    let methodCallResult = splice.apply(this, arguments);
    if (this.__array_observer__ !== undefined) {
      this.__array_observer__.addChangeRecord({
        type: 'splice',
        object: this,
        index: +arguments[0],
        removed: methodCallResult,
        addedCount: arguments.length > 2 ? arguments.length - 2 : 0
      });
    }
    return methodCallResult;
  };

  arrayProto.unshift = function() {
    let methodCallResult = unshift.apply(this, arguments);
    if (this.__array_observer__ !== undefined) {
      this.__array_observer__.addChangeRecord({
        type: 'splice',
        object: this,
        index: 0,
        removed: [],
        addedCount: arguments.length
      });
    }
    return methodCallResult;
  };
}

export function getArrayObserver(taskQueue, array) {
  return ModifyArrayObserver.for(taskQueue, array);
}

class ModifyArrayObserver extends ModifyCollectionObserver {
  constructor(taskQueue, array) {
    super(taskQueue, array);
  }

  /**
   * Searches for observer or creates a new one associated with given array instance
   * @param taskQueue
   * @param array instance for which observer is searched
   * @returns ModifyArrayObserver always the same instance for any given array instance
   */
  static for(taskQueue, array) {
    if (!('__array_observer__' in array)) {
      Reflect.defineProperty(array, '__array_observer__', {
        value: ModifyArrayObserver.create(taskQueue, array),
        enumerable: false, configurable: false
      });
    }
    return array.__array_observer__;
  }

  static create(taskQueue, array) {
    return new ModifyArrayObserver(taskQueue, array);
  }
}
<|endoftext|>


<commit_before>'use strict';

const Generator = require('yeoman-generator');
const chalk = require('chalk');
const yosay = require('yosay');
const _ = require('lodash');
const isInstalled = require('is-installed');

module.exports = Generator.extend({
  prompting: function() {

    this.log(yosay(`Welcome to the awe-inspiring ${chalk.red('generator-angular-library')} generator!`));

    const required = val => !!val;

    const githubUsernamePromise = new Promise(resolve => {
      try {
        this.user.github.username((err, username) => resolve(username));
      } catch (e) {
        resolve('');
      }
    });

    return githubUsernamePromise.then(githubUsername => {
      const prompts = [{
        type: 'input',
        name: 'githubUsername',
        message: 'What is the github project organisation or username?',
        validate: required,
        default: githubUsername
      }, {
        type: 'input',
        name: 'githubRepoName',
        message: 'What is the github repository name?',
        default: this.appname.replace(/ /g, '-')
      }, {
        type: 'input',
        name: 'npmModuleName',
        message: 'What is the npm module name?',
        default: this.appname.replace(/ /g, '-')
      }, {
        type: 'input',
        name: 'moduleGlobal',
        message: 'What should the module be exported as on the window for users not using module bundlers?',
        validate: required,
        default(answers) {
          return _.camelCase(answers.npmModuleName);
        }
      }, {
        type: 'input',
        name: 'ngModuleName',
        message: 'What should the NgModule name be?',
        validate: required,
        default(answers) {
          return _.upperFirst(_.camelCase(answers.npmModuleName)) + 'Module';
        }
      }, {
        type: 'input',
        name: 'selectorPrefix',
        message: 'What should the component / directive selector prefix be',
        validate: required
      }, {
        type: 'input',
        name: 'projectTitle',
        message: 'What is the human readable project title?',
        default: this.determineAppname()
      }, {
        type: 'input',
        name: 'projectDescription',
        message: 'What is the project description?'
      }, {
        type: 'input',
        name: 'authorName',
        message: 'What is the author name?',
        default: this.user.git.name()
      }];

      return this.prompt(prompts);

    }).then(props => {
      this.props = props;
      this.props.ngModuleFilename = _.lowerFirst(`${this.props.ngModuleName.replace(/Module$/, '')}.module.ts`);
    });

  },

  writing: function() {

    const folders = ['demo', 'test'];
    folders.forEach(folder => {
      this.fs.copyTpl(
        this.templatePath(`${folder}/**`),
        this.destinationPath(folder),
        this.props
      );
    });

    const files = [
      '.editorconfig',
      '.travis.yml',
      'karma.conf.js',
      'LICENSE',
      'README.md',
      'tsconfig.json',
      'tsconfig-ngc.json',
      'tsconfig-compodoc.json',
      'tslint.json',
      'webpack.config.umd.js',
      'webpack.config.js',
      'src/helloWorld.component.ts',
      'src/index.ts'
    ];
    files.forEach(file => {
      this.fs.copyTpl(
        this.templatePath(file),
        this.destinationPath(file),
        this.props
      );
    });

    this.fs.copyTpl(
      this.templatePath('_package.json'),
      this.destinationPath('package.json'),
      this.props
    );

    this.fs.copyTpl(
      this.templatePath('_.gitignore'),
      this.destinationPath('.gitignore'),
      this.props
    );

    this.fs.copyTpl(
      this.templatePath('_.npmrc'),
      this.destinationPath('.npmrc'),
      this.props
    );

    this.fs.copyTpl(
      this.templatePath('src/ngModule.module.ts'),
      this.destinationPath('src/' + this.props.ngModuleFilename),
      this.props
    );

  },

  install: function() {
    this.log('Make sure to now create the gh-pages branch:');
    this.log('`git branch gh-pages && git checkout gh-pages && git push --set-upstream origin gh-pages && git checkout master`');
    return isInstalled('yarn').then(exists => {
      if (exists) {
        this.yarnInstall();
      } else {
        this.npmInstall();
      }
    });
  }
});
<commit_msg>Warn the user when they try and start a package with ng2 or angular2. Closes #19<commit_after>'use strict';

const Generator = require('yeoman-generator');
const chalk = require('chalk');
const yosay = require('yosay');
const _ = require('lodash');
const isInstalled = require('is-installed');

module.exports = Generator.extend({
  prompting: function() {

    this.log(yosay(`Welcome to the awe-inspiring ${chalk.red('generator-angular-library')} generator!`));

    const required = val => !!val;

    const githubUsernamePromise = new Promise(resolve => {
      try {
        this.user.github.username((err, username) => resolve(username));
      } catch (e) {
        resolve('');
      }
    });

    return githubUsernamePromise.then(githubUsername => {
      const prompts = [{
        type: 'input',
        name: 'githubUsername',
        message: 'What is the github project organisation or username?',
        validate: required,
        default: githubUsername
      }, {
        type: 'input',
        name: 'githubRepoName',
        message: 'What is the github repository name?',
        default: this.appname.replace(/ /g, '-')
      }, {
        type: 'input',
        name: 'npmModuleName',
        message: 'What is the npm module name?',
        default: this.appname.replace(/ /g, '-')
      }, {
        type: 'confirm',
        name: 'allowNg2InModuleName',
        message: 'Starting angular module names with ng2 or angular2 is not advised as angular now follows semver. It is recommended that you start your library name with just angular. Would you like to continue anyway?',
        default: false,
        when(answers) {
          return answers.npmModuleName.startsWith('ng2') || answers.npmModuleName.startsWith('angular2');
        }
      }, {
        type: 'input',
        name: 'moduleGlobal',
        message: 'What should the module be exported as on the window for users not using module bundlers?',
        validate: required,
        default: (answers) => {

          if (answers.allowNg2InModuleName === false) {
            this.log('Please start again with a new package name that doesnt start with ng2 or angular2.');
            process.exit();
          }

          return _.camelCase(answers.npmModuleName);
        }
      }, {
        type: 'input',
        name: 'ngModuleName',
        message: 'What should the NgModule name be?',
        validate: required,
        default(answers) {
          return _.upperFirst(_.camelCase(answers.npmModuleName)) + 'Module';
        }
      }, {
        type: 'input',
        name: 'selectorPrefix',
        message: 'What should the component / directive selector prefix be',
        validate: required
      }, {
        type: 'input',
        name: 'projectTitle',
        message: 'What is the human readable project title?',
        default: this.determineAppname()
      }, {
        type: 'input',
        name: 'projectDescription',
        message: 'What is the project description?'
      }, {
        type: 'input',
        name: 'authorName',
        message: 'What is the author name?',
        default: this.user.git.name()
      }];

      return this.prompt(prompts);

    }).then(props => {
      this.props = props;
      this.props.ngModuleFilename = _.lowerFirst(`${this.props.ngModuleName.replace(/Module$/, '')}.module.ts`);
    });

  },

  writing: function() {

    const folders = ['demo', 'test'];
    folders.forEach(folder => {
      this.fs.copyTpl(
        this.templatePath(`${folder}/**`),
        this.destinationPath(folder),
        this.props
      );
    });

    const files = [
      '.editorconfig',
      '.travis.yml',
      'karma.conf.js',
      'LICENSE',
      'README.md',
      'tsconfig.json',
      'tsconfig-ngc.json',
      'tsconfig-compodoc.json',
      'tslint.json',
      'webpack.config.umd.js',
      'webpack.config.js',
      'src/helloWorld.component.ts',
      'src/index.ts'
    ];
    files.forEach(file => {
      this.fs.copyTpl(
        this.templatePath(file),
        this.destinationPath(file),
        this.props
      );
    });

    this.fs.copyTpl(
      this.templatePath('_package.json'),
      this.destinationPath('package.json'),
      this.props
    );

    this.fs.copyTpl(
      this.templatePath('_.gitignore'),
      this.destinationPath('.gitignore'),
      this.props
    );

    this.fs.copyTpl(
      this.templatePath('_.npmrc'),
      this.destinationPath('.npmrc'),
      this.props
    );

    this.fs.copyTpl(
      this.templatePath('src/ngModule.module.ts'),
      this.destinationPath('src/' + this.props.ngModuleFilename),
      this.props
    );

  },

  install: function() {
    this.log('Make sure to now create the gh-pages branch:');
    this.log('`git branch gh-pages && git checkout gh-pages && git push --set-upstream origin gh-pages && git checkout master`');
    return isInstalled('yarn').then(exists => {
      if (exists) {
        this.yarnInstall();
      } else {
        this.npmInstall();
      }
    });
  }
});
<|endoftext|>


<commit_before>const util = require('util');
const chalk = require('chalk');
const glob = require('glob');
const generator = require('yeoman-generator');
const packagejs = require('../../package.json');
const semver = require('semver');
const BaseGenerator = require('../common');
const jhipsterConstants = require('generator-jhipster/generators/generator-constants');

const JhipsterGenerator = generator.extend({});
util.inherits(JhipsterGenerator, BaseGenerator);

module.exports = JhipsterGenerator.extend({
    initializing: {
        readConfig() {
            this.jhipsterAppConfig = this.getJhipsterAppConfig();
            if (!this.jhipsterAppConfig) {
                this.error('Can\'t read .yo-rc.json');
            }
        },
        displayLogo() {
            // it's here to show that you can use functions from generator-jhipster
            // this function is in: generator-jhipster/generators/generator-base.js
            this.printJHipsterLogo();

            // Have Yeoman greet the user.
            this.log(`\nWelcome to the ${chalk.bold.yellow('JHipster postgresuuid-converter')} generator! ${chalk.yellow(`v${packagejs.version}\n`)}`);
        },
        checkJhipster() {
            const jhipsterVersion = this.jhipsterAppConfig.jhipsterVersion;
            const minimumJhipsterVersion = packagejs.dependencies['generator-jhipster'];
            if (!semver.satisfies(jhipsterVersion, minimumJhipsterVersion)) {
                this.warning(`\nYour generated project used an old JHipster version (${jhipsterVersion})... you need at least (${minimumJhipsterVersion})\n`);
            }
        }
    },

    prompting() {
        const prompts = [];
        const done = this.async();
        this.prompt(prompts).then((props) => {
            this.props = props;
            // To access props later use this.props.someOption;

            done();
        });
    },

    writing() {
        // function to use directly template
        this.template = function (source, destination) {
            this.fs.copyTpl(
                this.templatePath(source),
                this.destinationPath(destination),
                this
            );
        };

        // function to check if this generator has already run or not.
        this.isFirstRun = function () {
            return true;
        };

        // read config from .yo-rc.json
        this.baseName = this.jhipsterAppConfig.baseName;
        this.packageName = this.jhipsterAppConfig.packageName;
        this.packageFolder = this.jhipsterAppConfig.packageFolder;
        this.clientFramework = this.jhipsterAppConfig.clientFramework;
        this.clientPackageManager = this.jhipsterAppConfig.clientPackageManager;
        this.buildTool = this.jhipsterAppConfig.buildTool;

        // use function in generator-base.js from generator-jhipster
        // this.angularAppName = this.getAngularAppName();

        // use constants from generator-constants.js
        const javaDir = `${jhipsterConstants.SERVER_MAIN_SRC_DIR + this.packageFolder}/`;
        const javaTestDir = `${jhipsterConstants.SERVER_TEST_SRC_DIR + this.packageFolder}/`;
        // const resourceDir = jhipsterConstants.SERVER_MAIN_RES_DIR;
        // const webappDir = jhipsterConstants.CLIENT_MAIN_SRC_DIR;

        // variable from questions
        this.message = this.props.message;

        // show all variables
        // this.log('\n--- some config read from config ---');
        // this.log(`baseName=${this.baseName}`);
        // this.log(`packageName=${this.packageName}`);
        // this.log(`clientFramework=${this.clientFramework}`);
        // this.log(`clientPackageManager=${this.clientPackageManager}`);
        // this.log(`buildTool=${this.buildTool}`);
        //
        // this.log('\n--- some function ---');
        // this.log(`angularAppName=${this.angularAppName}`);
        //
        // this.log('\n--- some const ---');
        // this.log(`javaDir=${javaDir}`);
        // this.log(`resourceDir=${resourceDir}`);
        // this.log(`webappDir=${webappDir}`);
        //
        // this.log('\n--- variables from questions ---');
        // this.log(`\nmessage=${this.message}`);
        // this.log('------\n');

        // Convert Code here
        this.convertIDtoUUIDForColumn(`${javaDir}domain/User.java`, 'import java.time.Instant;', 'id');

        this.replaceContent(`${javaDir}domain/PersistentAuditEvent.java`, '    @Column(name = "event_id")\n', '');
        this.convertIDtoUUIDForColumn(`${javaDir}domain/PersistentAuditEvent.java`, 'import java.util.Map;', 'event_id');
        this.importUUID(`${javaDir}domain/PersistentAuditEvent.java`, 'import java.util.Map;');
        // And the Repository
        this.replaceContent(`${javaDir}repository/UserRepository.java`, 'import java.util.List;', 'import java.util.List;\nimport java.util.UUID;');
        this.longToUUID(`${javaDir}repository/UserRepository.java`);

        this.replaceContent(`${javaDir}repository/PersistenceAuditEventRepository.java`, 'import java.util.List;', 'import java.util.List;\nimport java.util.UUID;');
        this.longToUUID(`${javaDir}repository/PersistenceAuditEventRepository.java`);

        this.replaceContent(`${javaDir}service/AuditEventService.java`, 'import java.util.Optional;', 'import java.util.Optional;\nimport java.util.UUID;');
        this.longToUUID(`${javaDir}service/AuditEventService.java`);

        this.replaceContent(`${javaDir}service/UserService.java`, 'getUserWithAuthorities(Long id)', 'getUserWithAuthorities(UUID id)');

        this.replaceContent(`${javaDir}web/rest/AuditResource.java`, 'import java.util.List;', 'import java.util.List;\nimport java.util.UUID;');
        this.replaceContent(`${javaDir}web/rest/AuditResource.java`, 'get(@PathVariable Long id)', 'get(@PathVariable UUID id)');

        this.replaceContent(`${javaDir}service/mapper/UserMapper.java`, 'import java.util.List;', 'import java.util.List;\nimport java.util.UUID;');
        this.replaceContent(`${javaDir}service/mapper/UserMapper.java`, 'userFromId(Long id)', 'userFromId(UUID id)');

        this.replaceContent(`${javaDir}web/rest/vm/ManagedUserVM.java`, 'import java.util.Set;', 'import java.util.Set;\nimport java.util.UUID;');
        this.longToUUID(`${javaDir}web/rest/vm/ManagedUserVM.java`);

        this.replaceContent(`${javaDir}service/dto/UserDTO.java`, 'import java.util.Set;', 'import java.util.Set;\nimport java.util.UUID;');
        this.longToUUID(`${javaDir}service/dto/UserDTO.java`);

        this.replaceContent(`${javaDir}service/mapper/UserMapper.java`, 'import java.util.Set;', 'import java.util.Set;\nimport java.util.UUID;');
        this.longToUUID(`${javaDir}service/mapper/UserMapper.java`);

        this.longToUUID(`${javaDir}service/UserService.java`);

        // Tests
        this.longToUUID(`${javaTestDir}web/rest/UserResourceIntTest.java`);
        this.importUUID(`${javaTestDir}web/rest/UserResourceIntTest.java`, 'import java.util.List;');
        this.replaceContent(`${javaTestDir}web/rest/UserResourceIntTest.java`, '1L', 'UUID.fromString("00000000-0000-0000-0000-000000000001")', true);
        this.replaceContent(`${javaTestDir}web/rest/UserResourceIntTest.java`, '2L', 'UUID.fromString("00000000-0000-0000-0000-000000000002")', true);

        const file = glob.sync('src/main/resources/config/liquibase/changelog/*initial_schema.xml')[0];
        this.replaceContent(file, 'type="bigint"', 'type="uuid"', true);
        this.replaceContent(file, 'autoIncrement="\\$\\{autoIncrement\\}"', '', true);

        this.replaceContent('src/main/resources/config/liquibase/users.csv', '1;', '8d9b707a-ddf4-11e5-b86d-9a79f06e9478;', true);
        this.replaceContent('src/main/resources/config/liquibase/users.csv', '2;', '8d9b7412-ddf4-11e5-b86d-9a79f06e9478;', true);
        this.replaceContent('src/main/resources/config/liquibase/users.csv', '3;', '8d9b77f0-ddf4-11e5-b86d-9a79f06e9478;', true);
        this.replaceContent('src/main/resources/config/liquibase/users.csv', '4;', '8d9b79c6-ddf4-11e5-b86d-9a79f06e9478;', true);

        this.replaceContent('src/main/resources/config/liquibase/users_authorities.csv', '1;', '8d9b707a-ddf4-11e5-b86d-9a79f06e9478;', true);
        this.replaceContent('src/main/resources/config/liquibase/users_authorities.csv', '3;', '8d9b77f0-ddf4-11e5-b86d-9a79f06e9478;', true);
        this.replaceContent('src/main/resources/config/liquibase/users_authorities.csv', '4;', '8d9b79c6-ddf4-11e5-b86d-9a79f06e9478;', true);

        this.log(`${chalk.green.bold('SUCCESS!')} Update of core files complete...\n`);

        try {
            this.registerModule('generator-jhipster-postgresuuid-converter', 'entity', 'post', 'entity', 'Postgresql Long to UUID converter');
        } catch (err) {
            this.log(`${chalk.red.bold('WARN!')} Could not register as a jhipster entity post creation hook...\n`);
        }
    },

    install() {
        let logMsg =
            `To install your dependencies manually, run: ${chalk.yellow.bold(`${this.clientPackageManager} install`)}`;

        if (this.clientFramework === 'angular1') {
            logMsg =
                `To install your dependencies manually, run: ${chalk.yellow.bold(`${this.clientPackageManager} install & bower install`)}`;
        }
        const injectDependenciesAndConstants = (err) => {
            if (err) {
                this.warning('Install of dependencies failed!');
                this.log(logMsg);
            } else if (this.clientFramework === 'angular1') {
                this.spawnCommand('gulp', ['install']);
            }
        };
        const installConfig = {
            bower: this.clientFramework === 'angular1',
            npm: this.clientPackageManager !== 'yarn',
            yarn: this.clientPackageManager === 'yarn',
            callback: injectDependenciesAndConstants
        };
        if (this.options['skip-install']) {
            this.log(logMsg);
        } else {
            this.installDependencies(installConfig);
        }
    },

    end() {
        this.log('End of postgresuuid-converter generator');
    }
});
<commit_msg>Fixing bug: event_id column error in PersistentAuditEvent<commit_after>const util = require('util');
const chalk = require('chalk');
const glob = require('glob');
const generator = require('yeoman-generator');
const packagejs = require('../../package.json');
const semver = require('semver');
const BaseGenerator = require('../common');
const jhipsterConstants = require('generator-jhipster/generators/generator-constants');

const JhipsterGenerator = generator.extend({});
util.inherits(JhipsterGenerator, BaseGenerator);

module.exports = JhipsterGenerator.extend({
    initializing: {
        readConfig() {
            this.jhipsterAppConfig = this.getJhipsterAppConfig();
            if (!this.jhipsterAppConfig) {
                this.error('Can\'t read .yo-rc.json');
            }
        },
        displayLogo() {
            // it's here to show that you can use functions from generator-jhipster
            // this function is in: generator-jhipster/generators/generator-base.js
            this.printJHipsterLogo();

            // Have Yeoman greet the user.
            this.log(`\nWelcome to the ${chalk.bold.yellow('JHipster postgresuuid-converter')} generator! ${chalk.yellow(`v${packagejs.version}\n`)}`);
        },
        checkJhipster() {
            const jhipsterVersion = this.jhipsterAppConfig.jhipsterVersion;
            const minimumJhipsterVersion = packagejs.dependencies['generator-jhipster'];
            if (!semver.satisfies(jhipsterVersion, minimumJhipsterVersion)) {
                this.warning(`\nYour generated project used an old JHipster version (${jhipsterVersion})... you need at least (${minimumJhipsterVersion})\n`);
            }
        }
    },

    prompting() {
        const prompts = [];
        const done = this.async();
        this.prompt(prompts).then((props) => {
            this.props = props;
            // To access props later use this.props.someOption;

            done();
        });
    },

    writing() {
        // function to use directly template
        this.template = function (source, destination) {
            this.fs.copyTpl(
                this.templatePath(source),
                this.destinationPath(destination),
                this
            );
        };

        // function to check if this generator has already run or not.
        this.isFirstRun = function () {
            return true;
        };

        // read config from .yo-rc.json
        this.baseName = this.jhipsterAppConfig.baseName;
        this.packageName = this.jhipsterAppConfig.packageName;
        this.packageFolder = this.jhipsterAppConfig.packageFolder;
        this.clientFramework = this.jhipsterAppConfig.clientFramework;
        this.clientPackageManager = this.jhipsterAppConfig.clientPackageManager;
        this.buildTool = this.jhipsterAppConfig.buildTool;

        // use function in generator-base.js from generator-jhipster
        // this.angularAppName = this.getAngularAppName();

        // use constants from generator-constants.js
        const javaDir = `${jhipsterConstants.SERVER_MAIN_SRC_DIR + this.packageFolder}/`;
        const javaTestDir = `${jhipsterConstants.SERVER_TEST_SRC_DIR + this.packageFolder}/`;
        // const resourceDir = jhipsterConstants.SERVER_MAIN_RES_DIR;
        // const webappDir = jhipsterConstants.CLIENT_MAIN_SRC_DIR;

        // variable from questions
        this.message = this.props.message;

        // show all variables
        // this.log('\n--- some config read from config ---');
        // this.log(`baseName=${this.baseName}`);
        // this.log(`packageName=${this.packageName}`);
        // this.log(`clientFramework=${this.clientFramework}`);
        // this.log(`clientPackageManager=${this.clientPackageManager}`);
        // this.log(`buildTool=${this.buildTool}`);
        //
        // this.log('\n--- some function ---');
        // this.log(`angularAppName=${this.angularAppName}`);
        //
        // this.log('\n--- some const ---');
        // this.log(`javaDir=${javaDir}`);
        // this.log(`resourceDir=${resourceDir}`);
        // this.log(`webappDir=${webappDir}`);
        //
        // this.log('\n--- variables from questions ---');
        // this.log(`\nmessage=${this.message}`);
        // this.log('------\n');

        // Convert Code here
        this.convertIDtoUUIDForColumn(`${javaDir}domain/User.java`, 'import java.time.Instant;', 'id');

        this.convertIDtoUUIDForColumn(`${javaDir}domain/PersistentAuditEvent.java`, 'import java.util.Map;', 'event_id');
        this.importUUID(`${javaDir}domain/PersistentAuditEvent.java`, 'import java.util.Map;');
        // And the Repository
        this.replaceContent(`${javaDir}repository/UserRepository.java`, 'import java.util.List;', 'import java.util.List;\nimport java.util.UUID;');
        this.longToUUID(`${javaDir}repository/UserRepository.java`);

        this.replaceContent(`${javaDir}repository/PersistenceAuditEventRepository.java`, 'import java.util.List;', 'import java.util.List;\nimport java.util.UUID;');
        this.longToUUID(`${javaDir}repository/PersistenceAuditEventRepository.java`);

        this.replaceContent(`${javaDir}service/AuditEventService.java`, 'import java.util.Optional;', 'import java.util.Optional;\nimport java.util.UUID;');
        this.longToUUID(`${javaDir}service/AuditEventService.java`);

        this.replaceContent(`${javaDir}service/UserService.java`, 'getUserWithAuthorities(Long id)', 'getUserWithAuthorities(UUID id)');

        this.replaceContent(`${javaDir}web/rest/AuditResource.java`, 'import java.util.List;', 'import java.util.List;\nimport java.util.UUID;');
        this.replaceContent(`${javaDir}web/rest/AuditResource.java`, 'get(@PathVariable Long id)', 'get(@PathVariable UUID id)');

        this.replaceContent(`${javaDir}service/mapper/UserMapper.java`, 'import java.util.List;', 'import java.util.List;\nimport java.util.UUID;');
        this.replaceContent(`${javaDir}service/mapper/UserMapper.java`, 'userFromId(Long id)', 'userFromId(UUID id)');

        this.replaceContent(`${javaDir}web/rest/vm/ManagedUserVM.java`, 'import java.util.Set;', 'import java.util.Set;\nimport java.util.UUID;');
        this.longToUUID(`${javaDir}web/rest/vm/ManagedUserVM.java`);

        this.replaceContent(`${javaDir}service/dto/UserDTO.java`, 'import java.util.Set;', 'import java.util.Set;\nimport java.util.UUID;');
        this.longToUUID(`${javaDir}service/dto/UserDTO.java`);

        this.replaceContent(`${javaDir}service/mapper/UserMapper.java`, 'import java.util.Set;', 'import java.util.Set;\nimport java.util.UUID;');
        this.longToUUID(`${javaDir}service/mapper/UserMapper.java`);

        this.longToUUID(`${javaDir}service/UserService.java`);

        // Tests
        this.longToUUID(`${javaTestDir}web/rest/UserResourceIntTest.java`);
        this.importUUID(`${javaTestDir}web/rest/UserResourceIntTest.java`, 'import java.util.List;');
        this.replaceContent(`${javaTestDir}web/rest/UserResourceIntTest.java`, '1L', 'UUID.fromString("00000000-0000-0000-0000-000000000001")', true);
        this.replaceContent(`${javaTestDir}web/rest/UserResourceIntTest.java`, '2L', 'UUID.fromString("00000000-0000-0000-0000-000000000002")', true);

        const file = glob.sync('src/main/resources/config/liquibase/changelog/*initial_schema.xml')[0];
        this.replaceContent(file, 'type="bigint"', 'type="uuid"', true);
        this.replaceContent(file, 'autoIncrement="\\$\\{autoIncrement\\}"', '', true);

        this.replaceContent('src/main/resources/config/liquibase/users.csv', '1;', '8d9b707a-ddf4-11e5-b86d-9a79f06e9478;', true);
        this.replaceContent('src/main/resources/config/liquibase/users.csv', '2;', '8d9b7412-ddf4-11e5-b86d-9a79f06e9478;', true);
        this.replaceContent('src/main/resources/config/liquibase/users.csv', '3;', '8d9b77f0-ddf4-11e5-b86d-9a79f06e9478;', true);
        this.replaceContent('src/main/resources/config/liquibase/users.csv', '4;', '8d9b79c6-ddf4-11e5-b86d-9a79f06e9478;', true);

        this.replaceContent('src/main/resources/config/liquibase/users_authorities.csv', '1;', '8d9b707a-ddf4-11e5-b86d-9a79f06e9478;', true);
        this.replaceContent('src/main/resources/config/liquibase/users_authorities.csv', '3;', '8d9b77f0-ddf4-11e5-b86d-9a79f06e9478;', true);
        this.replaceContent('src/main/resources/config/liquibase/users_authorities.csv', '4;', '8d9b79c6-ddf4-11e5-b86d-9a79f06e9478;', true);

        this.log(`${chalk.green.bold('SUCCESS!')} Update of core files complete...\n`);

        try {
            this.registerModule('generator-jhipster-postgresuuid-converter', 'entity', 'post', 'entity', 'Postgresql Long to UUID converter');
        } catch (err) {
            this.log(`${chalk.red.bold('WARN!')} Could not register as a jhipster entity post creation hook...\n`);
        }
    },

    install() {
        let logMsg =
            `To install your dependencies manually, run: ${chalk.yellow.bold(`${this.clientPackageManager} install`)}`;

        if (this.clientFramework === 'angular1') {
            logMsg =
                `To install your dependencies manually, run: ${chalk.yellow.bold(`${this.clientPackageManager} install & bower install`)}`;
        }
        const injectDependenciesAndConstants = (err) => {
            if (err) {
                this.warning('Install of dependencies failed!');
                this.log(logMsg);
            } else if (this.clientFramework === 'angular1') {
                this.spawnCommand('gulp', ['install']);
            }
        };
        const installConfig = {
            bower: this.clientFramework === 'angular1',
            npm: this.clientPackageManager !== 'yarn',
            yarn: this.clientPackageManager === 'yarn',
            callback: injectDependenciesAndConstants
        };
        if (this.options['skip-install']) {
            this.log(logMsg);
        } else {
            this.installDependencies(installConfig);
        }
    },

    end() {
        this.log('End of postgresuuid-converter generator');
    }
});
<|endoftext|>


<commit_before>const fs = require('fs');
const Generator = require('yeoman-generator');

const buildPolicy = (serviceName, stage, region) => {
  return {
    "Version": "2012-10-17",
    "Statement": [
      {
        "Effect": "Allow",
        "Action": [
          "cloudformation:List*",
          "cloudformation:Get*",
          "cloudformation:PreviewStackUpdate"
        ],
        "Resource": "*"
      },
      {
        "Effect": "Allow",
        "Action":[
          "cloudformation:CreateStack",
          "cloudformation:CreateUploadBucket",
          "cloudformation:DeleteStack",
          "cloudformation:DescribeStackEvents",
          "cloudformation:DescribeStackResource",
          "cloudformation:DescribeStackResources",
          "cloudformation:UpdateStack",
          "cloudformation:DescribeStacks"
        ],
        "Resource": `arn:aws:cloudformation:${region}:*:stack/${serviceName}-${stage}/*`
      },
      {
        "Effect": "Allow",
        "Action": [
          "lambda:Get*",
          "lambda:List*",
          "lambda:CreateFunction"
        ],
        "Resource": "*"
      },
      {
        "Effect": "Allow",
        "Action": [
          "s3:CreateBucket"
        ],
        "Resource": [
          `arn:aws:s3:::${serviceName}*serverlessdeploymentbucket*`
        ]
      },
      {
        "Effect": "Allow",
        "Action": [
          "s3:PutObject",
          "s3:GetObject",
          "s3:ListBucket",
          "s3:DeleteObject",
          "s3:DeleteBucket",
          "s3:ListBucketVersions"
        ],
        "Resource": [
          `arn:aws:s3:::${serviceName}*serverlessdeploymentbucket*`
        ]
      },
      {
        "Effect": "Allow",
        "Action": [
          "lambda:AddPermission",
          "lambda:CreateAlias",
          "lambda:DeleteFunction",
          "lambda:InvokeFunction",
          "lambda:PublishVersion",
          "lambda:RemovePermission",
          "lambda:Update*"
        ],
        "Resource": `arn:aws:lambda:${region}:*:function:${serviceName}-${stage}-*`
      },
      {
        "Effect": "Allow",
        "Action": [
          "apigateway:GET"
        ],
        "Resource": [
          "arn:aws:apigateway:*::/restapis"
        ]
      },
      {
        "Effect": "Allow",
        "Action": [
          "apigateway:GET",
          "apigateway:POST",
          "apigateway:PUT",
          "apigateway:DELETE"
        ],
        "Resource": [
          "arn:aws:apigateway:*::/restapis/*/*"
        ]
      },
      {
        "Effect": "Allow",
        "Action": [
          "iam:PassRole"
        ],
        "Resource": "arn:aws:iam::*:role/*"
      },
      {
        "Effect": "Allow",
        "Action": "kinesis:*",
        "Resource": `arn:aws:kinesis:*:*:stream/${serviceName}-${stage}-${region}`
      },
      {
        "Effect": "Allow",
        "Action": "iam:*",
        "Resource": `arn:aws:iam::*:role/${serviceName}-${stage}-${region}-lambdaRole`
      },
      {
        "Effect": "Allow",
        "Action": "sqs:*",
        "Resource": `arn:aws:sqs:*:*:${serviceName}-${stage}-${region}`
      },
      {
        "Effect":"Allow",
        "Action":[
          "cloudwatch:GetMetricStatistics"
        ],
        "Resource":[
          "*"
        ]
      },
      {
        "Effect": "Allow",
        "Action": [
          "logs:DescribeLogStreams",
          "logs:FilterLogEvents"
        ],
        "Resource": [
          "*"
        ]
      },
      {
        "Effect": "Allow",
        "Action": [
          "events:Put*",
          "events:Remove*",
          "events:Delete*"
        ],
        "Resource": `arn:aws:events:*:*:rule/${serviceName}-${stage}-${region}`
      }
    ]
  };
};

const escapeValFilename = function (val) {
  return (val === '*') ? '_star_' : val;
};

module.exports = class extends Generator {
  constructor(args, opts) {
    super(args, opts);

    this.option('project', {
      description: 'The name of the Serverless project',
      type: String
    });
    this.option('stage', {
      description: 'The name of a single stage to target',
      type: String,
      default: '*'
    });
    this.option('region', {
      description: 'The name of a single region to target',
      type: String,
      default: '*'
    });
  }

  prompting() {
    return this.prompt([{
      type: 'input',
      name: 'name',
      message: 'Your Serverless service name',
      default: this.appname // Default to current folder name
    }, {
      type: 'input',
      name: 'stage',
      message: 'You can specify a specific stage, if you like:',
      default: '*'
    }, {
      type: 'input',
      name: 'region',
      message: 'You can specify a specific region, if you like:',
      default: '*'
    }, {
      type    : 'confirm',
      name    : 'dynamodb',
      message : 'Does your service rely on DynamoDB?'
    }]).then((answers) => {
      this.slsSettings = {
        name: answers.name,
        stage: answers.stage,
        region: answers.region,
        dynamodb: answers.dynamodb
      };
      this.log('app name', answers.name);
      this.log('app stage', answers.stage);
      this.log('app region', answers.region);
    });
  }

  writing() {
    const done = this.async();

    const project = this.slsSettings.name;
    const stage = this.slsSettings.stage;
    const region = this.slsSettings.region;

    const policy = buildPolicy(project, stage, region);
    if(this.slsSettings.dynamodb) {
      policy.Statement.push({
        "Effect": "Allow",
        "Action": [
          "dynamodb:*"
        ],
        "Resource": [
          "arn:aws:dynamodb:*:*:table/*"
        ]
      });
    }
    const policyString = JSON.stringify(policy);
    const fileName = `${project}-${escapeValFilename(stage)}-${escapeValFilename(region)}-policy.json`;

    this.log(`Writing to ${fileName}`);
    fs.writeFile(fileName, policyString, done);

  }

};<commit_msg>Prettified<commit_after>const fs = require('fs');
const Generator = require('yeoman-generator');

const buildPolicy = (serviceName, stage, region) => {
  return {
    Version: '2012-10-17',
    Statement: [
      {
        Effect: 'Allow',
        Action: [
          'cloudformation:List*',
          'cloudformation:Get*',
          'cloudformation:PreviewStackUpdate'
        ],
        Resource: ['*']
      },
      {
        Effect: 'Allow',
        Action: [
          'cloudformation:CreateStack',
          'cloudformation:CreateUploadBucket',
          'cloudformation:DeleteStack',
          'cloudformation:DescribeStackEvents',
          'cloudformation:DescribeStackResource',
          'cloudformation:DescribeStackResources',
          'cloudformation:UpdateStack',
          'cloudformation:DescribeStacks'
        ],
        Resource: [
          `arn:aws:cloudformation:${region}:*:stack/${serviceName}-${stage}/*`
        ]
      },
      {
        Effect: 'Allow',
        Action: ['lambda:Get*', 'lambda:List*', 'lambda:CreateFunction'],
        Resource: ['*']
      },
      {
        Effect: 'Allow',
        Action: ['s3:CreateBucket'],
        Resource: [`arn:aws:s3:::${serviceName}*serverlessdeploymentbucket*`]
      },
      {
        Effect: 'Allow',
        Action: [
          's3:PutObject',
          's3:GetObject',
          's3:ListBucket',
          's3:DeleteObject',
          's3:DeleteBucket',
          's3:ListBucketVersions'
        ],
        Resource: [`arn:aws:s3:::${serviceName}*serverlessdeploymentbucket*`]
      },
      {
        Effect: 'Allow',
        Action: [
          'lambda:AddPermission',
          'lambda:CreateAlias',
          'lambda:DeleteFunction',
          'lambda:InvokeFunction',
          'lambda:PublishVersion',
          'lambda:RemovePermission',
          'lambda:Update*'
        ],
        Resource: [
          `arn:aws:lambda:${region}:*:function:${serviceName}-${stage}-*`
        ]
      },
      {
        Effect: 'Allow',
        Action: ['apigateway:GET'],
        Resource: ['arn:aws:apigateway:*::/restapis']
      },
      {
        Effect: 'Allow',
        Action: [
          'apigateway:GET',
          'apigateway:POST',
          'apigateway:PUT',
          'apigateway:DELETE'
        ],
        Resource: ['arn:aws:apigateway:*::/restapis/*/*']
      },
      {
        Effect: 'Allow',
        Action: ['iam:PassRole'],
        Resource: ['arn:aws:iam::*:role/*']
      },
      {
        Effect: 'Allow',
        Action: 'kinesis:*',
        Resource: [
          `arn:aws:kinesis:*:*:stream/${serviceName}-${stage}-${region}`
        ]
      },
      {
        Effect: 'Allow',
        Action: 'iam:*',
        Resource: [
          `arn:aws:iam::*:role/${serviceName}-${stage}-${region}-lambdaRole`
        ]
      },
      {
        Effect: 'Allow',
        Action: 'sqs:*',
        Resource: [`arn:aws:sqs:*:*:${serviceName}-${stage}-${region}`]
      },
      {
        Effect: 'Allow',
        Action: ['cloudwatch:GetMetricStatistics'],
        Resource: ['*']
      },
      {
        Effect: 'Allow',
        Action: ['logs:DescribeLogStreams', 'logs:FilterLogEvents'],
        Resource: ['*']
      },
      {
        Effect: 'Allow',
        Action: ['events:Put*', 'events:Remove*', 'events:Delete*'],
        Resource: [`arn:aws:events:*:*:rule/${serviceName}-${stage}-${region}`]
      }
    ]
  };
};

const escapeValFilename = function(val) {
  return val === '*' ? '_star_' : val;
};

module.exports = class extends Generator {
  constructor(args, opts) {
    super(args, opts);

    this.option('project', {
      description: 'The name of the Serverless project',
      type: String
    });
    this.option('stage', {
      description: 'The name of a single stage to target',
      type: String,
      default: '*'
    });
    this.option('region', {
      description: 'The name of a single region to target',
      type: String,
      default: '*'
    });
  }

  prompting() {
    return this.prompt([
      {
        type: 'input',
        name: 'name',
        message: 'Your Serverless service name',
        default: this.appname // Default to current folder name
      },
      {
        type: 'input',
        name: 'stage',
        message: 'You can specify a specific stage, if you like:',
        default: '*'
      },
      {
        type: 'input',
        name: 'region',
        message: 'You can specify a specific region, if you like:',
        default: '*'
      },
      {
        type: 'confirm',
        name: 'dynamodb',
        message: 'Does your service rely on DynamoDB?'
      }
    ]).then(answers => {
      this.slsSettings = {
        name: answers.name,
        stage: answers.stage,
        region: answers.region,
        dynamodb: answers.dynamodb
      };
      this.log('app name', answers.name);
      this.log('app stage', answers.stage);
      this.log('app region', answers.region);
    });
  }

  writing() {
    const done = this.async();

    const project = this.slsSettings.name;
    const stage = this.slsSettings.stage;
    const region = this.slsSettings.region;

    const policy = buildPolicy(project, stage, region);
    if (this.slsSettings.dynamodb) {
      policy.Statement.push({
        Effect: 'Allow',
        Action: ['dynamodb:*'],
        Resource: ['arn:aws:dynamodb:*:*:table/*']
      });
    }
    const policyString = JSON.stringify(policy);
    const fileName = `${project}-${escapeValFilename(stage)}-${escapeValFilename(region)}-policy.json`;

    this.log(`Writing to ${fileName}`);
    fs.writeFile(fileName, policyString, done);
  }
};
<|endoftext|>


<commit_before>var generators = require('yeoman-generator');
var inquirer = require("inquirer");
var chalk = require('chalk');
var yosay = require('yosay');

module.exports = generators.Base.extend({

	initializing: function() {
		this.store = {
			"bower-dependencies": []
		}
	},

  	writing: function() {
  		// App directory structure
  		this.directory('app', 'app');

  		this.template('_bower.json', 'bower.json');
  		this.template('_.bowerrc', '.bowerrc');
		  this.template('_package.json', 'package.json');
		  this.template('_gulpfile.js', 'gulpfile.js');
      this.template('_.gitignore', '.gitignore');
      this.template('_index.jade', './app/index.jade');
  	},

  	install: function() {
		this.installDependencies();
  	},

  	end: function() {
  		this.log(yosay('Almost done! ' + chalk.green('running default gulp task')));
		this.spawnCommand('node_modules/gulp/bin/gulp.js');
  	}
});
<commit_msg>Refactoring<commit_after>var generators = require('yeoman-generator');
var inquirer = require("inquirer");
var chalk = require('chalk');
var yosay = require('yosay');

module.exports = generators.Base.extend({

    initializing: function () {
        this.store = {
            "bower-dependencies": []
        }
    },

    writing: function () {
        // App directory structure
        this.directory('app', 'app');

        this.template('_bower.json', 'bower.json');
        this.template('_.bowerrc', '.bowerrc');
        this.template('_package.json', 'package.json');
        this.template('_gulpfile.js', 'gulpfile.js');
        this.template('_.gitignore', '.gitignore');
        this.template('_index.jade', './app/index.jade');
    },

    install: function () {
        this.installDependencies();
    },

    end: function () {
        this.log(yosay('Almost done! ' + chalk.green('running default gulp task')));
        this.spawnCommand('node_modules/gulp/bin/gulp.js');
    }
});
<|endoftext|>


<commit_before>'use strict';

var generators = require('yeoman-generator'),
  optionOrPrompt = require('yeoman-option-or-prompt'),
  chalk = require('chalk'),
  mkdirp = require('mkdirp'),
  _ = require('lodash'),
  mainDependencies = require('./mainDeps.json'),
  gulpDependencies = require('./gulpDeps.json'),
  devDependencies = require('./devDeps.json');

module.exports = generators.Base.extend({
  _optionOrPrompt: optionOrPrompt,

  constructor: function () {
    // Clear screen before running generator
    this.spawnCommand('clear', []);
    generators.Base.apply(this, arguments);

    // Store user-inputed appname
    this.argument('appname', { type: String, required: true, desc:'Application name (Use only _ or -)', defaults:'example' });
  },

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

    // Displays solid line or specified character as a visual divider
    this.separator = function (c) {
      var line = c ? chalk.yellow(_.repeat(c, 60)) : chalk.gray.underline(_.repeat(' ', 60));

      this.log('\n' + line);
    };

    // Helper function to check if dependency exists
    this.checkDeps = function (depsObject, whereToLook) {
      var pkg = this.packageJson,
        log = this.log;

      return _.chain(depsObject)
      // Checks if dependency exist
      .pick(function (value, name) {
        var hasModule = !_.has(pkg[whereToLook], name);

        if (hasModule) {
          log(chalk.cyan(name) + chalk.cyan.bold(' does not exist: ') + value);
        }
        return hasModule;
      })
      // Maps module to module@version (i.e `gulp` -> `gulp@3.8.11`)
      .mapKeys(function (moduleVerison, moduleName) {
        if (moduleVerison.match(/\*/)) {
          console.log('Get latest ' + moduleName);
          return moduleName + moduleVerison.replace('*','@latest');
        } else {
          return moduleName + moduleVerison.replace('^','@');
        }
      })
      // Returns the keys
      .keys()
      .value();
    };

    this.separator('.');
    this.log('\nWelcome to the ' + chalk.yellow.bold('Clay Instance') + ' generator!');
    this.separator('.');
  },

  prompting: function () {
    var done = this.async(),
      prompts = require('./prompts.js')(this.packageJson);

    this._optionOrPrompt(prompts, function (props) {
      this.props = props;

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

  },

  writing: {
    packageJson: function () {
      var currentPackageJson,
        msg,
        newPackageJson = {},
        packageJsonOrder = ['name','version','description','license','main','scripts','keywords','repository','dependencies','devDependencies'];

      // Sets a field in package.json if it doesn't exist
      this.setPackageJsonField = function (field) {
        if (!this.packageJson[field]) {
          this.packageJson[field] = this.props[field];
        } else {
          msg = _.endsWith(field, 's') ? ' exist: ' : ' exists: ';
          console.log(chalk.blue(field) + chalk.blue.bold(msg) + this.packageJson[field]);
        }
      };

      if (this.fs.exists(this.destinationPath('package.json'))) {
        this.log(chalk.yellow('\npackage.json') + ' found. Revising it.');
        this.packageJson = this.fs.readJSON(this.destinationPath('package.json'),{});

        this.setPackageJsonField('description');
        this.setPackageJsonField('keywords');

        currentPackageJson = this.packageJson;

        // Re-order fiels in pre-specified order
        _.each(packageJsonOrder, function (key) {
          newPackageJson[key] = currentPackageJson[key];
        });

        this.fs.writeJSON('package.json', newPackageJson);

      } else {
        this.log('No ' + chalk.red('package.json') + ' found. Creating one.');
        this.fs.copyTpl(
          this.templatePath('_package.json'),
          this.destinationPath('package.json'),
          {
            appname: this.appname,
            description: this.props.description,
            keywords: this.props.keywords,
            dependencies: JSON.stringify(_.extend(mainDependencies, gulpDependencies), null, 4),
            devDependencies: JSON.stringify(devDependencies, null, 4)
          }
        );
      }
      this.separator();
    },

    createFolders: function () {
      var done = this.async(),
        log = this.log,
        folders = ['sites', 'components', 'behaviors', 'validators'];

      if (folders) {
        log('Generating ' + chalk.blue(folders));
      }

      // Create app folders
      _.each(folders, function (name) {
        mkdirp(name, function (err) {
          if (err) {
            log(chalk.red(err.message, err.stack));
            process.exit(0);
          }

          done();
        });
      });

    },

    gulp: function () {
      this.fs.copy(
        this.templatePath('_gulpfile.js'),
        this.destinationPath('gulpfile.js')
      );
      this.log('Generating ' + chalk.yellow.bold('gulpfile.js'));

      // Creates gulp/tasks & gulp/utils
      this.directory(
        this.templatePath('gulp'),
        this.destinationPath('gulp')
      );
      this.log('Generating ' + chalk.yellow.bold('gulp folders.'));
    },

    tests: function () {
      // Creates tests/mocha.opts
      this.directory(
        this.templatePath('test'),
        this.destinationPath('test')
      );
      this.log('Generating ' + chalk.yellow.bold('test folder.'));
    },

    app: function () {
      this.fs.copyTpl(
        this.templatePath('README.md'),
        this.destinationPath('README.md'),
        {
          appname: this.appname
        }
      );

      this.fs.copy(
        this.templatePath('_app.js'),
        this.destinationPath('app.js')
      );
    },

    git: function () {
      this.fs.copy(
        this.templatePath('gitignore'),
        this.destinationPath('.gitignore')
      );
    },

    projectfiles: function () {
      this.fs.copy(
        this.templatePath('eslintrc'),
        this.destinationPath('.eslintrc')
      );
      this.fs.copy(
        this.templatePath('_csscomb.json'),
        this.destinationPath('csscomb.json')
      );
    }
  },

  // Run npm install
  install: {
    app: function () {
      // Check if main dependencies exist
      var mainDependencies = require('./mainDeps.json');

      this.separator();
      mainDependencies = this.checkDeps(mainDependencies,'dependencies');
      this.npmInstall(mainDependencies, { 'save': true });
      this.log('Installed ' + chalk.yellow.bold('main dependencies.'));
    },

    gulp: function () {
      // Check if gulp dependencies exist
      var gulpDependencies = require('./gulpDeps.json');

      this.separator();
      gulpDependencies = this.checkDeps(gulpDependencies, 'dependencies');
      this.npmInstall(gulpDependencies, { 'save': true });
      this.log('Installed ' + chalk.yellow.bold('gulp dependencies.'));
    },

    devDeps: function () {
      // Check if devDependencies exist
      var devDependencies = require('./devDeps.json');

      this.separator();
      devDependencies = this.checkDeps(devDependencies, 'devDependencies');
      this.npmInstall(devDependencies, { 'saveDev': true });
      this.log('Installed ' + chalk.yellow.bold('dev dependencies.'));
    },

    main: function () {
      this.npmInstall();
      this.separator('x');
      this.log('\n\tYour app ' + chalk.yellow.bold(this.appname) + ' was created.');
      this.separator('x');
    }
  }
});
<commit_msg>App: Fixed error handling<commit_after>'use strict';

var generators = require('yeoman-generator'),
  optionOrPrompt = require('yeoman-option-or-prompt'),
  chalk = require('chalk'),
  mkdirp = require('mkdirp'),
  _ = require('lodash'),
  mainDependencies = require('./mainDeps.json'),
  gulpDependencies = require('./gulpDeps.json'),
  devDependencies = require('./devDeps.json');

module.exports = generators.Base.extend({
  _optionOrPrompt: optionOrPrompt,

  constructor: function () {
    // Clear screen before running generator
    this.spawnCommand('clear', []);

    try {
      generators.Base.apply(this, arguments);

      // Store user-inputed appname
      this.argument('appname', { type: String, required: true, desc:'Application name (Use only _ or -)', defaults:'example' });
    } catch (e) {
      this.env.error(chalk.red.bold('You must provide a name for your clay instance!'));
    }
  },

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

    // Displays solid line or specified character as a visual divider
    this.separator = function (c) {
      var line = c ? chalk.yellow(_.repeat(c, 60)) : chalk.gray.underline(_.repeat(' ', 60));

      this.log('\n' + line);
    };

    // Helper function to check if dependency exists
    this.checkDeps = function (depsObject, whereToLook) {
      var pkg = this.packageJson,
        log = this.log;

      return _.chain(depsObject)
      // Checks if dependency exist
      .pick(function (value, name) {
        var hasModule = !_.has(pkg[whereToLook], name);

        if (hasModule) {
          log(chalk.cyan(name) + chalk.cyan.bold(' does not exist: ') + value);
        }
        return hasModule;
      })
      // Maps module to module@version (i.e `gulp` -> `gulp@3.8.11`)
      .mapKeys(function (moduleVerison, moduleName) {
        if (moduleVerison.match(/\*/)) {
          console.log('Get latest ' + moduleName);
          return moduleName + moduleVerison.replace('*','@latest');
        } else {
          return moduleName + moduleVerison.replace('^','@');
        }
      })
      // Returns the keys
      .keys()
      .value();
    };

    this.separator('.');
    this.log('\nWelcome to the ' + chalk.yellow.bold('Clay Instance') + ' generator!');
    this.separator('.');
  },

  prompting: function () {
    var done = this.async(),
      prompts = require('./prompts.js')(this.packageJson);

    this._optionOrPrompt(prompts, function (props) {
      this.props = props;

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

  },

  writing: {
    packageJson: function () {
      var currentPackageJson,
        msg,
        newPackageJson = {},
        packageJsonOrder = ['name','version','description','license','main','scripts','keywords','repository','dependencies','devDependencies'];

      // Sets a field in package.json if it doesn't exist
      this.setPackageJsonField = function (field) {
        if (!this.packageJson[field]) {
          this.packageJson[field] = this.props[field];
        } else {
          msg = _.endsWith(field, 's') ? ' exist: ' : ' exists: ';
          console.log(chalk.blue(field) + chalk.blue.bold(msg) + this.packageJson[field]);
        }
      };

      if (this.fs.exists(this.destinationPath('package.json'))) {
        this.log(chalk.yellow('\npackage.json') + ' found. Revising it.');
        this.packageJson = this.fs.readJSON(this.destinationPath('package.json'),{});

        this.setPackageJsonField('description');
        this.setPackageJsonField('keywords');

        currentPackageJson = this.packageJson;

        // Re-order fiels in pre-specified order
        _.each(packageJsonOrder, function (key) {
          newPackageJson[key] = currentPackageJson[key];
        });

        this.fs.writeJSON('package.json', newPackageJson);

      } else {
        this.log('No ' + chalk.red('package.json') + ' found. Creating one.');
        this.fs.copyTpl(
          this.templatePath('_package.json'),
          this.destinationPath('package.json'),
          {
            appname: this.appname,
            description: this.props.description,
            keywords: this.props.keywords,
            dependencies: JSON.stringify(_.extend(mainDependencies, gulpDependencies), null, 4),
            devDependencies: JSON.stringify(devDependencies, null, 4)
          }
        );
      }
      this.separator();
    },

    createFolders: function () {
      var done = this.async(),
        log = this.log,
        folders = ['sites', 'components', 'behaviors', 'validators'];

      if (folders) {
        log('Generating ' + chalk.blue(folders));
      }

      // Create app folders
      _.each(folders, function (name) {
        mkdirp(name, function (err) {
          if (err) {
            log(chalk.red(err.message, err.stack));
            process.exit(0);
          }

          done();
        });
      });

    },

    gulp: function () {
      this.fs.copy(
        this.templatePath('_gulpfile.js'),
        this.destinationPath('gulpfile.js')
      );
      this.log('Generating ' + chalk.yellow.bold('gulpfile.js'));

      // Creates gulp/tasks & gulp/utils
      this.directory(
        this.templatePath('gulp'),
        this.destinationPath('gulp')
      );
      this.log('Generating ' + chalk.yellow.bold('gulp folders.'));
    },

    tests: function () {
      // Creates tests/mocha.opts
      this.directory(
        this.templatePath('test'),
        this.destinationPath('test')
      );
      this.log('Generating ' + chalk.yellow.bold('test folder.'));
    },

    app: function () {
      this.fs.copyTpl(
        this.templatePath('README.md'),
        this.destinationPath('README.md'),
        {
          appname: this.appname
        }
      );

      this.fs.copy(
        this.templatePath('_app.js'),
        this.destinationPath('app.js')
      );
    },

    git: function () {
      this.fs.copy(
        this.templatePath('gitignore'),
        this.destinationPath('.gitignore')
      );
    },

    projectfiles: function () {
      this.fs.copy(
        this.templatePath('eslintrc'),
        this.destinationPath('.eslintrc')
      );
      this.fs.copy(
        this.templatePath('_csscomb.json'),
        this.destinationPath('csscomb.json')
      );
    }
  },

  // Run npm install
  install: {
    app: function () {
      // Check if main dependencies exist
      var mainDependencies = require('./mainDeps.json');

      this.separator();
      mainDependencies = this.checkDeps(mainDependencies,'dependencies');
      this.npmInstall(mainDependencies, { 'save': true });
      this.log('Installed ' + chalk.yellow.bold('main dependencies.'));
    },

    gulp: function () {
      // Check if gulp dependencies exist
      var gulpDependencies = require('./gulpDeps.json');

      this.separator();
      gulpDependencies = this.checkDeps(gulpDependencies, 'dependencies');
      this.npmInstall(gulpDependencies, { 'save': true });
      this.log('Installed ' + chalk.yellow.bold('gulp dependencies.'));
    },

    devDeps: function () {
      // Check if devDependencies exist
      var devDependencies = require('./devDeps.json');

      this.separator();
      devDependencies = this.checkDeps(devDependencies, 'devDependencies');
      this.npmInstall(devDependencies, { 'saveDev': true });
      this.log('Installed ' + chalk.yellow.bold('dev dependencies.'));
    },

    main: function () {
      this.npmInstall();
      this.separator('x');
      this.log('\n\tYour app ' + chalk.yellow.bold(this.appname) + ' was created.');
      this.separator('x');
    }
  }
});
<|endoftext|>


<commit_before>/* eslint capitalized-comments: ["off"],
          comma-dangle: ["off"] */

/**
 * @fileOverview The main code for this generator.
 *
 * @author Andy Culbertson
 *
 * @requires NPM:yeoman-generator
 * @requires NPM:chalk
 * @requires NPM:yosay
 * @requires NPM:mkdirp
 */

'use strict';
const Generator = require('yeoman-generator');
const chalk = require('chalk');
const yosay = require('yosay');
const mkdirp = require('mkdirp');

module.exports = class extends Generator {
  prompting() {
    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the groovy ' + chalk.red('generator-python-cmd') + ' generator!'
    ));

    const prompts = [{
      type: 'input',
      name: 'projectName',
      message: 'What is the project name?',
      // Title case the appname. Based on https://stackoverflow.com/a/196991.
      default: this.appname.replace(/\b\w/g, function(txt){return txt.toUpperCase();}),
    },
    {
      type: 'input',
      name: 'projectSlug',
      message: 'What is the project slug?',
      default: this.appname.replace(/ /g, '-'),
    },
    {
      type: 'input',
      name: 'packageName',
      message: 'What is the package name?',
      default: this.appname.replace(/ /g, ''),
    },
    {
      type: 'input',
      name: 'projectDesc',
      message: 'What is the project description?',
    },
    {
      type: 'input',
      name: 'author',
      message: 'What is the author\'s name?',
    },
    {
      type: 'input',
      name: 'authorEmail',
      message: 'What is the author\'s email address?',
    },
    ];

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

  // Adapted from
  // https://github.com/yeoman/generator-webapp/blob/master/app/index.js
  writing() {
    this._writingGit();
    this._writingScript();
    this._writingConfig();
    this._writingLib();
    this._writingDocs();
    this._writingTests();
    this._writingSetup();
  }

  _writingGit() {
    this.fs.copy(
      this.templatePath('gitignore'),
      this.destinationPath('.gitignore'));
  }

  _writingScript() {
    const templatePaths = ['app.py'];
    const options = {packageName: this.props.packageName};
    this._copyTpls(templatePaths, options);
  }

  _writingConfig() {
    const dirPaths = ['config'];
    this._makeDirs(dirPaths);
  }

  _writingLib() {
    const templatePaths = [
      'cli.py',
      'config.py',
      'controller.py',
      '__init__.py',
    ];
    const options = {};
    this._copyPackageTpls(templatePaths, options);
  }

  _writingDocs() {
    const dirPaths = [
      'docs',
    ];
    this._makeDirs(dirPaths);

    const templatePaths = [
      'LICENSE.md',
      'README.md',
    ];
    const options = {projectName: this.props.projectName,
      author: this.props.author,
      authorEmail: this.props.authorEmail};
    this._copyTpls(templatePaths, options);
  }

  _writingTests() {
    const templatePaths = [
      'tests/context.py',
      'tests/test.py',
    ];
    const options = {packageName: this.props.packageName};
    this._copyTpls(templatePaths, options);
  }

  _writingSetup() {
    const templatePaths = [
      'setup.py',
      'requirements.txt',
      'requirements-dev.txt',
    ];
    const options = {packageName: this.props.packageName,
      projectName: this.props.projectName,
      projectDesc: this.props.projectDesc,
      author: this.props.author,
      authorEmail: this.props.authorEmail};
    this._copyTpls(templatePaths, options);
  }

  _copyTpls(templatePaths, options) {
    var i;
    for (i = 0; i < templatePaths.length; i++) {
      var templatePath = templatePaths[i];
      this.fs.copyTpl(
        this.templatePath(templatePath),
        this.destinationPath(templatePath),
        options
      );
    }
  }

  _copyPackageTpls(templatePaths, options) {
    var i;
    for (i = 0; i < templatePaths.length; i++) {
      var templatePath = 'package/' + templatePaths[i];
      var destinationPath = this.props.packageName + '/' + templatePaths[i];
      this.fs.copyTpl(
        this.templatePath(templatePath),
        this.destinationPath(destinationPath),
        options
      );
    }
  }

  _makeDirs(dirPaths) {
    var i;
    for (i = 0; i < dirPaths.length; i++) {
      var dirPath = this.destinationPath(dirPaths[i]);
      mkdirp.sync(dirPath, function (err) {
        if (err) {
          console.error(err);
        }
      });
    }
  }

  install() {
  }
};
<commit_msg>Comment out the projectSlug prompt<commit_after>/* eslint capitalized-comments: ["off"],
          comma-dangle: ["off"] */

/**
 * @fileOverview The main code for this generator.
 *
 * @author Andy Culbertson
 *
 * @requires NPM:yeoman-generator
 * @requires NPM:chalk
 * @requires NPM:yosay
 * @requires NPM:mkdirp
 */

'use strict';
const Generator = require('yeoman-generator');
const chalk = require('chalk');
const yosay = require('yosay');
const mkdirp = require('mkdirp');

module.exports = class extends Generator {
  prompting() {
    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the groovy ' + chalk.red('generator-python-cmd') + ' generator!'
    ));

    const prompts = [{
      type: 'input',
      name: 'projectName',
      message: 'What is the project name?',
      // Title case the appname. Based on https://stackoverflow.com/a/196991.
      default: this.appname.replace(/\b\w/g, function (txt) {
        return txt.toUpperCase();
      }),
    },
    // {
    //   type: 'input',
    //   name: 'projectSlug',
    //   message: 'What is the project slug?',
    //   default: this.appname.replace(/ /g, '-'),
    // },
    {
      type: 'input',
      name: 'packageName',
      message: 'What is the package name?',
      default: this.appname.replace(/ /g, ''),
    },
    {
      type: 'input',
      name: 'projectDesc',
      message: 'What is the project description?',
    },
    {
      type: 'input',
      name: 'author',
      message: 'What is the author\'s name?',
    },
    {
      type: 'input',
      name: 'authorEmail',
      message: 'What is the author\'s email address?',
    },
    ];

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

  // Adapted from
  // https://github.com/yeoman/generator-webapp/blob/master/app/index.js
  writing() {
    this._writingGit();
    this._writingScript();
    this._writingConfig();
    this._writingLib();
    this._writingDocs();
    this._writingTests();
    this._writingSetup();
  }

  _writingGit() {
    this.fs.copy(
      this.templatePath('gitignore'),
      this.destinationPath('.gitignore'));
  }

  _writingScript() {
    const templatePaths = ['app.py'];
    const options = {packageName: this.props.packageName};
    this._copyTpls(templatePaths, options);
  }

  _writingConfig() {
    const dirPaths = ['config'];
    this._makeDirs(dirPaths);
  }

  _writingLib() {
    const templatePaths = [
      'cli.py',
      'config.py',
      'controller.py',
      '__init__.py',
    ];
    const options = {};
    this._copyPackageTpls(templatePaths, options);
  }

  _writingDocs() {
    const dirPaths = [
      'docs',
    ];
    this._makeDirs(dirPaths);

    const templatePaths = [
      'LICENSE.md',
      'README.md',
    ];
    const options = {projectName: this.props.projectName,
      author: this.props.author,
      authorEmail: this.props.authorEmail};
    this._copyTpls(templatePaths, options);
  }

  _writingTests() {
    const templatePaths = [
      'tests/context.py',
      'tests/test.py',
    ];
    const options = {packageName: this.props.packageName};
    this._copyTpls(templatePaths, options);
  }

  _writingSetup() {
    const templatePaths = [
      'setup.py',
      'requirements.txt',
      'requirements-dev.txt',
    ];
    const options = {packageName: this.props.packageName,
      projectName: this.props.projectName,
      projectDesc: this.props.projectDesc,
      author: this.props.author,
      authorEmail: this.props.authorEmail};
    this._copyTpls(templatePaths, options);
  }

  _copyTpls(templatePaths, options) {
    var i;
    for (i = 0; i < templatePaths.length; i++) {
      var templatePath = templatePaths[i];
      this.fs.copyTpl(
        this.templatePath(templatePath),
        this.destinationPath(templatePath),
        options
      );
    }
  }

  _copyPackageTpls(templatePaths, options) {
    var i;
    for (i = 0; i < templatePaths.length; i++) {
      var templatePath = 'package/' + templatePaths[i];
      var destinationPath = this.props.packageName + '/' + templatePaths[i];
      this.fs.copyTpl(
        this.templatePath(templatePath),
        this.destinationPath(destinationPath),
        options
      );
    }
  }

  _makeDirs(dirPaths) {
    var i;
    for (i = 0; i < dirPaths.length; i++) {
      var dirPath = this.destinationPath(dirPaths[i]);
      mkdirp.sync(dirPath, function (err) {
        if (err) {
          console.error(err);
        }
      });
    }
  }

  install() {
  }
};
<|endoftext|>