<commit_before>/*!
Copyright 2013 Hewlett-Packard Development Company, L.P.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

"use strict";
/**
 * Proxy that enables access to statically defined properties common to all CAs.
 *
 * @name caf_session/proxy_prop
 * @namespace
 * @augments gen_proxy
 *
 */

var caf = require('caf_core');
var genProxy = caf.gen_proxy;

/**
 * Factory method to create a proxy to access tatically defined
 * properties common to all CAs.
 *
 *
 * @see sup_main
 */
exports.newInstance = function(context, spec, secrets, cb) {

    var that = genProxy.constructor(spec, secrets);

    var props = (spec && spec.env) || {};

    /**
     * Gets the value of a property defined in ca.json
     *
     * @param {string} name The name of the property.
     * @return {caf.json} The value of the property
     *
     * @name caf_session/proxy_prop#get
     * @function
     *
     */
    that.get = function(name) {
        return props[name];
    };

    Object.freeze(that);
    cb(null, that);
};
<commit_msg>Fixed jsdoc<commit_after>/*!
Copyright 2013 Hewlett-Packard Development Company, L.P.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

"use strict";
/**
 * Proxy that enables access to statically defined properties common to all CAs.
 *
 * @name caf_prop/proxy_prop
 * @namespace
 * @augments gen_proxy
 *
 */

var caf = require('caf_core');
var genProxy = caf.gen_proxy;

/**
 * Factory method to create a proxy to access tatically defined
 * properties common to all CAs.
 *
 *
 * @see sup_main
 */
exports.newInstance = function(context, spec, secrets, cb) {

    var that = genProxy.constructor(spec, secrets);

    var props = (spec && spec.env) || {};

    /**
     * Gets the value of a property defined in ca.json
     *
     * @param {string} name The name of the property.
     * @return {caf.json} The value of the property
     *
     * @name caf_prop/proxy_prop#get
     * @function
     *
     */
    that.get = function(name) {
        return props[name];
    };

    Object.freeze(that);
    cb(null, that);
};
<|endoftext|>


<commit_before>var blessed = require('blessed');
var moment = require('moment');
var header = require('./libs/widget/header');
// var week = require('./libs/partials/week');

var day = require('./libs/widget/day');

var screen = blessed.screen({
  smartCSR: true
});

screen.title = 'Can I Leave?';

screen.append(header.build(blessed, screen));

var today = moment('2015-09-01 00:00:00'); // not REALLY today here yet
var yesterday = today.clone().subtract(1, 'day');

var todayWidget = day.decorate(screen).widget(today, 4);
var yesterdayWidget = day.decorate(screen).widget(yesterday, 18);

screen.append(todayWidget);
screen.append(yesterdayWidget);

/**
 * Comment week section til I really have an implementation
 * screen.append(week.build(blessed, screen));
 */

screen.key(['escape', 'q'], function (ch, key){
  return process.exit(0);
});

function updateDateTime(screen) {
  screen.emit('updateDateTime');
}

setInterval(updateDateTime, 500, screen);

screen.render();<commit_msg>Remove mock data<commit_after>var blessed = require('blessed');
var moment = require('moment');
var header = require('./libs/widget/header');
// var week = require('./libs/partials/week');

var day = require('./libs/widget/day');

var screen = blessed.screen({
  smartCSR: true
});

screen.title = 'Can I Leave?';

screen.append(header.build(blessed, screen));

var today = moment();
var yesterday = today.clone().subtract(1, 'day');

var todayWidget = day.decorate(screen).widget(today, 4);
var yesterdayWidget = day.decorate(screen).widget(yesterday, 18);

screen.append(todayWidget);
screen.append(yesterdayWidget);

/**
 * Comment week section til I really have an implementation
 * screen.append(week.build(blessed, screen));
 */

screen.key(['escape', 'q'], function (ch, key){
  return process.exit(0);
});

function updateDateTime(screen) {
  screen.emit('updateDateTime');
}

setInterval(updateDateTime, 500, screen);

screen.render();<|endoftext|>


<commit_before>var yeoman = require('yeoman-generator'),
    chalk = require('chalk'),
    yosay = require('yosay'),
    crypto = require('crypto');

/**
 * List of questions
 * @type {Array}
 * @private
 */
var QUESTIONS_LIST = [{
    type: 'input',
    name: 'project:name',
    message: 'Type your project name',
    default: 'sails-rest-api'
}, {
    type: 'list',
    name: 'database:adapter',
    message: 'Choose database adapter',
    choices: [
        'MySQL',
        'Mongo',
        'PostgreSQL',
        'Redis'
    ],
    default: 1
}, {
    type: 'input',
    name: 'database:user',
    message: 'Type database username (if need)',
    default: ''
}, {
    type: 'password',
    name: 'database:password',
    message: 'Type database password (if need)',
    default: ''
}, {
    type: 'input',
    name: 'database:host',
    message: 'Type your database host',
    default: 'localhost'
}, {
    type: 'input',
    name: 'database:name',
    message: 'Type your database name',
    default: 'sails-rest-api'
}, {
    type: 'input',
    name: 'application:app-secret-token',
    message: 'Type application token (checking for isOurApp policy)',
    default: crypto.randomBytes(32).toString('hex')
}, {
    type: 'input',
    name: 'application:jwt-secret-token',
    message: 'Type JWT secret (overrides)',
    default: crypto.randomBytes(32).toString('hex')
}];

module.exports = yeoman.generators.Base.extend({
    initializing: function () {
        this.pkg = require('../package.json');
    },

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

        this.log(yosay('Welcome to the laudable ' + chalk.red('Sails REST API') + ' generator!'));

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

    configuring: function () {
        // TODO: maybe implement
    },

    writing: function () {
        this.directory(
            this.sourceRoot(),
            this.destinationRoot()
        )
    },

    conflicts: function () {
        // TODO: maybe implement
    },

    install: function () {
        // TODO: implement npm install
    },

    end: function () {
        this.log(
            '\n\n' +
            chalk.red("1) ") +
            chalk.yellow("Install dependencies via") +
            chalk.red(" npm install") +
            '\n'
        );

        this.log(
            chalk.red("2) ") +
            chalk.yellow("Configure you app in") +
            chalk.red(" config/**/*.js ") +
            chalk.yellow("and") +
            chalk.red(" api/services/*.js") +
            '\n\n'
        );
    }
});
<commit_msg>Change bg color for notification<commit_after>var yeoman = require('yeoman-generator'),
    chalk = require('chalk'),
    yosay = require('yosay'),
    crypto = require('crypto');

/**
 * List of questions
 * @type {Array}
 * @private
 */
var QUESTIONS_LIST = [{
    type: 'input',
    name: 'project:name',
    message: 'Type your project name',
    default: 'sails-rest-api'
}, {
    type: 'list',
    name: 'database:adapter',
    message: 'Choose database adapter',
    choices: [
        'MySQL',
        'Mongo',
        'PostgreSQL',
        'Redis'
    ],
    default: 1
}, {
    type: 'input',
    name: 'database:user',
    message: 'Type database username (if need)',
    default: ''
}, {
    type: 'password',
    name: 'database:password',
    message: 'Type database password (if need)',
    default: ''
}, {
    type: 'input',
    name: 'database:host',
    message: 'Type your database host',
    default: 'localhost'
}, {
    type: 'input',
    name: 'database:name',
    message: 'Type your database name',
    default: 'sails-rest-api'
}, {
    type: 'input',
    name: 'application:app-secret-token',
    message: 'Type application token (checking for isOurApp policy)',
    default: crypto.randomBytes(32).toString('hex')
}, {
    type: 'input',
    name: 'application:jwt-secret-token',
    message: 'Type JWT secret (overrides)',
    default: crypto.randomBytes(32).toString('hex')
}];

