<commit_before>'use strict';
var util = require('util');
var fs = require('fs');
var path = require('path');
var yeoman = require('yeoman-generator');
var _ = require('lodash');
var mout = require('mout');
var cordova = require('cordova');
var chalk = require('chalk');
var ionicUtils = require('../utils');

var IonicGenerator = module.exports = function IonicGenerator(args, options) {
  yeoman.generators.Base.apply(this, arguments);
  console.log(ionicUtils.greeting);

  this.argument('appName', { type: String, required: false });
  this.appName = this.appName || path.basename(process.cwd());
  this.appName = mout.string.pascalCase(this.appName);
  this.appId = 'com.example.' + this.appName;
  this.appPath = 'app';
  this.root = process.cwd();

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

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

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

IonicGenerator.prototype.askForCompass = function askForCompass() {
  var done = this.async();

  this.prompt([{
    type: 'confirm',
    name: 'compass',
    message: 'Would you like to use Sass with Compass (requires Ruby)?',
    default: false
  }], function (props) {
    this.compass = props.compass;

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

IonicGenerator.prototype.cordovaInit = function cordovaInit() {
  var done = this.async();
  cordova.create('.', this.appId, this.appName, function (error) {
    if (error) {
      console.log(chalk.yellow(error.message + ': Skipping `cordova create`'));
    } else {
      console.log(chalk.yellow('Created a new Cordova project with name "' + this.appName + '" and id "' + this.appId + '"'));
    }
    done();
  }.bind(this));
};

IonicGenerator.prototype.askForPlugins = function askForPlugins() {
  var done = this.async();

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

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

IonicGenerator.prototype.askForStarter = function askForStarter() {
  var done = this.async();

  this.prompt([{
    type: 'list',
    name: 'starter',
    message: 'Which starter template [T] or example app [A] would you like to use?',
    choices: _.pluck(ionicUtils.starters.templates, 'name')
  }], function (props) {
    this.starter = _.find(ionicUtils.starters.templates, { name: props.starter });
    done();
  }.bind(this));
};

IonicGenerator.prototype.installPlugins = function installPlugins() {
  console.log(chalk.yellow('\nInstall plugins registered at plugins.cordova.io: ') + chalk.green('grunt plugin:add:org.apache.cordova.globalization'));
  console.log(chalk.yellow('Or install plugins direct from source: ') + chalk.green('grunt plugin:add:https://github.com/apache/cordova-plugin-console.git\n'));
  if (this.plugins.length > 0) {
    console.log(chalk.yellow('Installing selected Cordova plugins, please wait.'));
    // Turns out plugin() doesn't accept a callback so we try/catch instead
    try {
      cordova.plugin('add', this.plugins);
    } catch (e) {
      console.log(e);
      this.log.error(chalk.red('Please run `yo ionic` in an empty directory, or in that of an already existing cordova project.'));
      process.exit(1);
    }
  }
};

IonicGenerator.prototype.installStarter = function installStarter() {
  console.log(chalk.yellow('Installing starter template. Please wait'));
  var done = this.async();

  this.remote(this.starter.user, this.starter.repo, 'master', function (error, remote) {
    if (error) {
      done(error);
    }
    remote.directory('app', 'app');
    this.starterCache = path.join(this.cacheRoot(), this.starter.user, this.starter.repo, 'master');
    done();
  }.bind(this), true);
};

IonicGenerator.prototype.setupEnv = function setupEnv() {
  // Copies the contents of the generator example app
  // directory into your users new application path
  this.sourceRoot(path.join(__dirname, '../templates/'));
  this.directory('common/root', '.', true);
};

IonicGenerator.prototype.readIndex = function readIndex() {
  this.indexFile = this.read(path.join(this.starterCache, 'index.html'));
};

IonicGenerator.prototype.appJs = function appJs() {
  var scripts = fs.readdirSync(path.join(process.cwd(), 'app/scripts'));
  scripts = _.map(scripts, function (script) {
    return 'scripts/' + script;
  });
  this.indexFile = this.appendScripts(this.indexFile, 'scripts/scripts.js', scripts);
};

IonicGenerator.prototype.createIndexHtml = function createIndexHtml() {
  this.indexFile = this.indexFile.replace(/'/g, "'");
  this.write(path.join(this.appPath, 'index.html'), this.indexFile);
};

IonicGenerator.prototype.copyStyles = function copyStyles() {
  var sass = this.compass;
  var mainFile = 'main.' + (sass ? 'sass' : 'css');

  // Only create a main style file if the starter template didn't
  // have any styles. In the case it does, the starter should
  // supply both main.css and main.sass files.
  if (_.isEmpty(this.expand('app/styles/main.*'))) {
    this.copy('styles/' + mainFile, 'app/styles/' + mainFile);
  }
};

IonicGenerator.prototype.packageFiles = function packageFiles() {
  this.template('common/_bower.json', 'bower.json');
  this.template('common/_bowerrc', '.bowerrc');
  this.template('common/_package.json', 'package.json');
  this.template('common/Gruntfile.js', 'Gruntfile.js');
  this.template('common/_gitignore', '.gitignore');
};

IonicGenerator.prototype.testFiles = function testFiles() {
  this.template('spec/controllers.js', 'test/spec/controllers.js');
};
<commit_msg>fix(generator): Fix broken template reference in index.html by running it through Yeoman engine<commit_after>'use strict';
var util = require('util');
var fs = require('fs');
var path = require('path');
var yeoman = require('yeoman-generator');
var _ = require('lodash');
var mout = require('mout');
var cordova = require('cordova');
var chalk = require('chalk');
var ionicUtils = require('../utils');

var IonicGenerator = module.exports = function IonicGenerator(args, options) {
  yeoman.generators.Base.apply(this, arguments);
  console.log(ionicUtils.greeting);

  this.argument('appName', { type: String, required: false });
  this.appName = this.appName || path.basename(process.cwd());
  this.appName = mout.string.pascalCase(this.appName);
  this.appId = 'com.example.' + this.appName;
  this.appPath = 'app';
  this.root = process.cwd();

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

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

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

IonicGenerator.prototype.askForCompass = function askForCompass() {
  var done = this.async();

  this.prompt([{
    type: 'confirm',
    name: 'compass',
    message: 'Would you like to use Sass with Compass (requires Ruby)?',
    default: false
  }], function (props) {
    this.compass = props.compass;

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

IonicGenerator.prototype.cordovaInit = function cordovaInit() {
  var done = this.async();
  cordova.create('.', this.appId, this.appName, function (error) {
    if (error) {
      console.log(chalk.yellow(error.message + ': Skipping `cordova create`'));
    } else {
      console.log(chalk.yellow('Created a new Cordova project with name "' + this.appName + '" and id "' + this.appId + '"'));
    }
    done();
  }.bind(this));
};

IonicGenerator.prototype.askForPlugins = function askForPlugins() {
  var done = this.async();

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

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

IonicGenerator.prototype.askForStarter = function askForStarter() {
  var done = this.async();

  this.prompt([{
    type: 'list',
    name: 'starter',
    message: 'Which starter template [T] or example app [A] would you like to use?',
    choices: _.pluck(ionicUtils.starters.templates, 'name')
  }], function (props) {
    this.starter = _.find(ionicUtils.starters.templates, { name: props.starter });
    done();
  }.bind(this));
};

IonicGenerator.prototype.installPlugins = function installPlugins() {
  console.log(chalk.yellow('\nInstall plugins registered at plugins.cordova.io: ') + chalk.green('grunt plugin:add:org.apache.cordova.globalization'));
  console.log(chalk.yellow('Or install plugins direct from source: ') + chalk.green('grunt plugin:add:https://github.com/apache/cordova-plugin-console.git\n'));
  if (this.plugins.length > 0) {
    console.log(chalk.yellow('Installing selected Cordova plugins, please wait.'));
    // Turns out plugin() doesn't accept a callback so we try/catch instead
    try {
      cordova.plugin('add', this.plugins);
    } catch (e) {
      console.log(e);
      this.log.error(chalk.red('Please run `yo ionic` in an empty directory, or in that of an already existing cordova project.'));
      process.exit(1);
    }
  }
};

IonicGenerator.prototype.installStarter = function installStarter() {
  console.log(chalk.yellow('Installing starter template. Please wait'));
  var done = this.async();

  this.remote(this.starter.user, this.starter.repo, 'master', function (error, remote) {
    if (error) {
      done(error);
    }
    remote.directory('app', 'app');
    this.starterCache = path.join(this.cacheRoot(), this.starter.user, this.starter.repo, 'master');
    done();
  }.bind(this), true);
};

IonicGenerator.prototype.setupEnv = function setupEnv() {
  // Copies the contents of the generator example app
  // directory into your users new application path
  this.sourceRoot(path.join(__dirname, '../templates/'));
  this.directory('common/root', '.', true);
};

IonicGenerator.prototype.readIndex = function readIndex() {
  this.indexFile = this.engine(this.read(path.join(this.starterCache, 'index.html')), this);
};

IonicGenerator.prototype.appJs = function appJs() {
  var scripts = fs.readdirSync(path.join(process.cwd(), 'app/scripts'));
  scripts = _.map(scripts, function (script) {
    return 'scripts/' + script;
  });
  this.indexFile = this.appendScripts(this.indexFile, 'scripts/scripts.js', scripts);
};

IonicGenerator.prototype.createIndexHtml = function createIndexHtml() {
  this.indexFile = this.indexFile.replace(/'/g, "'");
  this.write(path.join(this.appPath, 'index.html'), this.indexFile);
};

IonicGenerator.prototype.copyStyles = function copyStyles() {
  var sass = this.compass;
  var mainFile = 'main.' + (sass ? 'sass' : 'css');

  // Only create a main style file if the starter template didn't
  // have any styles. In the case it does, the starter should
  // supply both main.css and main.sass files.
  if (_.isEmpty(this.expand('app/styles/main.*'))) {
    this.copy('styles/' + mainFile, 'app/styles/' + mainFile);
  }
};

IonicGenerator.prototype.packageFiles = function packageFiles() {
  this.template('common/_bower.json', 'bower.json');
  this.template('common/_bowerrc', '.bowerrc');
  this.template('common/_package.json', 'package.json');
  this.template('common/Gruntfile.js', 'Gruntfile.js');
  this.template('common/_gitignore', '.gitignore');
};

IonicGenerator.prototype.testFiles = function testFiles() {
  this.template('spec/controllers.js', 'test/spec/controllers.js');
};
<|endoftext|>


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

var GeneratorJaderGenerator = module.exports = function GeneratorJaderGenerator(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(GeneratorJaderGenerator, yeoman.generators.Base);

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

  // have Yeoman greet the user.
  console.log(this.yeoman);
  var prompts = [{
    type: 'confirm',
    name: 'someOption',
    message: 'Would you like to enable this option?',
    default: true
  },{
  name: 'projectName',
  message: 'What do you call your project?'
},{
  name: 'gitUser',
  message: 'Please enter your gitUserName, if you have one.'
}];

  this.prompt(prompts, function (props) {
    //this.someOption = props.someOption;
    this.projectName = props.projectName;
    this.gitUser = props.gitUser;
    cb();
  }.bind(this));
};

GeneratorJaderGenerator.prototype.askForModules = function askForModules() {
  var cb = this.async();

  var prompts = [{
    type: 'checkbox',
    name: 'modules',
    message: 'Which modules would you like to include?',
    choices: [{
      value: 'jadeModule',
      name: 'jade',
      checked: true
    }, {
      value: 'stylusModule',
      name: 'stylus',
      checked: true
    }]
  }];

  this.prompt(prompts, function (props) {
    var hasMod = function (mod) { return props.modules.indexOf(mod) !== -1; };
    this.jadeModule = hasMod('jadeModule');
    this.stylusModule = hasMod('stylusModule');
    cb();
  }.bind(this));
};

GeneratorJaderGenerator.prototype.app = function app() {
  this.mkdir('app');
  this.mkdir('app/views');
  this.mkdir('app/public');
  this.mkdir('app/public/css');
  this.mkdir('app/public/js');
  this.mkdir('app/public/assets');
  this.mkdir('app/styles');

  this.template('Gruntfile.js', 'Gruntfile.js');

  this.template('_package.json', 'package.json');
  this.template('_bower.json', 'bower.json');
};

GeneratorJaderGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');
};
<commit_msg>Useless promt remove<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var GeneratorJaderGenerator = module.exports = function GeneratorJaderGenerator(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(GeneratorJaderGenerator, yeoman.generators.Base);

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

  // have Yeoman greet the user.
  console.log(this.yeoman);
  var prompts = [
  // {
  //   type: 'confirm',
  //   name: 'someOption',
  //   message: 'Would you like to enable this option?',
  //   default: true
  // },
  {
  name: 'projectName',
  message: 'What do you call your project?'
},{
  name: 'gitUser',
  message: 'Please enter your gitUserName, if you have one.'
}];

  this.prompt(prompts, function (props) {
    //this.someOption = props.someOption;
    this.projectName = props.projectName;
    this.gitUser = props.gitUser;
    cb();
  }.bind(this));
};

GeneratorJaderGenerator.prototype.askForModules = function askForModules() {
  var cb = this.async();

  var prompts = [{
    type: 'checkbox',
    name: 'modules',
    message: 'Which modules would you like to include?',
    choices: [{
      value: 'jadeModule',
      name: 'jade',
      checked: true
    }, {
      value: 'stylusModule',
      name: 'stylus',
      checked: true
    }]
  }];

  this.prompt(prompts, function (props) {
    var hasMod = function (mod) { return props.modules.indexOf(mod) !== -1; };
    this.jadeModule = hasMod('jadeModule');
    this.stylusModule = hasMod('stylusModule');
    cb();
  }.bind(this));
};

GeneratorJaderGenerator.prototype.app = function app() {
  this.mkdir('app');
  this.mkdir('app/views');
  this.mkdir('app/public');
  this.mkdir('app/public/css');
  this.mkdir('app/public/js');
  this.mkdir('app/public/assets');
  this.mkdir('app/styles');

  this.template('Gruntfile.js', 'Gruntfile.js');

  this.template('_package.json', 'package.json');
  this.template('_bower.json', 'bower.json');
};

GeneratorJaderGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');
};
<|endoftext|>


<commit_before>var exphbs = require("express-handlebars");
var express = require("express");
var favicon = require("serve-favicon");
var Handlebars = require("Handlebars");
var htmlToMarkdown = require("html-to-markdown");
var logger = require("./logger");
var morgan = require("morgan");
var path = require("path");

// For accessing public, views, and other sibling directories.
var ROOT_PATH = path.resolve(path.join(__dirname, ".."));

var app = express();

app.engine(".hbs", exphbs({
    extname: ".hbs",
    defaultLayout: false,
    helpers: {
        toJSON: function (object) {
            return new Handlebars.SafeString(JSON.stringify(object));
        },
    },
}));
app.set("view engine", ".hbs");
app.set("views", path.join(ROOT_PATH, "views"));

app.use(favicon(path.join(ROOT_PATH, "public", "favicon.ico")));
app.use(morgan("dev"));

// TODO: Setup proxy that
// * sniffs domain and makes guesses about filter
// * Makes GET request to remote page.
// * Returns the markdown in a minimal JSON object.
// * Return manageable errors and log on server side.
// * TODO Part 2: show in a client
// app.get("/api/fetch", function(req, res) {
//     var u = req.query.u; // url
//     if (u) {
//         htmlToMarkdown.fetch(u, "wikipedia", function(err, content) {
//             if (err || !content) {
//                 logger.error("Could not retrieve content from:", u, "with error:", err);
//                 res.send(404).send({
//                     error: "Could not retrieve content."
//                 });
//             } else {
//                 logger.debug("fetched content from:", u);
//                 res.send({
//                     content: content
//                 });
//             }
//         });
//     } else {
//         res.status(401).send({
//             error: "'u'rl querystring parameter required."
//         });
//     }
// });

app.get("/", function (req, res) {
    var u = req.query.u;

    // This is going to get nasty really quick, but for now...
    var filterGuesser = function (u) {
        if (/\.wikipedia\./.test(u)) {
            return "wikipedia";
        } else {
            return "normal";
        }
    };

    if (u) {
        var filter = filterGuesser(u);
        htmlToMarkdown.fetch(u, filter, function (err, content) {
            // Send no matter what, but log output. The client should
            // handle presence or lack of content and not care about
            // the URL.
            if (err) {
                logger.error("Could not retrieve content from:", u, "with error:", err);
            } else {
                logger.debug("fetched content from:", u, "using filter:", filter);
            }

            res.render("reader", {
                bootstrap: {
                    content: content,
                },
            });
        });
    } else {
        res.render("reader", {
            bootstrap: {
                content: "",
            },
        });
    }
});

app.use(express.static(path.join(ROOT_PATH, "public")));

module.exports = app;
<commit_msg>Fixes #7<commit_after>var exphbs = require("express-handlebars");
var express = require("express");
var favicon = require("serve-favicon");
var Handlebars = require("Handlebars");
var htmlToMarkdown = require("html-to-markdown");
var logger = require("./logger");
var morgan = require("morgan");
var path = require("path");

// For accessing public, views, and other sibling directories.
var ROOT_PATH = path.resolve(path.join(__dirname, ".."));

var app = express();

app.engine(".hbs", exphbs({
    extname: ".hbs",
    defaultLayout: false,
    helpers: {
        toJSON: function (object) {
            return new Handlebars.SafeString(JSON.stringify(object));
        },
    },
}));
app.set("view engine", ".hbs");
app.set("views", path.join(ROOT_PATH, "views"));

app.use(favicon(path.join(ROOT_PATH, "public", "favicon.ico")));
app.use(morgan("dev"));

// HTML page content ends up on the bootstrap.
app.use(function(req, res, next) {
    res.locals.bootstrap = {};
    next();
});

// All incoming requests might have a u query string parameter.
// If they do, we will attempt to retrieve the contents at the URL.
app.use(function(req, res, next) {
    var u = req.query.u;

    // This is going to get nasty really quick, but for now...
    var filterGuesser = function (u) {
        if (/\.wikipedia\./.test(u)) {
            return "wikipedia";
        } else {
            return "normal";
        }
    };

    if (u) {
        var filter = filterGuesser(u);
        htmlToMarkdown.fetch(u, filter, function (err, content) {
            // Send no matter what, but log output. The client should
            // handle presence or lack of content and not care about
            // the URL.
            if (err) {
                logger.error("Could not retrieve content from:", u, "with error:", err);
            } else {
                logger.debug("fetched content from:", u, "using filter:", filter);
            }

            res.locals.bootstrap.content = content;
            next();
        });
    } else {
        next();
    }
});

// TODO: Setup proxy that
// * sniffs domain and makes guesses about filter
// * Makes GET request to remote page.
// * Returns the markdown in a minimal JSON object.
// * Return manageable errors and log on server side.
// app.get("/api/fetch", function(req, res) {
//     var u = req.query.u; // url
//     if (u) {
//         htmlToMarkdown.fetch(u, "wikipedia", function(err, content) {
//             if (err || !content) {
//                 logger.error("Could not retrieve content from:", u, "with error:", err);
//                 res.send(404).send({
//                     error: "Could not retrieve content."
//                 });
//             } else {
//                 logger.debug("fetched content from:", u);
//                 res.send({
//                     content: content
//                 });
//             }
//         });
//     } else {
//         res.status(401).send({
//             error: "'u'rl querystring parameter required."
//         });
//     }
// });

app.get("/", function (req, res) {
    res.render("reader");
});

app.use(express.static(path.join(ROOT_PATH, "public")));

module.exports = app;
<|endoftext|>


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

var chalk = require('chalk');
var exec = require('child_process').exec;
var fs = require('fs');

function oneline(str) {
  return str.replace(/\n/g, '');
}

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

  this.distDir = options.dist || 'dist';

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

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

AppfogGenerator.prototype.checkInstallation = function checkInstallation() {
  var done = this.async();
  exec('af --version', function (err) {
    if (err) {
      this.log.error('You don\'t have the AppFog command line tool installed. ' +
          'Grab it from https://docs.appfog.com/getting-started/af-cli\n' + err);
    }
    done();
  }.bind(this));
};

AppfogGenerator.prototype.nodestatic = function nodestatic() {
  this.mkdir('appfog');

  this.copy('Procfile', 'appfog/Procfile');
  this.copy('server.js', 'appfog/server.js');
};

AppfogGenerator.prototype.distpackage = function distpackage() {
  var pkgPath = path.resolve('package.json');
  var pkg = {};

  if (fs.existsSync(pkgPath)) {
    pkg = JSON.parse(this.readFileAsString('package.json'));
  }

  var distPkg = {
    name: pkg.name || 'unnammed',
    version: pkg.version || '0.0.0',
    dependencies: {
      'statik': '~1.2.5'
    }
  };

  this.write('appfog/distpackage.json', JSON.stringify(distPkg, null, 2));
};

AppfogGenerator.prototype.rewiregrunt = function rewiregrunt() {
  var template = this.readFileAsString(path.join(__dirname, 'templates', 'copytemplate.js'));
  console.log(
    chalk.yellow('Please add this copy task rule to your Gruntfile: \n') +
    template
  );
};

AppfogGenerator.prototype.gitsetup = function gitsetup() {
  console.log(chalk.green('You\'re all set! Now go to ' +
      chalk.bold(this.distDir) + ' and run\n') +
      chalk.bold('  npm install && af push')
  );
}
<commit_msg>Add appfog/ into .gitignore<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var chalk = require('chalk');
var exec = require('child_process').exec;
var fs = require('fs');

function oneline(str) {
  return str.replace(/\n/g, '');
}

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

  this.distDir = options.dist || 'dist';

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

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

AppfogGenerator.prototype.checkInstallation = function checkInstallation() {
  var done = this.async();
  exec('af --version', function (err) {
    if (err) {
      this.log.error('You don\'t have the AppFog command line tool installed. ' +
          'Grab it from https://docs.appfog.com/getting-started/af-cli\n' + err);
    }
    done();
  }.bind(this));
};

AppfogGenerator.prototype.nodestatic = function nodestatic() {
  this.mkdir('appfog');

  this.copy('Procfile', 'appfog/Procfile');
  this.copy('server.js', 'appfog/server.js');
};

AppfogGenerator.prototype.distpackage = function distpackage() {
  var pkgPath = path.resolve('package.json');
  var pkg = {};

  if (fs.existsSync(pkgPath)) {
    pkg = JSON.parse(this.readFileAsString('package.json'));
  }

  var distPkg = {
    name: pkg.name || 'unnammed',
    version: pkg.version || '0.0.0',
    dependencies: {
      'statik': '~1.2.5'
    }
  };

  this.write('appfog/distpackage.json', JSON.stringify(distPkg, null, 2));
};

AppfogGenerator.prototype.gitignore = function gitignore() {
  var file = '.gitignore';

  function append(file, text) {
    fs.appendFile(file, text, function (err) {
      text = oneline(text);
      if (err) {
        this.log.error('Cannot append \'' + text + '\' into ' + file + '\n' + err);
        return;
      }
      console.log(chalk.green('  append ') + chalk.bold('\'' + text +
          '\' into ' + file));
    }.bind(this));
  }

  if (fs.existsSync(file)) {
    fs.readFile(file, { encoding: 'utf-8' }, function (err, data) {
      if (err) {
        this.log('Cannot open ' + file + ' for read\n' + err);
        return;
      }
      if (String(data).match(/^appfog[\/\n]?$/m) === null) {
        append(file, 'appfog/\n');
      }
    }.bind(this));
  } else {
    append(file, 'appfog/\n');
  }
}

AppfogGenerator.prototype.rewiregrunt = function rewiregrunt() {
  var template = this.readFileAsString(path.join(__dirname, 'templates', 'copytemplate.js'));
  console.log(
    chalk.yellow('Please add this copy task rule to your Gruntfile: \n') +
    template
  );
};

AppfogGenerator.prototype.gitsetup = function gitsetup() {
  console.log(chalk.green('You\'re all set! Now go to ' +
      chalk.bold(this.distDir) + ' and run\n') +
      chalk.bold('  npm install && af push')
  );
}
<|endoftext|>


<commit_before>var camelcase = require('camelcase');
var npmName = require('npm-name');
var path = require('path');
var yeoman = require('yeoman-generator');

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

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

    var prompts = [{
      name: 'name',
      message: 'Module Name',
      default: path.basename(process.cwd()),
    }, {
      type: 'confirm',
      name: 'pkgName',
      message: 'The name above already exists on npm, choose another?',
      default: true,
      when: function(answers) {
        var done = this.async();

        npmName(answers.name, function(err, available) {
          if (!available) {
            done(true);
            return;
          }

          done(false);
        });
      }
    }];

    this.prompt(prompts, function(props) {
      if (props.pkgName) {
        return this.askForModuleName();
      }
      this.name = props.name;
      this.camelCaseName = camelcase(this.name);
      done();
    }.bind(this));
  },

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

    var prompts = [{
      name: 'description',
      message: 'Description',
      default: 'The best module ever'
    }, {
      name: 'githubUsername',
      message: 'GitHub username or organization',
      default: 'kemitchell',
      store: true
    }, {
      name: 'keywords',
      message: 'keywords (comma to split)'
    }, {
      type: 'confirm',
      name: 'cli',
      message: 'Command-line interface'
    }];

    this.prompt(prompts, function(props) {
      this.repository = props.githubUsername + '/' + this.name + '.js';

      this.keywords = props.keywords
        .split(',')
        .map(function(element) {
          return element.trim();
        })
        .filter(function(element) {
          return element.length > 0;
        });

      this.props = props;

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

  app: function() {
    this.config.save();

    [
      'editorconfig',
      'gitattributes',
      'gitignore',
      'jscsrc',
      'jshintrc',
      'npmignore',
      'travis.yml'
    ]
      .forEach(function(dotfile) {
        this.copy(dotfile, '.' + dotfile);
      }.bind(this));

    [
      'README.md',
      'LICENSE'
    ]
      .forEach(function(file) {
        this.template(file, file);
      }.bind(this));

    if (this.props.cli) {
      this.mkdir('source');
      this.template('source/cli.js', 'source/cli.js');
      this.template('source/usage.txt', 'source/usage.txt');
      this.mkdir('bin');
      this.template('bin/cli', 'bin/' + this.name);
    }
  },

  projectfiles: function() {
    this.template('source/index.js', 'source/index.js');
    this.mkdir('test');
    this.template('test/module.test.js', 'test/module.test.js');
  },

  installDev: function() {
    this.npmInstall(
      [
        'covert',
        'fixpack',
        'jscs',
        'jsmd',
        'jshint',
        'tap'
      ],
      {saveDev: true}
    );
  },

  install: function() {
    if (this.props.cli) {
      this.npmInstall(['docopt'], {save: true});
    }
    this.installDependencies({
      bower: false,
      skipInstall: this.options['skip-install'],
      callback: function() {
        this.spawnCommand('./node_modules/.bin/fixpack');
      }.bind(this)
    });
  }
});
<commit_msg>optional Travis CI<commit_after>var camelcase = require('camelcase');
var npmName = require('npm-name');
var path = require('path');
var yeoman = require('yeoman-generator');

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

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

    var prompts = [{
      name: 'name',
      message: 'Module Name',
      default: path.basename(process.cwd()),
    }, {
      type: 'confirm',
      name: 'pkgName',
      message: 'The name above already exists on npm, choose another?',
      default: true,
      when: function(answers) {
        var done = this.async();

        npmName(answers.name, function(err, available) {
          if (!available) {
            done(true);
            return;
          }

          done(false);
        });
      }
    }];

    this.prompt(prompts, function(props) {
      if (props.pkgName) {
        return this.askForModuleName();
      }
      this.name = props.name;
      this.camelCaseName = camelcase(this.name);
      done();
    }.bind(this));
  },

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

    var prompts = [
      {
        name: 'description',
        message: 'Description',
        default: 'The best module ever'
      }, {
        name: 'githubUsername',
        message: 'GitHub username or organization',
        default: 'kemitchell',
        store: true
      }, {
        name: 'keywords',
        message: 'keywords (comma to split)'
      }, {
        type: 'confirm',
        name: 'cli',
        message: 'Command-line interface'
      }, {
        type: 'confirm',
        name: 'travis',
        message: 'Use Travis CI'
      }
    ];

    this.prompt(prompts, function(props) {
      this.repository = props.githubUsername + '/' + this.name + '.js';

      this.keywords = props.keywords
        .split(',')
        .map(function(element) {
          return element.trim();
        })
        .filter(function(element) {
          return element.length > 0;
        });

      this.props = props;

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

  app: function() {
    this.config.save();

    [
      'editorconfig',
      'gitattributes',
      'gitignore',
      'jscsrc',
      'jshintrc',
      'npmignore'
    ]
      .forEach(function(dotfile) {
        this.copy(dotfile, '.' + dotfile);
      }.bind(this));

    if (this.props.travis) {
      this.copy('travis.yml', '.travis.yml');
    }

    [
      'README.md',
      'LICENSE'
    ]
      .forEach(function(file) {
        this.template(file, file);
      }.bind(this));

    this.mkdir('source');

    if (this.props.cli) {
      this.template('source/cli.js', 'source/cli.js');
      this.template('source/usage.txt', 'source/usage.txt');
      this.mkdir('bin');
      this.template('bin/cli', 'bin/' + this.name);
    }
  },

  projectfiles: function() {
    this.template('source/index.js', 'source/index.js');
    this.mkdir('test');
    this.template('test/module.test.js', 'test/module.test.js');
  },

  installDev: function() {
    this.npmInstall(
      [
        'covert',
        'fixpack',
        'jscs',
        'jsmd',
        'jshint',
        'tap'
      ],
      {saveDev: true}
    );
  },

  install: function() {
    if (this.props.cli) {
      this.npmInstall(['docopt'], {save: true});
    }
    this.installDependencies({
      bower: false,
      skipInstall: this.options['skip-install'],
      callback: function() {
        this.spawnCommand('./node_modules/.bin/fixpack');
      }.bind(this)
    });
  }
});
<|endoftext|>


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

var appDirs = [
  'css',
  'fonts',
  'images',
  'images-imagemin',
  'includes',
  'js',
  'js/modules',
  'js/vendor',
  'pages',
  'sass',
  'sass/blocks',
  'ui-docs'
];

var appFiles = [
  { templateName: '_package.json', name: 'package.json' },
  { templateName: '_bower.json', name: 'bower.json' },
  { templateName: 'composer.json', name: 'composer.json' },
  { templateName: 'gitignore', name: '.gitignore' },
  { templateName: 'Gruntfile.js', name: 'Gruntfile.js' },
  { templateName: 'dploy.yaml', name: 'dploy.yaml' },
  { templateName: 'web.php', name: 'web.php' },

  { templateName: 'page-1.html', name: 'pages/page-1.html' },

  { templateName: 'main.scss', name: 'sass/main.scss' },
  { templateName: 'config.scss', name: 'sass/_config.scss' },
  { templateName: 'init.scss', name: 'sass/_init.scss' },
  { templateName: 'temp.scss', name: 'sass/_temp.scss' },

  { templateName: 'modules-main.js', name: 'js/modules/main.js' }
];

var componentChoices = [
  { name: 'almond', value: 'almond', checked: true },
  { name: 'chosen', value: 'chosen', checked: true },
  { name: 'handlebars', value: 'handlebars', checked: true },
  { name: 'html5shiv', value: 'html5shiv', checked: true },
  { name: 'jquery.syncHeight', value: 'jquerysyncHeight', checked: true },
  { name: 'jquery.ui', value: 'jqueryui', checked: true },
  { name: 'jquery-icheck', value: 'jqueryicheck', checked: true },
  { name: 'jquery-placeholder', value: 'jqueryplaceholder', checked: true },
  { name: 'modernizr', value: 'modernizr', checked: true },
  { name: 'requirejs', value: 'requirejs', checked: true },
  { name: 'respond', value: 'respond', checked: true },
  { name: 'sass-handy-mixins', value: 'sasshandymixins', checked: true },
  { name: 'selectivizr', value: 'selectivizr', checked: true },
  { name: 'strict-reset.css', value: 'strictresetcss', checked: true }
];

var FrontGenerator = module.exports = function FrontGenerator(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(FrontGenerator, yeoman.generators.Base);

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

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

  var prompts = [{
    type: 'input',
    name: 'appName',
    message: 'App name:',
    default: 'project'
  }, {
    type: 'checkbox',
    name: 'bowerComponents',
    message: 'Bower components (jquery already included):',
    choices: componentChoices
  }];

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

    var components = props.bowerComponents;

    function hasComponent(component) { return components.indexOf(component) !== -1; }

    // manually deal with the response, get back and store the results.
    // we change a bit this way of doing to automatically do this in the self.prompt() method.
    // this.jquery = hasComponent('jquery');
    // this.jqueryui = hasComponent('jqueryui');

    var value;
    var i;

    for (i = 0; i < componentChoices.length; ++i) {
      value = componentChoices[i].value;

      this[value] = hasComponent(value);
    };

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

FrontGenerator.prototype.app = function app() {
  var i, file;

  for (i = 0; i < appDirs.length; ++i) {
    this.mkdir(appDirs[i]);
  };

  for (i = 0; i < appFiles.length; ++i) {
    file = appFiles[i];

    this.copy(file.templateName, file.name);
  };
};

FrontGenerator.prototype.projectfiles = function projectfiles() {
  // this.copy('editorconfig', '.editorconfig');
  // this.copy('jshintrc', '.jshintrc');
};
<commit_msg>Generate views/ instead of includes/ & pages/<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var appDirs = [
  'css',
  'fonts',
  'images',
  'images-imagemin',
  'js',
  'js/modules',
  'js/vendor',
  'views',
  'sass',
  'sass/blocks',
  'ui-docs'
];

var appFiles = [
  { templateName: '_package.json', name: 'package.json' },
  { templateName: '_bower.json', name: 'bower.json' },
  { templateName: 'composer.json', name: 'composer.json' },
  { templateName: 'gitignore', name: '.gitignore' },
  { templateName: 'Gruntfile.js', name: 'Gruntfile.js' },
  { templateName: 'dploy.yaml', name: 'dploy.yaml' },
  { templateName: 'web.php', name: 'web.php' },

  { templateName: 'page-1.html', name: 'pages/page-1.html' },

  { templateName: 'main.scss', name: 'sass/main.scss' },
  { templateName: 'config.scss', name: 'sass/_config.scss' },
  { templateName: 'init.scss', name: 'sass/_init.scss' },
  { templateName: 'temp.scss', name: 'sass/_temp.scss' },

  { templateName: 'modules-main.js', name: 'js/modules/main.js' }
];

var componentChoices = [
  { name: 'almond', value: 'almond', checked: true },
  { name: 'chosen', value: 'chosen', checked: true },
  { name: 'handlebars', value: 'handlebars', checked: true },
  { name: 'html5shiv', value: 'html5shiv', checked: true },
  { name: 'jquery.syncHeight', value: 'jquerysyncHeight', checked: true },
  { name: 'jquery.ui', value: 'jqueryui', checked: true },
  { name: 'jquery-icheck', value: 'jqueryicheck', checked: true },
  { name: 'jquery-placeholder', value: 'jqueryplaceholder', checked: true },
  { name: 'modernizr', value: 'modernizr', checked: true },
  { name: 'requirejs', value: 'requirejs', checked: true },
  { name: 'respond', value: 'respond', checked: true },
  { name: 'sass-handy-mixins', value: 'sasshandymixins', checked: true },
  { name: 'selectivizr', value: 'selectivizr', checked: true },
  { name: 'strict-reset.css', value: 'strictresetcss', checked: true }
];

var FrontGenerator = module.exports = function FrontGenerator(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(FrontGenerator, yeoman.generators.Base);

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

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

  var prompts = [{
    type: 'input',
    name: 'appName',
    message: 'App name:',
    default: 'project'
  }, {
    type: 'checkbox',
    name: 'bowerComponents',
    message: 'Bower components (jquery already included):',
    choices: componentChoices
  }];

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

    var components = props.bowerComponents;

    function hasComponent(component) { return components.indexOf(component) !== -1; }

    // manually deal with the response, get back and store the results.
    // we change a bit this way of doing to automatically do this in the self.prompt() method.
    // this.jquery = hasComponent('jquery');
    // this.jqueryui = hasComponent('jqueryui');

    var value;
    var i;

    for (i = 0; i < componentChoices.length; ++i) {
      value = componentChoices[i].value;

      this[value] = hasComponent(value);
    };

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

FrontGenerator.prototype.app = function app() {
  var i, file;

  for (i = 0; i < appDirs.length; ++i) {
    this.mkdir(appDirs[i]);
  };

  for (i = 0; i < appFiles.length; ++i) {
    file = appFiles[i];

    this.copy(file.templateName, file.name);
  };
};

FrontGenerator.prototype.projectfiles = function projectfiles() {
  // this.copy('editorconfig', '.editorconfig');
  // this.copy('jshintrc', '.jshintrc');
};
<|endoftext|>


<commit_before>/*
    Inspired by https://github.com/assemble/generator-assemble/
    which is released under an MIT license
*/

'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var shell = require('shelljs');
var updateNotifier = require('update-notifier');
var metrics = require('famous-metrics');

var FamousGenerator = yeoman.generators.Base.extend({
  init: function () {
    var notifier = updateNotifier({
      packagePath: '../package.json',
      updateCheckInterval: 1
    });

    this.pkg = require('../package.json');

    /* This is unneccessary and gross... but stops you from having to update twice */
    if (notifier.update) {
      if (notifier.update.latest !== this.pkg.version) {
        notifier.notify();
        process.exit(1);
      }
    }
    if (!shell.which('git')) {
      this.log(chalk.red('(ERROR)') + ' It looks like you do not have git installed, please install it and try again.');
      process.exit(1);
    }

    this.description = this.pkg.description;

    this.option('init', {
      alias: 'i',
      desc: 'Force to prompt question and re-initialize of .yo-rc.json',
      type: String,
      defaults: false,
      required: false
    });

    this.init = this.options['init'] || this.options['i'] || false;

    this.on('end', function () {
      if (!this.options['skip-install']) {
        this.installDependencies({
          skipInstall: this.options['skip-install'] || this.options['s'],
          skipMessage: this.options['skip-welcome-message'] || this.options['w'],
          callback: function () {
            console.log('');
            console.log(chalk.green('Woot!') + ' It appears that everything installed correctly.');
            console.log('Please run the command ' + chalk.yellow('grunt serve') + ' to launch the development server.');
            console.log('');
          }
        });
      }
    });

    this.config.defaults({
      projectName: 'Famo.us Base',
      projectDesc: 'e.g. Seed project to get started with Famo.us',
      authorLogin: '',
      author: {
        name: this.user.git.username || process.env.user || process.env.username,
        email: this.user.git.email
      }
    });
  },

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

    // have Yeoman greet the user
    if (!this.options['skip-welcome-message']) {
      this.log(this.yeoman);
      // replace it with a short and sweet description of your generator
      this.log(chalk.magenta('You\'re using the fantastic Famo.us generator.'));
    }

    var force = false;

    if (!this.config.existed || this.init) {
      force = true;
    }

    var questions = [];

    if (!this.config.get('projectName') || force)  {
      questions.push({
        type : 'input',
        name : 'projectName',
        message : 'Your project name',
        default : this.appname || this.config.get('projectName')
      });
    }

    if (!this.config.get('projectDesc') || force) {
      questions.push({
        type : 'input',
        name : 'projectDesc',
        message : 'Your project description',
        default : this.config.get('projectDesc')
      });
    }

    if (!this.config.get('authorLogin') || force) {
      questions.push({
        type : 'input',
        name : 'authorLogin',
        message : 'Would you mind telling me your username on Github?',
        default : this.config.get('author').login || this.config.get('authorLogin')
      });
    }

    if (metrics.getTinfoil() === null) {
      questions.push({
        type : 'confirm',
        name : 'noTinfoil',
        message : chalk.green('(optional)') + ' Do you agree to our Terms of Service (https://famo.us/terms) and our Privacy Policy (http://famo.us/privacy)?',
        default : true
      });
    }

    this.prompt(questions, function (answers) {
      this.projectName = answers.projectName || this.config.get('projectName');
      this.projectDesc = answers.projectDesc || this.config.get('projectDesc');
      this.authorLogin = answers.authorLogin || this.config.get('authorLogin');

      this.authorName  = this.config.get('author').name;
      this.authorEmail = this.config.get('author').email;

      if (metrics.getTinfoil() === null) {
        if (answers.noTinfoil) {
          metrics.setTinfoil(this.authorEmail, function (err) {
            if (err) {
              return console.error('Failed to write ~/.famousrc');
            }
            metrics.track('initialization', {
              packageName: this.pkg.name,
              packageVersion: this.pkg.version,
              type: 'yo famous'
            });
          }.bind(this));
        }
        else {
          metrics.setTinfoil(false, function (err) {
            if (err) {
              return console.error('Failed to write ~/.famousrc');
            }
          });
        }
      }

      if (!metrics.getTinfoil()) {
        metrics.track('yo famous', {
          packageName: this.pkg.name,
          packageVersion: this.pkg.version
        });
      }

      //save config to .yo-rc.json
      this.config.set(answers);

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

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

    this.copy('README.md', 'README.md');

    this.template('_index.html', 'app/index.html');

    this.src.copy('images/_famous_logo.png', 'app/content/images/famous_logo.png');

    this.copy('styles/app.css', 'app/styles/app.css');

    this.template('src/requireConfig.js', 'app/src/requireConfig.js');
    this.template('src/_main.js', 'app/src/main.js');
  },

  manifests: function () {
    if (metrics.getTinfoil()) {
      this.copy('_package_tinfoil.json', 'package.json');
    }
    else {
      this.copy('_package.json', 'package.json');
    }
    this.copy('_bower.json', 'bower.json');
    this.copy('Gruntfile.js', 'Gruntfile.js');
  },

  dotfiles: function () {
    this.copy('editorconfig', '.editorconfig');
    this.copy('bowerrc', '.bowerrc');
    this.copy('eslint.json', '.eslintrc');
    this.copy('jscs.json', '.jscsrc');
    this.copy('gitignore', '.gitignore');
    this.copy('travis.yml', '.travis.yml');
  },

  gruntfiles: function () {
    this.mkdir('grunt');

    if (metrics.getTinfoil()) {
      this.src.copy('grunt/aliases_tinfoil.js', 'grunt/aliases.js');
    }
    else {
      this.src.copy('grunt/aliases.js', 'grunt/aliases.js');
    }

    this.src.copy('grunt/eslint.js', 'grunt/eslint.js');
    this.src.copy('grunt/jscs.js', 'grunt/jscs.js');
    this.src.copy('grunt/watch.js', 'grunt/watch.js');
    this.src.copy('grunt/connect.js', 'grunt/connect.js');
    this.src.copy('grunt/clean.js', 'grunt/clean.js');
    this.src.copy('grunt/bower.js', 'grunt/bower.js');
    this.src.copy('grunt/rev.js', 'grunt/rev.js');
    this.src.copy('grunt/processhtml.js', 'grunt/processhtml.js');
    this.src.copy('grunt/useminPrepare.js', 'grunt/useminPrepare.js');
    this.src.copy('grunt/usemin.js', 'grunt/usemin.js');
    this.src.copy('grunt/htmlmin.js', 'grunt/htmlmin.js');
    this.src.copy('grunt/copy.js', 'grunt/copy.js');
    this.src.copy('grunt/requirejs.js', 'grunt/requirejs.js');
  }
});

module.exports = FamousGenerator;
<commit_msg>Add ability to set config with env vars<commit_after>/*
    Inspired by https://github.com/assemble/generator-assemble/
    which is released under an MIT license
*/

'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var shell = require('shelljs');
var updateNotifier = require('update-notifier');
var metrics = require('famous-metrics');

var FamousGenerator = yeoman.generators.Base.extend({
  init: function () {
    var notifier = updateNotifier({
      packagePath: '../package.json',
      updateCheckInterval: 1
    });

    this.pkg = require('../package.json');

    /* This is unneccessary and gross... but stops you from having to update twice */
    if (notifier.update) {
      if (notifier.update.latest !== this.pkg.version) {
        notifier.notify();
        process.exit(1);
      }
    }

    if (!shell.which('git')) {
      this.log(chalk.red('(ERROR)') + ' It looks like you do not have git installed, please install it and try again.');
      process.exit(1);
    }

    this.description = this.pkg.description;

    this.option('init', {
      alias: 'i',
      desc: 'Force to prompt question and re-initialize of .yo-rc.json',
      type: String,
      defaults: false,
      required: false
    });

    this.init = this.options['init'] || this.options['i'] || false;

    this.on('end', function () {
      if (!this.options['skip-install']) {
        this.installDependencies({
          skipInstall: this.options['skip-install'] || this.options['s'],
          skipMessage: this.options['skip-welcome-message'] || this.options['w'],
          callback: function () {
            console.log('');
            console.log(chalk.green('Woot!') + ' It appears that everything installed correctly.');
            console.log('Please run the command ' + chalk.yellow('grunt serve') + ' to launch the development server.');
            console.log('');
          }
        });
      }
    });

    this.config.defaults({
      projectName: 'Famo.us Base',
      projectDesc: 'e.g. Seed project to get started with Famo.us',
      authorLogin: '',
      author: {
        name: this.user.git.username || process.env.user || process.env.username,
        email: this.user.git.email
      }
    });
  },

  envVars: function () {
    var projectSettings = {};
    if (process.env.PROJECT_NAME) {
      projectSettings.projectName = process.env.PROJECT_NAME;
    }
    if (process.env.PROJECT_DESCRIPTION) {
      projectSettings.projectDesc = process.env.PROJECT_DESCRIPTION;
    }
    if (process.env.GITHUB_USERNAME) {
      projectSettings.authorLogin = process.env.GITHUB_USERNAME;
    }
    if (process.env.NO_TINFOIL) {
      projectSettings.noTinfoil = process.env.NO_TINFOIL;
    }

    //save config to .yo-rc.json
    this.config.set(projectSettings);
  },

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

    // have Yeoman greet the user
    if (!this.options['skip-welcome-message']) {
      this.log(this.yeoman);
      // replace it with a short and sweet description of your generator
      this.log(chalk.magenta('You\'re using the fantastic Famo.us generator.'));
    }

    var force = false;

    if (!this.config.existed || this.init) {
      force = true;
    }

    var questions = [];

    if (!process.env.PROJECT_NAME && (!this.config.get('projectName') || force))  {
      questions.push({
        type : 'input',
        name : 'projectName',
        message : 'Your project name',
        default : this.appname || this.config.get('projectName')
      });
    }

    if (!process.env.PROJECT_DESCRIPTION && (!this.config.get('projectDesc') || force)) {
      questions.push({
        type : 'input',
        name : 'projectDesc',
        message : 'Your project description',
        default : this.config.get('projectDesc')
      });
    }

    if (!process.env.GITHUB_USERNAME && (!this.config.get('authorLogin') || force)) {
      questions.push({
        type : 'input',
        name : 'authorLogin',
        message : 'Would you mind telling me your username on Github?',
        default : this.config.get('author').login || this.config.get('authorLogin')
      });
    }

    if (!process.env.NO_TINFOIL && metrics.getTinfoil() === null) {
      questions.push({
        type : 'confirm',
        name : 'noTinfoil',
        message : chalk.green('(optional)') + ' Do you agree to our Terms of Service (https://famo.us/terms) and our Privacy Policy (http://famo.us/privacy)?',
        default : true
      });
    }

    this.prompt(questions, function (answers) {
      this.projectName = answers.projectName || this.config.get('projectName');
      this.projectDesc = answers.projectDesc || this.config.get('projectDesc');
      this.authorLogin = answers.authorLogin || this.config.get('authorLogin');

      this.authorName  = this.config.get('author').name;
      this.authorEmail = this.config.get('author').email;

      if (metrics.getTinfoil() === null) {
        if (answers.noTinfoil) {
          metrics.setTinfoil(this.authorEmail, function (err) {
            if (err) {
              return console.error('Failed to write ~/.famousrc');
            }
            metrics.track('initialization', {
              packageName: this.pkg.name,
              packageVersion: this.pkg.version,
              type: 'yo famous'
            });
          }.bind(this));
        }
        else {
          metrics.setTinfoil(false, function (err) {
            if (err) {
              return console.error('Failed to write ~/.famousrc');
            }
          });
        }
      }

      if (!metrics.getTinfoil()) {
        metrics.track('yo famous', {
          packageName: this.pkg.name,
          packageVersion: this.pkg.version
        });
      }

      //save config to .yo-rc.json
      this.config.set(answers);

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

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

    this.copy('README.md', 'README.md');

    this.template('_index.html', 'app/index.html');

    this.src.copy('images/_famous_logo.png', 'app/content/images/famous_logo.png');

    this.copy('styles/app.css', 'app/styles/app.css');

    this.template('src/requireConfig.js', 'app/src/requireConfig.js');
    this.template('src/_main.js', 'app/src/main.js');
  },

  manifests: function () {
    if (metrics.getTinfoil()) {
      this.copy('_package_tinfoil.json', 'package.json');
    }
    else {
      this.copy('_package.json', 'package.json');
    }
    this.copy('_bower.json', 'bower.json');
    this.copy('Gruntfile.js', 'Gruntfile.js');
  },

  dotfiles: function () {
    this.copy('editorconfig', '.editorconfig');
    this.copy('bowerrc', '.bowerrc');
    this.copy('eslint.json', '.eslintrc');
    this.copy('jscs.json', '.jscsrc');
    this.copy('gitignore', '.gitignore');
    this.copy('travis.yml', '.travis.yml');
  },

  gruntfiles: function () {
    this.mkdir('grunt');

    if (metrics.getTinfoil()) {
      this.src.copy('grunt/aliases_tinfoil.js', 'grunt/aliases.js');
    }
    else {
      this.src.copy('grunt/aliases.js', 'grunt/aliases.js');
    }

    this.src.copy('grunt/eslint.js', 'grunt/eslint.js');
    this.src.copy('grunt/jscs.js', 'grunt/jscs.js');
    this.src.copy('grunt/watch.js', 'grunt/watch.js');
    this.src.copy('grunt/connect.js', 'grunt/connect.js');
    this.src.copy('grunt/clean.js', 'grunt/clean.js');
    this.src.copy('grunt/bower.js', 'grunt/bower.js');
    this.src.copy('grunt/rev.js', 'grunt/rev.js');
    this.src.copy('grunt/processhtml.js', 'grunt/processhtml.js');
    this.src.copy('grunt/useminPrepare.js', 'grunt/useminPrepare.js');
    this.src.copy('grunt/usemin.js', 'grunt/usemin.js');
    this.src.copy('grunt/htmlmin.js', 'grunt/htmlmin.js');
    this.src.copy('grunt/copy.js', 'grunt/copy.js');
    this.src.copy('grunt/requirejs.js', 'grunt/requirejs.js');
  }
});

module.exports = FamousGenerator;
<|endoftext|>


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

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

  init: function () {
    this.pkg = require('../package.json');

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

  _hasFeature: function (feature) {
    return this.features && this.features.indexOf(feature) !== -1;
  },

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

    // Have Yeoman greet the user.
    this.log(yosay('Thank you for choosing Kickstart. Sit back and relax while I setup your project. '));

    var prompts = [
      {
        type: 'input',
        name: 'ProjectName',
        message: 'What is the project\'s name?'
      },
      {
        type: 'input',
        name: 'ProjectManager',
        message: 'Who is the project manager?'
      },
      {
        type: 'input',
        name: 'GraphicDesigner',
        message: 'Who is the graphic designer?'
      },
      {
        type: 'input',
        name: 'HTMLDeveloper',
        message: 'Who is developing the front end?'
      },
      {
        type: 'confirm',
        name: 'oldIE',
        message: 'Would you like to support legacy IE (<9)?',
        default: false
      },
      {
        type: 'checkbox',
        name: 'ContentElements',
        message: 'What more would you like?',
        choices: [
          {
            name: 'Colorbox',
            value: 'includeColorbox',
            checked: false
          },
          {
            name: 'AnythingSlider',
            value: 'includeAnythingSlider',
            checked: false
          },
          {
            name: 'Accordion',
            value: 'includeAccordion',
            checked: false
          },
          {
            name: 'ElementSwitcher',
            value: 'includeElementSwitcher',
            checked: false
          },
          {
            name: 'Tabs',
            value: 'includeTabs',
            checked: false
          },
          {
            name: 'jquery equal-height Plugin',
            value: 'includeEqualHeight',
            checked: false
          },
          {
            name: 'GridLayout',
            value: 'includeGridLayout',
            checked: true
          },
          {
            name: 'Base64BackgroundImages',
            value: 'includeBase64BackgroundImages',
            checked: true
          },
          {
            name: 'Modernizr',
            value: 'includeModernizr',
            checked: true
          }
        ]
      },
      {
        type: 'list',
        name: 'WCAG2',
        message: 'What WCAG2A level would you like to develop for?',
        choices: [{
          name: 'A',
          value: 'A'
        },
        {
          name: 'AA',
          value: 'AA'
        },
        {
          name: 'AAA',
          value: 'AAA'
        }]
      }
    ];

    this.prompt(prompts, function (answers) {

      // README
      this.GraphicDesigner = answers.GraphicDesigner;
      this.HTMLDeveloper = answers.HTMLDeveloper;
      this.ProjectManager = answers.ProjectManager;
      this.ProjectName = answers.ProjectName;

      // Bower components
      this.features = answers.ContentElements;

      this.includeAccordion = this._hasFeature('includeAccordion');
      this.includeAnythingSlider = this._hasFeature('includeAnythingSlider');
      this.includeBase64BackgroundImages = this._hasFeature('includeBase64BackgroundImages');
      this.includeColorbox = this._hasFeature('includeColorbox');
      this.includeElementSwitcher = this._hasFeature('includeElementSwitcher');
      this.includeEqualHeight = this._hasFeature('includeEqualHeight');
      this.includeGridLayout = this._hasFeature('includeGridLayout');
      this.includeModernizr = this._hasFeature('includeModernizr');
      this.includeTabs = this._hasFeature('includeTabs');

      // Support level
      this.oldIE = answers.oldIE;
      this.WCAG2 = answers.WCAG2;

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

  folders: function () {
    this.mkdir('components/libs');
    this.mkdir('img');
  },

  packagefiles: function () {
    this.copy('_bowerrc', '.bowerrc');
    this.copy('_gitignore', '.gitignore');

    this.template('_package.json', 'package.json');
    this.template('_bower.json', 'bower.json');
    this.template('_csslintrc', '.csslintrc');
    this.template('_gruntfile.js', 'gruntfile.js');
    this.template('_jshintrc', '.jshintrc');
    this.template('_readme.md', 'README.md');
  },

  javascript: function () {
    this.template('_frontend-template-setup.js', 'components/' + this._.slugify(this.ProjectName) + '.js');
    this.template('_main.js', 'components/app/main.js');
  },

  qunit: function () {
    this.template('qunit/_qunit-test-suite.html', 'qunit/_qunit-test-suite.html');
    this.copy('qunit/_qunit.js', 'qunit/_qunit.js');
  },

  styles: function () {
    this.copy('_frontend-template-setup.scss', 'components/' + this._.slugify(this.ProjectName) + '.scss');
  },

  html: function () {
    this.template('_sandbox.html', 'sandbox.html');
  },

  components: function () {

    // colors
    this.template('colors/_colors.scss', 'components/app/colors/_colors.scss');

    // common
    this.template('common/_common.scss', 'components/app/common/_common.scss');

    // rte
    this.template('rte/_rte.html', 'components/app/rte/rte.html');
    this.template('rte/_rte.scss', 'components/app/rte/_rte.scss');

  },

  optionalComponents: function () {

    // element-switcher
    if (this.includeElementSwitcher) {
      this.template('element-switcher/_element-switcher.html', 'components/app/element-switcher/element-switcher.html');
      this.template('element-switcher/_element-switcher.scss', 'components/app/element-switcher/_element-switcher.scss');
    }

    // Tabs
    if (this.includeTabs) {
      this.template('tabs/_tabs.html', 'components/app/tabs/tabs.html');
      this.template('tabs/_tabs.scss', 'components/app/tabs/_tabs.scss');
    }

    // Accordion
    if (this.includeAccordion) {
      this.template('accordion/_accordion.html', 'components/app/accordion/accordion.html');
      this.template('accordion/_accordion.scss', 'components/app/accordion/_accordion.scss');
    }

    // Colorbox
    if (this.includeColorbox) {
      this.template('overlay/_overlay.html', 'components/app/overlay/overlay.html');
      this.template('overlay/_overlay.js', 'components/app/overlay/overlay.js');
      this.template('overlay/_overlay.scss', 'components/app/overlay/_overlay.scss');
    }

    // AnythingSlider
    if (this.includeAnythingSlider) {
      this.template('slider/_slider.html', 'components/app/slider/slider.html');
      this.template('slider/_slider.js', 'components/app/slider/slider.js');
      this.template('slider/_slider.scss', 'components/app/slider/_slider.scss');
    }

  }

});

module.exports = KickstartGenerator;
<commit_msg>[Bugfix] change filename to qunit templates<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var chalk = require('chalk');

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

  init: function () {
    this.pkg = require('../package.json');

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

  _hasFeature: function (feature) {
    return this.features && this.features.indexOf(feature) !== -1;
  },

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

    // Have Yeoman greet the user.
    this.log(yosay('Thank you for choosing Kickstart. Sit back and relax while I setup your project. '));

    var prompts = [
      {
        type: 'input',
        name: 'ProjectName',
        message: 'What is the project\'s name?'
      },
      {
        type: 'input',
        name: 'ProjectManager',
        message: 'Who is the project manager?'
      },
      {
        type: 'input',
        name: 'GraphicDesigner',
        message: 'Who is the graphic designer?'
      },
      {
        type: 'input',
        name: 'HTMLDeveloper',
        message: 'Who is developing the front end?'
      },
      {
        type: 'confirm',
        name: 'oldIE',
        message: 'Would you like to support legacy IE (<9)?',
        default: false
      },
      {
        type: 'checkbox',
        name: 'ContentElements',
        message: 'What more would you like?',
        choices: [
          {
            name: 'Colorbox',
            value: 'includeColorbox',
            checked: false
          },
          {
            name: 'AnythingSlider',
            value: 'includeAnythingSlider',
            checked: false
          },
          {
            name: 'Accordion',
            value: 'includeAccordion',
            checked: false
          },
          {
            name: 'ElementSwitcher',
            value: 'includeElementSwitcher',
            checked: false
          },
          {
            name: 'Tabs',
            value: 'includeTabs',
            checked: false
          },
          {
            name: 'jquery equal-height Plugin',
            value: 'includeEqualHeight',
            checked: false
          },
          {
            name: 'GridLayout',
            value: 'includeGridLayout',
            checked: true
          },
          {
            name: 'Base64BackgroundImages',
            value: 'includeBase64BackgroundImages',
            checked: true
          },
          {
            name: 'Modernizr',
            value: 'includeModernizr',
            checked: true
          }
        ]
      },
      {
        type: 'list',
        name: 'WCAG2',
        message: 'What WCAG2A level would you like to develop for?',
        choices: [{
          name: 'A',
          value: 'A'
        },
        {
          name: 'AA',
          value: 'AA'
        },
        {
          name: 'AAA',
          value: 'AAA'
        }]
      }
    ];

    this.prompt(prompts, function (answers) {

      // README
      this.GraphicDesigner = answers.GraphicDesigner;
      this.HTMLDeveloper = answers.HTMLDeveloper;
      this.ProjectManager = answers.ProjectManager;
      this.ProjectName = answers.ProjectName;

      // Bower components
      this.features = answers.ContentElements;

      this.includeAccordion = this._hasFeature('includeAccordion');
      this.includeAnythingSlider = this._hasFeature('includeAnythingSlider');
      this.includeBase64BackgroundImages = this._hasFeature('includeBase64BackgroundImages');
      this.includeColorbox = this._hasFeature('includeColorbox');
      this.includeElementSwitcher = this._hasFeature('includeElementSwitcher');
      this.includeEqualHeight = this._hasFeature('includeEqualHeight');
      this.includeGridLayout = this._hasFeature('includeGridLayout');
      this.includeModernizr = this._hasFeature('includeModernizr');
      this.includeTabs = this._hasFeature('includeTabs');

      // Support level
      this.oldIE = answers.oldIE;
      this.WCAG2 = answers.WCAG2;

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

  folders: function () {
    this.mkdir('components/libs');
    this.mkdir('img');
  },

  packagefiles: function () {
    this.copy('_bowerrc', '.bowerrc');
    this.copy('_gitignore', '.gitignore');

    this.template('_package.json', 'package.json');
    this.template('_bower.json', 'bower.json');
    this.template('_csslintrc', '.csslintrc');
    this.template('_gruntfile.js', 'gruntfile.js');
    this.template('_jshintrc', '.jshintrc');
    this.template('_readme.md', 'README.md');
  },

  javascript: function () {
    this.template('_frontend-template-setup.js', 'components/' + this._.slugify(this.ProjectName) + '.js');
    this.template('_main.js', 'components/app/main.js');
  },

  qunit: function () {
    this.template('qunit/_qunit-test-suite.html', 'qunit/qunit-test-suite.html');
    this.copy('qunit/_qunit.js', 'qunit/qunit.js');
  },

  styles: function () {
    this.copy('_frontend-template-setup.scss', 'components/' + this._.slugify(this.ProjectName) + '.scss');
  },

  html: function () {
    this.template('_sandbox.html', 'sandbox.html');
  },

  components: function () {

    // colors
    this.template('colors/_colors.scss', 'components/app/colors/_colors.scss');

    // common
    this.template('common/_common.scss', 'components/app/common/_common.scss');

    // rte
    this.template('rte/_rte.html', 'components/app/rte/rte.html');
    this.template('rte/_rte.scss', 'components/app/rte/_rte.scss');

  },

  optionalComponents: function () {

    // element-switcher
    if (this.includeElementSwitcher) {
      this.template('element-switcher/_element-switcher.html', 'components/app/element-switcher/element-switcher.html');
      this.template('element-switcher/_element-switcher.scss', 'components/app/element-switcher/_element-switcher.scss');
    }

    // Tabs
    if (this.includeTabs) {
      this.template('tabs/_tabs.html', 'components/app/tabs/tabs.html');
      this.template('tabs/_tabs.scss', 'components/app/tabs/_tabs.scss');
    }

    // Accordion
    if (this.includeAccordion) {
      this.template('accordion/_accordion.html', 'components/app/accordion/accordion.html');
      this.template('accordion/_accordion.scss', 'components/app/accordion/_accordion.scss');
    }

    // Colorbox
    if (this.includeColorbox) {
      this.template('overlay/_overlay.html', 'components/app/overlay/overlay.html');
      this.template('overlay/_overlay.js', 'components/app/overlay/overlay.js');
      this.template('overlay/_overlay.scss', 'components/app/overlay/_overlay.scss');
    }

    // AnythingSlider
    if (this.includeAnythingSlider) {
      this.template('slider/_slider.html', 'components/app/slider/slider.html');
      this.template('slider/_slider.js', 'components/app/slider/slider.js');
      this.template('slider/_slider.scss', 'components/app/slider/_slider.scss');
    }

  }

});

module.exports = KickstartGenerator;
<|endoftext|>


<commit_before>'use strict'

var express = require('express');
var routes = require('./routes');
var path = require('path');

var app = module.exports = express();

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  next();
})

//app.use(express.static(path.join(__dirname, '/../public')));
//app.set('views', path.join(__dirname, '/../www/views'));
//app.set('view engine', 'jade');

app.locals.title = 'MarvelWar';

//app.get('/', routes);
app.use('/api', routes);

// ERRORS//
app
  .use(function (req, res, next) {
    res.status(404).send('404. This page does not exist');
  })
  .use(function (err, req, res, next) {
    console.log('error', err.stack);
    res.status(500).send('An error has occurred');
  });

startNodeListener();

function startNodeListener() {
  var port = process.env.PORT || 5000;
  var server = app.listen(port, function () {
    var port = server.address().port;
    var mode = app.get('env');

    console.log(`Server listening on port ${port} in ${mode} mode...`);
  });
};
<commit_msg>deleted commented out stuff<commit_after>'use strict'

var express = require('express');
var routes = require('./routes');
var path = require('path');

var app = module.exports = express();

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  next();
})

app.locals.title = 'MarvelWar';

app.use('/api', routes);

// ERRORS//
app
  .use(function (req, res, next) {
    res.status(404).send('404. This page does not exist');
  })
  .use(function (err, req, res, next) {
    console.log('error', err.stack);
    res.status(500).send('An error has occurred');
  });

startNodeListener();

function startNodeListener() {
  var port = process.env.PORT || 5000;
  var server = app.listen(port, function () {
    var port = server.address().port;
    var mode = app.get('env');

    console.log(`Server listening on port ${port} in ${mode} mode...`);
  });
};
<|endoftext|>


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

var CandlebarsGenerator = module.exports = function CandlebarsGenerator(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(CandlebarsGenerator, yeoman.generators.Base);

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

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

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

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

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

CandlebarsGenerator.prototype.app = function app() {
  this.mkdir('app');
  this.mkdir('app/templates');

  this.copy('_package.json', 'package.json');
  this.copy('_bower.json', 'bower.json');
};

CandlebarsGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');
};
<commit_msg>JSlint format error fixed.<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var CandlebarsGenerator = module.exports = function CandlebarsGenerator(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(CandlebarsGenerator, yeoman.generators.Base);

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

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

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

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

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

CandlebarsGenerator.prototype.app = function app() {
    this.mkdir('app');
    this.mkdir('app/templates');

    this.copy('_package.json', 'package.json');
    this.copy('_bower.json', 'bower.json');
};

CandlebarsGenerator.prototype.projectfiles = function projectfiles() {
    this.copy('editorconfig', '.editorconfig');
    this.copy('jshintrc', '.jshintrc');
};
<|endoftext|>


<commit_before>import Promise from 'bluebird'
import { createClient as createRedisClient } from 'redis'
import _ from 'lodash'
import IoServer from 'socket.io'
import redis_adapter from 'socket.io-redis'

import models from './models'
import config_loader from '../config/config'

export default class PubsubListener {
  constructor(server, app) {
    this.app = app

    var config = config_loader.load()

    var redisPub = createRedisClient(config.redis.port, config.redis.host, config.redis.options)
      , redisSub = createRedisClient(config.redis.port, config.redis.host, _.extend(config.redis.options, { detect_buffers: true }))

    redisPub.on('error', function(err) { console.log(err) })
    redisSub.on('error', function(err) { console.log(err) })

    this.io = IoServer(server)
    this.io.adapter(redis_adapter({
      pubClient: redisPub,
      subClient: redisSub
    }))

    this.io.sockets.on('error', function(err) { console.log(err) })
    this.io.sockets.on('connection', this.onConnect.bind(this))

    var redisClient = createRedisClient(config.redis.port, config.redis.host, {})
    redisClient.on('error', function(err) { console.log(err) })
    redisClient.subscribe('post:new', 'post:destroy', 'post:update',
      'comment:new', 'comment:destroy', 'comment:update',
      'like:new', 'like:remove', 'post:hide', 'post:unhide')

    redisClient.on('message', this.onRedisMessage.bind(this))
  }

  onConnect(socket) {
    var logger = this.app.logger

    socket.on('subscribe', function(data) {
      for (let channel of Object.keys(data)) {
        if (data[channel]) {
          data[channel].forEach(function(id) {
            if (id) {
              logger.info('User has subscribed to ' + id + ' ' + channel)

              socket.join(channel + ':' + id)
            }
          })
        }
      }
    })

    socket.on('unsubscribe', function(data) {
      for (let channel of Object.keys(data)) {
        if (data[channel]) {
          data[channel].forEach(function(id) {
            if (id) {
              logger.info('User has unsubscribed from ' + id + ' ' + channel)

              socket.leave(channel + ':' + id)
            }
          })
        }
      }
    })
  }

  onRedisMessage(channel, msg) {
    const messageRoutes = {
      'post:new':         this.onPostNew,
      'post:update':      this.onPostUpdate,
      'post:destroy':     this.onPostDestroy,
      'post:hide':        this.onPostHide,
      'post:unhide':      this.onPostUnhide,

      'comment:new':      this.onCommentNew,
      'comment:update':   this.onCommentUpdate,
      'comment:destroy':  this.onCommentDestroy,

      'like:new':         this.onLikeNew,
      'like:remove':      this.onLikeRemove
    }

    messageRoutes[channel](
      this.io.sockets,
      JSON.parse(msg)
    ).catch(e => {throw e})
  }

  // Message-handlers follow
  async onPostDestroy(sockets, data) {
    var event = { meta: { postId: data.postId } }

    sockets.in('timeline:' + data.timelineId).emit('post:destroy', event)
    sockets.in('post:' + data.postId).emit('post:destroy', event)
  }

  async onPostNew(sockets, data) {
    var post = await models.Post.findById(data.postId)
    var json = await new models.PostSerializer(post).promiseToJSON()

    sockets.in('timeline:' + data.timelineId).emit('post:new', json)
  }

  async onPostUpdate(sockets, data) {
    var post = await models.Post.findById(data.postId)
    var json = await new models.PostSerializer(post).promiseToJSON()

    sockets.in('timeline:' + data.timelineId).emit('post:update', json)
    sockets.in('post:' + data.postId).emit('post:update', json)
  }

  async onCommentNew(sockets, data) {
    var comment = await models.Comment.findById(data.commentId)
    var json = await new models.PubsubCommentSerializer(comment).promiseToJSON()

    if (data.timelineId) {
      sockets.in('timeline:' + data.timelineId).emit('comment:new', json)
    } else {
      sockets.in('post:' + data.postId).emit('comment:new', json)
    }
  }

  async onCommentUpdate(sockets, data) {
    var comment = await models.Comment.findById(data.commentId)
    var json = await new models.PubsubCommentSerializer(comment).promiseToJSON()

    if (data.timelineId) {
      sockets.in('timeline:' + data.timelineId).emit('comment:update', json)
    } else {
      sockets.in('post:' + data.postId).emit('comment:update', json)
    }
  }

  async onCommentDestroy(sockets, data) {
    var event = { postId: data.postId, commentId: data.commentId }

    sockets.in('post:' + data.postId).emit('comment:destroy', event)

    var post = await models.Post.findById(data.postId)
    var timeLineIds = await post.getTimelineIds()

    for (let timelineId of timeLineIds) {
      sockets.in('timeline:' + timelineId).emit('comment:destroy', event)
    }
  }

  async onLikeNew(sockets, data) {
    var user = await models.User.findById(data.userId)
    var event = await new models.LikeSerializer(user).promiseToJSON()
    event.meta = { postId: data.postId }

    if (data.timelineId) {
      sockets.in('timeline:' + data.timelineId).emit('like:new', event)
    } else {
      sockets.in('post:' + data.postId).emit('like:new', event)
    }
  }

  async onLikeRemove(sockets, data) {
    var event = { meta: { userId: data.userId, postId: data.postId } }

    if (data.timelineId)
      sockets.in('timeline:' + data.timelineId).emit('like:remove', event)
    else
      sockets.in('post:' + data.postId).emit('like:remove', event)
  }

  async onPostHide(sockets, data) {
    // NOTE: posts are hidden only on RiverOfNews timeline so this
    // event won't leak any personal information
    var event = { meta: { postId: data.postId } }
    sockets.in('timeline:' + data.timelineId).emit('post:hide', event)
  }

  async onPostUnhide(sockets, data) {
    // NOTE: posts are hidden only on RiverOfNews timeline so this
    // event won't leak any personal information
    var event = { meta: { postId: data.postId } }
    sockets.in('timeline:' + data.timelineId).emit('post:unhide', event)
  }
}
<commit_msg>Does not publish posts in real-time if user is not allowed to see them.<commit_after>import Promise from 'bluebird'
import { createClient as createRedisClient } from 'redis'
import _ from 'lodash'
import IoServer from 'socket.io'
import redis_adapter from 'socket.io-redis'
import jwt from 'jsonwebtoken'

import models from './models'
import config_loader from '../config/config'

export default class PubsubListener {
  constructor(server, app) {
    this.app = app

    var config = config_loader.load()

    var redisPub = createRedisClient(config.redis.port, config.redis.host, config.redis.options)
      , redisSub = createRedisClient(config.redis.port, config.redis.host, _.extend(config.redis.options, { detect_buffers: true }))

    redisPub.on('error', function(err) { console.log(err) })
    redisSub.on('error', function(err) { console.log(err) })

    this.io = IoServer(server)
    this.io.adapter(redis_adapter({
      pubClient: redisPub,
      subClient: redisSub
    }))

    this.io.sockets.on('error', function(err) { console.log(err) })
    this.io.sockets.on('connection', this.onConnect.bind(this))

    var redisClient = createRedisClient(config.redis.port, config.redis.host, {})
    redisClient.on('error', function(err) { console.log(err) })
    redisClient.subscribe('post:new', 'post:destroy', 'post:update',
      'comment:new', 'comment:destroy', 'comment:update',
      'like:new', 'like:remove', 'post:hide', 'post:unhide')

    redisClient.on('message', this.onRedisMessage.bind(this))
  }

  async onConnect(socket) {
    let authToken = socket.handshake.query.token
    let config = config_loader.load()
    let secret = config.secret
    let logger = this.app.logger

    let jwtAsync = Promise.promisifyAll(jwt)
    let decoded = await jwtAsync.verifyAsync(authToken, secret)
    socket.user = await models.User.findById(decoded.userId)

    socket.on('subscribe', function(data) {
      for (let channel of Object.keys(data)) {
        if (data[channel]) {
          data[channel].forEach(function(id) {
            if (id) {
              logger.info('User has subscribed to ' + id + ' ' + channel)

              socket.join(channel + ':' + id)
            }
          })
        }
      }
    })

    socket.on('unsubscribe', function(data) {
      for (let channel of Object.keys(data)) {
        if (data[channel]) {
          data[channel].forEach(function(id) {
            if (id) {
              logger.info('User has unsubscribed from ' + id + ' ' + channel)

              socket.leave(channel + ':' + id)
            }
          })
        }
      }
    })
  }

  onRedisMessage(channel, msg) {
    const messageRoutes = {
      'post:new':         this.onPostNew,
      'post:update':      this.onPostUpdate,
      'post:destroy':     this.onPostDestroy,
      'post:hide':        this.onPostHide,
      'post:unhide':      this.onPostUnhide,

      'comment:new':      this.onCommentNew,
      'comment:update':   this.onCommentUpdate,
      'comment:destroy':  this.onCommentDestroy,

      'like:new':         this.onLikeNew,
      'like:remove':      this.onLikeRemove
    }

    messageRoutes[channel](
      this.io.sockets,
      JSON.parse(msg)
    ).catch(e => {throw e})
  }

  // Message-handlers follow
  async onPostDestroy(sockets, data) {
    var event = { meta: { postId: data.postId } }

    sockets.in('timeline:' + data.timelineId).emit('post:destroy', event)
    sockets.in('post:' + data.postId).emit('post:destroy', event)
  }

  async onPostNew(sockets, data) {
    var post = await models.Post.findById(data.postId)
    var json = await new models.PostSerializer(post).promiseToJSON()

    var clientIds = Object.keys(sockets.adapter.rooms['timeline:' + data.timelineId])
    await* clientIds.map(async (clientId) => {
      var socket = sockets.connected[clientId]
      var user = socket.user

      var valid = await post.validateCanShow(user.id)

      if (valid)
        socket.emit('post:new', json)
    })
  }

  async onPostUpdate(sockets, data) {
    var post = await models.Post.findById(data.postId)
    var json = await new models.PostSerializer(post).promiseToJSON()

    sockets.in('timeline:' + data.timelineId).emit('post:update', json)
    sockets.in('post:' + data.postId).emit('post:update', json)
  }

  async onCommentNew(sockets, data) {
    var comment = await models.Comment.findById(data.commentId)
    var json = await new models.PubsubCommentSerializer(comment).promiseToJSON()

    if (data.timelineId) {
      sockets.in('timeline:' + data.timelineId).emit('comment:new', json)
    } else {
      sockets.in('post:' + data.postId).emit('comment:new', json)
    }
  }

  async onCommentUpdate(sockets, data) {
    var comment = await models.Comment.findById(data.commentId)
    var json = await new models.PubsubCommentSerializer(comment).promiseToJSON()

    if (data.timelineId) {
      sockets.in('timeline:' + data.timelineId).emit('comment:update', json)
    } else {
      sockets.in('post:' + data.postId).emit('comment:update', json)
    }
  }

  async onCommentDestroy(sockets, data) {
    var event = { postId: data.postId, commentId: data.commentId }

    sockets.in('post:' + data.postId).emit('comment:destroy', event)

    var post = await models.Post.findById(data.postId)
    var timeLineIds = await post.getTimelineIds()

    for (let timelineId of timeLineIds) {
      sockets.in('timeline:' + timelineId).emit('comment:destroy', event)
    }
  }

  async onLikeNew(sockets, data) {
    var user = await models.User.findById(data.userId)
    var event = await new models.LikeSerializer(user).promiseToJSON()
    event.meta = { postId: data.postId }

    if (data.timelineId) {
      sockets.in('timeline:' + data.timelineId).emit('like:new', event)
    } else {
      sockets.in('post:' + data.postId).emit('like:new', event)
    }
  }

  async onLikeRemove(sockets, data) {
    var event = { meta: { userId: data.userId, postId: data.postId } }

    if (data.timelineId)
      sockets.in('timeline:' + data.timelineId).emit('like:remove', event)
    else
      sockets.in('post:' + data.postId).emit('like:remove', event)
  }

  async onPostHide(sockets, data) {
    // NOTE: posts are hidden only on RiverOfNews timeline so this
    // event won't leak any personal information
    var event = { meta: { postId: data.postId } }
    sockets.in('timeline:' + data.timelineId).emit('post:hide', event)
  }

  async onPostUnhide(sockets, data) {
    // NOTE: posts are hidden only on RiverOfNews timeline so this
    // event won't leak any personal information
    var event = { meta: { postId: data.postId } }
    sockets.in('timeline:' + data.timelineId).emit('post:unhide', event)
  }
}
<|endoftext|>


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

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

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

    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the fantastic' + chalk.red('Fordlee404') + ' generator!'
    ));

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

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

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

  writing: {
    app: function () {
      this.fs.copy(
        this.templatePath('_package.json'),
        this.destinationPath('package.json')
      );
      this.fs.copy(
        this.templatePath('_bower.json'),
        this.destinationPath('bower.json')
      );
    },

    projectfiles: function () {
      this.fs.copy(
        this.templatePath('editorconfig'),
        this.destinationPath('.editorconfig')
      );
      this.fs.copy(
        this.templatePath('jshintrc'),
        this.destinationPath('.jshintrc')
      );
    }
  },

  install: function () {
    this.installDependencies({
      skipInstall: this.options['skip-install']
    });
  }
});
<commit_msg>在入口中添加所有的priorities<commit_after>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');

module.exports = yeoman.generators.Base.extend({
  // Your initialization methods (checking current project state, getting configs, etc)
  initializing: function () {
    this.pkg = require('../package.json');
  },

  // Where you prompt users for options (where you'd call this.prompt())
  prompting: function () {
    var done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the fantastic' + chalk.red('Fordlee404') + ' generator!'
    ));

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

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

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

  // Saving configurations and configure the project (creating .editorconfig files and other metadata files)
  // configuring: function(){},

  // If the method name doesn't match a priority, it is pushed in the default group
  // default: function(){},

  // Where you write the generator specific files (routes, controllers, etc)
  writing: {
    app: function () {
      this.fs.copy(
        this.templatePath('_package.json'),
        this.destinationPath('package.json')
      );
      this.fs.copy(
        this.templatePath('_bower.json'),
        this.destinationPath('bower.json')
      );
    },

    projectfiles: function () {
      this.fs.copy(
        this.templatePath('editorconfig'),
        this.destinationPath('.editorconfig')
      );
      this.fs.copy(
        this.templatePath('jshintrc'),
        this.destinationPath('.jshintrc')
      );
    }
  },

  // Where conflicts are handled (used internally)
  // conflicts: function(){},

  // Where installation are run (npm, bower)
  install: function () {
    this.installDependencies({
      skipInstall: this.options['skip-install']
    });
  }

  // Called last, cleanup, say good bye, etc
  // end: function(){}
});
<|endoftext|>


<commit_before>var User = require('../lib/users');
var tasks = require('../lib/tasks');
var _ = require('lodash');

module.exports = function (server) {

  server.post('/messages', function (req, res, next) {
    var phoneNumber = req.params.From;
    var message = req.params.Body;
    var responseMessage = '';

    // TODO: Remove this when moving out of beta.
    console.log('Received "' + message + '" from ' + phoneNumber);

    User.findOrCreate(phoneNumber, function (err, user) {

      if (err) { res.send(500, err); console.log(err); return; };

      console.log(user);

      // TODO: This is a just a WIP while we get the general flow down.
      if (!user.status) {
        user.set('status', 'waitingOnZipCode', function (err, doc) {
          if (err) console.log(err);
          user.message('Welcome. What zip code are you in?');
        });
        res.send(200, { from: phoneNumber, user: user });
        return;
      }

      console.log(user.status);
      console.log(user.status === 'waitingOnZipCode');

      if (user.status === 'waitingOnZipCode') {
        var zip = user.message.match(/\d{5}/) && user.message.match(/\d{5}/)[0];

        console.log(zip);

        if (zip) {
          tasks.getResourcesByZip(zip, function (err, resources) {
            if (err) console.log(err);
            user.set({ zip: zip, resourcesRequested: resources, status: 'waitingOnResources' }, function (err) {
              if (err) console.log(err);
              user.message('Okay, the following resources are needed in ' + user.zip + ': ' + resources.join(', '));
            });
          });
        }
        res.send(200, { from: phoneNumber, user: user });
        return;
      }

      if (user.status === 'waitingOnResources') {
        user.message('Not implemented.');
        res.send(200, { from: phoneNumber, user: user });
        return;
      }

    });
  });

};<commit_msg>Return after restarting<commit_after>var User = require('../lib/users');
var tasks = require('../lib/tasks');
var _ = require('lodash');

module.exports = function (server) {

  server.post('/messages', function (req, res, next) {
    var phoneNumber = req.params.From;
    var message = req.params.Body;
    var responseMessage = '';

    // TODO: Remove this when moving out of beta.
    console.log('Received "' + message + '" from ' + phoneNumber);

    User.findOrCreate(phoneNumber, function (err, user) {

      if (err) { res.send(500, err); console.log(err); return; };

      console.log(user);

      if (message.toUpperCase() === "RESTART") {
        user.set('status', null, function (err) {
          user.message('Resetting...');
        });
        return;
      }

      // TODO: This is a just a WIP while we get the general flow down.
      if (!user.status) {
        user.set('status', 'waitingOnZipCode', function (err, doc) {
          if (err) console.log(err);
          user.message('Welcome. What zip code are you in?');
        });
        res.send(200, { from: phoneNumber, user: user });
        return;
      }

      console.log(user.status);
      console.log(user.status === 'waitingOnZipCode');

      if (user.status === 'waitingOnZipCode') {
        console.log('I am inside the waitingOnZipCode conditional');
        var zip = user.message.match(/\d{5}/) && user.message.match(/\d{5}/)[0];

        console.log(zip);

        if (zip) {
          tasks.getResourcesByZip(zip, function (err, resources) {
            if (err) console.log(err);
            user.set({ zip: zip, resourcesRequested: resources, status: 'waitingOnResources' }, function (err) {
              if (err) console.log(err);
              user.message('Okay, the following resources are needed in ' + user.zip + ': ' + resources.join(', '));
            });
          });
        }
        res.send(200, { from: phoneNumber, user: user });
        return;
      }

      if (user.status === 'waitingOnResources') {
        user.message('Not implemented.');
        res.send(200, { from: phoneNumber, user: user });
        return;
      }

    });
  });

};<|endoftext|>