<commit_before>'use strict';

var util = require('util'),
    fs = require('fs'),
    path = require('path'),
    chalk = require('chalk'),
    yeoman = require('yeoman-generator'),
    pkg_name = require('pkg-name'),
    update_notifier = require('update-notifier'),
    compare_version = require('compare-version'),
    string_length = require('string-length'),
    _ = require('underscore.string'),
    mkdirp = require('mkdirp'),
    child_process = require('child_process'),
    pkg = require('../package.json'),
    template_name = 'freekerneljs-basic-app-md',
    generator_root = '',
    template_path = '',
    task_error = false;

var exec = child_process.exec;

function getDirectories(srcpath) {
    return fs.readdirSync(srcpath).filter(function (file) {
        return fs.statSync(path.join(srcpath, file)).isDirectory();
    });
}

var freekerneljsGenerator = yeoman.generators.Base.extend({
    constructor: function () {
        yeoman.generators.Base.apply(this, arguments);

        this.on('end', function () {
            this.log('Running ' + chalk.yellow('Grunt') + ' tasks now...');

            if (template_name == 'freekerneljs-basic-app') {
                var done = this.async();
                exec('grunt copy:bootstrap-fonts --project=' + this.slugname, function (err) {
                    if (err) {
                        task_error = true;
                        this.log(chalk.red('ERROR: ') + 'Grunt "copy:bootstrap-fonts" task.');
                        this.abort = true;
                    }
                    done();
                }.bind(this));
            }

            var done = this.async();
            exec('grunt default --project=' + this.slugname, function (err) {
                if (err) {
                    task_error = true;
                    this.log(chalk.red('ERROR: ') + 'Grunt "default" task.');
                    this.abort = true;
                }
                done();
            }.bind(this));

            var done = this.async();
            exec('grunt clean-workspace', function (err) {
                if (err) {
                    task_error = true;
                    this.log(chalk.red('ERROR: ') + 'Grunt "clean-workspace" task.');
                    this.abort = true;
                }
                done();
                task_error ? '' : this.log(chalk.green('Grunt tasks completed successfully.'));
            }.bind(this));
        });
    },

    initializing: function () {
        generator_root = this.templatePath('../../');
        template_path = this.templatePath();

        var done = this.async();
        update_notifier({
            pkg: pkg,
            callback: function (err, update) {
                if (err) {
                    this.log(err);
                }
                else if (compare_version(update.latest, update.current) == 1) {
                    var fill = function (str, count) {
                        return Array(count + 1).join(str);
                    };

                    var line1 = ' Update available: ' + chalk.green.bold(update.latest) + chalk.dim(' (current: ' + update.current + ')') + ' ',
                        line2 = ' Run ' + chalk.magenta('npm update -g ' + pkg.name) + ' to update. ',
                        contentWidth = Math.max(string_length(line1), string_length(line2)),
                        line1rest = contentWidth - string_length(line1),
                        line2rest = contentWidth - string_length(line2),
                        top = chalk.yellow('┌' + fill('─', contentWidth) + '┐'),
                        bottom = chalk.yellow('└' + fill('─', contentWidth) + '┘'),
                        side = chalk.yellow('│'),
                        updateMessage = '\n\n' + top + '\n' + side + line1 + fill(' ', line1rest) + side + '\n' + side + line2 + fill(' ', line2rest) + side + '\n' + bottom + '\n';

                    this.log(updateMessage);
                }

                done();
            }
        })
    },

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

        var welcomeMsg = '\n' +
          '+-+-+-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+\n' +
          '|F|r|e|e|K|e|r|n|e|l|J|S| |G|e|n|e|r|a|t|o|r|\n' +
          '+-+-+-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+\n' +
          '\n'

        this.log(welcomeMsg);

        var prompts = [{
            when: function (response) {
                if (getDirectories(template_path).length > 1)
                    return true

                return false
            },
            type: 'list',
            name: 'template',
            message: 'Select a template',
            choices: getDirectories(template_path),
            default: 'freekerneljs-basic-app-md'
        }, {
            when: function (response) {
                return response.template === 'freekerneljs-basic-app';
            },
            type: 'checkbox',
            name: 'modules',
            message: 'Which packages would you like to include?',
            choices: [{
                value: 'cookiesModule',
                name: 'angular-cookies',
                checked: false
            }, {
                value: 'resourceModule',
                name: 'angular-resource',
                checked: false
            }, {
                value: 'messagesModule',
                name: 'angular-messages',
                checked: false
            }, {
                value: 'sanitizeModule',
                name: 'angular-sanitize',
                checked: false
            }, {
                value: 'touchModule',
                name: 'angular-touch',
                checked: false
            }]
        }, {
            when: function (response) {
                return response.template === 'freekerneljs-basic-app-md';
            },
            type: 'checkbox',
            name: 'modules',
            message: 'Which packages would you like to include?',
            choices: [{
                value: 'cookiesModule',
                name: 'angular-cookies',
                checked: false
            }, {
                value: 'resourceModule',
                name: 'angular-resource',
                checked: false
            }, {
                value: 'messagesModule',
                name: 'angular-messages',
                checked: false
            }, {
                value: 'sanitizeModule',
                name: 'angular-sanitize',
                checked: false
            }, {
                value: 'touchModule',
                name: 'angular-touch',
                checked: false
            }, {
                value: 'iconicFont',
                name: 'material-design-iconic-font',
                checked: false
            }]
        }, {
            type: 'input',
            name: 'name',
            message: 'Project name',
            default: function (response) {
                //var name = this.appname || path.basename(process.cwd());
                //return name.replace(/\s+/g, '-');
                return response.template + '-' + Math.floor((Math.random() * 1000000) + 1).toString();
            },
            validate: function (str) {
                return fs.existsSync(str) ? chalk.red('ERROR: ') + 'Project name already exists.' : true;
            }
        }, {
            type: 'input',
            name: 'title',
            message: 'Title',
            default: 'FreeKernelJS App'
        }, {
            type: 'input',
            name: 'description',
            message: 'Description',
            default: 'A FreeKernelJS project'
        }, {
            type: 'input',
            name: 'version',
            message: 'Version',
            default: '1.0.0'
        }, {
            type: 'input',
            name: 'license',
            message: 'License',
            default: 'MIT'
        }, {
            type: 'input',
            name: 'repository',
            message: 'Repository',
            default: 'none'
        }, {
            type: 'input',
            name: 'author_name',
            message: 'Author name'
        }, {
            type: 'input',
            name: 'author_email',
            message: 'Author email'
        }, {
            type: 'input',
            name: 'author_url',
            message: 'Author url'
        }, {
            type: 'input',
            name: 'homepage',
            message: 'Home page'
        }];

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

            if (props.template) {
                template_name = props.template;
            }

            // For easier access in the templates.
            this.slugname = _.slugify(props.name);

            var hasMod = function (mod) {
                return props.modules.indexOf(mod) !== -1;
            };

            // Common modules.
            this.angularModule = true;
            this.mocksModule = true;
            this.routeModule = true;
            this.scriptjsModule = true;
            this.angularTranslateModule = true;
            this.angularTranslateLoaderStaticFilesModule = true;
            this.cookiesModule = hasMod('cookiesModule');
            this.resourceModule = hasMod('resourceModule');
            this.messagesModule = hasMod('messagesModule');
            this.sanitizeModule = hasMod('sanitizeModule');
            this.touchModule = hasMod('touchModule');

            switch (template_name) {
                case 'freekerneljs-basic-app':
                    this.bootstrapModule = true;
                    break;
                case 'freekerneljs-basic-app-md':
                    this.materialModule = true;
                    this.iconicFont = hasMod('iconicFont');
                    break;
                default:
            }

            mkdirp(this.slugname);

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

    configuration: function () {
        // Workspace
        this.template(template_name + '/_package.json', 'package.json');
        this.template(template_name + '/_bower.json', 'bower.json');
        this.template('_bowerrc', '.bowerrc');
        this.copy('Gruntfile.js', 'Gruntfile.js');

        // Project folder
        this.template(template_name + '/_package.json', this.slugname + '/package.json');
        this.template(template_name + '/_bower.json', this.slugname + '/bower.json');
        this.copy('Gruntfile.js', this.slugname + '/Gruntfile.js');
        this.copy(template_name + '/gitignore', this.slugname + '/.gitignore');
        this.copy(template_name + '/bowerrc', this.slugname + '/.bowerrc');
    },

    app: function () {
        this.copy(template_name + '/app/_app.bootstrap.js', this.slugname + '/app/app.bootstrap.js');
        this.copy(template_name + '/app/_app.module.js', this.slugname + '/app/app.module.js');
        this.copy(template_name + '/app/_app.routes.js', this.slugname + '/app/app.routes.js');
        this.copy(template_name + '/app/_index.html', this.slugname + '/app/index.html');
        this.bulkDirectory(template_name + '/app/assets/images', this.slugname + '/app/assets/images');
        this.bulkDirectory(template_name + '/app/assets/scss', this.slugname + '/app/assets/scss');
        this.bulkDirectory(template_name + '/app/assets/css', this.slugname + '/app/assets/css');
        this.bulkDirectory(template_name + '/app/views', this.slugname + '/app/views');
        this.bulkDirectory(template_name + '/app/widgets', this.slugname + '/app/widgets');
        this.bulkDirectory(template_name + '/app/services', this.slugname + '/app/services');
        this.bulkDirectory(template_name + '/app/data', this.slugname + '/app/data');
    },

    writing: function () {
        this.copy(template_name + '/README.md', this.slugname + '/README.md');
        this.copy(template_name + '/README.md', 'README.md');
    },

    test: function () {
        this.bulkDirectory(template_name + '/app/_test', this.slugname + '/app/_test');
    },

    install: function () {
        this.installDependencies({
            skipInstall: this.options['skip-install']
        });
    }
});

module.exports = freekerneljsGenerator;<commit_msg>Fixed: console.log to this.log (Update notifier) this.log undefined<commit_after>'use strict';

