<commit_before>var generators = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var _ = require('lodash');
var fs = require('fs');
var del = require('del');
var download = require('download');
var downloadStatus = require('download-status');
var walk = require('walk');
var path = require('path');

module.exports = generators.Base.extend({
  prompting: {
    askToUser: function askToUser() {
      var done = this.async();

      this.log(yosay(
        'Welcome to the kickass ' + chalk.red('wordpress-s-theme') + ' generator!'
      ));

      var prompts = [
				{
          type: 'input',
          name: 'proxyname',
          message: 'Localhost address',
          default: 'localhost'
        },
				{
          type: 'input',
          name: 'domenname',
          message: 'If you want to add a domain site',
          default: ''
        },
        {
          type: 'input',
          name: 'themename',
          message: 'Theme Name',
          default: 'Theme Name'
        },
        {
          type: 'input',
          name: 'themeslug',
          message: 'Theme Slug',
          default: 'Theme Slug'
        },
        {
          type: 'input',
          name: 'themeuri',
          message: 'Theme URI',
          default: 'https://example.com/themeuri/'
        },
        {
          type: 'input',
          name: 'author',
          message: 'Author',
          default: 'Author'
        },
        {
          type: 'input',
          name: 'authoruri',
          message: 'Author URI',
          default: 'https://example.com/authoruri/'
        },
        {
          type: 'input',
          name: 'authoremail',
          message: 'Author Email',
          default: 'info@example.com'
        },
        {
          type: 'input',
          name: 'description',
          message: 'Description',
          default: 'Description'
        },
        {
          type: 'input',
          name: 'bugreport',
          message: 'Bug Report',
          default: 'https://example.com/bugreport/'
        },
        {
          type: 'confirm',
          name: 'gitignore',
          message: 'Would you like to add a ' + chalk.white('.gitignore') + ' file?',
          default: true
        },
        {
          type: 'confirm',
          name: 'editorconfig',
          message: 'Would you like to add a ' + chalk.white('.editorconfig') + ' file?',
          default: true
        },
        {
          type: 'confirm',
          name: 'eslintrc.json',
          message: 'Would you like to add a ' + chalk.white('.eslintrc.json') + ' file?',
          default: true
        },
        {
          type: 'confirm',
          name: 'stylelintrc',
          message: 'Would you like to add a ' + chalk.white('.stylelintrc') + ' file?',
          default: true
        },
        {
          type: 'confirm',
          name: 'gulpfile',
          message: 'Would you like to add a ' + chalk.white('gulpfile.js') + ' file?',
          default: true
        },
        {
          type: 'confirm',
          name: 'npmrc',
          message: 'Would you like to add a ' + chalk.white('.npmrc') + ' file?',
          default: true
        },
        {
          type: 'confirm',
          name: 'npmsetup',
          message: 'Would you like to setup a configuration ready to use?',
          default: true
        }
      ];

      this.prompt(prompts, function (props) {
        this.props = props;
        this.props.prefix = _.snakeCase(this.props.themeslug) + '_';
        this.props.themeslug = _.kebabCase(this.props.themeslug);

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

  writing: {
    installUnderscores: function installUnderscores() {
      var done = this.async();
      var callback = function (error, remote) {
        if (error) {
          done(error);
        }

        done();
      }.bind(this);

      this.log(chalk.yellow('\nLet\'s grab the latest version of Underscores...'));

      new download({mode: '755', extract: true, strip: 1})
        .get('https://github.com/Automattic/_s/archive/master.tar.gz')
        .dest('.')
        .use(downloadStatus())
        .run(callback);
      fs.writeFileSync('sass/theme.scss', '/*!\n Theme Name: _s \n*/', 'utf-8');
      if ( !fs.existsSync('css') ) {
        fs.mkdirSync('css');
      }
      if ( !fs.existsSync('fonts') ) {
        fs.mkdirSync('fonts');
      }
      if ( !fs.existsSync('images') ) {
        fs.mkdirSync('images');
      }
    },

    deleteFiles: function deleteFiles() {
      var done = this.async();
      var dir = this.destinationRoot();

      var unusedFiles = ['.jscsrc', '.jshintignore', '.travis.yml', 'codesniffer.ruleset.xml', 'CONTRIBUTING.md', 'README.md'];

      this.log(chalk.yellow('\nDeleting some unused files...'));

      // Delete unused files
      unusedFiles = _.map(unusedFiles, function(file) {
        return dir + '/' + file;
      });

      del(unusedFiles).catch(function(error) {
        done(error);
      })
      .then(paths => {
        this.log(chalk.cyan(paths.join('\n')));

        done();
      });
    },

    parseThemeFiles: function parseThemeFiles() {
      var done = this.async();
      var _this = this;
      var walker;

      _this.log(chalk.yellow('\nParsing theme files...'));

      walker = walk.walk('.');

      _this.log.write().info('Please wait...');

      walker.on("file", function (root, fileStats, next) {
        var filePath = root + '/' + fileStats.name;

        if (path.extname(fileStats.name) == '.php') {
          fs.readFile(filePath, 'utf8', function (err,data) {
            if (err) {
              done(error);
            }

            var result;

            result = data.replace(/'_s'/g, "'" + _this.props.themeslug + "'");
            result = result.replace(/_s_/g, _this.props.prefix);
            result = result.replace(/ _s/g, ' ' + _this.props.themename);
            result = result.replace(/_s-/g, _this.props.themeslug + '-');

            fs.writeFile(filePath, result, 'utf8', function (err) {
              if (err) {
                done(error);
              }
            });

            next();
          });
        } else if (path.extname(fileStats.name) == '.css' || fileStats.name == 'style.scss' || fileStats.name == 'woocommerce.scss' || fileStats.name == 'theme.scss') {
          fs.readFile(filePath, 'utf8', function (err,data) {
            if (err) {
              done(error);
            }

            var result;

            result = data.replace(/(Theme Name: )(.+)/g, '$1' + _this.props.themename);
            result = result.replace(/(Theme URI: )(.+)/g, '$1' + _this.props.themeuri);
            result = result.replace(/(Author: )(.+)/g, '$1' + _this.props.author);
            result = result.replace(/(Author URI: )(.+)/g, '$1' + _this.props.authoruri);
            result = result.replace(/(Description: )(.+)/g, '$1' + _this.props.description);
            result = result.replace(/(Text Domain: )(.+)/g, '$1' + _this.props.themeslug);
            result = result.replace(/_s is based on Underscores/g, _this.props.themename + ' is based on Underscores');
            result = result.replace(/\@import "variables-site\/variables-site";/g, '\n\n// bower:scss' + '\n\n// endbower' + '\n\n@import "variables-site\/variables-site";');
            result = result.replace(/\@import "media\/media";/g, '@import "media\/media";' + '\n\n/*--------------------------------------------------------------\n\n' + '# Theme\n' + '--------------------------------------------------------------*/\n' + '@import "theme";\n');

            fs.writeFile(filePath, result, 'utf8', function (err) {
              if (err) {
                done(error);
              }
            });

            next();
          });
        } else if (fileStats.name === 'readme.txt') {
          fs.readFile(filePath, 'utf8', function (err,data) {
            if (err) {
              done(error);
            }

            var result;

            result = data.replace(/=== _s ===/g, '=== ' + _this.props.themename + ' ===');
            result = result.replace(/A starter theme called _s, or underscores./g, _this.props.description);
            result = result.replace(/(== Description ==\n\n)(.+)/g, '$1' + 'Long description here');
            result = result.replace(/== Frequently Asked Questions ==[\s\S]*?== Credits ==/g, '== Credits ==');

            fs.writeFile(filePath, result, 'utf8', function (err) {
              if (err) {
                done(error);
              }
            });

            next();
          });
        } else if (fileStats.name === '_s.pot') {
          fs.readFile(filePath, 'utf8', function (err,data) {
            if (err) {
              done(error);
            }

            var result;

            result = data.replace(/Copyright (C) 2016 Automattic/g, 'Copyright (C) 2016 ' + _this.props.author);
            result = result.replace(/Project-Id-Version: _s/g, 'Project-Id-Version: ' + _this.props.themename);
            result = result.replace(/Report-Msgid-Bugs-To: https:\/\/wordpress.org\/tags\/_s/g, 'Report-Msgid-Bugs-To: ' + _this.props.bugreport);
            result = result.replace(/Language-Team: LANGUAGE <LL@li\.org>/g, 'Language-Team: ' + _this.props.author + '<' + _this.props.authoremail + '>');
            result = result.replace(/@ _s/g, '@ ' + _this.props.themeslug);

            fs.writeFile(filePath, result, 'utf8', function (err) {
              if (err) {
                done(error);
              }
            });

            fs.rename(filePath, './languages/' + _this.props.themeslug + '.pot');

            next();
          });
        } else {
          next();
        }
      });

      walker.on("errors", function (root, nodeStatsArray, next) {
        done(error);
        next();
      });

      walker.on("end", function () {
        done();
      });
    },

    packageFiles: function packageFiles() {
      this.log(chalk.yellow('\nCopying configuration files...'));

      if (this.props.gitignore) {
        this.fs.copy(
          this.templatePath('_gitignore'),
          this.destinationPath('.gitignore')
        );
      }

      if (this.props.editorconfig) {
        this.fs.copy(
          this.templatePath('_editorconfig'),
          this.destinationPath('.editorconfig')
        );
      }

      if (this.props.eslintrc.json) {
        this.fs.copy(
          this.templatePath('_eslintrc.json'),
          this.destinationPath('.eslintrc.json')
        );
      }

      if (this.props.stylelintrc) {
        this.fs.copy(
          this.templatePath('_stylelintrc'),
          this.destinationPath('.stylelintrc')
        );
      }

      if (this.props.gulpfile) {
        this.fs.copy(
          this.templatePath('_gulpfile.js'),
          this.destinationPath('.gulpfile.js')
        );
      }

      if (this.props.npmrc) {
        this.fs.copy(
          this.templatePath('_npmrc'),
          this.destinationPath('.npmrc')
        );
      }

      if (this.props.npmsetup) {
        this.fs.copyTpl(
          this.templatePath('_package.json'),
          this.destinationPath('package.json'),
          {
            package_name: this.props.themeslug,
            package_description: this.props.description,
            package_author: this.props.author,
            proxy_address: this.props.proxyname,
            proxy_domain: this.props.domenname,
            theme_domain: this.props.themeslug,
            package_name: this.props.themename,
            theme_bugreport: this.props.bugreport,
            author: this.props.author,
            author_email: this.props.authoremail
          }
        );
      }
    }
  },

  install: {
    installPackages: function installPackages() {
      if (this.props.npmsetup) {
        this.log(chalk.yellow('\nInstalling required packages...'));

        this.npmInstall(['autoprefixer'], { 'saveDev': true, 'global': true });
        this.npmInstall(['browser-sync'], { 'saveDev': true, 'global': true });
        this.npmInstall(['eslint'], { 'saveDev': true, 'global': true });
        this.npmInstall(['eslint-config-standard'], { 'saveDev': true, 'global': true });
        this.npmInstall(['eslint-plugin-promise'], { 'saveDev': true, 'global': true });
        this.npmInstall(['eslint-plugin-standard'], { 'saveDev': true, 'global': true });
        this.npmInstall(['imagemin-cli'], { 'saveDev': true, 'global': true });
        this.npmInstall(['mkdirp'], { 'saveDev': true, 'global': true });
        this.npmInstall(['node-sass'], { 'saveDev': true, 'global': true });
        this.npmInstall(['npm-run-all'], { 'saveDev': true, 'global': true });
        this.npmInstall(['onchange'], { 'saveDev': true, 'global': true });
        this.npmInstall(['postcss-cli'], { 'saveDev': true, 'global': true });
        this.npmInstall(['rimraf'], { 'saveDev': true, 'global': true });
        this.npmInstall(['gulp'], { 'saveDev': true, 'global': true });
        this.npmInstall(['stylelint'], { 'saveDev': true, 'global': true });
        this.npmInstall(['uglify-js'], { 'saveDev': true, 'global': true });
        this.npmInstall(['wp-pot'], { 'saveDev': true, 'global': true });
        this.npmInstall(['wiredep-cli'], { 'saveDev': true, 'global': true });
        this.npmInstall(['bower'], { 'saveDev': true, 'global': true });
      }
    }
  },

  end: {
    endMessage: function endMessage() {
      this.log(chalk.green('\nAll Done!!\n------------------------\n'));

      if (this.props.npmsetup) {
        this.log('\nWarning! \nRun ' + chalk.green('npm link gulp') + ' before start the development');
        this.log('\nRun ' + chalk.green('npm run watch') + ' to start the development and ' + chalk.green('npm run build') + ' to create theme files in ' + chalk.white('dist/' + this.props.themeslug + '.zip') + ' ready for production.');
      }
    }
  },
});
<commit_msg>fix js<commit_after>var generators = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var _ = require('lodash');
var fs = require('fs');
var del = require('del');
var download = require('download');
var downloadStatus = require('download-status');
var walk = require('walk');
var path = require('path');

module.exports = generators.Base.extend({
  prompting: {
    askToUser: function askToUser() {
      var done = this.async();

      this.log(yosay(
        'Welcome to the kickass ' + chalk.red('wordpress-s-theme') + ' generator!'
      ));

      var prompts = [
				{
          type: 'input',
          name: 'proxyname',
          message: 'Localhost address',
          default: 'localhost'
        },
				{
          type: 'input',
          name: 'domenname',
          message: 'If you want to add a domain site',
          default: ''
        },
        {
          type: 'input',
          name: 'themename',
          message: 'Theme Name',
          default: 'Theme Name'
        },
        {
          type: 'input',
          name: 'themeslug',
          message: 'Theme Slug',
          default: 'Theme Slug'
        },
        {
          type: 'input',
          name: 'themeuri',
          message: 'Theme URI',
          default: 'https://example.com/themeuri/'
        },
        {
          type: 'input',
          name: 'author',
          message: 'Author',
          default: 'Author'
        },
        {
          type: 'input',
          name: 'authoruri',
          message: 'Author URI',
          default: 'https://example.com/authoruri/'
        },
        {
          type: 'input',
          name: 'authoremail',
          message: 'Author Email',
          default: 'info@example.com'
        },
        {
          type: 'input',
          name: 'description',
          message: 'Description',
          default: 'Description'
        },
        {
          type: 'input',
          name: 'bugreport',
          message: 'Bug Report',
          default: 'https://example.com/bugreport/'
        },
        {
          type: 'confirm',
          name: 'gitignore',
          message: 'Would you like to add a ' + chalk.white('.gitignore') + ' file?',
          default: true
        },
        {
          type: 'confirm',
          name: 'editorconfig',
          message: 'Would you like to add a ' + chalk.white('.editorconfig') + ' file?',
          default: true
        },
        {
          type: 'confirm',
          name: 'eslintrc.json',
          message: 'Would you like to add a ' + chalk.white('.eslintrc.json') + ' file?',
          default: true
        },
        {
          type: 'confirm',
          name: 'stylelintrc',
          message: 'Would you like to add a ' + chalk.white('.stylelintrc') + ' file?',
          default: true
        },
        {
          type: 'confirm',
          name: 'npmrc',
          message: 'Would you like to add a ' + chalk.white('.npmrc') + ' file?',
          default: true
        },
        {
          type: 'confirm',
          name: 'npmsetup',
          message: 'Would you like to setup a configuration ready to use?',
          default: true
        }
      ];

      this.prompt(prompts, function (props) {
        this.props = props;
        this.props.prefix = _.snakeCase(this.props.themeslug) + '_';
        this.props.themeslug = _.kebabCase(this.props.themeslug);

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

  writing: {
    installUnderscores: function installUnderscores() {
      var done = this.async();
      var callback = function (error, remote) {
        if (error) {
          done(error);
        }

        done();
      }.bind(this);

      this.log(chalk.yellow('\nLet\'s grab the latest version of Underscores...'));

      new download({mode: '755', extract: true, strip: 1})
        .get('https://github.com/Automattic/_s/archive/master.tar.gz')
        .dest('.')
        .use(downloadStatus())
        .run(callback);
      fs.writeFileSync('sass/theme.scss', '/*!\n Theme Name: _s \n*/', 'utf-8');
      if ( !fs.existsSync('css') ) {
        fs.mkdirSync('css');
      }
      if ( !fs.existsSync('fonts') ) {
        fs.mkdirSync('fonts');
      }
      if ( !fs.existsSync('images') ) {
        fs.mkdirSync('images');
      }
    },

    deleteFiles: function deleteFiles() {
      var done = this.async();
      var dir = this.destinationRoot();

      var unusedFiles = ['.jscsrc', '.jshintignore', '.travis.yml', 'codesniffer.ruleset.xml', 'CONTRIBUTING.md', 'README.md'];

      this.log(chalk.yellow('\nDeleting some unused files...'));

      // Delete unused files
      unusedFiles = _.map(unusedFiles, function(file) {
        return dir + '/' + file;
      });

      del(unusedFiles).catch(function(error) {
        done(error);
      })
      .then(paths => {
        this.log(chalk.cyan(paths.join('\n')));

        done();
      });
    },

    parseThemeFiles: function parseThemeFiles() {
      var done = this.async();
      var _this = this;
      var walker;

      _this.log(chalk.yellow('\nParsing theme files...'));

      walker = walk.walk('.');

      _this.log.write().info('Please wait...');

      walker.on("file", function (root, fileStats, next) {
        var filePath = root + '/' + fileStats.name;

        if (path.extname(fileStats.name) == '.php') {
          fs.readFile(filePath, 'utf8', function (err,data) {
            if (err) {
              done(error);
            }

            var result;

            result = data.replace(/'_s'/g, "'" + _this.props.themeslug + "'");
            result = result.replace(/_s_/g, _this.props.prefix);
            result = result.replace(/ _s/g, ' ' + _this.props.themename);
            result = result.replace(/_s-/g, _this.props.themeslug + '-');

            fs.writeFile(filePath, result, 'utf8', function (err) {
              if (err) {
                done(error);
              }
            });

            next();
          });
        } else if (path.extname(fileStats.name) == '.css' || fileStats.name == 'style.scss' || fileStats.name == 'woocommerce.scss' || fileStats.name == 'theme.scss') {
          fs.readFile(filePath, 'utf8', function (err,data) {
            if (err) {
              done(error);
            }

            var result;

            result = data.replace(/(Theme Name: )(.+)/g, '$1' + _this.props.themename);
            result = result.replace(/(Theme URI: )(.+)/g, '$1' + _this.props.themeuri);
            result = result.replace(/(Author: )(.+)/g, '$1' + _this.props.author);
            result = result.replace(/(Author URI: )(.+)/g, '$1' + _this.props.authoruri);
            result = result.replace(/(Description: )(.+)/g, '$1' + _this.props.description);
            result = result.replace(/(Text Domain: )(.+)/g, '$1' + _this.props.themeslug);
            result = result.replace(/_s is based on Underscores/g, _this.props.themename + ' is based on Underscores');
            result = result.replace(/\@import "variables-site\/variables-site";/g, '\n\n// bower:scss' + '\n\n// endbower' + '\n\n@import "variables-site\/variables-site";');
            result = result.replace(/\@import "media\/media";/g, '@import "media\/media";' + '\n\n/*--------------------------------------------------------------\n\n' + '# Theme\n' + '--------------------------------------------------------------*/\n' + '@import "theme";\n');

            fs.writeFile(filePath, result, 'utf8', function (err) {
              if (err) {
                done(error);
              }
            });

            next();
          });
        } else if (fileStats.name === 'readme.txt') {
          fs.readFile(filePath, 'utf8', function (err,data) {
            if (err) {
              done(error);
            }

            var result;

            result = data.replace(/=== _s ===/g, '=== ' + _this.props.themename + ' ===');
            result = result.replace(/A starter theme called _s, or underscores./g, _this.props.description);
            result = result.replace(/(== Description ==\n\n)(.+)/g, '$1' + 'Long description here');
            result = result.replace(/== Frequently Asked Questions ==[\s\S]*?== Credits ==/g, '== Credits ==');

            fs.writeFile(filePath, result, 'utf8', function (err) {
              if (err) {
                done(error);
              }
            });

            next();
          });
        } else if (fileStats.name === '_s.pot') {
          fs.readFile(filePath, 'utf8', function (err,data) {
            if (err) {
              done(error);
            }

            var result;

            result = data.replace(/Copyright (C) 2016 Automattic/g, 'Copyright (C) 2016 ' + _this.props.author);
            result = result.replace(/Project-Id-Version: _s/g, 'Project-Id-Version: ' + _this.props.themename);
            result = result.replace(/Report-Msgid-Bugs-To: https:\/\/wordpress.org\/tags\/_s/g, 'Report-Msgid-Bugs-To: ' + _this.props.bugreport);
            result = result.replace(/Language-Team: LANGUAGE <LL@li\.org>/g, 'Language-Team: ' + _this.props.author + '<' + _this.props.authoremail + '>');
            result = result.replace(/@ _s/g, '@ ' + _this.props.themeslug);

            fs.writeFile(filePath, result, 'utf8', function (err) {
              if (err) {
                done(error);
              }
            });

            fs.rename(filePath, './languages/' + _this.props.themeslug + '.pot');

            next();
          });
        } else {
          next();
        }
      });

      walker.on("errors", function (root, nodeStatsArray, next) {
        done(error);
        next();
      });

      walker.on("end", function () {
        done();
      });
    },

    packageFiles: function packageFiles() {
      this.log(chalk.yellow('\nCopying configuration files...'));

      if (this.props.gitignore) {
        this.fs.copy(
          this.templatePath('_gitignore'),
          this.destinationPath('.gitignore')
        );
      }

      if (this.props.editorconfig) {
        this.fs.copy(
          this.templatePath('_editorconfig'),
          this.destinationPath('.editorconfig')
        );
      }

      if (this.props.eslintrc.json) {
        this.fs.copy(
          this.templatePath('_eslintrc.json'),
          this.destinationPath('.eslintrc.json')
        );
      }

      if (this.props.stylelintrc) {
        this.fs.copy(
          this.templatePath('_stylelintrc'),
          this.destinationPath('.stylelintrc')
        );
      }

      if (this.props.npmrc) {
        this.fs.copy(
          this.templatePath('_npmrc'),
          this.destinationPath('.npmrc')
        );
      }

      if (this.props.npmsetup) {
        this.fs.copyTpl(
          this.templatePath('_package.json'),
          this.destinationPath('package.json'),
          {
            package_name: this.props.themeslug,
            package_description: this.props.description,
            package_author: this.props.author,
            proxy_address: this.props.proxyname,
            proxy_domain: this.props.domenname,
            theme_domain: this.props.themeslug,
            package_name: this.props.themename,
            theme_bugreport: this.props.bugreport,
            author: this.props.author,
            author_email: this.props.authoremail
          }
        );
      }
    }
  },

  install: {
    installPackages: function installPackages() {
      if (this.props.npmsetup) {
        this.log(chalk.yellow('\nInstalling required packages...'));

        this.npmInstall(['autoprefixer'], { 'saveDev': true, 'global': true });
        this.npmInstall(['browser-sync'], { 'saveDev': true, 'global': true });
        this.npmInstall(['eslint'], { 'saveDev': true, 'global': true });
        this.npmInstall(['eslint-config-standard'], { 'saveDev': true, 'global': true });
        this.npmInstall(['eslint-plugin-promise'], { 'saveDev': true, 'global': true });
        this.npmInstall(['eslint-plugin-standard'], { 'saveDev': true, 'global': true });
        this.npmInstall(['imagemin-cli'], { 'saveDev': true, 'global': true });
        this.npmInstall(['mkdirp'], { 'saveDev': true, 'global': true });
        this.npmInstall(['node-sass'], { 'saveDev': true, 'global': true });
        this.npmInstall(['npm-run-all'], { 'saveDev': true, 'global': true });
        this.npmInstall(['onchange'], { 'saveDev': true, 'global': true });
        this.npmInstall(['postcss-cli'], { 'saveDev': true, 'global': true });
        this.npmInstall(['rimraf'], { 'saveDev': true, 'global': true });
        this.npmInstall(['gulp'], { 'saveDev': true, 'global': true });
        this.npmInstall(['stylelint'], { 'saveDev': true, 'global': true });
        this.npmInstall(['uglify-js'], { 'saveDev': true, 'global': true });
        this.npmInstall(['wp-pot'], { 'saveDev': true, 'global': true });
        this.npmInstall(['wiredep-cli'], { 'saveDev': true, 'global': true });
        this.npmInstall(['bower'], { 'saveDev': true, 'global': true });
      }
    }
  },

  end: {
    endMessage: function endMessage() {
      this.log(chalk.green('\nAll Done!!\n------------------------\n'));

      if (this.props.npmsetup) {
        this.log('\nWarning! \nRun ' + chalk.green('npm link gulp') + ' before start the development');
        this.log('\nRun ' + chalk.green('npm run watch') + ' to start the development and ' + chalk.green('npm run build') + ' to create theme files in ' + chalk.white('dist/' + this.props.themeslug + '.zip') + ' ready for production.');
      }
    }
  },
});
<|endoftext|>


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

var foldername = path.basename(process.cwd());

var DjangoGenerator = module.exports = function DjangoGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);
  // have Yeoman greet the user.
  this.log(this.yeoman);

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

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

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

// Checks whether we are in a virtual environemnt and warns user if not
DjangoGenerator.prototype.checkVirtualenv = function checkVirtualenv() {
    var done = this.async();
    var command = 'python -c "import sys; print hasattr(sys, \'real_prefix\')"';
    childProcess.exec(command, function(err, out){
        // TODO That's a rather dirty string check
        if(out === 'False\n') {
            this.log(chalk.bold.yellow('WARNING - You are not in a virtual environment, it strongly advised that you activate a virtual environment before continuing'));
        }
        done();
    }.bind(this));
};

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

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

  var prompts = [{
    name: 'siteName',
    message: 'Whats the name of the website?',
    default: foldername
  }, {
    name: 'author',
    message: 'Who is the creator?',
    default: 'dummy'
  }, {
    name: 'projectRepo',
    message: 'Whats the repo clone URL?'
  }];

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

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

DjangoGenerator.prototype.app = function app() {
  // Apps folder.
  this.mkdir('apps');

  // Settings folder.
  this.mkdir('settings');

  // Requirements folder.
  this.mkdir('requirements');

  // Libs and bins folder.
  this.mkdir('bin');
  this.mkdir('libs');

  // Templates folder.
  this.mkdir('templates');
  this.mkdir('templates/layout');

  // Static files folder.
  this.mkdir('static');
  this.mkdir('static/js');
  this.mkdir('static/css');
  this.mkdir('static/img');
  this.mkdir('static/vendor');
};

DjangoGenerator.prototype.git = function git() {
  this.template('_gitignore', '.gitignore');
};

DjangoGenerator.prototype.bower = function bower() {
  this.copy('bowerrc', '.bowerrc');
  this.template('_bower.json', 'bower.json');
};

DjangoGenerator.prototype.bin = function bin() {
  this.copy('bin/watchmedo.sh', 'bin/watchmedo.sh');
};

DjangoGenerator.prototype.requirements = function requirements() {
  this.copy('requirements/common', 'requirements/COMMON');
  this.copy('requirements/testing', 'requirements/TESTING');
  this.copy('requirements/development', 'requirements/DEVELOPMENT');
  this.copy('requirements/production', 'requirements/PRODUCTION');
};

DjangoGenerator.prototype.settings = function settings() {
  this.copy('init.py', 'settings/.gitignore');
  this.copy('init.py', 'settings/__init__.py');
  this.template('settings/_common.py', 'settings/common.py');
  this.template('settings/_testing.py', 'settings/testing.py');
  this.template('settings/_development.py', 'settings/development.py');
};

DjangoGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');
  this.template('_readme.md', 'README.md');
  this.copy('urls.py', 'urls.py');
  this.copy('_wsgi.py', 'wsgi.py');
  this.copy('manage.py', 'manage.py');
  this.copy('init.py', '__init__.py');
  this.template('_fabfile.py', 'fabfile.py');
  this.template('_package.json', 'package.json');
};
<commit_msg>Move the yeoman greeting to initialize and use yeoman.log instead of console.log (as per suggestion in doc)<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var childProcess = require('child_process');
var chalk = require('chalk');

var foldername = path.basename(process.cwd());

var DjangoGenerator = module.exports = function DjangoGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);
  // have Yeoman greet the user.
  this.log(this.yeoman);

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

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

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

// Checks whether we are in a virtual environemnt and warns user if not
DjangoGenerator.prototype.checkVirtualenv = function checkVirtualenv() {
    var done = this.async();
    var command = 'python -c "import sys; print hasattr(sys, \'real_prefix\')"';
    childProcess.exec(command, function(err, out){
        // TODO That's a rather dirty string check
        if(out === 'False\n') {
            this.log(chalk.bold.yellow('WARNING - You are not in a virtual environment, it strongly advised that you activate a virtual environment before continuing'));
        }
        done();
    }.bind(this));
};

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

  var prompts = [{
    name: 'siteName',
    message: 'Whats the name of the website?',
    default: foldername
  }, {
    name: 'author',
    message: 'Who is the creator?',
    default: 'dummy'
  }, {
    name: 'projectRepo',
    message: 'Whats the repo clone URL?'
  }];

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

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

DjangoGenerator.prototype.app = function app() {
  // Apps folder.
  this.mkdir('apps');

  // Settings folder.
  this.mkdir('settings');

  // Requirements folder.
  this.mkdir('requirements');

  // Libs and bins folder.
  this.mkdir('bin');
  this.mkdir('libs');

  // Templates folder.
  this.mkdir('templates');
  this.mkdir('templates/layout');

  // Static files folder.
  this.mkdir('static');
  this.mkdir('static/js');
  this.mkdir('static/css');
  this.mkdir('static/img');
  this.mkdir('static/vendor');
};

DjangoGenerator.prototype.git = function git() {
  this.template('_gitignore', '.gitignore');
};

DjangoGenerator.prototype.bower = function bower() {
  this.copy('bowerrc', '.bowerrc');
  this.template('_bower.json', 'bower.json');
};

DjangoGenerator.prototype.bin = function bin() {
  this.copy('bin/watchmedo.sh', 'bin/watchmedo.sh');
};

DjangoGenerator.prototype.requirements = function requirements() {
  this.copy('requirements/common', 'requirements/COMMON');
  this.copy('requirements/testing', 'requirements/TESTING');
  this.copy('requirements/development', 'requirements/DEVELOPMENT');
  this.copy('requirements/production', 'requirements/PRODUCTION');
};

DjangoGenerator.prototype.settings = function settings() {
  this.copy('init.py', 'settings/.gitignore');
  this.copy('init.py', 'settings/__init__.py');
  this.template('settings/_common.py', 'settings/common.py');
  this.template('settings/_testing.py', 'settings/testing.py');
  this.template('settings/_development.py', 'settings/development.py');
};

DjangoGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');
  this.template('_readme.md', 'README.md');
  this.copy('urls.py', 'urls.py');
  this.copy('_wsgi.py', 'wsgi.py');
  this.copy('manage.py', 'manage.py');
  this.copy('init.py', '__init__.py');
  this.template('_fabfile.py', 'fabfile.py');
  this.template('_package.json', 'package.json');
};
<|endoftext|>


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

var PhpstylGenerator = yeoman.generators.Base.extend({
  init: function () {
    this.pkg = require('../package.json');

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

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

    // Have Yeoman greet the user.
    this.log(yosay('Welcome to the marvelous Phpstyl generator!'));

    var prompts = [{
      name: 'title',
      message: 'What is the title of your application?',
      default: 'Hello-World'
    }];

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

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

  app: function () {
    this.mkdir('src');
    this.mkdir('src/scripts');
    this.mkdir('src/styles');

    this.template('src/index.php', 'src/index.php');
    this.template('src/scripts/main.js', 'src/scripts/main.js');
    this.template('src/styles/main.styl', 'src/styles/main.styl');
    this.copy('_package.json', 'package.json');
    this.copy('_bower.json', 'bower.json');
    this.copy('editorconfig', '.editorconfig');
    this.copy('gitignore', '.gitignore');
    this.copy('bowerrc', '.bowerrc');
    this.copy('jshintrc', '.jshintrc');
    this.template('Gruntfile.js', 'Gruntfile.js');
    this.template('README.md', 'README.md');
  },

  projectfiles: function () {
  }
});

module.exports = PhpstylGenerator;
<commit_msg>Update index.js<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var chalk = require('chalk');

var PhpstylGenerator = yeoman.generators.Base.extend({
  init: function () {
    this.pkg = require('../package.json');

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

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

    // Have Yeoman greet the user.
    this.log(yosay('Welcome to the marvelous Phpstyl generator!'));

    var prompts = [{
      name: 'title',
      message: 'What is the title of your application?',
      default: 'Hello World'
    }];

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

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

   var extractGeneratorName = function (_, appname) {
    var slugged = _.slugify(title);
    var match = slugged.match(/^$/);

    if (match && match.length === 2) {
      return match[1].toLowerCase();
  }

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

  app: function () {
    this.mkdir('src');
    this.mkdir('src/scripts');
    this.mkdir('src/styles');

    this.template('src/index.php', 'src/index.php');
    this.template('src/scripts/main.js', 'src/scripts/main.js');
    this.template('src/styles/main.styl', 'src/styles/main.styl');
    this.copy('_package.json', 'package.json');
    this.copy('_bower.json', 'bower.json');
    this.copy('editorconfig', '.editorconfig');
    this.copy('gitignore', '.gitignore');
    this.copy('bowerrc', '.bowerrc');
    this.copy('jshintrc', '.jshintrc');
    this.template('Gruntfile.js', 'Gruntfile.js');
    this.template('README.md', 'README.md');
  },

  projectfiles: function () {
  }
});

module.exports = PhpstylGenerator;
<|endoftext|>


<commit_before>const camelCase = require('lodash.camelcase');
const chalk = require('chalk');
const Generator = require('yeoman-generator');
const hasbin = require('hasbin');
const kebabCase = require('lodash.kebabcase');
const shell = require('shelljs');

module.exports = class extends Generator {
  prompting() {
    this.log();

    return this.prompt([
      {
        name: 'moduleName',
        message: 'Module name:',
        default: this.appname.replace(/\s/g, '-'),
      },
      {
        name: 'description',
        message: 'Description:',
        default: 'as cute as bunny',
        store: true,
      },
      {
        name: 'global',
        message: 'Let user install as global:',
        type: 'confirm',
        default: false,
      },
      {
        name: 'name',
        message: "Author's name:",
        default: this.user.git.name(),
        store: true,
      },
      {
        name: 'email',
        message: "Author's email:",
        default: this.user.git.email(),
        store: true,
      },
      {
        name: 'githubUsername',
        message: 'GitHub username:',
        store: true,
      },
      {
        name: 'website',
        message: 'Website:',
        store: true,
      },
    ]).then((props) => {
      this.log();

      this.tpl = {
        moduleName: kebabCase(props.moduleName).toLowerCase(),
        camelModule: camelCase(props.moduleName),
        description: props.description,
        global: props.global,
        name: props.name,
        email: props.email,
        githubUsername: props.githubUsername,
        website: props.website,
        hasYarn: hasbin.sync('yarn'),
      };

      this.spawnCommand('git', ['init', '--quiet']);
    });
  }
  writing() {
    const mv = (from, to) => {
      this.fs.move(this.destinationPath(from), this.destinationPath(to));
    };

    this.fs.copyTpl(
      [`${this.templatePath()}/**`],
      this.destinationPath(),
      this.tpl
    );

    mv('_all-contributorsrc', '.all-contributorsrc');
    mv('_babelrc', '.babelrc');
    mv('_editorconfig', '.editorconfig');
    mv('_eslintignore', '.eslintignore');
    mv('_eslintrc.json', '.eslintrc.json');
    mv('_flowconfig', '.flowconfig');
    mv('_gitattributes', '.gitattributes');
    mv('_github/issue_template.md', '.github/issue_template.md');
    mv(
      '_github/pull_request_template.md',
      '.github/pull_request_template.md'
    );
    mv('_gitignore', '.gitignore');
    mv('_npmrc', '.npmrc');
    mv('_package.json', 'package.json');
    mv('_travis.yml', '.travis.yml');
    mv('src/index._test_.js', 'src/index.test.js');
  }
  install() {
    this.log('\x1Bc');
    this.log();
    this.log(
      chalk.green('Important files have been generated to your directory')
    );

    this.log();
    this.log('Installing dependencies...');
    this.log('This might take a couple minutes');
    this.log();

    this.installDependencies({
      skipMessage: true,
      bower: false,
      yarn: this.tpl.hasYarn,
      npm: !this.tpl.hasYarn,
    });
  }
  end() {
    this.log();
    this.log(`Installing ${chalk.cyan('libdefs...')}`);
    this.log();
    shell.exec('npm start flow.typed', { silent: true });

    this.log(chalk.cyan(`Thanks for using generator-bunny, ${this.tpl.name}!`));
    this.log();

    shell.rm('.yo-rc.json');
    shell.exec('git add -A', { silent: true });
    shell.exec('git commit -qnm "feat(package): initial commit"', {
      silent: true,
    });
  }
};
<commit_msg>fix(git): initial commit type should be `chore`<commit_after>const camelCase = require('lodash.camelcase');
const chalk = require('chalk');
const Generator = require('yeoman-generator');
const hasbin = require('hasbin');
const kebabCase = require('lodash.kebabcase');
const shell = require('shelljs');

module.exports = class extends Generator {
  prompting() {
    this.log();

    return this.prompt([
      {
        name: 'moduleName',
        message: 'Module name:',
        default: this.appname.replace(/\s/g, '-'),
      },
      {
        name: 'description',
        message: 'Description:',
        default: 'as cute as bunny',
        store: true,
      },
      {
        name: 'global',
        message: 'Let user install as global:',
        type: 'confirm',
        default: false,
      },
      {
        name: 'name',
        message: "Author's name:",
        default: this.user.git.name(),
        store: true,
      },
      {
        name: 'email',
        message: "Author's email:",
        default: this.user.git.email(),
        store: true,
      },
      {
        name: 'githubUsername',
        message: 'GitHub username:',
        store: true,
      },
      {
        name: 'website',
        message: 'Website:',
        store: true,
      },
    ]).then((props) => {
      this.log();

      this.tpl = {
        moduleName: kebabCase(props.moduleName).toLowerCase(),
        camelModule: camelCase(props.moduleName),
        description: props.description,
        global: props.global,
        name: props.name,
        email: props.email,
        githubUsername: props.githubUsername,
        website: props.website,
        hasYarn: hasbin.sync('yarn'),
      };

      this.spawnCommand('git', ['init', '--quiet']);
    });
  }
  writing() {
    const mv = (from, to) => {
      this.fs.move(this.destinationPath(from), this.destinationPath(to));
    };

    this.fs.copyTpl(
      [`${this.templatePath()}/**`],
      this.destinationPath(),
      this.tpl
    );

    mv('_all-contributorsrc', '.all-contributorsrc');
    mv('_babelrc', '.babelrc');
    mv('_editorconfig', '.editorconfig');
    mv('_eslintignore', '.eslintignore');
    mv('_eslintrc.json', '.eslintrc.json');
    mv('_flowconfig', '.flowconfig');
    mv('_gitattributes', '.gitattributes');
    mv('_github/issue_template.md', '.github/issue_template.md');
    mv(
      '_github/pull_request_template.md',
      '.github/pull_request_template.md'
    );
    mv('_gitignore', '.gitignore');
    mv('_npmrc', '.npmrc');
    mv('_package.json', 'package.json');
    mv('_travis.yml', '.travis.yml');
    mv('src/index._test_.js', 'src/index.test.js');
  }
  install() {
    this.log('\x1Bc');
    this.log();
    this.log(
      chalk.green('Important files have been generated to your directory')
    );

    this.log();
    this.log('Installing dependencies...');
    this.log('This might take a couple minutes');
    this.log();

    this.installDependencies({
      skipMessage: true,
      bower: false,
      yarn: this.tpl.hasYarn,
      npm: !this.tpl.hasYarn,
    });
  }
  end() {
    this.log();
    this.log(`Installing ${chalk.cyan('libdefs...')}`);
    this.log();
    shell.exec('npm start flow.typed', { silent: true });

    this.log(chalk.cyan(`Thanks for using generator-bunny, ${this.tpl.name}!`));
    this.log();

    shell.rm('.yo-rc.json');
    shell.exec('git add -A', { silent: true });
    shell.exec('git commit -qnm "chore: initial commit"', {
      silent: true,
    });
  }
};
<|endoftext|>


<commit_before>import '../app/style.css';

import angular from 'angular';
import 'angular-sanitize';
import 'lodash';
import 'angular-simple-logger';
import 'angular-google-maps';
import {app} from '../app/app'
import {pharmacyOnDuty} from '../app/ViewDistrict'

  let MainController = function( pharmacyOnDuty, $http, uiGmapGoogleMapApi, $log) {
    let self = this;

    self.map = {
      center: { latitude: 41.1, longitude:29 },
      zoom: 12,
    };
    let createMarker = function(info) {
      let marker = {
       id: info.id,
       coords: {
         latitude: info.coordinates[0],
         longitude: info.coordinates[1]
       },
       options: {
         title: info.name,
         labelContent: info.id,
         labelAnchor: "0 53",
         labelClass: "marker-labels"
       }
     };
     self.map.markers.push(marker);
    }

    let isUpToDate = function(date) {
      if (date == self.todaysDate) {
        return true;
      }
      return false
    }

    let addMarkers = function() {
      self.map.markers = [];
      for (let i in self.pharmacies) {
        self.pharmacies[i].id = parseInt(i) +1;
        createMarker(self.pharmacies[i])
      }
      self.map.center.latitude = self.pharmacies[0].coordinates[0]
      self.map.center.longitude = self.pharmacies[0].coordinates[1]
    }

    let onComplete = function(data){
      self.dataDate = data.date;
      self.district = data.name;
      self.slug = data.slug;
      self.pharmacies = data.pharmacies;
      self.error = null;
      addMarkers();
    }

    let onError = function(reason){
      self.error = "*Böyle bir semt yok."
    }

    self.search = function(district) {
      pharmacyOnDuty.getPharmacies(district)
                    .then(onComplete, onError)
      $log.info("searching for " + district)

  };

  self.todaysDate = new Date();
  self.slug = "kartal"
};

    app.controller("MainController", MainController )
<commit_msg>error message fixed<commit_after>import '../app/style.css';

import angular from 'angular';
import 'angular-sanitize';
import 'lodash';
import 'angular-simple-logger';
import 'angular-google-maps';
import {app} from '../app/app'
import {pharmacyOnDuty} from '../app/ViewDistrict'

  let MainController = function( pharmacyOnDuty, $http, uiGmapGoogleMapApi, $log) {
    let self = this;

    self.map = {
      center: { latitude: 41.1, longitude:29 },
      zoom: 12,
    };
    let createMarker = function(info) {
      let marker = {
       id: info.id,
       coords: {
         latitude: info.coordinates[0],
         longitude: info.coordinates[1]
       },
       options: {
         title: info.name,
         labelContent: info.id,
         labelAnchor: "0 53",
         labelClass: "marker-labels"
       }
     };
     self.map.markers.push(marker);
    }

    let isUpToDate = function(date) {
      if (date == self.todaysDate) {
        return true;
      }
      return false
    }

    let addMarkers = function() {
      self.map.markers = [];
      for (let i in self.pharmacies) {
        self.pharmacies[i].id = parseInt(i) +1;
        createMarker(self.pharmacies[i])
      }
      self.map.center.latitude = self.pharmacies[0].coordinates[0]
      self.map.center.longitude = self.pharmacies[0].coordinates[1]
    }

    let onComplete = function(data){
      self.dataDate = data.date;
      self.district = data.name;
      self.slug = data.slug;
      self.pharmacies = data.pharmacies;
      self.error = null;
      addMarkers();
    }

    let onError = function(reason){
      self.error = "*Böyle bir ilçe yok."
    }

    self.search = function(district) {
      pharmacyOnDuty.getPharmacies(district)
                    .then(onComplete, onError)
      $log.info("searching for " + district)

  };

  self.todaysDate = new Date();
  self.slug = "kartal"
};

    app.controller("MainController", MainController )
<|endoftext|>


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

var sdkVersions = [
    'API level 1: Android 1.0',
    'API level 2: Android 1.1',
    'API level 3: Android 1.5, NDK 1  (Cupcake)',
    'API level 4: Android 1.6, NDK 2  (Donut)',
    'API level 5: Android 2.0 (Eclair)',
    'API level 6: Android 2.0.1 (Eclair)',
    'API level 7: Android 2.1, NDK 3  (Eclair)',
    'API level 8: Android 2.2.x, NDK 4  (Froyo)',
    'API level 9: Android 2.3 - 2.3.2, NDK 5 (Gingerbread)',
    'API level 10: Android 2.3.3 - 2.3.7: (Gingerbread)',
    'API level 11: Android 3.0: (Honeycomb)',
    'API level 12: Android 3.1, NDK 6 (Honeycomb)',
    'API level 13: Android 3.2.x (Honeycomb)',
    'API level 14: Android 4.0.1 - 4.0.2, NDK 7 (Ice Cream Sandwich)',
    'API level 15: Android 4.0.3 - 4.0.4, NDK 8 (Ice Cream Sandwich)',
    'API level 16: Android 4.1.x (Jelly Bean)',
    'API level 17: Android 4.2.x (Jelly Bean)',
    'API level 18: Android 4.3.x (Jelly Bean)',
    'API level 19: Android 4.4 - 4.4.2 (KitKat)'
  ].map(function(name, value) {
    return {name: name, value: value};
});

var AndroidGradleGenerator = yeoman.generators.Base.extend({
  init: function () {
    this.pkg = require('../package.json');

    this.on('end', function () {
      this.log("\n");
      this.log("Finished creating your " + chalk.red.bold(this.appName) + " Android+Gradle application.");
      this.log("Please update the " + chalk.yellow.bold('local.properties') + " with the Android SDK path");
      this.log("\nOpen your favorite IDE and have fun building your next great app.");
      this.log("\n");
    });
  },

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

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

    // replace it with a short and sweet description of your generator
    this.log(chalk.magenta('This generator will allow you to create a minimal Android project with Gradle support.'));

    var prompts = [
    {
      name: 'appName',
      message: 'What is the name of your Android application?',
      default: 'Hello World'
    },
    {
      name: 'packageName',
      message: 'What is the package name?',
      default: 'com.example.mobile.app'
    },
    {
      name: 'minApiLevel',
      message: 'Minimum required Android SDK:',
      type: 'list',
      choices: sdkVersions,
      default: 18
    }
    ];

    this.prompt(prompts, function (props) {
      this.appName = props.appName;
      this.packageName = props.packageName;
      this.packageFolder = this.packageName.replace(/\./g, '/');
      this.minApiLevel = props.minApiLevel;
      this.minAndroidSDK = (this.minApiLevel + 1);
      this.className = this._.classify(this._.slugify(this._.humanize(props.appName.replace(/ /g, ''))));
      this.projectName = this._.camelize(this.className);

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

  app: function () {
    var _appDir = [
      'AndroidApp',
      'AndroidApp/assets',
      'AndroidApp/bin',
      'AndroidApp/gen',
      'AndroidApp/src',
      'AndroidApp/tests',
      'AndroidApp/tests/res',
      'AndroidApp/tests/src',
    ];

    this.log('\n' + chalk.green('Creating ') + 'project directories:');
    var _appDirLength = _appDir.length;

    for(var idx = 0; idx < _appDirLength; idx++) {
      this.mkdir(_appDir[idx]);
      this.log('\t' + chalk.green('create ') + _appDir[idx]);
    }

    this.log('\n' + chalk.green('Creating ') + 'android resources:');
    this.directory('res', 'AndroidApp/res');

    this.log('\n' + chalk.green('Creating ') + 'android libs:');
    this.directory('libs', 'AndroidApp/libs');

    this.log('\n' + chalk.green('Creating ') + 'android configurations:');
    this.template('config/android/_AndroidManifest.xml', 'AndroidApp/AndroidManifest.xml');
    this.template('config/android/_build.gradle', 'AndroidApp/build.gradle');
    this.template('config/android/_proguard-project.txt', 'AndroidApp/proguard-project.txt');
    this.template('config/android/_project.properties', 'AndroidApp/project.properties');
  }
});

module.exports = AndroidGradleGenerator;

/*
 * Method copies the project configration files from the template/config/project
 * directory to the project's root directory.
 */
AndroidGradleGenerator.prototype.projectConfigFiles = function projectConfigFiles() {
  var _configs = [
    'editorconfig',
    'jshintrc',
    'gitignore',
    'checkstyle.xml',
    'eclipse-formatter.xml',
    'findbugs-exclude.xml'
  ];

  this.log('\n' + chalk.green('Creating ') + 'project configuration files:');
  var _configLength = _configs.length;

  for(var idx = 0; idx < _configLength; idx++) {
      var s = _configs[idx];
      if(s.substring(s.length - 3) === 'xml')
        this.copy('config/project/_' + _configs[idx], _configs[idx]);
      else
        this.copy('config/project/_' + _configs[idx], '.' + _configs[idx]);
  }
};

/*
 * Method copies the gradle configration files form the template/config/gradle
 * directory to the project's root directory
 */
AndroidGradleGenerator.prototype.gradleConfigFiles = function gradleConfigFiles() {
  var _configs = [
    'build.gradle',
    'gradle.properties',
    'local.properties',
    'settings.gradle'
  ];

  this.log('\n' + chalk.green('Creating ') + 'gradle configuration files:');
  var _configLength = _configs.length;

  for(var idx = 0; idx < _configLength; idx++) {
      this.template('config/gradle/_' + _configs[idx], _configs[idx]);
  }
};

/*
 * Method copies the android resource files
 */
AndroidGradleGenerator.prototype.androidResFiles = function androidResFiles() {
  this.log('\n' + chalk.green('Creating ') + 'android resource files:');

  this.template('config/android/_strings.xml', 'AndroidApp/res/values/strings.xml');
  this.template('config/android/_main.xml', 'AndroidApp/res/menu/main.xml');

  this.template('config/android/_fragment_main.xml', 'AndroidApp/res/layout/fragment_main.xml');
  this.template('config/android/_activity_main.xml', 'AndroidApp/res/layout/activity_main.xml');

  this.copy('config/android/web_hi_res_512.png', 'AndroidApp/web_hi_res_512.png');
};

/*
 * Method copies the android source files
 */
AndroidGradleGenerator.prototype.androidSrcFiles = function androidSrcFiles() {
  this.log('\n' + chalk.green('Creating ') + 'android source files:');

  var srcDir = 'AndroidApp/src/' + this.packageFolder + '/';
  this.template('src/main/_MainActivity.java', srcDir + 'MainActivity.java');

  srcDir += 'common/logger/';
  this.template('src/main/common/logger/_Log.java', srcDir + 'Log.java');
  this.template('src/main/common/logger/_LogFragment.java', srcDir + 'LogFragment.java');
  this.template('src/main/common/logger/_LogNode.java', srcDir + 'LogNode.java');
  this.template('src/main/common/logger/_LogView.java', srcDir + 'LogView.java');
  this.template('src/main/common/logger/_LogWrapper.java', srcDir + 'LogWrapper.java');
  this.template('src/main/common/logger/_MessageOnlyLogFilter.java', srcDir + 'MessageOnlyLogFilter.java');
};
<commit_msg>Fixed test failures<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var chalk = require('chalk');

var sdkVersions = [
    'API level 1: Android 1.0',
    'API level 2: Android 1.1',
    'API level 3: Android 1.5, NDK 1  (Cupcake)',
    'API level 4: Android 1.6, NDK 2  (Donut)',
    'API level 5: Android 2.0 (Eclair)',
    'API level 6: Android 2.0.1 (Eclair)',
    'API level 7: Android 2.1, NDK 3  (Eclair)',
    'API level 8: Android 2.2.x, NDK 4  (Froyo)',
    'API level 9: Android 2.3 - 2.3.2, NDK 5 (Gingerbread)',
    'API level 10: Android 2.3.3 - 2.3.7: (Gingerbread)',
    'API level 11: Android 3.0: (Honeycomb)',
    'API level 12: Android 3.1, NDK 6 (Honeycomb)',
    'API level 13: Android 3.2.x (Honeycomb)',
    'API level 14: Android 4.0.1 - 4.0.2, NDK 7 (Ice Cream Sandwich)',
    'API level 15: Android 4.0.3 - 4.0.4, NDK 8 (Ice Cream Sandwich)',
    'API level 16: Android 4.1.x (Jelly Bean)',
    'API level 17: Android 4.2.x (Jelly Bean)',
    'API level 18: Android 4.3.x (Jelly Bean)',
    'API level 19: Android 4.4 - 4.4.2 (KitKat)'
  ].map(function(name, value) {
    return {name: name, value: value};
});

var AndroidGradleGenerator = yeoman.generators.Base.extend({
  init: function () {
    this.pkg = require('../package.json');

    this.on('end', function () {
      this.log("\n");
      this.log("Finished creating your " + chalk.red.bold(this.appName) + " Android+Gradle application.");
      this.log("Please update the " + chalk.yellow.bold('local.properties') + " with the Android SDK path");
      this.log("\nOpen your favorite IDE and have fun building your next great app.");
      this.log("\n");
    });
  },

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

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

    // replace it with a short and sweet description of your generator
    this.log(chalk.magenta('This generator will allow you to create a minimal Android project with Gradle support.'));

    var prompts = [
    {
      name: 'appName',
      message: 'What is the name of your Android application?',
      default: 'Hello World'
    },
    {
      name: 'packageName',
      message: 'What is the package name?',
      default: 'com.example.mobile.app'
    },
    {
      name: 'minApiLevel',
      message: 'Minimum required Android SDK:',
      type: 'list',
      choices: sdkVersions,
      default: 18
    }
    ];

    this.prompt(prompts, function (props) {
      this.appName = props.appName;
      this.packageName = props.packageName;
      this.minApiLevel = props.minApiLevel;
      this.minAndroidSDK = (this.minApiLevel + 1);

      if(this.packageName !== undefined) {
        this.packageFolder = this.packageName.replace(/\./g, '/');
      }

      if(this.appName !== undefined) {
          this.className = this._.classify(this._.slugify(this._.humanize(props.appName.replace(/ /g, ''))));
          this.projectName = this._.camelize(this.className);
      }

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

  app: function () {
    var _appDir = [
      'AndroidApp',
      'AndroidApp/assets',
      'AndroidApp/bin',
      'AndroidApp/gen',
      'AndroidApp/src',
      'AndroidApp/tests',
      'AndroidApp/tests/res',
      'AndroidApp/tests/src',
    ];

    this.log('\n' + chalk.green('Creating ') + 'project directories:');
    var _appDirLength = _appDir.length;

    for(var idx = 0; idx < _appDirLength; idx++) {
      this.mkdir(_appDir[idx]);
      this.log('\t' + chalk.green('create ') + _appDir[idx]);
    }

    this.log('\n' + chalk.green('Creating ') + 'android resources:');
    this.directory('res', 'AndroidApp/res');

    this.log('\n' + chalk.green('Creating ') + 'android libs:');
    this.directory('libs', 'AndroidApp/libs');

    this.log('\n' + chalk.green('Creating ') + 'android configurations:');
    this.template('config/android/_AndroidManifest.xml', 'AndroidApp/AndroidManifest.xml');
    this.template('config/android/_build.gradle', 'AndroidApp/build.gradle');
    this.template('config/android/_proguard-project.txt', 'AndroidApp/proguard-project.txt');
    this.template('config/android/_project.properties', 'AndroidApp/project.properties');
  }
});

module.exports = AndroidGradleGenerator;

/*
 * Method copies the project configration files from the template/config/project
 * directory to the project's root directory.
 */
AndroidGradleGenerator.prototype.projectConfigFiles = function projectConfigFiles() {
  var _configs = [
    'editorconfig',
    'jshintrc',
    'gitignore',
    'checkstyle.xml',
    'eclipse-formatter.xml',
    'findbugs-exclude.xml'
  ];

  this.log('\n' + chalk.green('Creating ') + 'project configuration files:');
  var _configLength = _configs.length;

  for(var idx = 0; idx < _configLength; idx++) {
      var s = _configs[idx];
      if(s.substring(s.length - 3) === 'xml')
        this.copy('config/project/_' + _configs[idx], _configs[idx]);
      else
        this.copy('config/project/_' + _configs[idx], '.' + _configs[idx]);
  }
};

/*
 * Method copies the gradle configration files form the template/config/gradle
 * directory to the project's root directory
 */
AndroidGradleGenerator.prototype.gradleConfigFiles = function gradleConfigFiles() {
  var _configs = [
    'build.gradle',
    'gradle.properties',
    'local.properties',
    'settings.gradle'
  ];

  this.log('\n' + chalk.green('Creating ') + 'gradle configuration files:');
  var _configLength = _configs.length;

  for(var idx = 0; idx < _configLength; idx++) {
      this.template('config/gradle/_' + _configs[idx], _configs[idx]);
  }
};

/*
 * Method copies the android resource files
 */
AndroidGradleGenerator.prototype.androidResFiles = function androidResFiles() {
  this.log('\n' + chalk.green('Creating ') + 'android resource files:');

  this.template('config/android/_strings.xml', 'AndroidApp/res/values/strings.xml');
  this.template('config/android/_main.xml', 'AndroidApp/res/menu/main.xml');

  this.template('config/android/_fragment_main.xml', 'AndroidApp/res/layout/fragment_main.xml');
  this.template('config/android/_activity_main.xml', 'AndroidApp/res/layout/activity_main.xml');

  this.copy('config/android/web_hi_res_512.png', 'AndroidApp/web_hi_res_512.png');
};

/*
 * Method copies the android source files
 */
AndroidGradleGenerator.prototype.androidSrcFiles = function androidSrcFiles() {
  this.log('\n' + chalk.green('Creating ') + 'android source files:');

  var srcDir = 'AndroidApp/src/' + this.packageFolder + '/';
  this.template('src/main/_MainActivity.java', srcDir + 'MainActivity.java');

  srcDir += 'common/logger/';
  this.template('src/main/common/logger/_Log.java', srcDir + 'Log.java');
  this.template('src/main/common/logger/_LogFragment.java', srcDir + 'LogFragment.java');
  this.template('src/main/common/logger/_LogNode.java', srcDir + 'LogNode.java');
  this.template('src/main/common/logger/_LogView.java', srcDir + 'LogView.java');
  this.template('src/main/common/logger/_LogWrapper.java', srcDir + 'LogWrapper.java');
  this.template('src/main/common/logger/_MessageOnlyLogFilter.java', srcDir + 'MessageOnlyLogFilter.java');
};
<|endoftext|>


<commit_before>var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var chalk = require('chalk');
var inquirer = require('yeoman-generator/node_modules/inquirer');

var Generator = yeoman.generators.Base.extend({
    init: function() {
        this.argument('appname', {
            type: String,
            required: false
        });
        this.pkg = require('../package.json');
        this.on('end', function() {
            if (!this.options['skip-install']) {
                this.installDependencies();
            }
        });
    },

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

        // Have Yeoman greet the user.
        this.log(yosay('Welcome to the marvelous AngularFamous generator!'));

        var prompts = [{
            name: 'appname',
            message: 'What\'s your project\'s name?',
            default: this.appname,
        }];

        this.prompt(prompts, function(answers) {
            this.appname = answers.appname;
            done();
        }.bind(this));
    },

    app: function() {
        this.mkdir('app');
        this.mkdir('app/templates');
        this.mkdir('gulp');
        this.copy('_package.json', 'package.json');
        this.copy('_bower.json', 'bower.json');
    },

    projectfiles: function() {
        this.copy('editorconfig', '.editorconfig');
        this.copy('jshintrc', '.jshintrc');
        this.copy('jscsrc', '.jscsrc');
        this.copy('gulpfile.js', 'gulpfile.js');
        this.directory('gulp');
    }
});

module.exports = Generator;
<commit_msg>Change welcome message and infer the project name from the current directory<commit_after>var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var chalk = require('chalk');
var inquirer = require('yeoman-generator/node_modules/inquirer');

var Generator = yeoman.generators.Base.extend({
    init: function() {
        this.argument('appname', {
            type: String,
            required: false
        });
        this.appname = this.appname || path.basename(process.cwd());
        this.appname = this._.camelize(this._.slugify(this._.humanize(this.appname)));
        this.pkg = require('../package.json');
        this.on('end', function() {
            if (!this.options['skip-install']) {
                this.installDependencies();
            }
        });
    },

    welcome: function() {
        // Have Yeoman greet the user.
        if (!this.options['skip-welcome-message']) {
            this.log(yosay('Welcome to the marvelous angular-famous generator!'));
            this.log(
                chalk.magenta(
                    'Out of the box I include browserify, famous-angular and some angular recommended modules.' +
                    '\n'
                )
            );
        }
    },

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

        var prompts = [{
            name: 'appname',
            message: 'What\'s your project\'s name?',
            default: this.appname,
        }];

        this.prompt(prompts, function(answers) {
            this.appname = answers.appname;
            done();
        }.bind(this));
    },

    app: function() {
        this.mkdir('app');
        this.mkdir('app/templates');
        this.mkdir('gulp');
        this.copy('_package.json', 'package.json');
        this.copy('_bower.json', 'bower.json');
    },

    projectfiles: function() {
        this.copy('editorconfig', '.editorconfig');
        this.copy('jshintrc', '.jshintrc');
        this.copy('jscsrc', '.jscsrc');
        this.copy('gulpfile.js', 'gulpfile.js');
        this.directory('gulp');
    }
});

module.exports = Generator;
<|endoftext|>


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

var conf =  {
    repoUser: 'sourcejs',
    repoSource: 'Source',
    repoSourceBranch: 'v.0.4.0',
    repoInit: 'init'
};

//TODO: add check if already inited, create project in new folder

var SourcejsGenerator = yeoman.generators.Base.extend({

    init: function () {
        this.pkg = require('../package.json');
        this.cleanName = this.pkg.name.replace('generator-','');

        this.currentAction = this.arguments[0];

        // Have Yeoman greet the user.
        this.log(yosay('Welcome to the SourceJS generator!'));
    },

    actionList: function () {
        if (this.arguments.length === 0) {
            var done = this.async();

            var prompts = [
                {
                    type: 'list',
                    name: 'actionsList',
                    message: 'Which action would you like to perform?',
                    choices: [
                        {
                            'name': 'Init SourceJS in this folder',
                            'value': 'init'
                        }
//                        {
//                            'name': 'Create new Spec page',
//                            'value': 'spec'
//                        }
                    ]
                }
            ];

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

                this.currentAction = this.actionsList;

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

/*
*
* Init
*
* */

SourcejsGenerator.prototype.askForServe = function (cb) {
    if (this.currentAction === 'init') {
        var done = this.async();

        var prompts = [
            {
                type: 'confirm',
                name: 'runSource',
                message: 'Run SourceJS server after install?',
                default: false
            }
        ];

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

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

SourcejsGenerator.prototype.initSource = function () {
    if (this.currentAction === 'init') {
        var cb = this.async();
        var _this = this;

        this._getSource(function(){
            _this.depsNeeded = true;

            cb();
        });
    }
};

SourcejsGenerator.prototype.installDeps = function () {
    if (this.depsNeeded) {
        var cb = this.async();
        var _this = this;

        this.npmInstall(null, null, function () {
             _this.gruntNeeded = true;

            // Copy first Spec from docs/stating
            _this.spawnCommand('cp',['-R','docs/starting','user/specs/starting']);

            cb();
        });
    }
};

SourcejsGenerator.prototype.runGrunt = function () {
    if (this.gruntNeeded) {
        var cb = this.async();
        var _this = this;

        this.spawnCommand('grunt', ['update']).on('close', function () {
            if(_this.runSource) {
                _this._serve();

                cb();
            }
        });
    }
};

// Silent methods
SourcejsGenerator.prototype._getSource = function (cb) {
    var _this = this;

    this.log.writeln('Cloning SourceJS');
    this.spawnCommand('git',['clone','-b',conf.repoSourceBranch,'https://github.com/'+conf.repoUser+'/'+conf.repoSource, '.'])
        .on('close', function (code) {
            if (code === 0) {
                _this._getSourceInit(function(){
                    cb();
                });
            } else {
                _this.log.writeln('Error cloning repo');
            }
        });
};

SourcejsGenerator.prototype._serve = function (cb) {
    this.spawnCommand('node', ['app']);
};

SourcejsGenerator.prototype._getSourceInit = function (cb) {
    var _this = this;

    // Removing cache, for clean git clone
    this.log.writeln('Cleaning cache for github repo:' + conf.repoInit);
    rimraf.sync(path.join(this.cacheRoot(), this.cleanName, conf.repoInit));

    this.remote(conf.repoUser, conf.repoInit, function (err, remote) {
        remote.directory('.', 'user');

        if (typeof cb === 'function') cb();
    });
};

/*
*
* Create spec
*
* */

SourcejsGenerator.prototype.createSpec = function (cb) {
    if (this.currentAction === 'spec') {
        console.log('Spec creation isn\'t supported yet');
    }
};

module.exports = SourcejsGenerator;<commit_msg>Master branch as SourceJS source :)<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var rimraf = require('rimraf');

var conf =  {
    repoUser: 'sourcejs',
    repoSource: 'Source',
    repoSourceBranch: 'master',
    repoInit: 'init'
};

//TODO: add check if already inited, create project in new folder

var SourcejsGenerator = yeoman.generators.Base.extend({

    init: function () {
        this.pkg = require('../package.json');
        this.cleanName = this.pkg.name.replace('generator-','');

        this.currentAction = this.arguments[0];

        // Have Yeoman greet the user.
        this.log(yosay('Welcome to the SourceJS generator!'));
    },

    actionList: function () {
        if (this.arguments.length === 0) {
            var done = this.async();

            var prompts = [
                {
                    type: 'list',
                    name: 'actionsList',
                    message: 'Which action would you like to perform?',
                    choices: [
                        {
                            'name': 'Init SourceJS in this folder',
                            'value': 'init'
                        }
//                        {
//                            'name': 'Create new Spec page',
//                            'value': 'spec'
//                        }
                    ]
                }
            ];

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

                this.currentAction = this.actionsList;

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

/*
*
* Init
*
* */

SourcejsGenerator.prototype.askForServe = function (cb) {
    if (this.currentAction === 'init') {
        var done = this.async();

        var prompts = [
            {
                type: 'confirm',
                name: 'runSource',
                message: 'Run SourceJS server after install?',
                default: false
            }
        ];

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

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

SourcejsGenerator.prototype.initSource = function () {
    if (this.currentAction === 'init') {
        var cb = this.async();
        var _this = this;

        this._getSource(function(){
            _this.depsNeeded = true;

            cb();
        });
    }
};

SourcejsGenerator.prototype.installDeps = function () {
    if (this.depsNeeded) {
        var cb = this.async();
        var _this = this;

        this.npmInstall(null, null, function () {
             _this.gruntNeeded = true;

            // Copy first Spec from docs/stating
            _this.spawnCommand('cp',['-R','docs/starting','user/specs/starting']);

            cb();
        });
    }
};

SourcejsGenerator.prototype.runGrunt = function () {
    if (this.gruntNeeded) {
        var cb = this.async();
        var _this = this;

        this.spawnCommand('grunt', ['update']).on('close', function () {
            if(_this.runSource) {
                _this._serve();

                cb();
            }
        });
    }
};

// Silent methods
SourcejsGenerator.prototype._getSource = function (cb) {
    var _this = this;

    this.log.writeln('Cloning SourceJS');
    this.spawnCommand('git',['clone','-b',conf.repoSourceBranch,'https://github.com/'+conf.repoUser+'/'+conf.repoSource, '.'])
        .on('close', function (code) {
            if (code === 0) {
                _this._getSourceInit(function(){
                    cb();
                });
            } else {
                _this.log.writeln('Error cloning repo');
            }
        });
};

SourcejsGenerator.prototype._serve = function (cb) {
    this.spawnCommand('node', ['app']);
};

SourcejsGenerator.prototype._getSourceInit = function (cb) {
    var _this = this;

    // Removing cache, for clean git clone
    this.log.writeln('Cleaning cache for github repo:' + conf.repoInit);
    rimraf.sync(path.join(this.cacheRoot(), this.cleanName, conf.repoInit));

    this.remote(conf.repoUser, conf.repoInit, function (err, remote) {
        remote.directory('.', 'user');

        if (typeof cb === 'function') cb();
    });
};

/*
*
* Create spec
*
* */

SourcejsGenerator.prototype.createSpec = function (cb) {
    if (this.currentAction === 'spec') {
        console.log('Spec creation isn\'t supported yet');
    }
};

module.exports = SourcejsGenerator;<|endoftext|>


<commit_before>import { compose, createStore, applyMiddleware } from 'redux'
import thunkMiddleware from 'redux-thunk' // lets us dispatch() functions
import createLogger from 'redux-logger'
import persistState from 'redux-localstorage'
import Immutable, { Map } from 'immutable'

import reducer from './reducers'

// Initialize persistent state to avoid error when resetting data
if (!localStorage.getItem('bc-planner')) {
  localStorage.setItem('bc-planner', '{}')
}

const createPersistentStore = compose(
  persistState(['events'], {
    // to avoid conflict with other redux projects on localhost
    key: 'bc-planner',
    deserialize: str => ({ events: Map(JSON.parse(str).events)})
  }),
)(createStore)

// Better logging for Immutable data structure
const stateTransformer = (state) => {
  let newState = {}
  for (var i of Object.keys(state)) {
    newState[i] = Immutable.Iterable.isIterable(state[i])
      ? state[i].toJS()
      : state[i]
  }
  return newState
}

var middlewares = __DEV__
  ? applyMiddleware(thunkMiddleware, createLogger({ collapsed: true, stateTransformer }))
  : applyMiddleware(thunkMiddleware)

const store = middlewares(createPersistentStore)(reducer)

if (__DEV__ && module.hot) {
  // Enable Webpack hot module replacement for reducers
  module.hot.accept('./reducers', () => {
    const nextRootReducer = require('./reducers/index')
    store.replaceReducer(nextRootReducer)
  })
}

export default store
<commit_msg>feat: add devToolsExtension store enhancer<commit_after>import { compose, createStore, applyMiddleware } from 'redux'
import thunkMiddleware from 'redux-thunk'
import createLogger from 'redux-logger'
import persistState from 'redux-localstorage'
import Immutable, { Map } from 'immutable'

import reducer from './reducers'

// lets us dispatch() functions
const middlewares = [thunkMiddleware]
if (__DEV__) {
  middlewares.push(createLogger({
    collapsed: true,
    // Better logging for Immutable data structure
    stateTransformer: (state) => {
      let newState = {}
      for (var i of Object.keys(state)) {
        newState[i] = Immutable.Iterable.isIterable(state[i])
          ? state[i].toJS()
          : state[i]
      }
      return newState
    }
  }))
}

const enhancer = compose(
  applyMiddleware(...middlewares),
  window.devToolsExtension ? window.devToolsExtension() : f => f
)
const enhancedCreateStore = enhancer(createStore)

// keu to avoid conflict with other redux projects on localhost
const KEY = 'bc-planner'
// Initialize persistent state to avoid error when resetting data
if (!localStorage.getItem(KEY)) {
  localStorage.setItem(KEY, '{}')
}
const createPersistentStore = persistState(['events'], {
  key: KEY,
  deserialize: str => ({ events: Map(JSON.parse(str).events)})
})(enhancedCreateStore)

const store = createPersistentStore(reducer)

if (__DEV__ && module.hot) {
  // Enable Webpack hot module replacement for reducers
  module.hot.accept('./reducers', () => {
    const nextRootReducer = require('./reducers/index')
    store.replaceReducer(nextRootReducer)
  })
}

export default store
<|endoftext|>


<commit_before>import { createStore, applyMiddleware, combineReducers, compose } from 'redux';
import { hashHistory } from 'react-router';
import { routerMiddleware, routerReducer as routing, push } from 'react-router-redux';
///import persistState from 'redux-localstorage';
import thunk from 'redux-thunk';

import telemetry from './reducers/telemetryReducer';
import settings from './reducers/settingReducer';

const initialState = {
    telemetry: {
        times: [],
        primary: {
            temps: [],
            press: [],
            hmdts: []
        },
        gps: {
            latts: [],
            latts_o: [],
            longs: [],
            longs_o: [],
            altts: []
        },
        stats: {
            rssis: [],
            batlvls: [],
            proprots: []
        },
        acc: {
            xs: [],
            ys: [],
            zs: []
        },
        rot: {
            xs: [],
            ys: [],
            zs: []
        },
        mag: {
            xs: [],
            ys: [],
            zs: []
        },
        vel: {
            accs: [],
            altts: [],
            press: []
        }
    },
    settings: {
    }
};

const router = routerMiddleware(hashHistory);

const actionCreators = {
    push
};

const reducers = {
    routing,
    telemetry,
    settings
};

const middlewares = [ thunk, router ];

const composeEnhancers = (() => {
    const compose_ = window && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__;
    if(process.env.NODE_ENV === 'development' && compose_) {
        return compose_({ actionCreators });
    }
    return compose;
})();

function configureStore(initialState) {
    const enhancer = composeEnhancers(applyMiddleware(...middlewares)/*, persistState()*/);
    const rootReducer = combineReducers(reducers);

    return createStore(rootReducer, initialState, enhancer);
}
export default configureStore(initialState);
<commit_msg>Enable store persist<commit_after>import { createStore, applyMiddleware, combineReducers, compose } from 'redux';
import { hashHistory } from 'react-router';
import { routerMiddleware, routerReducer as routing, push } from 'react-router-redux';
import persistState from 'redux-localstorage';
import thunk from 'redux-thunk';

import telemetry from './reducers/telemetryReducer';
import settings from './reducers/settingReducer';

const initialState = {
    telemetry: {
        times: [],
        primary: {
            temps: [],
            press: [],
            hmdts: []
        },
        gps: {
            latts: [],
            latts_o: [],
            longs: [],
            longs_o: [],
            altts: []
        },
        stats: {
            rssis: [],
            batlvls: [],
            proprots: []
        },
        acc: {
            xs: [],
            ys: [],
            zs: []
        },
        rot: {
            xs: [],
            ys: [],
            zs: []
        },
        mag: {
            xs: [],
            ys: [],
            zs: []
        },
        vel: {
            accs: [],
            altts: [],
            press: []
        }
    },
    settings: {
    }
};

const router = routerMiddleware(hashHistory);

const actionCreators = {
    push
};

const reducers = {
    routing,
    telemetry,
    settings
};

const middlewares = [ thunk, router ];

const composeEnhancers = (() => {
    const compose_ = window && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__;
    if(process.env.NODE_ENV === 'development' && compose_) {
        return compose_({ actionCreators });
    }
    return compose;
})();

function configureStore(initialState) {
    const enhancer = composeEnhancers(applyMiddleware(...middlewares), persistState());
    const rootReducer = combineReducers(reducers);

    return createStore(rootReducer, initialState, enhancer);
}
export default configureStore(initialState);
<|endoftext|>


<commit_before>'use strict';

/* global Connector */

Connector.playerSelector = '#player';

Connector.getTrack = function() {
	var track = $('#song-info .song').text();

	//strip extras
	track = track.replace(/\"(.+?)\"/g,'$1'); // stripping WWOZ's double quotes around name
	track = track.replace(/\s*\[[^\]]+\]$/, ''); // [whatever]
	track = track.replace(/\s*\([^\)]*version\)$/i, ''); // (whatever version)

	return track || null;
};

Connector.getArtist = function() {
	return $('#song-info .artist').text().replace(/BY: (.+)/g,'$1') || null; // + stripping WWOZ's BY: before artist's name
};

Connector.isPlaying = function() {
	return $('#jp_container_1').hasClass('jp-state-playing');
};
<commit_msg>Update wwoz scrobbler<commit_after>'use strict';

/* global Connector */

Connector.playerSelector = '#player';

Connector.getTrack = function() {
	var track = $('#player .title').text();

	//strip extras
	track = track.replace(/\"(.+?)\"/g,'$1'); // stripping WWOZ's double quotes around name
	track = track.replace(/\s*\[[^\]]+\]$/, ''); // [whatever]
	track = track.replace(/\s*\([^\)]*version\)$/i, ''); // (whatever version)

	return track || null;
};

Connector.getArtist = function() {
	return $('#player .artist').text() || null;
};

Connector.isPlaying = function() {
	return $('#oz-audio-container').hasClass('jp-state-playing');
};
<|endoftext|>