module.exports = yeoman.generators.Base.extend({
    initializing: function () {
        this.pkg = require('../package.json');
    },

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

        this.log(yosay('Welcome to the laudable ' + chalk.red('Sails REST API') + ' generator!'));

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

    configuring: function () {
        // TODO: maybe implement
    },

    writing: function () {
        this.directory(
            this.sourceRoot(),
            this.destinationRoot()
        )
    },

    conflicts: function () {
        // TODO: maybe implement
    },

    install: function () {
        // TODO: implement npm install
    },

    end: function () {
        this.log(
            '\n\n' +
            chalk.yellow("1) Install dependencies via ") +
            chalk.red.bgWhite(" npm install ") +
            '\n'
        );

        this.log(
            chalk.yellow("2) Configure you app in ") +
            chalk.red.bgWhite(" config/**/*.js ") +
            chalk.yellow(" and ") +
            chalk.red.bgWhite(" api/services/*.js ") +
            '\n\n'
        );
    }
});
<|endoftext|>


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

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

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

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

util.inherits(ExpressGenerator, yeoman.generators.NamedBase);

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

    // welcome message
    var welcome =
    '\n     _-----_' +
    '\n    |       |' +
    '\n    |' + '--(o)--'.red + '|   .--------------------------.' +
    '\n   `---------´  |    ' + 'Welcome to Yeoman,'.yellow.bold + '    |' +
    '\n    ' + '( '.yellow + '_' + '´U`'.yellow + '_' + ' )'.yellow + '   |   ' + 'ladies and gentlemen!'.yellow.bold + '  |' +
    '\n    /___A___\\   \'__________________________\'' +
    '\n     |  ~  |'.yellow +
    '\n   __' + '\'.___.\''.yellow + '__' +
    '\n ´   ' + '`  |'.red + '° ' + '´ Y'.red + ' `\n';

    console.log(welcome);

    var prompts = [{
        name: 'cloud',
        message: 'Is this app going to be deployed on a Paas (Cloudfoundry, Appfog, etc.)?',
        default: 'Y/n'
    },{
        name: 'includeSassLibs',
        message: 'Would you like some additional SASS librairies?',
        default: 'Y/n'
    }];

    this.prompt(prompts, function (err, props) {
        if (err) {
            return this.emit('error', err);
        }

        this.cloud = (/y/i).test(props.cloud);
        this.includeSassLibs = (/y/i).test(props.includeSassLibs);

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

ExpressGenerator.prototype.gruntfile = function gruntfile() {
    this.template('Gruntfile.js');
};

ExpressGenerator.prototype.packageJSON = function packageJSON() {
    this.template('_package.json', 'package.json');
};

ExpressGenerator.prototype.git = function git() {
    this.copy('gitignore', '.gitignore');
    this.copy('gitattributes', '.gitattributes');
};

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

ExpressGenerator.prototype.jshint = function jshint() {
    this.copy('jshintrc', '.jshintrc');
};

ExpressGenerator.prototype.editorConfig = function editorConfig() {
    this.copy('editorconfig', '.editorconfig');
};

ExpressGenerator.prototype.cfManifests = function cfManifests() {
    if (this.cloud) {
        this.template('cf.yml', 'manifests/cf.yml');
        this.template('appfog.yml', 'manifests/appfog.yml');
    }
};

ExpressGenerator.prototype.mainStylesheet = function mainStylesheet() {
    if (this.includeSassLibs) {
        this.directory('sass', 'client/styles/libs');
        this.write('client/styles/main.scss', '@import "compass";\n@import "compass/css3";\n@import "compass/reset";\n\n@import "libs/animations";\n@import "libs/media-queries";');
    }else {
        this.write('client/styles/main.scss', '@import "compass";\n@import "compass/css3";\n@import "compass/reset";');
    }
};

ExpressGenerator.prototype.app = function app() {
    this.directory('client');
    this.mkdir('client/styles');
    this.mkdir('client/images');
    this.directory('server');

    if (this.cloud) {
        this.mkdir('manifests');
    }
};
<commit_msg>add views folder in styles<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

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

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

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

util.inherits(ExpressGenerator, yeoman.generators.NamedBase);

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

    // welcome message
    var welcome =
    '\n     _-----_' +
    '\n    |       |' +
    '\n    |' + '--(o)--'.red + '|   .--------------------------.' +
    '\n   `---------´  |    ' + 'Welcome to Yeoman,'.yellow.bold + '    |' +
    '\n    ' + '( '.yellow + '_' + '´U`'.yellow + '_' + ' )'.yellow + '   |   ' + 'ladies and gentlemen!'.yellow.bold + '  |' +
    '\n    /___A___\\   \'__________________________\'' +
    '\n     |  ~  |'.yellow +
    '\n   __' + '\'.___.\''.yellow + '__' +
    '\n ´   ' + '`  |'.red + '° ' + '´ Y'.red + ' `\n';

    console.log(welcome);

    var prompts = [{
        name: 'cloud',
        message: 'Is this app going to be deployed on a Paas (Cloudfoundry, Appfog, etc.)?',
        default: 'Y/n'
    },{
        name: 'includeSassLibs',
        message: 'Would you like some additional SASS librairies?',
        default: 'Y/n'
    }];

    this.prompt(prompts, function (err, props) {
        if (err) {
            return this.emit('error', err);
        }

        this.cloud = (/y/i).test(props.cloud);
        this.includeSassLibs = (/y/i).test(props.includeSassLibs);

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

ExpressGenerator.prototype.gruntfile = function gruntfile() {
    this.template('Gruntfile.js');
};

ExpressGenerator.prototype.packageJSON = function packageJSON() {
    this.template('_package.json', 'package.json');
};

ExpressGenerator.prototype.git = function git() {
    this.copy('gitignore', '.gitignore');
    this.copy('gitattributes', '.gitattributes');
};

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

ExpressGenerator.prototype.jshint = function jshint() {
    this.copy('jshintrc', '.jshintrc');
};

ExpressGenerator.prototype.editorConfig = function editorConfig() {
    this.copy('editorconfig', '.editorconfig');
};

ExpressGenerator.prototype.cfManifests = function cfManifests() {
    if (this.cloud) {
        this.template('cf.yml', 'manifests/cf.yml');
        this.template('appfog.yml', 'manifests/appfog.yml');
    }
};

ExpressGenerator.prototype.mainStylesheet = function mainStylesheet() {
    if (this.includeSassLibs) {
        this.directory('sass', 'client/styles/libs');
        this.write('client/styles/main.scss', '@import "compass";\n@import "compass/css3";\n@import "compass/reset";\n\n@import "libs/animations";\n@import "libs/media-queries";');
    }else {
        this.write('client/styles/main.scss', '@import "compass";\n@import "compass/css3";\n@import "compass/reset";');
    }
};

ExpressGenerator.prototype.app = function app() {
    this.directory('client');
    this.mkdir('client/styles');
    this.mkdir('client/views');
    this.mkdir('client/images');
    this.directory('server');

    if (this.cloud) {
        this.mkdir('manifests');
    }
};
<|endoftext|>


<commit_before>'use strict';

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

function cleanAppname(appname) {
    return appname.replace(/\s/g, '-');
}

module.exports = yeoman.Base.extend({
    prompting: function () {
        this.log(yosay(
            'You are about to build a simple React/Redux application!'
        ));

        const prompts = [
            {
                type   : 'input',
                name   : 'appname',
                message: 'Enter your application name',
                default: cleanAppname(this.appname)
            },
            {
                type   : 'input',
                name   : 'description',
                message: 'Enter your application description',
                default: ''
            },
            {
                type   : 'input',
                name   : 'authorName',
                message: 'Author name?',
                default: ''
            },
            {
                type: 'input',
                name: 'authorEmail',
                message: 'Author\'s email?',
                default: ''
            },
            {
                type   : 'confirm',
                name   : 'npmInstall',
                message: 'Would you like to install dependencies?',
                default: true
            }
        ];

        return this.prompt(prompts).then(props => {
            this.props.appname = cleanAppname(props.appname);

            this.props = props;
        });
    },

    writing: function () {
        // templated files
        this.fs.copyTpl(
            this.templatePath('package.json'),
            this.destinationPath('package.json'),
            this.props
        );

        this.fs.copyTpl(
            this.templatePath('index.js'),
            this.destinationPath('index.js'),
            this.props
        );

        // root files
        this.fs.copy(this.templatePath('.eslintrc'), this.destinationPath('.eslintrc'));
        this.fs.copy(this.templatePath('.babelrc'), this.destinationPath('.babelrc'));
        this.fs.copy(this.templatePath('webpack.config.js'), this.destinationPath('webpack.config.js'));

        // directories
        this.fs.copy(this.templatePath('config/'), this.destinationPath('config/'));
        this.fs.copy(this.templatePath('src'), this.destinationPath('src'));
    },

    install: function () {
        if (!this.props.npmInstall) {
            return;
        }

        this.npmInstall();
    }
});
<commit_msg>fix prop name assignment<commit_after>'use strict';

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

function cleanAppname(appname) {
    return appname.replace(/\s/g, '-');
}

module.exports = yeoman.Base.extend({
    prompting: function () {
        this.log(yosay(
            'You are about to build a simple React/Redux application!'
        ));

        const prompts = [
            {
                type   : 'input',
                name   : 'appname',
                message: 'Enter your application name',
                default: cleanAppname(this.appname)
            },
            {
                type   : 'input',
                name   : 'description',
                message: 'Enter your application description',
                default: ''
            },
            {
                type   : 'input',
                name   : 'authorName',
                message: 'Author name?',
                default: ''
            },
            {
                type: 'input',
                name: 'authorEmail',
                message: 'Author\'s email?',
                default: ''
            },
            {
                type   : 'confirm',
                name   : 'npmInstall',
                message: 'Would you like to install dependencies?',
                default: true
            }
        ];

        return this.prompt(prompts).then(props => {
            props.appname = cleanAppname(props.appname);

            this.props = props;
        });
    },

    writing: function () {
        // templated files
        this.fs.copyTpl(
            this.templatePath('package.json'),
            this.destinationPath('package.json'),
            this.props
        );

        this.fs.copyTpl(
            this.templatePath('index.js'),
            this.destinationPath('index.js'),
            this.props
        );

        // root files
        this.fs.copy(this.templatePath('.eslintrc'), this.destinationPath('.eslintrc'));
        this.fs.copy(this.templatePath('.babelrc'), this.destinationPath('.babelrc'));
        this.fs.copy(this.templatePath('webpack.config.js'), this.destinationPath('webpack.config.js'));

        // directories
        this.fs.copy(this.templatePath('config/'), this.destinationPath('config/'));
        this.fs.copy(this.templatePath('src'), this.destinationPath('src'));
    },

    install: function () {
        if (!this.props.npmInstall) {
            return;
        }

        this.npmInstall();
    }
});
<|endoftext|>


<commit_before>const Generator = require('yeoman-generator')
const path = require('path')
const camelize = require('camelize')
const prefixnote = require('prefixnote')
const chalk = require('chalk')
const striate = require('gulp-striate')
const R = require('ramda')
const indent = require('indent-string')
const pkg = require('../package.json')

// files that should never be copied
const ignore = ['.DS_Store']

// parse an array from a string
function parseArray(str) {
  return R.filter(R.identity, str.split(',').map(R.invoker(0, 'trim')))
}

// stringify an object and indent everything after the opening line
function stringifyIndented(value, chr, n) {
  return indent(JSON.stringify(value, null, n), chr, n).slice(chr.length * n)
}

module.exports = class extends Generator {

  constructor(args, opts) {

    super(args, opts)

    this.option('test')

    // if the package name is yogini then we are in creation mode
    // which will recursively copy this generator itself and give it a new
    // project name so that subsequent runs will generate from app/templates
    this.createMode = !this.options.test && pkg.name === 'generator-yogini'

    // parse yogini.json and report error messages for missing/invalid
    try {
      if (this.createMode) {
        this.yoginiFile = require('../create/yogini.json')
      }
      else if (this.options.test) {
        this.yoginiFile = require('../test/testapp/yogini.json')
      }
      else {
        try {
          this.yoginiFile = require('./yogini.json')
        }
        catch (e) {
          if (e.code !== 'MODULE_NOT_FOUND') {
            this.yoginiFile = require('./yogini.js')
          }
          else {
            throw e
          }
        }
      }
    }
    catch (e) {
      if (e.code === 'MODULE_NOT_FOUND') {
        console.log(chalk.red('No yogini file found. Proceeding with simple copy.'))
      }
      else {
        console.log(chalk.red('Invalid yogini file'))
        console.log(chalk.red(e))
      }
    }

  }

  async prompting() {

    if (this.yoginiFile && !(this.yoginiFile.prompts && this.yoginiFile.prompts.length)) {
      console.log(chalk.red('No prompts in yogini.json. Proceeding with simple copy.'))
      return
    }

    // set the default project name to the destination folder name and provide a validation function
    if (this.createMode) {
      const projectPrompt = this.yoginiFile.prompts.find(R.propEq('name', 'project'))
      projectPrompt.default = path.basename(this.env.cwd)
      projectPrompt.validate = function (input) {
        return input === 'yogini' ? 'Cannot be named "yogini"' :
          input.indexOf('generator-') !== 0 ? 'Must start with "generator-"' :
          true
      }
    }

    const props = await this.prompt(this.yoginiFile.prompts)

    // populate viewData from the prompts and formatted values
    this.viewData = R.merge(props, {
      camelize: camelize,
      keywordsFormatted: props.keywords ? stringifyIndented(parseArray(props.keywords), ' ', 2) : ''
    })
  }

  // Copies all files from the template directory to the destination path
  // parsing filenames using prefixnote and running them through striate
  writing() {

    const done = this.async()

    if (this.createMode) {

      // copy yogini-generator itself
      this.fs.copy(path.join(__dirname, '../'), this.destinationPath(), {
        globOptions: {
          dot: true,
          ignore: [
            '**/.DS_Store',
            '**/.git',
            '**/.git/**/*',
            '**/node_modules',
            '**/node_modules/**/*',
            '**/test/**/*',
            '**/create/**/*'
          ]
        }
      })

      // copy the package.json and README
      this.fs.copyTpl(
        path.join(__dirname, '../create/{}package.json'),
        this.destinationPath('package.json'),
        this.viewData
      )

      this.fs.copyTpl(
        path.join(__dirname, '../create/README.md'),
        this.destinationPath('README.md'),
        this.viewData
      )

      done()
    }
    else {
      this.registerTransformStream(striate(this.viewData))

      prefixnote.parseFiles(this.templatePath(), this.viewData)

        // copy each file that is traversed
        .on('data', function (file) {
          const filename = path.basename(file.original)

          // always ignore files like .DS_Store
          if (ignore.indexOf(filename) === -1) {
            const from = file.original
            const to = this.destinationPath(path.relative(this.templatePath(), file.parsed))

            // copy the file with templating
            this.fs.copyTpl(from, to, this.viewData)
          }
        }.bind(this))

        .on('end', done)
        .on('error', done)
    }
  }

  end() {
    this.installDependencies()
  }

}
<commit_msg>Use console.warn for warnings.<commit_after>const Generator = require('yeoman-generator')
const path = require('path')
const camelize = require('camelize')
const prefixnote = require('prefixnote')
const chalk = require('chalk')
const striate = require('gulp-striate')
const R = require('ramda')
const indent = require('indent-string')
const pkg = require('../package.json')

// files that should never be copied
const ignore = ['.DS_Store']

// parse an array from a string
function parseArray(str) {
  return R.filter(R.identity, str.split(',').map(R.invoker(0, 'trim')))
}

// stringify an object and indent everything after the opening line
function stringifyIndented(value, chr, n) {
  return indent(JSON.stringify(value, null, n), chr, n).slice(chr.length * n)
}

module.exports = class extends Generator {

  constructor(args, opts) {

    super(args, opts)

    this.option('test')

    // if the package name is yogini then we are in creation mode
    // which will recursively copy this generator itself and give it a new
    // project name so that subsequent runs will generate from app/templates
    this.createMode = !this.options.test && pkg.name === 'generator-yogini'

    // parse yogini.json and report error messages for missing/invalid
    try {
      if (this.createMode) {
        this.yoginiFile = require('../create/yogini.json')
      }
      else if (this.options.test) {
        this.yoginiFile = require('../test/testapp/yogini.json')
      }
      else {
        try {
          this.yoginiFile = require('./yogini.json')
        }
        catch (e) {
          if (e.code !== 'MODULE_NOT_FOUND') {
            this.yoginiFile = require('./yogini.js')
          }
          else {
            throw e
          }
        }
      }
    }
    catch (e) {
      if (e.code === 'MODULE_NOT_FOUND') {
        console.warn(chalk.yellow('No yogini file found. Proceeding with simple copy.'))
      }
      else {
        console.error(chalk.red('Invalid yogini file'))
        console.error(chalk.red(e))
      }
    }

  }

  async prompting() {

    if (this.yoginiFile && !(this.yoginiFile.prompts && this.yoginiFile.prompts.length)) {
      console.warn(chalk.yellow('No prompts in yogini.json. Proceeding with simple copy.'))
      return
    }

    // set the default project name to the destination folder name and provide a validation function
    if (this.createMode) {
      const projectPrompt = this.yoginiFile.prompts.find(R.propEq('name', 'project'))
      projectPrompt.default = path.basename(this.env.cwd)
      projectPrompt.validate = function (input) {
        return input === 'yogini' ? 'Cannot be named "yogini"' :
          input.indexOf('generator-') !== 0 ? 'Must start with "generator-"' :
          true
      }
    }

    const props = await this.prompt(this.yoginiFile.prompts)

    // populate viewData from the prompts and formatted values
    this.viewData = R.merge(props, {
      camelize: camelize,
      keywordsFormatted: props.keywords ? stringifyIndented(parseArray(props.keywords), ' ', 2) : ''
    })
  }

  // Copies all files from the template directory to the destination path
  // parsing filenames using prefixnote and running them through striate
  writing() {

    const done = this.async()

    if (this.createMode) {

      // copy yogini-generator itself
      this.fs.copy(path.join(__dirname, '../'), this.destinationPath(), {
        globOptions: {
          dot: true,
          ignore: [
            '**/.DS_Store',
            '**/.git',
            '**/.git/**/*',
            '**/node_modules',
            '**/node_modules/**/*',
            '**/test/**/*',
            '**/create/**/*'
          ]
        }
      })

      // copy the package.json and README
      this.fs.copyTpl(
        path.join(__dirname, '../create/{}package.json'),
        this.destinationPath('package.json'),
        this.viewData
      )

      this.fs.copyTpl(
        path.join(__dirname, '../create/README.md'),
        this.destinationPath('README.md'),
        this.viewData
      )

      done()
    }
    else {
      this.registerTransformStream(striate(this.viewData))

      prefixnote.parseFiles(this.templatePath(), this.viewData)

        // copy each file that is traversed
        .on('data', function (file) {
          const filename = path.basename(file.original)

          // always ignore files like .DS_Store
          if (ignore.indexOf(filename) === -1) {
            const from = file.original
            const to = this.destinationPath(path.relative(this.templatePath(), file.parsed))

            // copy the file with templating
            this.fs.copyTpl(from, to, this.viewData)
          }
        }.bind(this))

        .on('end', done)
        .on('error', done)
    }
  }

  end() {
    this.installDependencies()
  }

}
<|endoftext|>


<commit_before>// ==UserScript==
// @name         JazzGadget - Loop
// @namespace    https://github.com/SirPython/JazzGadgets/tree/master/loop
// @version      0.2
// @description  Loops a time-segment.
// @author       SirPython
// @match        *://www.youtube.com/watch?v=*
// @grant        none
// ==/UserScript==
/* jshint -W097 */
'use strict';

// IF YOU CHANGE THE TIME, THE CANCEL BUTTON BECOMES STUPID.

const [alert, prompt] = [window.alert, window.prompt];

const welcome = "Welcome to JazzGadget - Loop!\n\n" +
                "To start looping or change the current looping times, enter the starting and ending times below separated by a comma like so: 1:34,3:35.\n\n" +
                "When entering the times, use the format [[h]h:][[m]m:][s]s\n\n\n" +
                "If you wish to cancel the current loop, hit Cancel.\n\n" +
                "If you hit this button by accident, leave the textbox blank and hit OK.";

const makePanelButton = (onclick) => {
    const button = document.createElement("button");
    button.className = "ytp-button";
    button.onclick = onclick;
    button.innerHTML = "JG-Loop";
    return button;
};

/**
 * Parses a HH:MM:SS string, and returns a double of the equivalent amount of seconds.
 */
const timeToSeconds = (hhmmss) => {
    /**
     * Accepted formats:
     *
     * S
     * SS
     * M:SS
     * MM:SS
     * H:MM:SS
     * HH:MM:SS
     */
    const timeFormat = /^((\d?\d)|((\d?\d):(\d\d))|((\d?\d):(\d\d):(\d\d)))$/;
    if(!timeFormat.test(hhmmss)) {
        alert("String is not of the form [[h]h:][[m]m:][s]s\n\nHere are some sample times:\n\n1\n12\n1:23\n12:34\n1:23:45\n12:34:56");
        return null;
    }

    const mat = hhmmss.match(timeFormat);
    const time = { // Depending on which format is used, the minutes and seconds will be at varying points in the matches array.
        hours:   parseInt(mat[7] || 0               , 10),
        minutes: parseInt(mat[8] || mat[4] || 0     , 10),
        seconds: parseInt(mat[9] || mat[5] || mat[0], 10)
    };

    return (
        (time.hours   * 3600) +
        (time.minutes * 60)   +
        (time.seconds)
    );
};

;(function() {
    let video, start, end, interval, resp;
    document.getElementsByClassName("ytp-right-controls")[0].appendChild(makePanelButton(() => {

        if((resp = prompt(welcome)) === null) { // hit cancel; wants to cancel loop
            clearInterval(interval);
            return;
        }
        if(resp === "") { // hit OK; accidentally hit button
            return;
        }

        resp = resp.split(/[^\d:]/g);
        start = timeToSeconds(resp[0]);
        end = timeToSeconds(resp.pop());

        if(start > end) {
            alert("The start time cannot come after the end time.");
        }
        if(start === null) { // entered wrong format
            return;
        }

        video = video || document.getElementsByClassName("html5-main-video")[0];
        video.currentTime = start;
        clearInterval(interval);
        interval = setInterval(() => video.currentTime >= end+1 ? video.currentTime = start : null, 1);

    }));
})();
<commit_msg>Delete jazzgadget-loop.user.js<commit_after><|endoftext|>


<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: '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() {
      if (this.props.npmsetup) {
        this.log('\nWarning! \nRun: ' + chalk.green('run link gulp') + ' to start the development');
      }
      this.log(chalk.green('\nAll Done!!\n------------------------\n'));

      if (this.props.npmsetup) {
        this.log('\nRun ' + chalk.green('npm run watch ') + ' to start the development and ' + chalk.green('npm run build') + ' to create a file in ' + chalk.white('dist/' + this.props.themeslug ) + ' ready for production.');
      }
    }
  },
});
<commit_msg>Add gulpfile.js & final message<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: '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() {
      if (this.props.npmsetup) {
        this.log(chalk.red('\nWarning! \nRun: ') + chalk.yellow('npm link gulp') + ' to start the development theme');
      }
      this.log(chalk.green('\nAll Done!!\n------------------------\n'));

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