var util = require('util'),
    fs = require('fs'),
    path = require('path'),
    chalk = require('chalk'),
    yeoman = require('yeoman-generator'),
    pkg_name = require('pkg-name'),
    update_notifier = require('update-notifier'),
    compare_version = require('compare-version'),
    string_length = require('string-length'),
    _ = require('underscore.string'),
    mkdirp = require('mkdirp'),
    child_process = require('child_process'),
    pkg = require('../package.json'),
    template_name = 'freekerneljs-basic-app-md',
    generator_root = '',
    template_path = '',
    task_error = false;

var exec = child_process.exec;

function getDirectories(srcpath) {
    return fs.readdirSync(srcpath).filter(function (file) {
        return fs.statSync(path.join(srcpath, file)).isDirectory();
    });
}

var freekerneljsGenerator = yeoman.generators.Base.extend({
    constructor: function () {
        yeoman.generators.Base.apply(this, arguments);

        this.on('end', function () {
            this.log('Running ' + chalk.yellow('Grunt') + ' tasks now...');

            if (template_name == 'freekerneljs-basic-app') {
                var done = this.async();
                exec('grunt copy:bootstrap-fonts --project=' + this.slugname, function (err) {
                    if (err) {
                        task_error = true;
                        this.log(chalk.red('ERROR: ') + 'Grunt "copy:bootstrap-fonts" task.');
                        this.abort = true;
                    }
                    done();
                }.bind(this));
            }

            var done = this.async();
            exec('grunt default --project=' + this.slugname, function (err) {
                if (err) {
                    task_error = true;
                    this.log(chalk.red('ERROR: ') + 'Grunt "default" task.');
                    this.abort = true;
                }
                done();
            }.bind(this));

            var done = this.async();
            exec('grunt clean-workspace', function (err) {
                if (err) {
                    task_error = true;
                    this.log(chalk.red('ERROR: ') + 'Grunt "clean-workspace" task.');
                    this.abort = true;
                }
                done();
                task_error ? '' : this.log(chalk.green('Grunt tasks completed successfully.'));
            }.bind(this));
        });
    },

    initializing: function () {
        generator_root = this.templatePath('../../');
        template_path = this.templatePath();

        var done = this.async();
        update_notifier({
            pkg: pkg,
            callback: function (err, update) {
                if (err) {
                    this.log(err);
                }
                else if (compare_version(update.latest, update.current) == 1) {
                    var fill = function (str, count) {
                        return Array(count + 1).join(str);
                    };

                    var line_1 = ' Update available: ' + chalk.green.bold(update.latest) + chalk.dim(' (current: ' + update.current + ')') + ' ',
                        line_2 = ' Run ' + chalk.magenta('npm update -g ' + pkg.name) + ' to update. ',
                        content_width = Math.max(string_length(line_1), string_length(line_2)),
                        line_1_rest = content_width - string_length(line_1),
                        line_2_rest = content_width - string_length(line_2),
                        top = chalk.yellow('┌' + fill('─', content_width) + '┐'),
                        bottom = chalk.yellow('└' + fill('─', content_width) + '┘'),
                        side = chalk.yellow('│'),
                        update_message = '\n\n' + top + '\n' + side + line_1 + fill(' ', line_1_rest) + side + '\n' + side + line_2 + fill(' ', line_2_rest) + side + '\n' + bottom + '\n';

                    this.log(update_message);
                }

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

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

        var welcomeMsg = '\n' +
          '+-+-+-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+\n' +
          '|F|r|e|e|K|e|r|n|e|l|J|S| |G|e|n|e|r|a|t|o|r|\n' +
          '+-+-+-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+\n' +
          '\n'

        this.log(welcomeMsg);

        var prompts = [{
            when: function (response) {
                if (getDirectories(template_path).length > 1)
                    return true

                return false
            },
            type: 'list',
            name: 'template',
            message: 'Select a template',
            choices: getDirectories(template_path),
            default: 'freekerneljs-basic-app-md'
        }, {
            when: function (response) {
                return response.template === 'freekerneljs-basic-app';
            },
            type: 'checkbox',
            name: 'modules',
            message: 'Which packages would you like to include?',
            choices: [{
                value: 'cookiesModule',
                name: 'angular-cookies',
                checked: false
            }, {
                value: 'resourceModule',
                name: 'angular-resource',
                checked: false
            }, {
                value: 'messagesModule',
                name: 'angular-messages',
                checked: false
            }, {
                value: 'sanitizeModule',
                name: 'angular-sanitize',
                checked: false
            }, {
                value: 'touchModule',
                name: 'angular-touch',
                checked: false
            }]
        }, {
            when: function (response) {
                return response.template === 'freekerneljs-basic-app-md';
            },
            type: 'checkbox',
            name: 'modules',
            message: 'Which packages would you like to include?',
            choices: [{
                value: 'cookiesModule',
                name: 'angular-cookies',
                checked: false
            }, {
                value: 'resourceModule',
                name: 'angular-resource',
                checked: false
            }, {
                value: 'messagesModule',
                name: 'angular-messages',
                checked: false
            }, {
                value: 'sanitizeModule',
                name: 'angular-sanitize',
                checked: false
            }, {
                value: 'touchModule',
                name: 'angular-touch',
                checked: false
            }, {
                value: 'iconicFont',
                name: 'material-design-iconic-font',
                checked: false
            }]
        }, {
            type: 'input',
            name: 'name',
            message: 'Project name',
            default: function (response) {
                //var name = this.appname || path.basename(process.cwd());
                //return name.replace(/\s+/g, '-');
                return response.template + '-' + Math.floor((Math.random() * 1000000) + 1).toString();
            },
            validate: function (str) {
                return fs.existsSync(str) ? chalk.red('ERROR: ') + 'Project name already exists.' : true;
            }
        }, {
            type: 'input',
            name: 'title',
            message: 'Title',
            default: 'FreeKernelJS App'
        }, {
            type: 'input',
            name: 'description',
            message: 'Description',
            default: 'A FreeKernelJS project'
        }, {
            type: 'input',
            name: 'version',
            message: 'Version',
            default: '1.0.0'
        }, {
            type: 'input',
            name: 'license',
            message: 'License',
            default: 'MIT'
        }, {
            type: 'input',
            name: 'repository',
            message: 'Repository',
            default: 'none'
        }, {
            type: 'input',
            name: 'author_name',
            message: 'Author name'
        }, {
            type: 'input',
            name: 'author_email',
            message: 'Author email'
        }, {
            type: 'input',
            name: 'author_url',
            message: 'Author url'
        }, {
            type: 'input',
            name: 'homepage',
            message: 'Home page'
        }];

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

            if (props.template) {
                template_name = props.template;
            }

            // For easier access in the templates.
            this.slugname = _.slugify(props.name);

            var hasMod = function (mod) {
                return props.modules.indexOf(mod) !== -1;
            };

            // Common modules.
            this.angularModule = true;
            this.mocksModule = true;
            this.routeModule = true;
            this.scriptjsModule = true;
            this.angularTranslateModule = true;
            this.angularTranslateLoaderStaticFilesModule = true;
            this.cookiesModule = hasMod('cookiesModule');
            this.resourceModule = hasMod('resourceModule');
            this.messagesModule = hasMod('messagesModule');
            this.sanitizeModule = hasMod('sanitizeModule');
            this.touchModule = hasMod('touchModule');

            switch (template_name) {
                case 'freekerneljs-basic-app':
                    this.bootstrapModule = true;
                    break;
                case 'freekerneljs-basic-app-md':
                    this.materialModule = true;
                    this.iconicFont = hasMod('iconicFont');
                    break;
                default:
            }

            mkdirp(this.slugname);

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

    configuration: function () {
        // Workspace
        this.template(template_name + '/_package.json', 'package.json');
        this.template(template_name + '/_bower.json', 'bower.json');
        this.template('_bowerrc', '.bowerrc');
        this.copy('Gruntfile.js', 'Gruntfile.js');

        // Project folder
        this.template(template_name + '/_package.json', this.slugname + '/package.json');
        this.template(template_name + '/_bower.json', this.slugname + '/bower.json');
        this.copy('Gruntfile.js', this.slugname + '/Gruntfile.js');
        this.copy(template_name + '/gitignore', this.slugname + '/.gitignore');
        this.copy(template_name + '/bowerrc', this.slugname + '/.bowerrc');
    },

    app: function () {
        this.copy(template_name + '/app/_app.bootstrap.js', this.slugname + '/app/app.bootstrap.js');
        this.copy(template_name + '/app/_app.module.js', this.slugname + '/app/app.module.js');
        this.copy(template_name + '/app/_app.routes.js', this.slugname + '/app/app.routes.js');
        this.copy(template_name + '/app/_index.html', this.slugname + '/app/index.html');
        this.bulkDirectory(template_name + '/app/assets/images', this.slugname + '/app/assets/images');
        this.bulkDirectory(template_name + '/app/assets/scss', this.slugname + '/app/assets/scss');
        this.bulkDirectory(template_name + '/app/assets/css', this.slugname + '/app/assets/css');
        this.bulkDirectory(template_name + '/app/views', this.slugname + '/app/views');
        this.bulkDirectory(template_name + '/app/widgets', this.slugname + '/app/widgets');
        this.bulkDirectory(template_name + '/app/services', this.slugname + '/app/services');
        this.bulkDirectory(template_name + '/app/data', this.slugname + '/app/data');
    },

    writing: function () {
        this.copy(template_name + '/README.md', this.slugname + '/README.md');
        this.copy(template_name + '/README.md', 'README.md');
    },

    test: function () {
        this.bulkDirectory(template_name + '/app/_test', this.slugname + '/app/_test');
    },

    install: function () {
        this.installDependencies({
            skipInstall: this.options['skip-install']
        });
    }
});

module.exports = freekerneljsGenerator;<|endoftext|>


<commit_before>'use strict';

var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var npmName = require('npm-name');

var GruntpluginGenerator = module.exports = function GruntpluginGenerator(args, options) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({
      bower: false,
      skipInstall: options['skip-install']
    });
  });

  this.pkg = require(path.join(__dirname, '../package.json'));
};
util.inherits(GruntpluginGenerator, yeoman.generators.NamedBase);

GruntpluginGenerator.prototype.askFor = function askFor() {
  var cb = this.async();
  var log = this.log;

  console.log(
    this.yeoman +
    '\nFor more information about Grunt plugin best practices,' +
    '\nplease see the docs at http://gruntjs.com/creating-plugins');

  var prompts = [{
    name: 'name',
    message: 'Plugin Name',
    filter: function (value) {
      var done = this.async();
      var contribRegex = /^grunt-contrib/;

      if (contribRegex.test(value)) {
        log.error(
          'Removing "contrib" from your project\'s name. The grunt-contrib' +
          '\nnamespace would like to be reserved for tasks maintained by the grunt team.'
        );
        value = value.replace(contribRegex, 'grunt');
      }

      npmName(value, function (err, available) {
        if (!available) {
          log.info(chalk.yellow(value) + ' already exists on npm. You might want to use another name.');
        }

        done(value);
      });
    }
  }, {
    name: 'description',
    message: 'Description',
    default: 'The best Grunt plugin ever.'
  }, {
    name: 'version',
    message: 'Version',
    default: '0.0.1'
  }, {
    name: 'repository',
    message: 'Project git repository'
  }, {
    name: 'homepage',
    message: 'Project homepage'
  }, {
    name: 'license',
    message: 'License',
    default: 'MIT'
  }, {
    name: 'authorName',
    message: 'Author name'
  }, {
    name: 'authorEmail',
    message: 'Author email'
  }, {
    name: 'authorUrl',
    message: 'Author url'
  }, {
    name: 'nodeVersion',
    message: 'What versions of node does it run on?',
    default: '>= 0.8.0'
  }, {
    name: 'gruntVersion',
    message: 'What version of grunt does it need?',
    default: '~0.4.2'
  }];

  this.currentYear = (new Date()).getFullYear();

  this.prompt(prompts, function (props) {
    this.slugname = this._.slugify(props.name);

    this.shortName = props.name.replace(/^grunt[\-_]?/, '').replace(/[\W_]+/g, '_').replace(/^(\d)/, '_$1');
    this.authorOriginalName = props.authorName;
    this.authorName = props.authorName.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');

    if (!props.homepage) {
      props.homepage = this.repoUrl;
    }

    this.props = props;

    cb();
  }.bind(this));
};

GruntpluginGenerator.prototype.tasks = function tasks() {
  this.mkdir('tasks');
  this.template('tasks/name.js', 'tasks/' + this.shortName + '.js');
};

GruntpluginGenerator.prototype.test = function test() {
  this.directory('test/expected');
  this.directory('test/fixtures');
  this.template('test/name_test.js', 'test/' + this.shortName + '_test.js');
};

GruntpluginGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('jshintrc', '.jshintrc');
  this.copy('gitignore', '.gitignore');
  this.copy('editorconfig', '.editorconfig');

  this.template('_README.md', 'README.md');
  this.template('_Gruntfile.js', 'Gruntfile.js');
};

GruntpluginGenerator.prototype.packageFile = function packageFile() {
  var pkgFile = {
    name: this.slugname,
    version: this.props.version,
    description: this.props.description,
    homepage: this.props.homepage,
    repository: this.props.repository,
    author: {
      name: this.authorOriginalName,
      email: this.props.authorEmail
    },
    keywords: [
      'gruntplugin'
    ],
    main: 'Gruntfile.js',
    engines: {
      node: this.props.nodeVersion
    },
    licenses: [
      {
        type: this.props.license
      }
    ],
    devDependencies: {
      'grunt-contrib-clean': '~0.5.0',
      'grunt-contrib-jshint': '~0.8.0',
      'grunt-contrib-nodeunit': '~0.3.0',
      'grunt': this.props.gruntVersion,
      'jshint-stylish': '~0.1.5',
      'load-grunt-tasks': '~0.3.0'
    },
    scripts: {
      test: 'grunt test'
    }
  };

  if (this.props.authorUrl) {
    pkgFile.author.url = this.props.authorUrl;
  }

  this.writeFileFromString(JSON.stringify(pkgFile, null, 2), 'package.json');
};
<commit_msg>Update package.json template<commit_after>'use strict';

var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var npmName = require('npm-name');

var GruntpluginGenerator = module.exports = function GruntpluginGenerator(args, options) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({
      bower: false,
      skipInstall: options['skip-install']
    });
  });

  this.pkg = require(path.join(__dirname, '../package.json'));
};
util.inherits(GruntpluginGenerator, yeoman.generators.NamedBase);

GruntpluginGenerator.prototype.askFor = function askFor() {
  var cb = this.async();
  var log = this.log;

  console.log(
    this.yeoman +
    '\nFor more information about Grunt plugin best practices,' +
    '\nplease see the docs at http://gruntjs.com/creating-plugins');

  var prompts = [{
    name: 'name',
    message: 'Plugin Name',
    filter: function (value) {
      var done = this.async();
      var contribRegex = /^grunt-contrib/;

      if (contribRegex.test(value)) {
        log.error(
          'Removing "contrib" from your project\'s name. The grunt-contrib' +
          '\nnamespace would like to be reserved for tasks maintained by the grunt team.'
        );
        value = value.replace(contribRegex, 'grunt');
      }

      npmName(value, function (err, available) {
        if (!available) {
          log.info(chalk.yellow(value) + ' already exists on npm. You might want to use another name.');
        }

        done(value);
      });
    }
  }, {
    name: 'description',
    message: 'Description',
    default: 'The best Grunt plugin ever.'
  }, {
    name: 'version',
    message: 'Version',
    default: '0.0.1'
  }, {
    name: 'repository',
    message: 'Project git repository'
  }, {
    name: 'homepage',
    message: 'Project homepage'
  }, {
    name: 'license',
    message: 'License',
    default: 'MIT'
  }, {
    name: 'authorName',
    message: 'Author name'
  }, {
    name: 'authorEmail',
    message: 'Author email'
  }, {
    name: 'authorUrl',
    message: 'Author url'
  }, {
    name: 'nodeVersion',
    message: 'What versions of node does it run on?',
    default: '>= 0.8.0'
  }, {
    name: 'gruntVersion',
    message: 'What version of grunt does it need?',
    default: '~0.4.2'
  }];

  this.currentYear = (new Date()).getFullYear();

  this.prompt(prompts, function (props) {
    this.slugname = this._.slugify(props.name);

    this.shortName = props.name.replace(/^grunt[\-_]?/, '').replace(/[\W_]+/g, '_').replace(/^(\d)/, '_$1');
    this.authorOriginalName = props.authorName;
    this.authorName = props.authorName.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');

    if (!props.homepage) {
      props.homepage = this.repoUrl;
    }

    this.props = props;

    cb();
  }.bind(this));
};

GruntpluginGenerator.prototype.tasks = function tasks() {
  this.mkdir('tasks');
  this.template('tasks/name.js', 'tasks/' + this.shortName + '.js');
};

GruntpluginGenerator.prototype.test = function test() {
  this.directory('test/expected');
  this.directory('test/fixtures');
  this.template('test/name_test.js', 'test/' + this.shortName + '_test.js');
};

GruntpluginGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('jshintrc', '.jshintrc');
  this.copy('gitignore', '.gitignore');
  this.copy('editorconfig', '.editorconfig');

  this.template('_README.md', 'README.md');
  this.template('_Gruntfile.js', 'Gruntfile.js');
};

GruntpluginGenerator.prototype.packageFile = function packageFile() {
  var pkgFile = {
    name: this.slugname,
    version: this.props.version,
    description: this.props.description,
    homepage: this.props.homepage,
    repository: this.props.repository,
    author: {
      name: this.authorOriginalName,
      email: this.props.authorEmail,
      url: this.props.authorUrl
    },
    keywords: [
      'gruntplugin'
    ],
    main: 'Gruntfile.js',
    engines: {
      node: this.props.nodeVersion
    },
    licenses: this.props.license,
    devDependencies: {
      'grunt-contrib-clean': '~0.5.0',
      'grunt-contrib-jshint': '~0.8.0',
      'grunt-contrib-nodeunit': '~0.3.0',
      'grunt': this.props.gruntVersion,
      'jshint-stylish': '~0.1.5',
      'load-grunt-tasks': '~0.3.0'
    },
    scripts: {
      test: 'grunt test'
    }
  };

  if (this.props.authorUrl) {
    pkgFile.author.url = this.props.authorUrl;
  }

  this.writeFileFromString(JSON.stringify(pkgFile, null, 2), 'package.json');
};
<|endoftext|>


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