<commit_before>'use strict';

var util    = require('util');
var path    = require('path');
var yeoman  = require('yeoman-generator');
var latest  = require('github-latest');
var wrench  = require('wrench');
var async   = require('async');
var chalk   = require('chalk');
var crypto  = require('crypto');
var request = require('request');
var keygen  = require('ssh-keygen');
var fs      = require('fs');

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

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

  this.on('end', function() {
    this.installDependencies({
      bower:        true,
      npm:          false,
      skipInstall:  options['skip-install'],
      skipMessage:  true,
      callback:     function() {
        this.log.write();
        this.log.ok('All done! Run ' + chalk.yellow('vagrant up') + ' to get started!');
      }.bind(this)
    });
  });
};

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

WordpressGenerator.prototype.welcome = function() {
  var message = this.readFileAsString(path.join(__dirname, 'welcome.txt'));

  message = message.replace(/./g, function(match) {
    return /\w/.test(match) ? chalk.yellow(match) : chalk.cyan(match);
  });

  this.log.writeln(message);
};

WordpressGenerator.prototype.promptForName = function() {
  var existing = function() {
    try {
      var bower = JSON.parse(this.readFileAsString(path.join(this.env.cwd, 'bower.json')));

      return bower.name;
    } catch(e) {};
  }.bind(this);

  this.prompts.push({
    required: true,
    type:     'text',
    name:     'name',
    message:  'Repository name (e.g. MySite)',
    default:  function() {
      return existing() || path.basename(this.env.cwd);
    }.bind(this)
  });
};