var Test2Generator = yeoman.generators.Base.extend({
  askForForlderName: function () {
    var done = this.async();
    this.log('                            ____    __    ____  _______ .______   ');
    this.log('                            \\   \\  /  \\  /   / |   ____||   _  \\  ');
    this.log('                             \\   \\/    \\/   /  |  |__   |  |_)  | ');
    this.log('                              \\            /   |   __|  |   _  <  ');
    this.log('                               \\    /\\    /    |  |____ |  |_)  | ');
    this.log('                                \\__/  \\__/     |_______||______/  ');
    this.log('                                                                  ');
    this.log('     _______.___________.    ___      .______     .___________. _______ .______          __  ');
    this.log('    /       |           |   /   \\     |   _  \\    |           ||   ____||   _  \\        |  | ');
    this.log('   |   (----`---|  |----`  /  ^  \\    |  |_)  |   `---|  |----`|  |__   |  |_)  |       |  | ');
    this.log('    \\   \\       |  |      /  /_\\  \\   |      /        |  |     |   __|  |      /        |  | ');
    this.log('(----)   |      |  |     /  _____  \\  |  |\\  \\----.   |  |     |  |____ |  |\\  \\----.   |__| ');
    this.log('|_______/       |__|    /__/     \\__\\ | _| `._____|   |__|     |_______|| _| `._____|   (__) ');
    this.log(" ");
    var prompts = [{
      name: 'appName',
      message: 'Hello! What\'s your folder\'s name ?'
    },
    {
      name: 'needJquery',
      type: 'confirm',
      message: 'Do you want to include jQuery ?'
    }];

    this.prompt(prompts, function (props) {
      for(var k in props){
        this[k]=props[k];
      }
      done();
    }.bind(this));
  },

  askForFrameworkNeeds: function () {
    var done = this.async();
    var prompts = [{
      name: 'needFrontFramework',
      type: 'confirm',
      message: 'Would you like to use a Front-end Framework?',
      default: true
    }, {
      when: function (response) {
        return response.needFrontFramework;
      },
      name: 'frontFramework',
      type: 'list',
      message: 'Which one do you need ?',
      choices: [{
        name: 'Bootstrap',
        value: 'bootstrap',
        checked: true
      }, {
        name: 'Foundation',
        value: 'bower-foundation',
        checked: false
      }]
    }];

    this.prompt(prompts, function (props) {
      for(var k in props){
        this[k]=props[k];
      }
      done();
    }.bind(this));
  },
  askForTaskRunnerNeeds: function () {
    var done = this.async();
    var prompts = [{
      name: 'needTaskRunner',
      type: 'confirm',
      message: 'Would you like to use a task runner ?',
      default: true
    }, {
      when: function (response) {
        return response.needTaskRunner;
      },
      name: 'taskRunner',
      type: 'list',
      message: 'Which one do you need ?',
      choices: [{
        name: 'Gulp',
        value: 'gulp',
        checked: true
      },
      {
        name: 'Grunt',
        value: 'grunt',
        checked: false
      }]
    }];
    var extraPrompts = [{
      name: 'needCustomConfig',
      type: 'confirm',
      message: 'Do you want to select tasks in addition to default tasks ?',
      default: true
    }, {
      when: function (response) {
        return response.needCustomConfig;
      },
      name: 'customConfig',
      type: 'checkbox',
      message: 'What do you need ?',
      choices: [{
        name: 'SASS support',
        value: 'sass',
        checked: false
      },
      {
        name: 'CSS minification',
        value: 'cssmin',
        checked: false
      }, {
        name: 'Javascript minification',
        value: 'uglify',
        checked: false
      },
      {
        name: 'Image optimization',
        value: 'imagemin',
        checked: false
      },
      {
        name: 'JS linting',
        value: 'jshint',
        checked: false
      },
      {
        name: 'File concatenation',
        value: 'concat',
        checked: false
      }
      ]
    }];
    this.prompt(prompts, function (props) {
      for(var k in props){
        this[k]=props[k];
      }
      if (props.needTaskRunner){
       this.prompt(extraPrompts, function (extraProps) {
        this.taskNames = [];
        for(var k in extraProps.customConfig){
          this.taskNames.push(extraProps.customConfig[k]);
          var prefix = (this.taskRunner == "gulp") ? "gulp-" : "grunt-contrib-";
          extraProps.customConfig[k] = prefix+extraProps.customConfig[k];
        }
        this.customConfig = extraProps.customConfig;
        done();
      }.bind(this));
     }
     else
        done();
   }.bind(this));
  },
  enforceFolderName: function () {
    if (this.appName !== this._.last(this.destinationRoot().split(path.sep))) {
      this.destinationRoot(this.appName);
    }
  },
  app: function () {
    this.mkdir('build');
    this.mkdir('build/css');
    this.mkdir('build/js');
    this.mkdir('build/img');
    this.mkdir('src');
    this.mkdir('src/js');
    var cssPath = (this.needTaskRunner && this.taskNames.indexOf("sass") != -1) ? 'sass' : 'css'
    this.mkdir('src/'+cssPath);
    this.mkdir('src/img');
    this.copy('_index.html', 'index.html');
    this.copy('_main.js', 'src/js/main.js');
    this.copy('_package.json', 'package.json');
    this.copy('_bower.json', 'bower.json');
    this._processDirectory(this.taskRunner);
  },

  projectfiles: function () {
    this.copy('editorconfig', '.editorconfig');
    this.copy('jshintrc', '.jshintrc');
  },
  installDeps: function() {
  this.installDependencies();
  }
});

Test2Generator.prototype._processDirectory = function(taskRunner) {
  if ('gulp' === taskRunner){
    this.mkdir('gulp');
    this.mkdir('gulp/tasks');
    this.directory('gulp/util', 'gulp/util');
    this.copy('_gulpfile.js', 'gulpfile.js');
    this.copy('gulp/_index.js', 'gulp/index.js');
    this.copy('gulp/tasks/_default.js', 'gulp/tasks/default.js');
    this.copy('gulp/tasks/_build.js', 'gulp/tasks/build.js');
    this.copy('gulp/tasks/_watch.js', 'gulp/tasks/watch.js');
    for (var i in this.taskNames){
      console.log("task", this.taskNames[i]);
      this.copy('gulp/tasks/_'+this.taskNames[i]+'.js', 'gulp/tasks/'+this.taskNames[i]+'.js');
    }
  }
    else if ('grunt' === taskRunner){
      this.copy('_Gruntfile.js', 'Gruntfile.js');
    }
};
module.exports = Test2Generator;
<commit_msg>modified generator name<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var fs = require('fs');

var WebstarterGenerator = yeoman.generators.Base.extend({
  askForForlderName: function () {
    var done = this.async();
    this.log('                            ____    __    ____  _______ .______   ');
    this.log('                            \\   \\  /  \\  /   / |   ____||   _  \\  ');
    this.log('                             \\   \\/    \\/   /  |  |__   |  |_)  | ');
    this.log('                              \\            /   |   __|  |   _  <  ');
    this.log('                               \\    /\\    /    |  |____ |  |_)  | ');
    this.log('                                \\__/  \\__/     |_______||______/  ');
    this.log('                                                                  ');
    this.log('     _______.___________.    ___      .______     .___________. _______ .______          __  ');
    this.log('    /       |           |   /   \\     |   _  \\    |           ||   ____||   _  \\        |  | ');
    this.log('   |   (----`---|  |----`  /  ^  \\    |  |_)  |   `---|  |----`|  |__   |  |_)  |       |  | ');
    this.log('    \\   \\       |  |      /  /_\\  \\   |      /        |  |     |   __|  |      /        |  | ');
    this.log('(----)   |      |  |     /  _____  \\  |  |\\  \\----.   |  |     |  |____ |  |\\  \\----.   |__| ');
    this.log('|_______/       |__|    /__/     \\__\\ | _| `._____|   |__|     |_______|| _| `._____|   (__) ');
    this.log(" ");
    var prompts = [{
      name: 'appName',
      message: 'Hello! What\'s your folder\'s name ?'
    },
    {
      name: 'needJquery',
      type: 'confirm',
      message: 'Do you want to include jQuery ?'
    }];

    this.prompt(prompts, function (props) {
      for(var k in props){
        this[k]=props[k];
      }
      done();
    }.bind(this));
  },

  askForFrameworkNeeds: function () {
    var done = this.async();
    var prompts = [{
      name: 'needFrontFramework',
      type: 'confirm',
      message: 'Would you like to use a Front-end Framework?',
      default: true
    }, {
      when: function (response) {
        return response.needFrontFramework;
      },
      name: 'frontFramework',
      type: 'list',
      message: 'Which one do you need ?',
      choices: [{
        name: 'Bootstrap',
        value: 'bootstrap',
        checked: true
      }, {
        name: 'Foundation',
        value: 'bower-foundation',
        checked: false
      }]
    }];

    this.prompt(prompts, function (props) {
      for(var k in props){
        this[k]=props[k];
      }
      done();
    }.bind(this));
  },
  askForTaskRunnerNeeds: function () {
    var done = this.async();
    var prompts = [{
      name: 'needTaskRunner',
      type: 'confirm',
      message: 'Would you like to use a task runner ?',
      default: true
    }, {
      when: function (response) {
        return response.needTaskRunner;
      },
      name: 'taskRunner',
      type: 'list',
      message: 'Which one do you need ?',
      choices: [{
        name: 'Gulp',
        value: 'gulp',
        checked: true
      },
      {
        name: 'Grunt',
        value: 'grunt',
        checked: false
      }]
    }];
    var extraPrompts = [{
      name: 'needCustomConfig',
      type: 'confirm',
      message: 'Do you want to select tasks in addition to default tasks ?',
      default: true
    }, {
      when: function (response) {
        return response.needCustomConfig;
      },
      name: 'customConfig',
      type: 'checkbox',
      message: 'What do you need ?',
      choices: [{
        name: 'SASS support',
        value: 'sass',
        checked: false
      },
      {
        name: 'CSS minification',
        value: 'cssmin',
        checked: false
      }, {
        name: 'Javascript minification',
        value: 'uglify',
        checked: false
      },
      {
        name: 'Image optimization',
        value: 'imagemin',
        checked: false
      },
      {
        name: 'JS linting',
        value: 'jshint',
        checked: false
      },
      {
        name: 'File concatenation',
        value: 'concat',
        checked: false
      }
      ]
    }];
    this.prompt(prompts, function (props) {
      for(var k in props){
        this[k]=props[k];
      }
      if (props.needTaskRunner){
       this.prompt(extraPrompts, function (extraProps) {
        this.taskNames = [];
        for(var k in extraProps.customConfig){
          this.taskNames.push(extraProps.customConfig[k]);
          var prefix = (this.taskRunner == "gulp") ? "gulp-" : "grunt-contrib-";
          extraProps.customConfig[k] = prefix+extraProps.customConfig[k];
        }
        this.customConfig = extraProps.customConfig;
        done();
      }.bind(this));
     }
     else
        done();
   }.bind(this));
  },
  enforceFolderName: function () {
    if (this.appName !== this._.last(this.destinationRoot().split(path.sep))) {
      this.destinationRoot(this.appName);
    }
  },
  app: function () {
    this.mkdir('build');
    this.mkdir('build/css');
    this.mkdir('build/js');
    this.mkdir('build/img');
    this.mkdir('src');
    this.mkdir('src/js');
    var cssPath = (this.needTaskRunner && this.taskNames.indexOf("sass") != -1) ? 'sass' : 'css'
    this.mkdir('src/'+cssPath);
    this.mkdir('src/img');
    this.copy('_index.html', 'index.html');
    this.copy('_main.js', 'src/js/main.js');
    this.copy('_package.json', 'package.json');
    this.copy('_bower.json', 'bower.json');
    this._processDirectory(this.taskRunner);
  },

  projectfiles: function () {
    this.copy('editorconfig', '.editorconfig');
    this.copy('jshintrc', '.jshintrc');
  },
  installDeps: function() {
  this.installDependencies();
  }
});

WebstarterGenerator.prototype._processDirectory = function(taskRunner) {
  if ('gulp' === taskRunner){
    this.mkdir('gulp');
    this.mkdir('gulp/tasks');
    this.directory('gulp/util', 'gulp/util');
    this.copy('_gulpfile.js', 'gulpfile.js');
    this.copy('gulp/_index.js', 'gulp/index.js');
    this.copy('gulp/tasks/_default.js', 'gulp/tasks/default.js');
    this.copy('gulp/tasks/_build.js', 'gulp/tasks/build.js');
    this.copy('gulp/tasks/_watch.js', 'gulp/tasks/watch.js');
    for (var i in this.taskNames){
      console.log("task", this.taskNames[i]);
      this.copy('gulp/tasks/_'+this.taskNames[i]+'.js', 'gulp/tasks/'+this.taskNames[i]+'.js');
    }
  }
    else if ('grunt' === taskRunner){
      this.copy('_Gruntfile.js', 'Gruntfile.js');
    }
};
module.exports = WebstarterGenerator;
<|endoftext|>


<commit_before>'use strict';

var fs     = require('fs'),
    path   = require('path'),
    util   = require('util'),
    walk   = require(__dirname + '/lib/walk'),
    yeoman = require('yeoman-generator')

var ChaplinGenerator = module.exports = function ChaplinGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    if(!this.exists) {
      this.installDependencies({ skipInstall: options['skip-install'] });
    }
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(ChaplinGenerator, yeoman.generators.Base);

ChaplinGenerator.prototype.askFor = function askFor() {

  var cb = this.async();

  var _this = this;

  fs.exists('Gruntfile.coffee', function(exists) {

    if(exists) {
      console.warn("This folder is not empty.")
      _this.exists = true;
      return cb();
    }

    else {

      // have Yeoman greet the user.
      console.log(this.yeoman);

      var prompts = [
        {
          name: 'appName',
          message: 'Application name'
        },
        {
          name: 'controllerSuffix',
          message: 'Controller suffix (leave this blank if you dont want one)'
        },
        {
          name: 'skeleton',
          message: " \
          [0] Barebones (minimum to get started)\n \
          [1] HTML 5 Boilerplate\n \
          [2] Twitter Bootstrap\n \
          Please enter the number next to the skeleton you would like\n\n \
          "
        }
      ];

      this.prompt(prompts, function (props) {
        this.appName = props.appName;

        if(typeof props.controllerSuffix == 'string' && props.controllerSuffix.length > 0) {
          this.controllerSuffix = props.controllerSuffix;
        }

        else {
          this.controllerSuffix = '';
        }

        if(typeof props.skeleton == null) {
          this.skeleton = 0;
        }

        else {
          this.skeleton = parseInt(props.skeleton);
        }

        cb();

      }.bind(this));
    }
  })

};

ChaplinGenerator.prototype.app = function app() {

  if(this.exists) {
    return;
  }

  var cb = this.async();

  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');

  this.mkdir('app');
  this.mkdir('app/assets');
  this.mkdir('app/assets/fonts');
  this.mkdir('app/assets/img');
  this.mkdir('app/controllers');
  this.mkdir('app/lib');
  this.mkdir('app/models');
  this.mkdir('app/styles');
  this.mkdir('app/templates');
  this.mkdir('app/views');
  this.mkdir('test');

  this.template('_config.json', 'config.json');
  this.template('_package.json', 'package.json');
  this.copy('server.coffee', 'server.coffee');
  this.template('app/_initialize.coffee', 'app/initialize.coffee');

  var path;

  switch(this.skeleton) {

    // HTML5 Boilerplate
    case 1: {
      break;
    }

    // Twitter Bootstrap
    case 2: {
      path = '../skeletons/bootstrap3';

      this.template(path + '/_bower.json',                      'bower.json');
      this.copy(path + '/Gruntfile.coffee',                     'Gruntfile.coffee');
      this.copy(path + '/app/controllers/_home.coffee',         'app/controllers/home' + this.controllerSuffix + '.coffee')
      this.copy(path + '/app/styles/application.styl',          'app/styles/application.styl')
      this.copy(path + '/app/templates/footer.hbs',             'app/templates/footer.hbs')
      this.copy(path + '/app/templates/header.hbs',             'app/templates/header.hbs')
      this.copy(path + '/app/templates/home.hbs',               'app/templates/home.hbs')
      this.copy(path + '/app/templates/jumbotron.hbs',          'app/templates/jumbotron.hbs')
      this.copy(path + '/app/templates/site.hbs',               'app/templates/site.hbs')
      this.copy(path + '/app/views/bootstrap/jumbotron.coffee', 'app/views/bootstrap/jumbotron.coffee')
      this.copy(path + '/app/views/footer.coffee',              'app/views/footer.coffee')
      this.copy(path + '/app/views/header.coffee',              'app/views/header.coffee')
      this.copy(path + '/app/views/home/home-page.coffee',      'app/views/home/home-page.coffee')
      this.copy(path + '/app/views/site-view.coffee',           'app/views/site-view.coffee')

      break;
    }

    // Barebones
    default: {
      path = '../skeletons/barebones';

      this.template(path + '/_bower.json',                      'bower.json');
      this.copy(path + '/Gruntfile.coffee',                     'Gruntfile.coffee');
      this.copy(path + '/app/controllers/_home.coffee',         'app/controllers/home' + this.controllerSuffix + '.coffee')
      this.copy(path + '/app/styles/application.styl',          'app/styles/application.styl')
      this.copy(path + '/app/templates/header.hbs',             'app/templates/header.hbs')
      this.copy(path + '/app/templates/home.hbs',               'app/templates/home.hbs')
      this.copy(path + '/app/templates/site.hbs',               'app/templates/site.hbs')
      this.copy(path + '/app/views/site-view.coffee',           'app/views/site-view.coffee')
      this.copy(path + '/app/views/home/header-view.coffee',    'app/views/home/header-view.coffee')
      this.copy(path + '/app/views/home/home-page-view.coffee', 'app/views/home/home-page-view.coffee')
    }
  }

  var _this = this;

  walk(__dirname + '/templates/app', function(err, files) {
    if (err) throw err;

    files.forEach(function(file) {

      // Ignore .DS_Store files as well as files that start with _.
      if ( file.indexOf('.DS_Store') === -1 && file.indexOf('_') === -1 ) {

        file = file.replace(__dirname + '/templates/', '');

        _this.copy(file, file);
      }
    });

    cb();
  }.bind(this));

}
<commit_msg>Fix binding.<commit_after>'use strict';

var fs     = require('fs'),
    path   = require('path'),
    util   = require('util'),
    walk   = require(__dirname + '/lib/walk'),
    yeoman = require('yeoman-generator')