WordpressGenerator.prototype.promptForDomain = function() {
  this.prompts.push({
    required: true,
    type:     'text',
    name:     'domain',
    message:  'Domain name (e.g. mysite.com)',
    default:  path.basename(this.env.cwd).toLowerCase(),
    validate: function(input) {
      if (/^[\w-]+\.\w+$/.test(input)) {
        return true;
      } else if (!input) {
        return "Domain is required";
      }

      return chalk.yellow(input) + ' does not match the example';
    }
  });
};

WordpressGenerator.prototype.promptForGenesis = function() {
  this.prompts.push({
    type:     'text',
    name:     'genesis',
    message:  'Genesis library version',
    default:  '~0.1.6'
  });
};

WordpressGenerator.prototype.promptForWeb = function() {
  this.prompts.push({
    type:     'text',
    name:     'web',
    message:  'WordPress directory',
    default:  'web'
  });
};

WordpressGenerator.prototype.promptForWordPress = function() {
  var existing = function(web) {
    try {
      var file    = this.readFileAsString(path.join(web, 'wp-includes', 'version.php'));
      var version = file.match(/\$wp_version\s=\s['"]([^'"]+)/);

      if (version.length) {
        return version[1];
      }
    } catch(e) {}
  }.bind(this);

  this.prompts.push({
    type:     'text',
    name:     'wordpress',
    message:  'WordPress version',
    default:  function(answers) {
      return existing(answers.web) || '3.6.1';
    }
  });
};

WordpressGenerator.prototype.promptForDatabase = function() {
  var done      = this.async();
  var existing  = function(web, constant) {
    try {
      var config = this.readFileAsString(path.join(web, 'wp-config.php'));
      var regex   = new RegExp(constant + '[\'"],\\s*[\'"]([^\'"]+)');
      var matches = regex.exec(config);

      return matches && matches[1];
    } catch(e) {}
  }.bind(this);

  crypto.randomBytes(12, function(err, buffer) {
    this.prompts.push({
      type:     'text',
      name:     'DB_NAME',
      message:  'Database name',
      default:  function(answers) { return existing(answers.web, 'DB_NAME') || 'wordpress'; }
    });

    this.prompts.push({
      type:     'text',
      name:     'DB_USER',
      message:  'Database user',
      default:  function(answers) { return existing(answers.web, 'DB_USER') || 'wordpress'; }
    });

    this.prompts.push({
      type:     'text',
      name:     'DB_PASSWORD',
      message:  'Database password',
      default:  function(answers) { return existing(answers.web, 'DB_PASSWORD') || buffer.toString('base64'); }
    });

    this.prompts.push({
      type:     'text',
      name:     'DB_HOST',
      message:  'Database host',
      default:  function(answers) { return existing(answers.web, 'DB_HOST') || 'localhost'; }
    });

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

WordpressGenerator.prototype.promptForIp = function() {
  // Private IP blocks
  var blocks = [
    ['192.168.0.0', '192.168.255.255'],
    ['172.16.0.0',  '172.31.255.255'],
    ['10.0.0.0',    '10.255.255.255']
  ];

  // Long IP ranges
  var ranges = blocks.map(function(block) {
    return block.map(function(ip) {
      var parts = ip.split('.');

      return parts[0] << 24 | parts[1] << 16 | parts[2] << 8 | parts[3] >>> 0;
    });
  });

  // Randomize IP addresses
  var ips = ranges.map(function(range) {
    return Math.random() * (range[1] - range[0]) + range[0];
  }).map(function(ip) {
    return [
      (ip & (0xff << 24)) >>> 24,
      (ip & (0xff << 16)) >>> 16,
      (ip & (0xff << 8)) >>> 8,
      (ip & (0xff << 0)) >>> 0
    ].join('.');
  });

  try {
    var vagrant = this.readFileAsString('Vagrantfile').match(/ip:\s['"]([\d\.]+)['"]/);

    if (vagrant.length) {
      ips.unshift(vagrant[1]);
    }
  } catch(e) {}

  this.prompts.push({
    required: true,
    type:     'list',
    name:     'ip',
    message:  'Vagrant IP',
    pattern:  /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,
    choices:  ips
  });
};

WordpressGenerator.prototype.ask = function() {
  var done = this.async();

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

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

WordpressGenerator.prototype.ready = function() {
  this.log.write('\n');
  this.log.info(chalk.green('Here we go!'));
};

WordpressGenerator.prototype.writeProjectFiles = function() {
  this.log.info('Writing project files...');

  try {
    this.readmeFile = this.readFileAsString(path.join(this.env.cwd, 'README.md'));
  } catch(e) {
    this.readmeFile = '';
  }

  this.template('gitignore',   '.gitignore');
  this.template('bower.json',   'bower.json');
  this.template('Capfile',      'Capfile');
  this.template('editorconfig', '.editorconfig');
  this.template('README.md',    'README.md');
  this.template('Vagrantfile',  'Vagrantfile');
};

WordpressGenerator.prototype.writeWordPress = function() {
  var done = this.async();

  this.log.info('Downloading WordPress...');

  this.remote('wordpress', 'wordpress', this.props.wordpress, function(err, remote) {
    this.log.info('Writing WordPress to ' + chalk.yellow(this.props.web));

    wrench.copyDirSyncRecursive(remote.cachePath, this.props.web);

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

WordpressGenerator.prototype.writeWeb = function() {
  this.log.info('Writing ' + chalk.yellow(this.props.web) + ' files...');

  try {
    this.htaccessFile = this.readFileAsString(path.join(this.env.cwd, this.props.web, '.htaccess'));
  } catch(e) {
    this.htaccessFile = '';
  }

  this.template('web/htaccess',      path.join(this.props.web, '.htaccess'));
  this.template('web/no_robots.txt',  path.join(this.props.web, 'no_robots.txt'));
  this.template('web/robots.txt',     path.join(this.props.web, 'robots.txt'));
};

WordpressGenerator.prototype.fetchSalts = function() {
  var done = this.async();

  request('https://api.wordpress.org/secret-key/1.1/salt/', function(err, response, salts) {
    if (err) {
      throw err;
    }

    this.props.salts = salts;
    done();
  }.bind(this));
};

WordpressGenerator.prototype.setupWordPressConfig = function() {
  this.log.info('Configuring ' + chalk.yellow('wp-config.php'));

  this.wpConfigFile = this.readFileAsString(path.join(this.env.cwd, this.props.web, 'wp-config-sample.php'));
  this.template('web/wp-config.php', path.join(this.props.web, 'wp-config.php'));
};

WordpressGenerator.prototype.setupProvisioning = function() {
  this.log.info('Creating provisioning scripts...');

  this.mkdir(path.join(this.env.cwd, 'bin'));
  this.template('bin/provision', 'bin/provision');

  this.mkdir(path.join(this.env.cwd, 'provisioning'));
  this.template('provisioning/localhost', 'provisioning/localhost');
  this.template('provisioning/local', 'provisioning/local');
  this.template('provisioning/staging', 'provisioning/staging');
  this.template('provisioning/production', 'provisioning/production');
  this.template('provisioning/provision.yml', 'provisioning/provision.yml');

  this.mkdir(path.join(this.env.cwd, 'provisioning', 'group_vars'));
  this.template('provisioning/group_vars/webservers', 'provisioning/group_vars/webservers');
};

WordpressGenerator.prototype.createSshKeys = function() {
  var done      = this.async();
  var location  = path.join(this.env.cwd, 'provisioning', 'files', 'ssh', 'id_rsa');

  this.log.info('Creating SSH keys...');

  this.mkdir(path.dirname(location));

  keygen({
    location: location,
    comment:  'deploy@' + this.props.domain,
    read: false
  }, done);
};

WordpressGenerator.prototype.fixPermissions = function() {
  fs.chmodSync(path.join(this.env.cwd, 'bin', 'provision'), '744');
  fs.chmodSync(path.join(this.env.cwd, 'provisioning', 'files', 'ssh', 'id_rsa'), '600');
};

WordpressGenerator.prototype.setupDeployment = function() {
  this.log.info('Creating deployment scripts...');

  this.mkdir(path.join(this.env.cwd, 'deployment'));
  this.mkdir(path.join(this.env.cwd, 'deployment', 'deploy'));

  this.template('deployment/deploy.rb', 'deployment/deploy.rb');
  this.template('deployment/stages/local.rb', 'deployment/stages/local.rb');
  this.template('deployment/stages/staging.rb', 'deployment/stages/staging.rb');
  this.template('deployment/stages/production.rb', 'deployment/stages/production.rb');
};

module.exports = WordpressGenerator;
<commit_msg>Refernce genesis/wordpress#~0.1*<commit_after>'use strict';

var util    = require('util');
var path    = require('path');
var yeoman  = require('yeoman-generator');
var latest  = require('github-latest');
var wrench  = require('wrench');
var async   = require('async');
var chalk   = require('chalk');
var crypto  = require('crypto');
var request = require('request');
var keygen  = require('ssh-keygen');
var fs      = require('fs');

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

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

  this.on('end', function() {
    this.installDependencies({
      bower:        true,
      npm:          false,
      skipInstall:  options['skip-install'],
      skipMessage:  true,
      callback:     function() {
        this.log.write();
        this.log.ok('All done! Run ' + chalk.yellow('vagrant up') + ' to get started!');
      }.bind(this)
    });
  });
};

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

WordpressGenerator.prototype.welcome = function() {
  var message = this.readFileAsString(path.join(__dirname, 'welcome.txt'));

  message = message.replace(/./g, function(match) {
    return /\w/.test(match) ? chalk.yellow(match) : chalk.cyan(match);
  });

  this.log.writeln(message);
};

WordpressGenerator.prototype.promptForName = function() {
  var existing = function() {
    try {
      var bower = JSON.parse(this.readFileAsString(path.join(this.env.cwd, 'bower.json')));

      return bower.name;
    } catch(e) {};
  }.bind(this);

  this.prompts.push({
    required: true,
    type:     'text',
    name:     'name',
    message:  'Repository name (e.g. MySite)',
    default:  function() {
      return existing() || path.basename(this.env.cwd);
    }.bind(this)
  });
};

WordpressGenerator.prototype.promptForDomain = function() {
  this.prompts.push({
    required: true,
    type:     'text',
    name:     'domain',
    message:  'Domain name (e.g. mysite.com)',
    default:  path.basename(this.env.cwd).toLowerCase(),
    validate: function(input) {
      if (/^[\w-]+\.\w+$/.test(input)) {
        return true;
      } else if (!input) {
        return "Domain is required";
      }

      return chalk.yellow(input) + ' does not match the example';
    }
  });
};

WordpressGenerator.prototype.promptForGenesis = function() {
  this.prompts.push({
    type:     'text',
    name:     'genesis',
    message:  'Genesis library version',
    default:  '~0.1.*'
  });
};

WordpressGenerator.prototype.promptForWeb = function() {
  this.prompts.push({
    type:     'text',
    name:     'web',
    message:  'WordPress directory',
    default:  'web'
  });
};

WordpressGenerator.prototype.promptForWordPress = function() {
  var existing = function(web) {
    try {
      var file    = this.readFileAsString(path.join(web, 'wp-includes', 'version.php'));
      var version = file.match(/\$wp_version\s=\s['"]([^'"]+)/);

      if (version.length) {
        return version[1];
      }
    } catch(e) {}
  }.bind(this);

  this.prompts.push({
    type:     'text',
    name:     'wordpress',
    message:  'WordPress version',
    default:  function(answers) {
      return existing(answers.web) || '3.6.1';
    }
  });
};

WordpressGenerator.prototype.promptForDatabase = function() {
  var done      = this.async();
  var existing  = function(web, constant) {
    try {
      var config = this.readFileAsString(path.join(web, 'wp-config.php'));
      var regex   = new RegExp(constant + '[\'"],\\s*[\'"]([^\'"]+)');
      var matches = regex.exec(config);

      return matches && matches[1];
    } catch(e) {}
  }.bind(this);

  crypto.randomBytes(12, function(err, buffer) {
    this.prompts.push({
      type:     'text',
      name:     'DB_NAME',
      message:  'Database name',
      default:  function(answers) { return existing(answers.web, 'DB_NAME') || 'wordpress'; }
    });

    this.prompts.push({
      type:     'text',
      name:     'DB_USER',
      message:  'Database user',
      default:  function(answers) { return existing(answers.web, 'DB_USER') || 'wordpress'; }
    });

    this.prompts.push({
      type:     'text',
      name:     'DB_PASSWORD',
      message:  'Database password',
      default:  function(answers) { return existing(answers.web, 'DB_PASSWORD') || buffer.toString('base64'); }
    });

    this.prompts.push({
      type:     'text',
      name:     'DB_HOST',
      message:  'Database host',
      default:  function(answers) { return existing(answers.web, 'DB_HOST') || 'localhost'; }
    });

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

WordpressGenerator.prototype.promptForIp = function() {
  // Private IP blocks
  var blocks = [
    ['192.168.0.0', '192.168.255.255'],
    ['172.16.0.0',  '172.31.255.255'],
    ['10.0.0.0',    '10.255.255.255']
  ];

  // Long IP ranges
  var ranges = blocks.map(function(block) {
    return block.map(function(ip) {
      var parts = ip.split('.');

      return parts[0] << 24 | parts[1] << 16 | parts[2] << 8 | parts[3] >>> 0;
    });
  });

  // Randomize IP addresses
  var ips = ranges.map(function(range) {
    return Math.random() * (range[1] - range[0]) + range[0];
  }).map(function(ip) {
    return [
      (ip & (0xff << 24)) >>> 24,
      (ip & (0xff << 16)) >>> 16,
      (ip & (0xff << 8)) >>> 8,
      (ip & (0xff << 0)) >>> 0
    ].join('.');
  });

  try {
    var vagrant = this.readFileAsString('Vagrantfile').match(/ip:\s['"]([\d\.]+)['"]/);

    if (vagrant.length) {
      ips.unshift(vagrant[1]);
    }
  } catch(e) {}

  this.prompts.push({
    required: true,
    type:     'list',
    name:     'ip',
    message:  'Vagrant IP',
    pattern:  /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,
    choices:  ips
  });
};

WordpressGenerator.prototype.ask = function() {
  var done = this.async();

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

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

WordpressGenerator.prototype.ready = function() {
  this.log.write('\n');
  this.log.info(chalk.green('Here we go!'));
};

WordpressGenerator.prototype.writeProjectFiles = function() {
  this.log.info('Writing project files...');

  try {
    this.readmeFile = this.readFileAsString(path.join(this.env.cwd, 'README.md'));
  } catch(e) {
    this.readmeFile = '';
  }

  this.template('gitignore',   '.gitignore');
  this.template('bower.json',   'bower.json');
  this.template('Capfile',      'Capfile');
  this.template('editorconfig', '.editorconfig');
  this.template('README.md',    'README.md');
  this.template('Vagrantfile',  'Vagrantfile');
};

WordpressGenerator.prototype.writeWordPress = function() {
  var done = this.async();

  this.log.info('Downloading WordPress...');

  this.remote('wordpress', 'wordpress', this.props.wordpress, function(err, remote) {
    this.log.info('Writing WordPress to ' + chalk.yellow(this.props.web));

    wrench.copyDirSyncRecursive(remote.cachePath, this.props.web);

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

WordpressGenerator.prototype.writeWeb = function() {
  this.log.info('Writing ' + chalk.yellow(this.props.web) + ' files...');

  try {
    this.htaccessFile = this.readFileAsString(path.join(this.env.cwd, this.props.web, '.htaccess'));
  } catch(e) {
    this.htaccessFile = '';
  }

  this.template('web/htaccess',      path.join(this.props.web, '.htaccess'));
  this.template('web/no_robots.txt',  path.join(this.props.web, 'no_robots.txt'));
  this.template('web/robots.txt',     path.join(this.props.web, 'robots.txt'));
};

WordpressGenerator.prototype.fetchSalts = function() {
  var done = this.async();

  request('https://api.wordpress.org/secret-key/1.1/salt/', function(err, response, salts) {
    if (err) {
      throw err;
    }

    this.props.salts = salts;
    done();
  }.bind(this));
};

WordpressGenerator.prototype.setupWordPressConfig = function() {
  this.log.info('Configuring ' + chalk.yellow('wp-config.php'));

  this.wpConfigFile = this.readFileAsString(path.join(this.env.cwd, this.props.web, 'wp-config-sample.php'));
  this.template('web/wp-config.php', path.join(this.props.web, 'wp-config.php'));
};

WordpressGenerator.prototype.setupProvisioning = function() {
  this.log.info('Creating provisioning scripts...');

  this.mkdir(path.join(this.env.cwd, 'bin'));
  this.template('bin/provision', 'bin/provision');

  this.mkdir(path.join(this.env.cwd, 'provisioning'));
  this.template('provisioning/localhost', 'provisioning/localhost');
  this.template('provisioning/local', 'provisioning/local');
  this.template('provisioning/staging', 'provisioning/staging');
  this.template('provisioning/production', 'provisioning/production');
  this.template('provisioning/provision.yml', 'provisioning/provision.yml');

  this.mkdir(path.join(this.env.cwd, 'provisioning', 'group_vars'));
  this.template('provisioning/group_vars/webservers', 'provisioning/group_vars/webservers');
};

WordpressGenerator.prototype.createSshKeys = function() {
  var done      = this.async();
  var location  = path.join(this.env.cwd, 'provisioning', 'files', 'ssh', 'id_rsa');

  this.log.info('Creating SSH keys...');

  this.mkdir(path.dirname(location));

  keygen({
    location: location,
    comment:  'deploy@' + this.props.domain,
    read: false
  }, done);
};

WordpressGenerator.prototype.fixPermissions = function() {
  fs.chmodSync(path.join(this.env.cwd, 'bin', 'provision'), '744');
  fs.chmodSync(path.join(this.env.cwd, 'provisioning', 'files', 'ssh', 'id_rsa'), '600');
};

WordpressGenerator.prototype.setupDeployment = function() {
  this.log.info('Creating deployment scripts...');

  this.mkdir(path.join(this.env.cwd, 'deployment'));
  this.mkdir(path.join(this.env.cwd, 'deployment', 'deploy'));

  this.template('deployment/deploy.rb', 'deployment/deploy.rb');
  this.template('deployment/stages/local.rb', 'deployment/stages/local.rb');
  this.template('deployment/stages/staging.rb', 'deployment/stages/staging.rb');
  this.template('deployment/stages/production.rb', 'deployment/stages/production.rb');
};

module.exports = WordpressGenerator;
<|endoftext|>


<commit_before>"use strict";

var config = require('../config'),
    helpers = require('../helpers'),
    Request = require('../request'),
    printer = require('../printer'),
    fetch = require('node-fetch'),
    chalk = require('chalk'),
    Promise = require('es6-promise').Promise;

//TODO handle case sensitivity in yml keys
//TODO handle missing yml keys/values
//TODO pass in config as arg to exec from commmand?
class RequestCommand {

  constructor(program) {
      this._program = program;
      this._queue = [];
  }

  exec() {

      this._queue = this._createRequestQueue();

      this._executeRequests().then(() => {

          if (this._program.info) {
            console.log(chalk.white.underline('stats:'));
            console.log(JSON.stringify(this._stats, null, 4));
          }

      });
  }

  _createRequestQueue() {

      var env = config.envs[this._program.env || 'default'] || config.envs.default;

      return this._program.args.reduce((queue, curr) => {

          if (!config.requests[curr]) {
              console.log(`[info] request \"${curr}\" not found in requests.yml. Skipping.`);
              return queue;
          };

          queue.push(
            new Request(
              curr,
              config.requests[curr],
              { env: env, query: this._program.query })
          );

          return queue;

      }, []);
  }

  _executeRequests() {
      if  (this._program.async) {
          return this._executeRequestsAsync();
      } else {
          return this._executeRequestsSync();
      }
  }

  _executeRequestsSync() {

      return this._queue.reduce((sequence, request) => {

          return sequence.then(() => {

              request.start = process.hrtime();

              return fetch(request.url, request.config);

          }).then((resp) => {

              request.end = process.hrtime(request.start);

              return this._processResponse(request, resp);

          }).catch((e) => console.log(e));

      }, Promise.resolve());
  }

  _executeRequestsAsync() {

      var requestPromises = [];

      this._queue.reduce((requests, request) => {

        request.start = process.hrtime();

          var requestPromise = fetch(request.url, request.config)
              .then((resp) => {

                request.end = process.hrtime(request.start);

                  this._processResponse(request, resp);

              }).catch((e) => console.log(e));

          requestPromises.push(requestPromise);

      }, requestPromises);

      return Promise.all(requestPromises);
  }

  _processResponse(request, resp) {

      var retrieveMethod = resp.headers.get('content-type') === 'application/json' ?
          'json' :
          'text';

      return resp[retrieveMethod]().then((data) => {
          printer.printRequestInfo(this._program, request, resp, data);
      });
  }

}

module.exports = RequestCommand;
<commit_msg>remove unneeded comments<commit_after>"use strict";

var config = require('../config'),
    helpers = require('../helpers'),
    Request = require('../request'),
    printer = require('../printer'),
    fetch = require('node-fetch'),
    chalk = require('chalk'),
    Promise = require('es6-promise').Promise;

class RequestCommand {

  constructor(program) {
      this._program = program;
      this._queue = [];
  }

  exec() {

      this._queue = this._createRequestQueue();

      this._executeRequests().then(() => {

          if (this._program.info) {
            console.log(chalk.white.underline('stats:'));
            console.log(JSON.stringify(this._stats, null, 4));
          }

      });
  }

  _createRequestQueue() {

      var env = config.envs[this._program.env || 'default'] || config.envs.default;

      return this._program.args.reduce((queue, curr) => {

          if (!config.requests[curr]) {
              console.log(`[info] request \"${curr}\" not found in requests.yml. Skipping.`);
              return queue;
          };

          queue.push(
            new Request(
              curr,
              config.requests[curr],
              { env: env, query: this._program.query })
          );

          return queue;

      }, []);
  }

  _executeRequests() {
      if  (this._program.async) {
          return this._executeRequestsAsync();
      } else {
          return this._executeRequestsSync();
      }
  }

  _executeRequestsSync() {

      return this._queue.reduce((sequence, request) => {

          return sequence.then(() => {

              request.start = process.hrtime();

              return fetch(request.url, request.config);

          }).then((resp) => {

              request.end = process.hrtime(request.start);

              return this._processResponse(request, resp);

          }).catch((e) => console.log(e));

      }, Promise.resolve());
  }

  _executeRequestsAsync() {

      var requestPromises = [];

      this._queue.reduce((requests, request) => {

        request.start = process.hrtime();

          var requestPromise = fetch(request.url, request.config)
              .then((resp) => {

                request.end = process.hrtime(request.start);

                  this._processResponse(request, resp);

              }).catch((e) => console.log(e));

          requestPromises.push(requestPromise);

      }, requestPromises);

      return Promise.all(requestPromises);
  }

  _processResponse(request, resp) {

      var retrieveMethod = resp.headers.get('content-type') === 'application/json' ?
          'json' :
          'text';

      return resp[retrieveMethod]().then((data) => {
          printer.printRequestInfo(this._program, request, resp, data);
      });
  }

}

module.exports = RequestCommand;
<|endoftext|>


<commit_before>#!/usr/bin/env node
const AbstractApplication = require('@jeneric/core/app/abstract-application');
const config = require('./config/config.js');

class Main extends AbstractApplication {

    constructor(config) {
        super(config);
    }

    start() {

        this.say('Systeme erfolgreich gestartet.');

        setInterval(this.loop.bind(this), 5000);
        this.logger.info('application started');

    }

    loop() {

        this.logger.debug('loop ' + Date.now());

    }

    say(message) {
        return this.services.speaker.say(message);
    }
}

new Main(config);
<commit_msg>remove start method<commit_after>#!/usr/bin/env node
const AbstractApplication = require('@jeneric/core/app/abstract-application');
const config = require('./config/config.js');

class Main extends AbstractApplication {

    constructor(config) {
        super(config);

        this.say('Systeme erfolgreich gestartet.');

        setInterval(this.loop.bind(this), 5000);
        this.logger.info('application started');

    }

    loop() {

        this.logger.debug('loop ' + Date.now());

    }

    say(message) {
        return this.services.speaker.say(message);
    }
}

new Main(config);
<|endoftext|>


<commit_before>/** @namespace Base32 encoding/decoding */
sjcl.codec.base32 = {
	/** The base32 alphabet.
	* @private
	*/
	_chars: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",

	/** Convert from a bitArray to a base32 string. */
	fromBits: function (arr, _noEquals) {
		var out = "", i, bits=0, c = sjcl.codec.base32._chars, ta=0, bl = sjcl.bitArray.bitLength(arr);
		for (i=0; out.length * 5 < bl; ) {
			out += c.charAt((ta ^ arr[i]>>>bits) >>> 27);
			if (bits < 5) {
				ta = arr[i] << (5-bits);
				bits += 27;
				i++;
			} else {
				ta <<= 5;
				bits -= 5;
			}
		}
		while (out.length % 8 && !_noEquals) { out += "="; }
		return out;
	},

	/** Convert from a base32 string to a bitArray */
	toBits: function(str) {
		str = str.replace(/\s|=/g,'');
		var out = [], i, bits=0, c = sjcl.codec.base32._chars, ta=0, x;
		for (i=0; i<str.length; i++) {
			x = c.indexOf(str.charAt(i));
			if (x < 0) {
				throw new sjcl.exception.invalid("this isn't base32!");
			}
			if (bits > 27) {
				bits -= 27;
				out.push(ta ^ x>>>bits);
				ta  = x << (32-bits);
			} else {
				bits += 5;
				ta ^= x << (32-bits);
			}
		}
		if (bits&56) {
			out.push(sjcl.bitArray.partial(bits&56, ta, 1));
		}
		return out;
	}
};
<commit_msg>style: tabs => spaces<commit_after>/** @namespace Base32 encoding/decoding */
sjcl.codec.base32 = {
  /** The base32 alphabet.
  * @private
  */
  _chars: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",

  /** Convert from a bitArray to a base32 string. */
  fromBits: function (arr, _noEquals) {
    var out = "", i, bits=0, c = sjcl.codec.base32._chars, ta=0, bl = sjcl.bitArray.bitLength(arr);
    for (i=0; out.length * 5 < bl; ) {
      out += c.charAt((ta ^ arr[i]>>>bits) >>> 27);
      if (bits < 5) {
        ta = arr[i] << (5-bits);
        bits += 27;
        i++;
      } else {
        ta <<= 5;
        bits -= 5;
      }
    }
    while (out.length % 8 && !_noEquals) { out += "="; }
    return out;
  },

  /** Convert from a base32 string to a bitArray */
  toBits: function(str) {
    str = str.replace(/\s|=/g,'');
    var out = [], i, bits=0, c = sjcl.codec.base32._chars, ta=0, x;
    for (i=0; i<str.length; i++) {
      x = c.indexOf(str.charAt(i));
      if (x < 0) {
        throw new sjcl.exception.invalid("this isn't base32!");
      }
      if (bits > 27) {
        bits -= 27;
        out.push(ta ^ x>>>bits);
        ta  = x << (32-bits);
      } else {
        bits += 5;
        ta ^= x << (32-bits);
      }
    }
    if (bits&56) {
      out.push(sjcl.bitArray.partial(bits&56, ta, 1));
    }
    return out;
  }
};
<|endoftext|>