var ChaplinGenerator = module.exports = function ChaplinGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  this.exists = false;

  this.on('end', function () {
    if(!this.exists) {
      this.installDependencies({ skipInstall: options['skip-install'] });
    }
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(ChaplinGenerator, yeoman.generators.Base);

ChaplinGenerator.prototype.askFor = function askFor() {

  var cb = this.async();

  fs.exists('Gruntfile.coffee', function(exists) {

    if(exists) {
      console.warn("This folder is not empty.")
      this.exists = true;
      return cb();
    }

    else {

      // have Yeoman greet the user.
      console.log(this.yeoman);

      var prompts = [
        {
          name: 'appName',
          message: 'Application name'
        },
        {
          name: 'controllerSuffix',
          message: 'Controller suffix (leave this blank if you dont want one)'
        },
        {
          name: 'skeleton',
          message: " \
          [0] Barebones (minimum to get started)\n \
          [1] HTML 5 Boilerplate\n \
          [2] Twitter Bootstrap\n \
          Please enter the number next to the skeleton you would like\n\n \
          "
        }
      ];

      this.prompt(prompts, function (props) {
        this.appName = props.appName;

        if(typeof props.controllerSuffix == 'string' && props.controllerSuffix.length > 0) {
          this.controllerSuffix = props.controllerSuffix;
        }

        else {
          this.controllerSuffix = '';
        }

        if(typeof props.skeleton == null) {
          this.skeleton = 0;
        }

        else {
          this.skeleton = parseInt(props.skeleton);
        }

        cb();

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

};

ChaplinGenerator.prototype.app = function app() {

  if(this.exists) {
    return;
  }

  var cb = this.async();

  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');

  this.mkdir('app');
  this.mkdir('app/assets');
  this.mkdir('app/assets/fonts');
  this.mkdir('app/assets/img');
  this.mkdir('app/controllers');
  this.mkdir('app/lib');
  this.mkdir('app/models');
  this.mkdir('app/styles');
  this.mkdir('app/templates');
  this.mkdir('app/views');
  this.mkdir('test');

  this.template('_config.json', 'config.json');
  this.template('_package.json', 'package.json');
  this.copy('server.coffee', 'server.coffee');
  this.template('app/_initialize.coffee', 'app/initialize.coffee');

  var path;

  switch(this.skeleton) {

    // HTML5 Boilerplate
    case 1: {
      break;
    }

    // Twitter Bootstrap
    case 2: {
      path = '../skeletons/bootstrap3';

      this.template(path + '/_bower.json',                      'bower.json');
      this.copy(path + '/Gruntfile.coffee',                     'Gruntfile.coffee');
      this.copy(path + '/app/controllers/_home.coffee',         'app/controllers/home' + this.controllerSuffix + '.coffee')
      this.copy(path + '/app/styles/application.styl',          'app/styles/application.styl')
      this.copy(path + '/app/templates/footer.hbs',             'app/templates/footer.hbs')
      this.copy(path + '/app/templates/header.hbs',             'app/templates/header.hbs')
      this.copy(path + '/app/templates/home.hbs',               'app/templates/home.hbs')
      this.copy(path + '/app/templates/jumbotron.hbs',          'app/templates/jumbotron.hbs')
      this.copy(path + '/app/templates/site.hbs',               'app/templates/site.hbs')
      this.copy(path + '/app/views/bootstrap/jumbotron.coffee', 'app/views/bootstrap/jumbotron.coffee')
      this.copy(path + '/app/views/footer.coffee',              'app/views/footer.coffee')
      this.copy(path + '/app/views/header.coffee',              'app/views/header.coffee')
      this.copy(path + '/app/views/home/home-page.coffee',      'app/views/home/home-page.coffee')
      this.copy(path + '/app/views/site-view.coffee',           'app/views/site-view.coffee')

      break;
    }

    // Barebones
    default: {
      path = '../skeletons/barebones';

      this.template(path + '/_bower.json',                      'bower.json');
      this.copy(path + '/Gruntfile.coffee',                     'Gruntfile.coffee');
      this.copy(path + '/app/controllers/_home.coffee',         'app/controllers/home' + this.controllerSuffix + '.coffee')
      this.copy(path + '/app/styles/application.styl',          'app/styles/application.styl')
      this.copy(path + '/app/templates/header.hbs',             'app/templates/header.hbs')
      this.copy(path + '/app/templates/home.hbs',               'app/templates/home.hbs')
      this.copy(path + '/app/templates/site.hbs',               'app/templates/site.hbs')
      this.copy(path + '/app/views/site-view.coffee',           'app/views/site-view.coffee')
      this.copy(path + '/app/views/home/header-view.coffee',    'app/views/home/header-view.coffee')
      this.copy(path + '/app/views/home/home-page-view.coffee', 'app/views/home/home-page-view.coffee')
    }
  }

  var _this = this;

  walk(__dirname + '/templates/app', function(err, files) {
    if (err) throw err;

    files.forEach(function(file) {

      // Ignore .DS_Store files as well as files that start with _.
      if ( file.indexOf('.DS_Store') === -1 && file.indexOf('_') === -1 ) {

        file = file.replace(__dirname + '/templates/', '');

        _this.copy(file, file);
      }
    });

    cb();
  }.bind(this));

}
<|endoftext|>


<commit_before>import React from 'react';
import { render } from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import net from 'net';
import Root from './containers/Root';
import { configureStore, history } from './store/configureStore';
import './app.global.scss';

import { changeCoin } from './helpers/global';

const store = configureStore();
console.log('process.env', process.env);

let isFirstTime = false;

// ======================================================
// Variables
// ======================================================
const DROP_PRODUCT_DELAY_MS = 2000;
const MONEY_BOX_DELAY_MS = 500;
const SERVER_MODE = 4;

/*
  case1: disable 20
  case2: disable 50
  case3: disable 100
  default: disable 500
*/
class Server {
  canReceiveCoin;
  baht1;
  baht5;
  baht10;
  limitBanknote;
  constructor(mode) {
    this.canReceiveCoin = false;
    switch (mode) {
      case 1:
        this.baht1 = 1;
        this.baht5 = 1;
        this.baht10 = 1;
        break;
      case 2:
        this.baht1 = 1;
        this.baht5 = 1;
        this.baht10 = 2;
        break;
      case 3:
        this.baht1 = 5;
        this.baht5 = 5;
        this.baht10 = 5;
        break;
      default:
        this.baht1 = 10;
        this.baht5 = 10;
        this.baht10 = 10;
        break;
    }
    this.limitBanknote = 500;
  }
  getCanReceiveCoin() {
    return this.canReceiveCoin;
  }
  setCanReceiveCoin(canReceiveCoin) {
    this.canReceiveCoin = canReceiveCoin;
  }
  getCoins() {
    return {
      baht1: this.getCoinOneBaht(),
      baht5: this.getCoinFiveBaht(),
      baht10: this.getCoinTenBaht(),
    }
  }
  getCoinOneBaht() {
    return this.baht1;
  }
  getCoinFiveBaht() {
    return this.baht5;
  }
  getCoinTenBaht() {
    return this.baht10;
  }
  addCoinOneBaht(number) {
    this.baht1 += number;
  }
  addCoinFiveBaht(number) {
    this.baht5 += number;
  }
  addCoinTenBaht(number) {
    this.baht10 += number;
  }
  minusCoinOneBaht(number) {
    this.baht1 -= number;
  }
  minusCoinFiveBaht(number) {
    this.baht5 -= number;
  }
  minusCoinTenBaht(number) {
    this.baht10 -= number;
  }
  canChange(changeCoins) {
    const minimumExistingCoin = 3;
    // {baht1: 0, baht5: 1, baht10: 4}
    console.log(this.getCoins());
    if (changeCoins.baht1 > 0 && this.getCoinOneBaht() <= minimumExistingCoin) return false;
    if (changeCoins.baht5 > 0 && this.getCoinFiveBaht() <= minimumExistingCoin) return false;
    if (changeCoins.baht10 > 0 && this.getCoinTenBaht() <= minimumExistingCoin) return false;
    return true;
  }
  getLimitBanknote() {
    return this.limitBanknote;
  }
  setLimitBanknote(banknoteValue) {
    this.limitBanknote = banknoteValue;
  }
  verifyCanReceiveBanknote(banknoteValue) {
    if (banknoteValue >= this.getLimitBanknote()) return false;
    return true;
  }
}

const serverLog = 'background: blue; color: #fff';

if (process.env.NODE_ENV !== 'production') {
  console.log('development:createServer at 127.0.0.1:1337');
  const server = net.createServer(socket => {
    const sv = new Server(SERVER_MODE);
    console.log('%c Init Server:', serverLog, sv);
    setTimeout(() => {
      socket.write(
        JSON.stringify({
          action: 4,
          initialized: 0,
        }),
      );
    }, 500);
    setTimeout(() => {
      socket.write(
        JSON.stringify({
          action: 4,
          initialized: 1,
        }),
      );
    }, 1000);

    // socket.pipe(socket);
    // setInterval(() => {
    //   socket.write(
    //     JSON.stringify({
    //       action: 0,
    //       sensor: 'temp',
    //       msg: {
    //         temp: 4.3,
    //       },
    //     }),
    //   );
    // }, 20000);
    // setInterval(() => {
    //   socket.write(
    //     JSON.stringify({
    //       action: 2,
    //       msg: 50,
    //     }),
    //   );
    // }, 10000);
    socket.on('data', data => {
      // ======================================================
      // Received data from client.write
      // ======================================================
      const dataChunk = data.toString('utf8');
      console.log('%c Server: Received: ', serverLog, dataChunk);
      const objectData = JSON.parse(dataChunk);
      // ======================================================
      // Declare Protocols
      // ======================================================
      // ======================================================
      // DROP PRODUCT
      // ======================================================
      if (objectData.action === 1 && objectData.msg !== 'failed') {
        console.log('%c Server: Drop product', serverLog, data);
        const successPercent = Math.floor(((Math.random() * 10))) + 1;
        console.log('successPercent', successPercent);
        // if (successPercent <= 10 && !isFirstTime) {
        //   isFirstTime = true;
        //   setTimeout(() => {
        //     socket.write(
        //       JSON.stringify({
        //         action: 1,
        //         result: 'success',
        //         description: 'Item XX delivered',
        //       }),
        //     );
        //   }, DROP_PRODUCT_DELAY_MS);
        // } else {
        //   isFirstTime = false;
          setTimeout(() => {
            socket.write(
              JSON.stringify({
                action: 1,
                result: 'fail',
                description: 'Item delivered failed',
              }),
            );
          }, DROP_PRODUCT_DELAY_MS);
        // }
      }
      // ======================================================
      // CASH CHANGE
      // ======================================================
      if (objectData.action === 2 && objectData.mode === 'coin') {
        if (!sv.getCanReceiveCoin()) {
          console.log('%c Server: Cash Change', serverLog, Number(objectData.msg), changeCoin(Number(objectData.msg)));
          const changeCoins = changeCoin(Number(objectData.msg));
          if (sv.canChange(changeCoins)) {
            sv.minusCoinOneBaht(changeCoins.baht1);
            sv.minusCoinFiveBaht(changeCoins.baht5);
            sv.minusCoinTenBaht(changeCoins.baht10);
            socket.write(
              JSON.stringify({
                action: 2,
                result: 'success',
                description: 'cash change completed',
              }),
            );
          } else {
            socket.write(
              JSON.stringify({
                action: 2,
                result: 'fail',
                description: 'cash change failed',
              }),
            );
          }
        } else {
          console.error('Server cannot change cash because Money Box is enable');
        }
      }
      // ======================================================
      // CASH REMAINING
      // ======================================================
      if (objectData.action === 2 && objectData.mode === 'remain') {
        if (!sv.getCanReceiveCoin()) {
          console.log('%c Server: Cash remaining', serverLog, sv);
          socket.write(
            JSON.stringify({
              action: 2,
              result: 'success',
              remain: {
                baht1: sv.getCoinOneBaht(),
                baht5: sv.getCoinFiveBaht(),
                baht10: sv.getCoinTenBaht(),
              },
            }),
          );
        } else {
          console.error('Server cannot show remaining because Money Box is enable');
        }
      }
      // ======================================================
      // RESET TAIKO
      // ======================================================
      if (objectData.action === 2 && objectData.mode === 'bill' && objectData.msg === '01') {
        // reset TAIKO
        socket.write(
          JSON.stringify({
            action: 2,
            msg: '01',
            result: 'success',
            description: 'taiko reset completed'
          }),
        );
      }
      // ======================================================
      // ENABLE MONEY BOX
      // ======================================================
      if (objectData.action === 2 && objectData.mode === 'both' && objectData.msg === '020') {
        // enable money box
        const success = {
          action: 2,
          msg: '020',
          result: 'success',
          description: 'Disable Off.'
        };
        const failed = {
          action: 2,
          msg: '020',
          result: 'failed',
          description: 'failed please try again'
        };
        const isSuccess = _.random(1, 5) <= 5;
        if (isSuccess) sv.setCanReceiveCoin(true);
        setTimeout(() => {
          socket.write(
            JSON.stringify(isSuccess ? success : failed),
          );
        }, MONEY_BOX_DELAY_MS);
      }
      // ======================================================
      // DISABLE MONEY BOX
      // ======================================================
      if (objectData.action === 2 && objectData.mode === 'both' && objectData.msg === '021') {
        // disable money box
        const success = {
          action: 2,
          msg: '021',
          result: 'success',
          description: 'Disable On.'
        };
        const failed = {
          action: 2,
          msg: '021',
          result: 'failed',
          description: 'failed please try again'
        };
        const isSuccess = _.random(1, 5) <= 5;
        if (isSuccess) sv.setCanReceiveCoin(false);
        setTimeout(() => {
          socket.write(
            JSON.stringify(isSuccess ? success : failed),
          );
        }, MONEY_BOX_DELAY_MS);
      }
      if (objectData.action === 2 && objectData.mode === 'limit') {
        const success = {
          action: 2,
          result: 'success',
          description: `Cash is now limit to ${objectData.msg}`
        };
        sv.setLimitBanknote(Number(objectData.msg));
        // const failed = {
        //   action: 2,
        //   msg: '021',
        //   result: 'failed',
        //   description: 'failed please try again'
        // };
        // const isSuccess = true; // _.random(1, 5) <= 4;
        socket.write(
          // JSON.stringify(isSuccess ? success : failed),
          JSON.stringify(success),
        );
      }
      // ======================================================
      // INSERT COIN
      // ======================================================
      if (objectData.action === 999) {
        if (sv.getCanReceiveCoin()) {
          const insertedValue = Number(objectData.msg);
          const canReceiveBanknote = sv.verifyCanReceiveBanknote(insertedValue);
          if (canReceiveBanknote) {
            if (insertedValue === 1) {
              sv.addCoinOneBaht(1);
            } else if (insertedValue === 5) {
              sv.addCoinFiveBaht(1);
            } else if (insertedValue === 10) {
              sv.addCoinTenBaht(1);
            }
            socket.write(
              JSON.stringify({
                action: 2,
                msg: insertedValue,
              }),
            );
          } else {
            // คืนเงิน
            console.log('Cannot receive this banknote', insertedValue);
          }
        } else {
          // MONEY BOX IS DISABLE
          console.log('Cannot receive money because money box is disable');
        }
      }
      // ======================================================
      // QR CODE
      // ======================================================
      if (objectData.action === 998) {
        const scannedValue = objectData.msg;
        socket.write(
          JSON.stringify({
            action: 0,
            sensor: 'qrcode',
            msg: scannedValue,
          }),
        );
      }
    });
    socket.on('error', err => {
      console.error(err);
    });
  });
  // server.listen(8080, '192.168.1.41');
  server.listen(1337, '127.0.0.1');
}
render(
  <AppContainer>
    <Root store={store} history={history} />
  </AppContainer>,
  document.getElementById('root'),
);

if (module.hot) {
  module.hot.accept('./containers/Root', () => {
    const NextRoot = require('./containers/Root'); // eslint-disable-line global-require
    render(
      <AppContainer>
        <NextRoot store={store} history={history} />
      </AppContainer>,
      document.getElementById('root'),
    );
  });
}

export default store;
<commit_msg>Add Door open / Door close server.<commit_after>import React from 'react';
import { render } from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import net from 'net';
import Root from './containers/Root';
import { configureStore, history } from './store/configureStore';
import './app.global.scss';

import { changeCoin } from './helpers/global';

const store = configureStore();
console.log('process.env', process.env);

let isFirstTime = false;

// ======================================================
// Variables
// ======================================================
const DROP_PRODUCT_DELAY_MS = 2000;
const MONEY_BOX_DELAY_MS = 500;
const SERVER_MODE = 4;

/*
  case1: disable 20
  case2: disable 50
  case3: disable 100
  default: disable 500
*/
class Server {
  canReceiveCoin;
  baht1;
  baht5;
  baht10;
  limitBanknote;
  constructor(mode) {
    this.canReceiveCoin = false;
    switch (mode) {
      case 1:
        this.baht1 = 1;
        this.baht5 = 1;
        this.baht10 = 1;
        break;
      case 2:
        this.baht1 = 1;
        this.baht5 = 1;
        this.baht10 = 2;
        break;
      case 3:
        this.baht1 = 5;
        this.baht5 = 5;
        this.baht10 = 5;
        break;
      default:
        this.baht1 = 10;
        this.baht5 = 10;
        this.baht10 = 10;
        break;
    }
    this.limitBanknote = 500;
  }
  getCanReceiveCoin() {
    return this.canReceiveCoin;
  }
  setCanReceiveCoin(canReceiveCoin) {
    this.canReceiveCoin = canReceiveCoin;
  }
  getCoins() {
    return {
      baht1: this.getCoinOneBaht(),
      baht5: this.getCoinFiveBaht(),
      baht10: this.getCoinTenBaht(),
    }
  }
  getCoinOneBaht() {
    return this.baht1;
  }
  getCoinFiveBaht() {
    return this.baht5;
  }
  getCoinTenBaht() {
    return this.baht10;
  }
  addCoinOneBaht(number) {
    this.baht1 += number;
  }
  addCoinFiveBaht(number) {
    this.baht5 += number;
  }
  addCoinTenBaht(number) {
    this.baht10 += number;
  }
  minusCoinOneBaht(number) {
    this.baht1 -= number;
  }
  minusCoinFiveBaht(number) {
    this.baht5 -= number;
  }
  minusCoinTenBaht(number) {
    this.baht10 -= number;
  }
  canChange(changeCoins) {
    const minimumExistingCoin = 3;
    // {baht1: 0, baht5: 1, baht10: 4}
    console.log(this.getCoins());
    if (changeCoins.baht1 > 0 && this.getCoinOneBaht() <= minimumExistingCoin) return false;
    if (changeCoins.baht5 > 0 && this.getCoinFiveBaht() <= minimumExistingCoin) return false;
    if (changeCoins.baht10 > 0 && this.getCoinTenBaht() <= minimumExistingCoin) return false;
    return true;
  }
  getLimitBanknote() {
    return this.limitBanknote;
  }
  setLimitBanknote(banknoteValue) {
    this.limitBanknote = banknoteValue;
  }
  verifyCanReceiveBanknote(banknoteValue) {
    if (banknoteValue >= this.getLimitBanknote()) return false;
    return true;
  }
}

const serverLog = 'background: blue; color: #fff';

if (process.env.NODE_ENV !== 'production') {
  console.log('development:createServer at 127.0.0.1:1337');
  const server = net.createServer(socket => {
    const sv = new Server(SERVER_MODE);
    console.log('%c Init Server:', serverLog, sv);
    setTimeout(() => {
      socket.write(
        JSON.stringify({
          action: 4,
          initialized: 0,
        }),
      );
    }, 500);
    setTimeout(() => {
      socket.write(
        JSON.stringify({
          action: 4,
          initialized: 1,
        }),
      );
    }, 1000);

    // socket.pipe(socket);
    // setInterval(() => {
    //   socket.write(
    //     JSON.stringify({
    //       action: 0,
    //       sensor: 'temp',
    //       msg: {
    //         temp: 4.3,
    //       },
    //     }),
    //   );
    // }, 20000);
    // setInterval(() => {
    //   socket.write(
    //     JSON.stringify({
    //       action: 2,
    //       msg: 50,
    //     }),
    //   );
    // }, 10000);
    socket.on('data', data => {
      // ======================================================
      // Received data from client.write
      // ======================================================
      const dataChunk = data.toString('utf8');
      console.log('%c Server: Received: ', serverLog, dataChunk);
      const objectData = JSON.parse(dataChunk);
      // ======================================================
      // Declare Protocols
      // ======================================================
      // ======================================================
      // DROP PRODUCT
      // ======================================================
      if (objectData.action === 1 && objectData.msg !== 'failed') {
        console.log('%c Server: Drop product', serverLog, data);
        const successPercent = Math.floor(((Math.random() * 10))) + 1;
        console.log('successPercent', successPercent);
        // if (successPercent <= 10 && !isFirstTime) {
        //   isFirstTime = true;
        //   setTimeout(() => {
        //     socket.write(
        //       JSON.stringify({
        //         action: 1,
        //         result: 'success',
        //         description: 'Item XX delivered',
        //       }),
        //     );
        //   }, DROP_PRODUCT_DELAY_MS);
        // } else {
        //   isFirstTime = false;
          setTimeout(() => {
            socket.write(
              JSON.stringify({
                action: 1,
                result: 'fail',
                description: 'Item delivered failed',
              }),
            );
          }, DROP_PRODUCT_DELAY_MS);
        // }
      }
      // ======================================================
      // CASH CHANGE
      // ======================================================
      if (objectData.action === 2 && objectData.mode === 'coin') {
        if (!sv.getCanReceiveCoin()) {
          console.log('%c Server: Cash Change', serverLog, Number(objectData.msg), changeCoin(Number(objectData.msg)));
          const changeCoins = changeCoin(Number(objectData.msg));
          if (sv.canChange(changeCoins)) {
            sv.minusCoinOneBaht(changeCoins.baht1);
            sv.minusCoinFiveBaht(changeCoins.baht5);
            sv.minusCoinTenBaht(changeCoins.baht10);
            socket.write(
              JSON.stringify({
                action: 2,
                result: 'success',
                description: 'cash change completed',
              }),
            );
          } else {
            socket.write(
              JSON.stringify({
                action: 2,
                result: 'fail',
                description: 'cash change failed',
              }),
            );
          }
        } else {
          console.error('Server cannot change cash because Money Box is enable');
        }
      }
      // ======================================================
      // CASH REMAINING
      // ======================================================
      if (objectData.action === 2 && objectData.mode === 'remain') {
        if (!sv.getCanReceiveCoin()) {
          console.log('%c Server: Cash remaining', serverLog, sv);
          socket.write(
            JSON.stringify({
              action: 2,
              result: 'success',
              remain: {
                baht1: sv.getCoinOneBaht(),
                baht5: sv.getCoinFiveBaht(),
                baht10: sv.getCoinTenBaht(),
              },
            }),
          );
        } else {
          console.error('Server cannot show remaining because Money Box is enable');
        }
      }
      // ======================================================
      // RESET TAIKO
      // ======================================================
      if (objectData.action === 2 && objectData.mode === 'bill' && objectData.msg === '01') {
        // reset TAIKO
        socket.write(
          JSON.stringify({
            action: 2,
            msg: '01',
            result: 'success',
            description: 'taiko reset completed'
          }),
        );
      }
      // ======================================================
      // ENABLE MONEY BOX
      // ======================================================
      if (objectData.action === 2 && objectData.mode === 'both' && objectData.msg === '020') {
        // enable money box
        const success = {
          action: 2,
          msg: '020',
          result: 'success',
          description: 'Disable Off.'
        };
        const failed = {
          action: 2,
          msg: '020',
          result: 'failed',
          description: 'failed please try again'
        };
        const isSuccess = _.random(1, 5) <= 5;
        if (isSuccess) sv.setCanReceiveCoin(true);
        setTimeout(() => {
          socket.write(
            JSON.stringify(isSuccess ? success : failed),
          );
        }, MONEY_BOX_DELAY_MS);
      }
      // ======================================================
      // DISABLE MONEY BOX
      // ======================================================
      if (objectData.action === 2 && objectData.mode === 'both' && objectData.msg === '021') {
        // disable money box
        const success = {
          action: 2,
          msg: '021',
          result: 'success',
          description: 'Disable On.'
        };
        const failed = {
          action: 2,
          msg: '021',
          result: 'failed',
          description: 'failed please try again'
        };
        const isSuccess = _.random(1, 5) <= 5;
        if (isSuccess) sv.setCanReceiveCoin(false);
        setTimeout(() => {
          socket.write(
            JSON.stringify(isSuccess ? success : failed),
          );
        }, MONEY_BOX_DELAY_MS);
      }
      if (objectData.action === 2 && objectData.mode === 'limit') {
        const success = {
          action: 2,
          result: 'success',
          description: `Cash is now limit to ${objectData.msg}`
        };
        sv.setLimitBanknote(Number(objectData.msg));
        // const failed = {
        //   action: 2,
        //   msg: '021',
        //   result: 'failed',
        //   description: 'failed please try again'
        // };
        // const isSuccess = true; // _.random(1, 5) <= 4;
        socket.write(
          // JSON.stringify(isSuccess ? success : failed),
          JSON.stringify(success),
        );
      }
      // ======================================================
      // INSERT COIN
      // ======================================================
      if (objectData.action === 999) {
        if (sv.getCanReceiveCoin()) {
          const insertedValue = Number(objectData.msg);
          const canReceiveBanknote = sv.verifyCanReceiveBanknote(insertedValue);
          if (canReceiveBanknote) {
            if (insertedValue === 1) {
              sv.addCoinOneBaht(1);
            } else if (insertedValue === 5) {
              sv.addCoinFiveBaht(1);
            } else if (insertedValue === 10) {
              sv.addCoinTenBaht(1);
            }
            socket.write(
              JSON.stringify({
                action: 2,
                msg: insertedValue,
              }),
            );
          } else {
            // คืนเงิน
            console.log('Cannot receive this banknote', insertedValue);
          }
        } else {
          // MONEY BOX IS DISABLE
          console.log('Cannot receive money because money box is disable');
        }
      }
      // ======================================================
      // QR CODE
      // ======================================================
      if (objectData.action === 998) {
        const scannedValue = objectData.msg;
        socket.write(
          JSON.stringify({
            action: 0,
            sensor: 'qrcode',
            msg: scannedValue,
          }),
        );
      }
      if (objectData.action === 'door-open') {
        socket.write(
          JSON.stringify({
            action: 0,
            sensor: 'door',
            msg: 'open',
          }),
        );
      }
      if (objectData.action === 'door-close') {
        socket.write(
          JSON.stringify({
            action: 0,
            sensor: 'door',
            msg: 'close',
          }),
        );
      }
    });
    socket.on('error', err => {
      console.error(err);
    });
  });
  // server.listen(8080, '192.168.1.41');
  server.listen(1337, '127.0.0.1');
}
render(
  <AppContainer>
    <Root store={store} history={history} />
  </AppContainer>,
  document.getElementById('root'),
);

if (module.hot) {
  module.hot.accept('./containers/Root', () => {
    const NextRoot = require('./containers/Root'); // eslint-disable-line global-require
    render(
      <AppContainer>
        <NextRoot store={store} history={history} />
      </AppContainer>,
      document.getElementById('root'),
    );
  });
}

export default store;
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var mv = require('mv');
var async = require('async');
var mkdirp = require('mkdirp');
var absorb = require('absorb');
var path = require('path');
var util = require('util');
var yeoman = require('yeoman-generator');
var pathInstall = '';

var Generator = module.exports = function Generator(args, options) {
  yeoman.generators.Base.apply(this, arguments);
};

util.inherits(Generator, yeoman.generators.Base);

Generator.prototype.askFor = function askFor(argument) {
    var cb = this.async();
    var options = ['yes', 'no'];
    var prompts = [{
        type: 'list',
        name: 'install',
        message: 'Would you like to install a frontsize theme?',
        choices: options
    },{
        when: function (response) {
            return response.install == 'yes';
        },
        type: 'input',
        name: 'path',
        message: 'Where do you want to install frontsize theme? (Ex: css/frontsize/your_theme_name)',
        defaults: 'css/frontsize'
    }];

    this.prompt(prompts, function (props) {
        this.pathInstall = props.path;
        cb();
    }.bind(this));
};

Generator.prototype.frontsizeFiles = function frontsizeFiles() {
    var here = this;
    async.parallel([
        function(){
            console.info('download');
            here.bowerInstall('frontsize-sass', { save: true });
        }],
        function(error, results) {
            console.info('callback');
            var directory = 'bower_components';
            var pattern = /\/$/;
            if (fs.existsSync('./.bowerrc')) {
                var obj = JSON.parse(fs.readFileSync('./.bowerrc', 'utf8'));
                if(obj.directory !== undefined){
                    directory = obj.directory;
                }
            }
            directory = directory.replace(pattern, '');

            //check if package.json exists in root
            if (fs.existsSync('./package.json')) {
                var dependenciesFrontsize = '';
                var dependenciesRoot = '';

                var packageJsonFrontsize = JSON.parse(fs.readFileSync(directory + '/frontsize-sass/package.json', 'utf8'));
                if(packageJsonFrontsize.dependencies !== undefined){
                    dependenciesFrontsize = packageJsonFrontsize.dependencies;
                }
                var packageJsonRoot = JSON.parse(fs.readFileSync('./package.json', 'utf8'));
                if(packageJsonRoot.dependencies !== undefined){
                    dependenciesRoot = packageJsonRoot.dependencies;
                }

                if(dependenciesRoot != ''){
                    packageJsonRoot.dependencies = absorb(dependenciesRoot, dependenciesFrontsize);
                }
                else{
                    packageJsonRoot.dependencies = dependenciesFrontsize;
                }

                fs.writeFile('./package.json', JSON.stringify(packageJsonRoot, null, 2), function(err) {
                    if(err) {
                        return console.log(err);
                    }
                });
            }
            else{
                fs.createReadStream(directory + '/frontsize-sass/package.json').pipe(fs.createWriteStream('./package.json'));
            }

            //quando inserisco il path devo verificare che non esista e lo creo, se esiste gia la cartella theme al suo interno dare errore
            if(fs.exists(here.pathInstall)){
                return console.log('Path already exist!');
            }
            else{
                //create directory
                mkdirp(here.pathInstall);

                //move files
                mv(directory + '/frontsize-sass/themes/default/', here.pathInstall + '/', {mkdirp: true}, function(err) {
                    return console.log('Error moving files! ' + err);
                });
            }
        }
    );
};
<commit_msg>removed async function to test<commit_after>'use strict';

var fs = require('fs');
var mv = require('mv');
var async = require('async');
var mkdirp = require('mkdirp');
var absorb = require('absorb');
var path = require('path');
var util = require('util');
var yeoman = require('yeoman-generator');
var pathInstall = '';

var Generator = module.exports = function Generator(args, options) {
  yeoman.generators.Base.apply(this, arguments);
};

util.inherits(Generator, yeoman.generators.Base);

Generator.prototype.askFor = function askFor(argument) {
    var cb = this.async();
    var options = ['yes', 'no'];
    var prompts = [{
        type: 'list',
        name: 'install',
        message: 'Would you like to install a frontsize theme?',
        choices: options
    },{
        when: function (response) {
            return response.install == 'yes';
        },
        type: 'input',
        name: 'path',
        message: 'Where do you want to install frontsize theme? (Ex: css/frontsize/your_theme_name)',
        defaults: 'css/frontsize'
    }];

    this.prompt(prompts, function (props) {
        this.pathInstall = props.path;
        cb();
    }.bind(this));
};

Generator.prototype.frontsizeFiles = function frontsizeFiles() {
    var here = this;
    //async.parallel([
        //function(callback){
            console.info('download');
            here.bowerInstall('frontsize-sass', { save: true });
        //    callback(null, 'xyz\n');
        //}],
        //function(error, results) {
            console.info('callback');
            var directory = 'bower_components';
            var pattern = /\/$/;
            if (fs.existsSync('./.bowerrc')) {
                var obj = JSON.parse(fs.readFileSync('./.bowerrc', 'utf8'));
                if(obj.directory !== undefined){
                    directory = obj.directory;
                }
            }
            directory = directory.replace(pattern, '');

            //check if package.json exists in root
            if (fs.existsSync('./package.json')) {
                var dependenciesFrontsize = '';
                var dependenciesRoot = '';

                var packageJsonFrontsize = JSON.parse(fs.readFileSync(directory + '/frontsize-sass/package.json', 'utf8'));
                if(packageJsonFrontsize.dependencies !== undefined){
                    dependenciesFrontsize = packageJsonFrontsize.dependencies;
                }
                var packageJsonRoot = JSON.parse(fs.readFileSync('./package.json', 'utf8'));
                if(packageJsonRoot.dependencies !== undefined){
                    dependenciesRoot = packageJsonRoot.dependencies;
                }

                if(dependenciesRoot != ''){
                    packageJsonRoot.dependencies = absorb(dependenciesRoot, dependenciesFrontsize);
                }
                else{
                    packageJsonRoot.dependencies = dependenciesFrontsize;
                }

                fs.writeFile('./package.json', JSON.stringify(packageJsonRoot, null, 2), function(err) {
                    if(err) {
                        return console.log(err);
                    }
                });
            }
            else{
                fs.createReadStream(directory + '/frontsize-sass/package.json').pipe(fs.createWriteStream('./package.json'));
            }

            //quando inserisco il path devo verificare che non esista e lo creo, se esiste gia la cartella theme al suo interno dare errore
            if(fs.exists(here.pathInstall)){
                return console.log('Path already exist!');
            }
            else{
                //create directory
                mkdirp(here.pathInstall);

                //move files
                mv(directory + '/frontsize-sass/themes/default/', here.pathInstall + '/', {mkdirp: true}, function(err) {
                    return console.log('Error moving files! ' + err);
                });
            }
        //}
    //);
};
<|endoftext|>