<commit_before>'use strict';

var fs = require('fs'),
  npm = require('npm'),
  shell = require('shelljs'),
  chalk = require('chalk'),
  cliVersion = require('../package').version;

var pkgType = {
  contrib: 'Contrib',
  custom: 'Custom'
};

function Progress() {
  var interval, counter;

  function printMsg() {
    switch (counter) {
      case 0:
        console.log('Use `mean --help` from command line for all CLI options');
        break;
      case 1:
        console.log('Be sure to checkout all the docs on http://mean.io');
        break;
      case 2:
        console.log('This may take a little while depending on your connection speed');
        break;
      case 15:
        console.log('Seems a bit slow. Check your internet connection...');
        break;
      default:
        console.log('Still cloning...');
        break;
    }
    counter++;
  }

  return {
    start: function() {
      counter = 0;
      interval = setInterval(printMsg, 3000);
    },
    stop: function() {
      clearInterval(interval);
    }
  };
}
var progress = new Progress();

// From express
function emptyDirectory(path, callback) {
  fs.readdir('./' + path, function(err, files) {
    if (err && 'ENOENT' !== err.code) throw new Error(err);
    callback(!files || !files.length);
  });
}

function ensureEmpty(path, force, callback) {
  emptyDirectory(path, function(empty) {
    if (empty || force) {
      callback();
    } else {
      console.log(chalk.yellow('Destination is not empty:'), path);
    }
  });
}

function getPackageInfo(type, data) {
  if (!data) return;
  var author = data.author ? chalk.green('  Author: ') + data.author.name : '';
  return chalk.green('   ' + type + ': ') + data.name + '@' + data.version + author;
}

function loadPackageJson(path, callback) {
  fs.readFile(path, function(err, data) {
    if (err) return callback(err);

    try {
      var pkg = JSON.parse(data.toString());
      pkg.meanVersion = pkg.mean || pkg.version;
      callback(null, pkg);
    } catch (err) {
      return callback(err);
    }
  });
}

function checkVersion() {
  console.log();
  console.log('    checking meanio command line version');

  npm.load({
    global: true,
    loglevel: 'warn'
  }, function(err, npm) {
    npm.commands.outdated('meanio', true, function(err, list) {
      if (err) {
        console.log(chalk.red('Error: npm install failed'));
        return console.error(err);
      }
      var latest = list[2]; // list[2] holds the 'latest' value
      if (latest < cliVersion) {
        console.log(chalk.yellow('    meanio command line is out of date'));
        console.log('    Current: ' + cliVersion + ' Latest: ' + latest);
      } else {
        console.log(chalk.green('    meanio command line at latest version:'), cliVersion);
      }
    });
  });
}

function requiresRoot(callback) {
  loadPackageJson(process.cwd() + '/package.json', function(err, data) {
    if (err || (data.name !== 'mean' && !data.mean)) {
      console.log(chalk.yellow('Invalid MEAN app or not in app root'));
    } else {
      callback();
    }
  });
}

function mongoConnect(env, callback) {

  loadPackageJson('./package.json', function(err, data) {

    var path = (data.version < '0.4.0' ? '/server' : '') + '/config/env/' + env + '.js';

    var config = require(process.cwd() + path);

    require('mongodb').MongoClient.connect(config.db, function(err, db) {
      if (err) {
        console.log(chalk.red('    Error Connecting to database'));
        console.log(err);
      } else {
        console.log(chalk.green('    DB connection successful!'));
        console.log();
        callback(err, db);
      }
    });
  });
}

exports.init = function(name, options) {
  if (!shell.which('git')) return console.log(chalk.red('    Prerequisite not installed: git'));

  var source = (options.git ? 'git@github.com:linnovate/mean.git' : 'https://github.com/linnovate/mean.git');

  // Allow specifying specific repo
  if (options.repo) {
    source = options.repo;
  }

  console.log(chalk.green('Cloning branch: %s into destination folder:'), options.branch, name);

  progress.start();
  source = options.branch + ' ' + source + ' ' + name;
  shell.exec('git clone -b ' + source, function(code) {
    progress.stop();
    if (code) return console.log(chalk.red('Error: git clone failed'));

    loadPackageJson('./' + name + '/package.json', function(err, data) {
      if (err) {
        console.log(chalk.yellow('Something went wrong. Try again or use --git flag'));
        console.log(chalk.yellow('If the problem persists see past issues here: https://github.com/linnovate/mean/issues'));
        console.log(chalk.yellow('Or open a new issue here https://github.com/linnovate/mean/issues/new'));
        //fallback code here
        process.exit();
      }

      console.log(chalk.green('Version: %s cloned'), data.meanVersion);
      console.log();

      fs.readFile(__dirname + '/../img/logo.txt', function(err, data) {
        console.log(data.toString());
        console.log();

        shell.cd(name);
        shell.exec('git remote rename origin upstream', function(code) {
          if (!code) {
            console.log('   git remote upstream set');
            console.log();
          }
        });

        if (options.quick) {
          npm.load(function(err, npm) {
            console.log(chalk.green('   installing dependencies...'));
            console.log();
            npm.commands.install(function(err) {
              if (err) {
                console.log(chalk.red('Error: npm install failed'));
                return console.error(err);
              }
              console.log(chalk.green('   running the mean app...'));
              console.log();
              if (shell.which('grunt')) {
                shell.exec('grunt', ['-f']);
              }
            });
          });
        } else {
          console.log('   install dependencies:');
          console.log('     $ cd %s && npm install', name);
          console.log();
          console.log('   run the app:');
          console.log('     $ grunt');
          console.log();
        }
        console.log('   Extra Docs at http://mean.io');
        console.log();
      });
    });
  });
};

exports.postinstall = function() {
  requiresRoot(function() {
    // install bower
    console.log(chalk.green('Installing Bower packages'));
    require('bower').commands.install().on('error', function(err) {
      console.log(chalk.red(err));
    });

    console.log(chalk.green('Auto installing package dependencies'));
    var source = 'packages';
    var rootDir = process.cwd();
    npm.load({
      loglevel: 'error'
    }, function(err, npm) {
      fs.readdir(rootDir + '/' + source, function(err, files) {
        if (err && 'ENOENT' !== err.code) throw Error(err);

        files.forEach(function(file) {
          npm.commands.install([rootDir + '/' + source + '/' + file], function(err) {
            if (err) {
              console.log(chalk.red('Error: npm install failed'));
              return console.error(err);
            } else {
              console.log(chalk.green('    Dependencies installed for package ' + file));
            }
          });
        });
      });
    });
  });
};

exports.install = function(module, options) {
  requiresRoot(function() {
    var source = 'https://github.com/linnovate/' + module + '/tarball/' + options.branch;

    // Allow specifying specific repo
    if (options.repo) {
      source = options.repo;
    }

    // Allow installing packages from npm
    if (options.npm) {
      source = module;
    }

    console.log(chalk.green('Installing module: %s from branch (version):'), module, options.branch);
    console.log();

    npm.load(function(err, npm) {
      npm.commands.install([source], function(err) {
        if (err) {
          console.log(chalk.red('Error: npm install failed'));
          return console.error(err);
        }

        loadPackageJson('./node_modules/' + module + '/package.json', function(err, data) {
          if (err) return console.error(err);

          console.log();
          console.log(getPackageInfo(pkgType.contrib, data));
          if (!data.mean) {
            console.log();
            console.log(chalk.yellow('Warning: The module installed is not a valid MEAN module'));
          }
        });
      });
    });
  });
};

exports.uninstall = function(module) {
  requiresRoot(function() {
    console.log(chalk.yellow('Removing module:'), module);

    npm.load(function(err, npm) {
      npm.commands.uninstall([module], function(err) {
        if (err) {
          console.log(chalk.red('Error: npm install failed'));
          return console.error(err);
        }
        console.log(chalk.green('   npm uninstall complete'));
      });
    });
  });
};

exports.list = function() {
  requiresRoot(function() {

    console.log(chalk.green('   MEAN Packages List:'));
    console.log('   -----------------');

    function look(type) {
      var path = type === pkgType.contrib ? './node_modules/' : './packages/';
      fs.readdir(path, function(err, files) {
        if (err || !files.length) return console.log(chalk.yellow('   No ' + type + ' Packages'));
        files.forEach(function(file) {
          loadPackageJson(path + file + '/package.json', function(err, data) {
            if (!err && data.mean) console.log(getPackageInfo(type, data));
          });
        });
      });
    }

    // look in node_modules for external packages
    look(pkgType.contrib);

    // look in packages for local packages
    look(pkgType.custom);
  });
};

exports.status = function(options) {
  requiresRoot(function() {
    console.log();
    console.log(chalk.green('    MEAN Status'));
    console.log('    -----------');
    console.log();
    loadPackageJson('./package.json', function(err, data) {
      console.log('    MEAN VERSION: ' + data.meanVersion);
      console.log();
      mongoConnect(options.env, function(err, db) {
        console.log('    MongoDB URI: ' + db.options.url);
        checkVersion();
        db.close();
      });
    });
  });
};

exports.pkg = function(name, options) {
  requiresRoot(function() {
    if (options.delete) {
      console.log(chalk.yellow('Removing package:'), name);
      shell.rm('-rf', './packages/' + name);
    } else {
      ensureEmpty('./packages/' + name, options.force, function() {
        require('./scaffold.js').packages(name, options);
      });
    }
  });
};

exports.printUser = function(email, options) {
  requiresRoot(function() {
    mongoConnect(options.env, function(err, db) {
      db.collection('users').find({
        email: email
      }).toArray(function(err, user) {
        console.dir(user);
        db.close();
      });
    });
  });
};

exports.updateRole = function(email, options, type) {
  requiresRoot(function() {
    var update = {};
    switch (type) {
      case 'a':
        console.log(chalk.green('  Adding role `' + options.addRole + '` to user `' + email + '`'));
        update.$push = {
          roles: options.addRole
        };
        break;
      case 'r':
        console.log(chalk.green('  Removing role `' + options.removeRole + '` from user `' + email + '`'));
        update.$pull = {
          roles: options.removeRole
        };
        break;
      default:
        return;
    }
    mongoConnect(options.env, function(err, db) {
      db.collection('users').update({
        email: email
      }, update, {
        w: 1,
        upsert: false,
        multi: false
      }, function(err) {
        if (err) console.error(err);
        else console.log(chalk.green('successfully updated'));
        db.close();
      });
    });
  });
};
<commit_msg>fix postinstall<commit_after>'use strict';

var fs = require('fs'),
  npm = require('npm'),
  shell = require('shelljs'),
  chalk = require('chalk'),
  cliVersion = require('../package').version;

var pkgType = {
  contrib: 'Contrib',
  custom: 'Custom',
  core: 'Core'
};

function Progress() {
  var interval, counter;

  function printMsg() {
    switch (counter) {
      case 0:
        console.log('Use `mean --help` from command line for all CLI options');
        break;
      case 1:
        console.log('Be sure to checkout all the docs on http://mean.io');
        break;
      case 2:
        console.log('This may take a little while depending on your connection speed');
        break;
      case 15:
        console.log('Seems a bit slow. Check your internet connection...');
        break;
      default:
        console.log('Still cloning...');
        break;
    }
    counter++;
  }

  return {
    start: function() {
      counter = 0;
      interval = setInterval(printMsg, 3000);
    },
    stop: function() {
      clearInterval(interval);
    }
  };
}
var progress = new Progress();

// From express
function emptyDirectory(path, callback) {
  fs.readdir('./' + path, function(err, files) {
    if (err && 'ENOENT' !== err.code) throw new Error(err);
    callback(!files || !files.length);
  });
}

function ensureEmpty(path, force, callback) {
  emptyDirectory(path, function(empty) {
    if (empty || force) {
      callback();
    } else {
      console.log(chalk.yellow('Destination is not empty:'), path);
    }
  });
}

function getPackageInfo(type, data) {
  if (!data) return;
  var author = data.author ? chalk.green('  Author: ') + data.author.name : '';
  if (type === pkgType.custom && data.author.name === 'Linnovate') type = pkgType.core;
  return chalk.green('   ' + type + ': ') + data.name + '@' + data.version + author;
}

function loadPackageJson(path, callback) {
  fs.readFile(path, function(err, data) {
    if (err) return callback(err);

    try {
      var pkg = JSON.parse(data.toString());
      pkg.meanVersion = pkg.mean || pkg.version;
      callback(null, pkg);
    } catch (err) {
      return callback(err);
    }
  });
}

function checkVersion() {
  console.log();
  console.log('    checking meanio command line version');

  npm.load({
    global: true,
    loglevel: 'warn'
  }, function(err, npm) {
    npm.commands.outdated('meanio', true, function(err, list) {
      if (err) {
        console.log(chalk.red('Error: npm install failed'));
        return console.error(err);
      }
      var latest = list[2]; // list[2] holds the 'latest' value
      if (latest < cliVersion) {
        console.log(chalk.yellow('    meanio command line is out of date'));
        console.log('    Current: ' + cliVersion + ' Latest: ' + latest);
      } else {
        console.log(chalk.green('    meanio command line at latest version:'), cliVersion);
      }
    });
  });
}

function requiresRoot(callback) {
  loadPackageJson(process.cwd() + '/package.json', function(err, data) {
    if (err || (data.name !== 'mean' && !data.mean)) {
      console.log(chalk.yellow('Invalid MEAN app or not in app root'));
    } else {
      callback();
    }
  });
}

function mongoConnect(env, callback) {

  loadPackageJson('./package.json', function(err, data) {

    var path = (data.version < '0.4.0' ? '/server' : '') + '/config/env/' + env + '.js';

    var config = require(process.cwd() + path);

    require('mongodb').MongoClient.connect(config.db, function(err, db) {
      if (err) {
        console.log(chalk.red('    Error Connecting to database'));
        console.log(err);
      } else {
        console.log(chalk.green('    DB connection successful!'));
        console.log();
        callback(err, db);
      }
    });
  });
}

exports.init = function(name, options) {
  if (!shell.which('git')) return console.log(chalk.red('    Prerequisite not installed: git'));

  var source = (options.git ? 'git@github.com:linnovate/mean.git' : 'https://github.com/linnovate/mean.git');

  // Allow specifying specific repo
  if (options.repo) {
    source = options.repo;
  }

  console.log(chalk.green('Cloning branch: %s into destination folder:'), options.branch, name);

  progress.start();
  source = options.branch + ' ' + source + ' ' + name;
  shell.exec('git clone -b ' + source, function(code) {
    progress.stop();
    if (code) return console.log(chalk.red('Error: git clone failed'));

    loadPackageJson('./' + name + '/package.json', function(err, data) {
      if (err) {
        console.log(chalk.yellow('Something went wrong. Try again or use --git flag'));
        console.log(chalk.yellow('If the problem persists see past issues here: https://github.com/linnovate/mean/issues'));
        console.log(chalk.yellow('Or open a new issue here https://github.com/linnovate/mean/issues/new'));
        //fallback code here
        process.exit();
      }

      console.log(chalk.green('Version: %s cloned'), data.meanVersion);
      console.log();

      fs.readFile(__dirname + '/../img/logo.txt', function(err, data) {
        console.log(data.toString());
        console.log();

        shell.cd(name);
        shell.exec('git remote rename origin upstream', function(code) {
          if (!code) {
            console.log('   git remote upstream set');
            console.log();
          }
        });

        if (options.quick) {
          npm.load(function(err, npm) {
            console.log(chalk.green('   installing dependencies...'));
            console.log();
            npm.commands.install(function(err) {
              if (err) {
                console.log(chalk.red('Error: npm install failed'));
                return console.error(err);
              }
              console.log(chalk.green('   running the mean app...'));
              console.log();
              if (shell.which('grunt')) {
                shell.exec('grunt', ['-f']);
              }
            });
          });
        } else {
          console.log('   install dependencies:');
          console.log('     $ cd %s && npm install', name);
          console.log();
          console.log('   run the app:');
          console.log('     $ grunt');
          console.log();
        }
        console.log('   Extra Docs at http://mean.io');
        console.log();
      });
    });
  });
};

exports.postinstall = function() {
  requiresRoot(function() {
    // install bower
    console.log(chalk.green('Installing Bower packages'));
    require('bower').commands.install().on('error', function(err) {
      console.log(chalk.red(err));
    });

    console.log(chalk.green('Auto installing package dependencies'));
    var source = 'packages';
    var rootDir = process.cwd();
    npm.load({
      loglevel: 'error'
    }, function(err, npm) {
      fs.readdir(rootDir + '/' + source, function(err, files) {
        if (err && 'ENOENT' !== err.code) throw Error(err);

        files.forEach(function(file) {
          shell.cd(rootDir + '/' + source + '/' + file);
          npm.commands.install(['.'], function(err) {
            if (err) {
              console.log(chalk.red('Error: npm install failed'));
              return console.error(err);
            } else {
              console.log(chalk.green('    Dependencies installed for package ' + file));
            }
          });
        });
      });
    });
  });
};

exports.install = function(module, options) {
  requiresRoot(function() {
    var source = 'https://github.com/linnovate/' + module + '/tarball/' + options.branch;

    // Allow specifying specific repo
    if (options.repo) {
      source = options.repo;
    }

    // Allow installing packages from npm
    if (options.npm) {
      source = module;
    }

    console.log(chalk.green('Installing module: %s from branch (version):'), module, options.branch);
    console.log();

    npm.load(function(err, npm) {
      npm.commands.install([source], function(err) {
        if (err) {
          console.log(chalk.red('Error: npm install failed'));
          return console.error(err);
        }

        loadPackageJson('./node_modules/' + module + '/package.json', function(err, data) {
          if (err) return console.error(err);

          console.log();
          console.log(getPackageInfo(pkgType.contrib, data));
          if (!data.mean) {
            console.log();
            console.log(chalk.yellow('Warning: The module installed is not a valid MEAN module'));
          }
        });
      });
    });
  });
};

exports.uninstall = function(module) {
  requiresRoot(function() {
    console.log(chalk.yellow('Removing module:'), module);

    npm.load(function(err, npm) {
      npm.commands.uninstall([module], function(err) {
        if (err) {
          console.log(chalk.red('Error: npm install failed'));
          return console.error(err);
        }
        console.log(chalk.green('   npm uninstall complete'));
      });
    });
  });
};

exports.list = function() {
  requiresRoot(function() {

    console.log(chalk.green('   MEAN Packages List:'));
    console.log('   -----------------');

    function look(type) {
      var path = type === pkgType.contrib ? './node_modules/' : './packages/';
      fs.readdir(path, function(err, files) {
        if (err || !files.length) return console.log(chalk.yellow('   No ' + type + ' Packages'));
        files.forEach(function(file) {
          loadPackageJson(path + file + '/package.json', function(err, data) {
            if (!err && data.mean) console.log(getPackageInfo(type, data));
          });
        });
      });
    }

    // look in node_modules for external packages
    look(pkgType.contrib);

    // look in packages for local packages
    look(pkgType.custom);
  });
};

exports.status = function(options) {
  requiresRoot(function() {
    console.log();
    console.log(chalk.green('    MEAN Status'));
    console.log('    -----------');
    console.log();
    loadPackageJson('./package.json', function(err, data) {
      console.log('    MEAN VERSION: ' + data.meanVersion);
      console.log();
      mongoConnect(options.env, function(err, db) {
        console.log('    MongoDB URI: ' + db.options.url);
        checkVersion();
        db.close();
      });
    });
  });
};

exports.pkg = function(name, options) {
  requiresRoot(function() {
    if (options.delete) {
      console.log(chalk.yellow('Removing package:'), name);
      shell.rm('-rf', './packages/' + name);
    } else {
      ensureEmpty('./packages/' + name, options.force, function() {
        require('./scaffold.js').packages(name, options);
      });
    }
  });
};

exports.printUser = function(email, options) {
  requiresRoot(function() {
    mongoConnect(options.env, function(err, db) {
      db.collection('users').find({
        email: email
      }).toArray(function(err, user) {
        console.dir(user);
        db.close();
      });
    });
  });
};

exports.updateRole = function(email, options, type) {
  requiresRoot(function() {
    var update = {};
    switch (type) {
      case 'a':
        console.log(chalk.green('  Adding role `' + options.addRole + '` to user `' + email + '`'));
        update.$push = {
          roles: options.addRole
        };
        break;
      case 'r':
        console.log(chalk.green('  Removing role `' + options.removeRole + '` from user `' + email + '`'));
        update.$pull = {
          roles: options.removeRole
        };
        break;
      default:
        return;
    }
    mongoConnect(options.env, function(err, db) {
      db.collection('users').update({
        email: email
      }, update, {
        w: 1,
        upsert: false,
        multi: false
      }, function(err) {
        if (err) console.error(err);
        else console.log(chalk.green('successfully updated'));
        db.close();
      });
    });
  });
};
<|endoftext|>


<commit_before>var program = require('commander');
var prompt = require('prompt');

var promptSchema = require('./promptSchema/config');
var pkg = require('../package.json');
var actions = require('./actions');
var logger = require('./logger');
var messages = require('./env/messages');

program
  .version(pkg.version);

// program: init
program
  .command('init [dir]')
  .description('wp init [dir]')
  .action(function(dir) {
    // welcome
    var docRoot = (dir) ? `${actions.utils.getWorkingDir()}/${dir}` : `${actions.utils.getWorkingDir()}/`;
    var params = {
      '<cliVersion>': pkg.version,
      '<docRoot>': docRoot
    };
    logger.log(messages.config.init.allReplace(params));

    // set `rootDir`
    var rootDir = './';
    if (dir) {
      rootDir = `./${dir}/`;
    }

    // check for existing project
    if (actions.utils.isFileExists(`${rootDir}site.json`)) {
      logger.error(messages.config.alreadyExists);
      return;
    }

    // prompt for user inputs
    logger.log(messages.config.promptForUserInputs);

    prompt.start();
    prompt.get(promptSchema, function (err, config) {
      if (err) {
        logger.error(`${err.name}: ${err.message}`);
        return;
      }
      actions.config.init(dir, config);
    });
  });

// program: config
program
  .command('config <opt> <key> <val>')
  .description('wp config update <key> <val>')
  .action(function(opt, key, val) {
    switch (opt) {
      case 'update':
        actions.config.update(key, val);
        break;
      default:
        logger.error(`\r\n  error: invalid option flag \`${opt}\` \r\n`);
        break;
    }
});

// program: plugin
program
  .command('plugin <opt> <pluginName>')
  .description('wp plugin <opt> <pluginName>@<pluginVersion>')
  .action(function(opt, pluginName) {
    switch (opt) {
      case 'add':
        actions.plugin.add(pluginName);
        break;
      case 'remove':
        actions.plugin.remove(pluginName);
        break;
      default:
        logger.error(`\r\n  error: invalid option flag \`${opt}\` \r\n`);
        break;
    }
});

// program: template
program
  .command('template <opt>')
  .description('wp template <opt>')
  .action(function(opt) {
    switch (opt) {
      case 'init':
        actions.template.init();
        break;
      default:
       logger.error(`\r\n  error: invalid option flag \`${opt}\` \r\n`);
        break;
    }
});

// program: serve
program
  .command('serve')
  .option('-p, --port [value]', 'Port to listen on (instead of the default 8888).')
  .description('wp serve')
  .action(function(options) {
    actions.server.start(options);
  });

// program: [anything else]
program
  .command('*')
  .action(function(env) {
    logger.error(`\r\n  error: invalid command input \`${env}\` \r\n`);
  });

program.parse(process.argv);
<commit_msg>Add alias (s) to serve<commit_after>var program = require('commander');
var prompt = require('prompt');

var promptSchema = require('./promptSchema/config');
var pkg = require('../package.json');
var actions = require('./actions');
var logger = require('./logger');
var messages = require('./env/messages');

program
  .version(pkg.version);

// program: init
program
  .command('init [dir]')
  .description('wp init [dir]')
  .action(function(dir) {
    // welcome
    var docRoot = (dir) ? `${actions.utils.getWorkingDir()}/${dir}` : `${actions.utils.getWorkingDir()}/`;
    var params = {
      '<cliVersion>': pkg.version,
      '<docRoot>': docRoot
    };
    logger.log(messages.config.init.allReplace(params));

    // set `rootDir`
    var rootDir = './';
    if (dir) {
      rootDir = `./${dir}/`;
    }

    // check for existing project
    if (actions.utils.isFileExists(`${rootDir}site.json`)) {
      logger.error(messages.config.alreadyExists);
      return;
    }

    // prompt for user inputs
    logger.log(messages.config.promptForUserInputs);

    prompt.start();
    prompt.get(promptSchema, function (err, config) {
      if (err) {
        logger.error(`${err.name}: ${err.message}`);
        return;
      }
      actions.config.init(dir, config);
    });
  });

// program: config
program
  .command('config <opt> <key> <val>')
  .description('wp config update <key> <val>')
  .action(function(opt, key, val) {
    switch (opt) {
      case 'update':
        actions.config.update(key, val);
        break;
      default:
        logger.error(`\r\n  error: invalid option flag \`${opt}\` \r\n`);
        break;
    }
});

// program: plugin
program
  .command('plugin <opt> <pluginName>')
  .description('wp plugin <opt> <pluginName>@<pluginVersion>')
  .action(function(opt, pluginName) {
    switch (opt) {
      case 'add':
        actions.plugin.add(pluginName);
        break;
      case 'remove':
        actions.plugin.remove(pluginName);
        break;
      default:
        logger.error(`\r\n  error: invalid option flag \`${opt}\` \r\n`);
        break;
    }
});

// program: template
program
  .command('template <opt>')
  .description('wp template <opt>')
  .action(function(opt) {
    switch (opt) {
      case 'init':
        actions.template.init();
        break;
      default:
       logger.error(`\r\n  error: invalid option flag \`${opt}\` \r\n`);
        break;
    }
});

// program: serve
program
  .command('serve')
  .alias('s')
  .option('-p, --port [value]', 'Port to listen on (instead of the default 8888).')
  .description('wp serve')
  .action(function(options) {
    actions.server.start(options);
  });

// program: [anything else]
program
  .command('*')
  .action(function(env) {
    logger.error(`\r\n  error: invalid command input \`${env}\` \r\n`);
  });

program.parse(process.argv);
<|endoftext|>


<commit_before>var fs     = require('fs'),
    path   = require('path'),
    spawn  = require('child_process').spawn,
    colors = require('colors'),
    mkdirp = require('mkdirp'),
    Table  = require('cli-table'),
    format = require('./formatter').format,
    api

var rl = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
})

var conf = require('./conf'),
    globalConfigPath = conf.path,
    webInterfaceId   = conf.webId

var tableOptions = {
    style: { compact: true, 'padding-left': 4 },
    chars: { 'top': '' , 'top-mid': '' , 'top-left': '' , 'top-right': ''
     , 'bottom': '' , 'bottom-mid': '' , 'bottom-left': '' , 'bottom-right': ''
     , 'left': '' , 'left-mid': '' , 'mid': '' , 'mid-mid': ''
     , 'right': '' , 'right-mid': '' , 'middle': ' ' },
    head: ['name', 'status', 'port', 'restarts', 'uptime', 'memory', 'CPU'].map(function (field) {
        return field.grey
    })
}

var cli = {

    help: function () {
        console.log('\n  POD '.green + 'v' + api.version)
        console.log(fs.readFileSync(__dirname + '/../help/usage', 'utf-8'))
        process.exit(0)
    },

    create: function (appname) {
        if (!appname) exit()
        api.createApp(appname, output)
    },

    remote: function (appname, repo, branch) {
        if (!appname || !repo) exit()
        api.createApp(appname, {
            remote: repo,
            branch: branch
        }, output)
    },

    rm: function (arg1, arg2) {
        var force = false,
            appname = arg1
        if (arg1 === '-f') {
            force = true
            appname = arg2
        } else if (arg2 === '-f') {
            force = true
        }
        if (!appname) exit()
        if (force) {
            return api.removeApp(appname, output)
        }
        rl.question('really delete ' + appname.yellow + '? (y/N)', function (reply) {
            if (reply.toLowerCase() === 'y') {
                api.removeApp(appname, output)
            } else {
                log('aborted.')
                process.exit(0)
            }
        })
    },

    start: function (appname) {
        if (!appname) exit()
        api.startApp(appname, output)
    },

    stop: function (appname) {
        if (!appname) exit()
        api.stopApp(appname, output)
    },

    restart: function (appname) {
        if (!appname) exit()
        api.restartApp(appname, output)
    },

    startall: function () {
        api.startAllApps(output)
    },

    stopall: function () {
        api.stopAllApps(output)
    },

    restartall: function () {
        api.restartAllApps(output)
    },

    list: function () {
        api.listApps(function (err, apps) {
            if (err) {
                warn(err)
                process.exit(1)
            }
            if (!apps || !apps.length) {
                log('no apps found.')
            } else {
                var table = new Table(tableOptions)
                table.push(new Array(7))
                apps.forEach(function (app) {
                    table.push(toArray(app))
                })
                console.log()
                console.log(table.toString())
                console.log()
            }
            process.exit(0)
        })
    },

    prune: function () {
        api.prune(output)
    },

    hooks: function () {
        api.updateHooks(output)
    },

    web: function (action) {
        if (action === 'stop') {
            api.stopApp(webInterfaceId, output)
        } else if (action === 'restart') {
            api.restartApp(webInterfaceId, output)
        } else if (action === 'status') {
            logStatus()
        } else {
            api.startApp(webInterfaceId, function (err, msg) {
                if (msg && msg.indexOf('already') > 0) { // web interface already on
                    logStatus()
                } else {
                    output(err, msg)
                }
            })
        }

        function logStatus () {
            api.proxy('getMonitorData', {}, function (err, list) {
                if (err) return output(err)
                list.forEach(function (proc) {
                    if (proc.pm2_env.name === webInterfaceId) {
                        var app = api.getAppInfo(webInterfaceId)
                        app.instances = [proc]
                        var table = new Table(tableOptions)
                        table.push(toArray(format(app)))
                        console.log(table.toString())
                        process.exit(0)
                    }
                })
                output(null, 'web interface is not running.')
            })
        }
    }
}

// Init
if (!fs.existsSync(globalConfigPath)) {
    if (process.env.POD_ROOT_DIR) return createRootDir(process.env.POD_ROOT_DIR)
    console.log(
        'Hello! It seems it\'s your first time running pod on this machine.\n' +
        'Please specify a directory for pod to put stuff in.\n' +
        '- Make sure your account has full access to that directory.\n' +
        '- You can use relative paths (resolved against your cwd).'
    )
    rl.question('path: ', createRootDir)
} else {
    loadAPI()
}

function createRootDir (dir) {
    if (dir.charAt(0) === '~') { // home path
        dir = process.env.HOME + dir.slice(1)
    } else {
        dir = path.resolve(process.cwd(), dir)
    }
    if (fs.existsSync(dir)) {
        if (!fs.statSync(dir).isDirectory()) {
            warn('target path ' + dir.grey + ' is not a directory.')
            process.exit(1)
        } else {
            initConfig(dir)
            loadAPI()
        }
    } else {
        if (process.env.TEST) return make()
        rl.question('target path ' + dir.grey + ' doesn\'t exist. create it? (y/N)', function (reply) {
            if (reply.toLowerCase() === 'y') {
                make()
            } else {
                process.exit(0)
            }
        })
    }

    function make () {
        console.log()
        mkdirp.sync(dir)
        log('created root directory: ' + dir.grey)
        fs.mkdirSync(dir + '/repos')
        log('created repos directory: ' + (dir + '/repos').grey)
        fs.mkdirSync(dir + '/apps')
        log('created apps directory: ' + (dir + '/apps').grey)
        initConfig(dir)
        log('created config file at: ' + globalConfigPath.grey)
        loadAPI()
    }
}

function initConfig (root) {
    var globalConfig = {
        root: root,
        node_env: 'development',
        default_script: 'app.js',
        apps: {},
        web: {}
    }
    mkdirp.sync(globalConfigPath.slice(0, globalConfigPath.lastIndexOf('/')))
    fs.writeFileSync(globalConfigPath, JSON.stringify(globalConfig, null, 4))
}

// env editor vars might contain args, which breaks edit()
function stripArgs (cmd) {
    if (cmd) return cmd.split(' ')[0]
}

function loadAPI () {
    api = require('./api')
    api.once('ready', parseCommand)
}

function parseCommand () {
    var args = process.argv.slice(2),
        command = args[0] || 'help'
    if (cli[command]) {
        cli[command].apply(null, args.slice(1))
    } else {
        if (command) {
            warn('unknown command ' + command.red)
            process.exit(1)
        }
    }
}

function output (err, msg) {
    if (err) {
        warn(err)
        process.exit(1)
    } else {
        log(msg)
        process.exit(0)
    }
}

function log (msg) {
    if (!Array.isArray(msg)) {
        console.log('POD '.green + msg)
    } else {
        msg.forEach(function (m) {
            console.log('POD '.green + m)
        })
    }
}

function warn (err) {
    err = err.toString().replace('Error: ', '')
    console.warn('POD '.green + 'ERR '.red + err)
}

function toArray (app) {

    var restarts = app.restarts
    if (restarts === 0) restarts = restarts.toString().green
    if (restarts > 0 && restarts < 10) restarts = restarts.toString().yellow
    if (restarts > 10) restarts = restarts.toString().red

    var status = app.status
    if (status === 'ON') status = status.green
    if (status === 'OFF') status = status.magenta
    if (status === 'BROKEN' || status === 'ERROR') status = status.red

    var uptime = app.uptime
    if (uptime) uptime = uptime.cyan

    return [
        app.name.yellow,
        status,
        app.port,
        restarts || '',
        uptime || '',
        app.memory || '',
        app.cpu || ''
    ]
}

function exit () {
    warn('invalid command arguments')
    process.exit(1)
}<commit_msg>Resolved issue with input being blocked when running an  command () when needing to input username/password.<commit_after>var fs     = require('fs'),
    path   = require('path'),
    spawn  = require('child_process').spawn,
    colors = require('colors'),
    mkdirp = require('mkdirp'),
    Table  = require('cli-table'),
    format = require('./formatter').format,
    api

var rl = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
})

var conf = require('./conf'),
    globalConfigPath = conf.path,
    webInterfaceId   = conf.webId

var tableOptions = {
    style: { compact: true, 'padding-left': 4 },
    chars: { 'top': '' , 'top-mid': '' , 'top-left': '' , 'top-right': ''
     , 'bottom': '' , 'bottom-mid': '' , 'bottom-left': '' , 'bottom-right': ''
     , 'left': '' , 'left-mid': '' , 'mid': '' , 'mid-mid': ''
     , 'right': '' , 'right-mid': '' , 'middle': ' ' },
    head: ['name', 'status', 'port', 'restarts', 'uptime', 'memory', 'CPU'].map(function (field) {
        return field.grey
    })
}

var cli = {

    help: function () {
        console.log('\n  POD '.green + 'v' + api.version)
        console.log(fs.readFileSync(__dirname + '/../help/usage', 'utf-8'))
        process.exit(0)
    },

    create: function (appname) {
        if (!appname) exit()

        rl.close()
        api.createApp(appname, output)
    },

    remote: function (appname, repo, branch) {
        if (!appname || !repo) exit()

        rl.close()
        api.createApp(appname, {
            remote: repo,
            branch: branch
        }, output)
    },

    rm: function (arg1, arg2) {
        var force = false,
            appname = arg1
        if (arg1 === '-f') {
            force = true
            appname = arg2
        } else if (arg2 === '-f') {
            force = true
        }
        if (!appname) exit()
        if (force) {
            rl.close()
            return api.removeApp(appname, output)
        }
        rl.question('really delete ' + appname.yellow + '? (y/N)', function (reply) {
            if (reply.toLowerCase() === 'y') {
                rl.close()
                api.removeApp(appname, output)
            } else {
                log('aborted.')
                process.exit(0)
            }
        })
    },

    start: function (appname) {
        if (!appname) exit()
        api.startApp(appname, output)
    },

    stop: function (appname) {
        if (!appname) exit()
        api.stopApp(appname, output)
    },

    restart: function (appname) {
        if (!appname) exit()
        api.restartApp(appname, output)
    },

    startall: function () {
        api.startAllApps(output)
    },

    stopall: function () {
        api.stopAllApps(output)
    },

    restartall: function () {
        api.restartAllApps(output)
    },

    list: function () {
        api.listApps(function (err, apps) {
            if (err) {
                warn(err)
                process.exit(1)
            }
            if (!apps || !apps.length) {
                log('no apps found.')
            } else {
                var table = new Table(tableOptions)
                table.push(new Array(7))
                apps.forEach(function (app) {
                    table.push(toArray(app))
                })
                console.log()
                console.log(table.toString())
                console.log()
            }
            process.exit(0)
        })
    },

    prune: function () {
        api.prune(output)
    },

    hooks: function () {
        api.updateHooks(output)
    },

    web: function (action) {
        if (action === 'stop') {
            api.stopApp(webInterfaceId, output)
        } else if (action === 'restart') {
            api.restartApp(webInterfaceId, output)
        } else if (action === 'status') {
            logStatus()
        } else {
            api.startApp(webInterfaceId, function (err, msg) {
                if (msg && msg.indexOf('already') > 0) { // web interface already on
                    logStatus()
                } else {
                    output(err, msg)
                }
            })
        }

        function logStatus () {
            api.proxy('getMonitorData', {}, function (err, list) {
                if (err) return output(err)
                list.forEach(function (proc) {
                    if (proc.pm2_env.name === webInterfaceId) {
                        var app = api.getAppInfo(webInterfaceId)
                        app.instances = [proc]
                        var table = new Table(tableOptions)
                        table.push(toArray(format(app)))
                        console.log(table.toString())
                        process.exit(0)
                    }
                })
                output(null, 'web interface is not running.')
            })
        }
    }
}

// Init
if (!fs.existsSync(globalConfigPath)) {
    if (process.env.POD_ROOT_DIR) return createRootDir(process.env.POD_ROOT_DIR)
    console.log(
        'Hello! It seems it\'s your first time running pod on this machine.\n' +
        'Please specify a directory for pod to put stuff in.\n' +
        '- Make sure your account has full access to that directory.\n' +
        '- You can use relative paths (resolved against your cwd).'
    )
    rl.question('path: ', createRootDir)
} else {
    loadAPI()
}

function createRootDir (dir) {
    if (dir.charAt(0) === '~') { // home path
        dir = process.env.HOME + dir.slice(1)
    } else {
        dir = path.resolve(process.cwd(), dir)
    }
    if (fs.existsSync(dir)) {
        if (!fs.statSync(dir).isDirectory()) {
            warn('target path ' + dir.grey + ' is not a directory.')
            process.exit(1)
        } else {
            initConfig(dir)
            loadAPI()
        }
    } else {
        if (process.env.TEST) return make()
        rl.question('target path ' + dir.grey + ' doesn\'t exist. create it? (y/N)', function (reply) {
            if (reply.toLowerCase() === 'y') {
                make()
            } else {
                process.exit(0)
            }
        })
    }

    function make () {
        console.log()
        mkdirp.sync(dir)
        log('created root directory: ' + dir.grey)
        fs.mkdirSync(dir + '/repos')
        log('created repos directory: ' + (dir + '/repos').grey)
        fs.mkdirSync(dir + '/apps')
        log('created apps directory: ' + (dir + '/apps').grey)
        initConfig(dir)
        log('created config file at: ' + globalConfigPath.grey)
        loadAPI()
    }
}

function initConfig (root) {
    var globalConfig = {
        root: root,
        node_env: 'development',
        default_script: 'app.js',
        apps: {},
        web: {}
    }
    mkdirp.sync(globalConfigPath.slice(0, globalConfigPath.lastIndexOf('/')))
    fs.writeFileSync(globalConfigPath, JSON.stringify(globalConfig, null, 4))
}

// env editor vars might contain args, which breaks edit()
function stripArgs (cmd) {
    if (cmd) return cmd.split(' ')[0]
}

function loadAPI () {
    api = require('./api')
    api.once('ready', parseCommand)
}

function parseCommand () {
    var args = process.argv.slice(2),
        command = args[0] || 'help'
    if (cli[command]) {
        cli[command].apply(null, args.slice(1))
    } else {
        if (command) {
            warn('unknown command ' + command.red)
            process.exit(1)
        }
    }
}

function output (err, msg) {
    if (err) {
        warn(err)
        process.exit(1)
    } else {
        log(msg)
        process.exit(0)
    }
}

function log (msg) {
    if (!Array.isArray(msg)) {
        console.log('POD '.green + msg)
    } else {
        msg.forEach(function (m) {
            console.log('POD '.green + m)
        })
    }
}

function warn (err) {
    err = err.toString().replace('Error: ', '')
    console.warn('POD '.green + 'ERR '.red + err)
}

function toArray (app) {

    var restarts = app.restarts
    if (restarts === 0) restarts = restarts.toString().green
    if (restarts > 0 && restarts < 10) restarts = restarts.toString().yellow
    if (restarts > 10) restarts = restarts.toString().red

    var status = app.status
    if (status === 'ON') status = status.green
    if (status === 'OFF') status = status.magenta
    if (status === 'BROKEN' || status === 'ERROR') status = status.red

    var uptime = app.uptime
    if (uptime) uptime = uptime.cyan

    return [
        app.name.yellow,
        status,
        app.port,
        restarts || '',
        uptime || '',
        app.memory || '',
        app.cpu || ''
    ]
}

function exit () {
    warn('invalid command arguments')
    process.exit(1)
}
<|endoftext|>


<commit_before>/*
 * Copyright 2012 Amadeus s.a.s.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var TestCampaign = require('./test-campaign/campaign.js');
var TestServer = require('./test-server/server.js');
var optimist = require('optimist');
var fs = require('fs');
var yaml = require('js-yaml');
var Logger = require('./logging/logger.js');
var ConsoleLogger = require('./logging/console-logger.js');
var ConsoleReport = require('./reports/console-report.js');
var JsonConsole = require('./reports/json-console.js');
var JsonReport = require('./reports/json-report.js');
var JsonLogReport = require('./reports/json-log-report.js');
var colors = require('colors');
var writeReports = require('./reports/write-reports.js');
var merge = require('./merge.js');
var childProcesses = require('./child-processes');
var exitProcess = require('./exit-process.js');

var readConfigFile = function (configFile, logger) {
    var configFileContent;
    try {
        configFileContent = fs.readFileSync(configFile, "utf8");
    } catch (e) {
        logger.logError("Error while opening the configuration file: %s", [e]);
        return false;
    }
    try {
        return (/\.ya?ml$/i).test(configFile) ? yaml.load(configFileContent) : JSON.parse(configFileContent);
    } catch (e) {
        logger.logError("Unable to parse configuration file %s : %s", [configFile, e]);
        return false;
    }
};

var run = function () {
    var opt = optimist.usage('Usage: $0 [options] [config.yml|config.json]').boolean(['json-console', 'help', 'server-only', 'version', 'colors', 'ignore-errors', 'ignore-failures']).string(['phantomjs-path']).describe({
        'log-level': 'Level of logging: integer from 0 (no logging) to 4 (debug).',
        'port': 'Port used for the web server. If set to 0, an available port is automatically selected.',
        'json-console': 'When enabled, JSON objects will be sent to stdout to provide information about tests.',
        'heartbeats': 'Delay (in ms) for heartbeats messages sent when --json-console is enabled. Use 0 to disable them.',
        'server-only': 'Only starts the web server, and configure it for the test campaign but do not start the campaign.',
        'phantomjs-instances': 'Number of instances of PhantomJS to start.',
        'phantomjs-path': 'Path to PhantomJS executable.',
        'browser': 'Path to any browser executable to execute the tests. Can be repeated multiple times.',
        'ignore-errors': 'When enabled, test errors (not including failures) will not cause this process to return a non-zero value.',
        'ignore-failures': 'When enabled, test failures (anticipated errors) will not cause this process to return a non-zero value.',
        'help': 'Displays this help message and exits.',
        'colors': 'Uses colors (disable with --no-colors).',
        'version': 'Displays the version number and exits.'
    }).alias({
        'j': 'json-console',
        'p': 'port'
    })['default']({
        'heartbeats': 2000,
        'port': 0,
        'log-level': 3,
        'colors': true,
        'phantomjs-instances': process.env.npm_package_config_phantomjsInstances || 0,
        'phantomjs-path': 'phantomjs',
        'ignore-errors': false,
        'ignore-failures': false
    });
    var argv = opt.argv;
    var reports = [];
    if (argv.help) {
        opt.showHelp();
        exitProcess(0);
        return;
    }
    if (argv.version) {
        console.log(require('../package.json').version);
        exitProcess(0);
        return;
    }

    var testServer = null;
    var endProcess = function (success) {
        if (testServer) {
            testServer.close();
        }
        childProcesses.closeAll();
        exitProcess(success ? 0 : 1);
    };

    if (argv['json-console']) {
        var jsonConsole = new JsonConsole(process.stdout, argv.heartbeats);
        process.stdout.on('error', function () {
            // the process listening on this stream was closed
            endProcess();
        });
        process.stdout = process.stderr;
        console.log = console.warn;
        reports.push(jsonConsole);
    }
    colors.mode = argv.colors ? "console" : "none";

    var logger = new Logger("attester");
    logger.logLevels['.'] = argv['log-level'];
    var consoleLogger = new ConsoleLogger(process.stdout);
    consoleLogger.attach(logger);

    var configData = {
        'coverage': null,
        'resources': {
            '/': []
        },
        'test-reports': {
            'json-log-file': [],
            'json-file': [],
            'xml-file': [],
            'xml-directory': []
        },
        'coverage-reports': {
            'json-file': [],
            'lcov-file': []
        }
    };
    var configFile = argv._[0];
    if (configFile) {
        configFile = readConfigFile(configFile, logger);
        if (configFile === false) {
            return;
        }
        merge(configData, configFile);
    }

    if (argv.config) {
        var argvResources = argv.config.resources;
        if (argvResources) { // "array-ify" entries in resources so they can get merged properly
            for (var key in argvResources) {
                if (argvResources.hasOwnProperty(key) && !Array.isArray(argvResources[key])) {
                    argvResources[key] = [argvResources[key]];
                }
            }
        }

        merge(configData, argv.config);
    }

    var campaign = new TestCampaign(configData, logger);

    var jsonReport = new JsonReport();
    reports.push(jsonReport);
    reports.push(new ConsoleReport(logger));
    var logReports = configData['test-reports']['json-log-file'];
    var i, l;
    for (i = 0, l = logReports.length; i < l; i++) {
        reports.push(new JsonLogReport(logReports[i]));
    }

    for (i = 0, l = reports.length; i < l; i++) {
        var curReport = reports[i];
        campaign.on('result', curReport.addResult.bind(curReport));
    }

    var phantomJSinstances = argv['phantomjs-instances'];
    if (phantomJSinstances > 0) {
        campaign.on('result-serverAttached', function (event) {
            var path = argv['phantomjs-path'];
            var args = event.phantomJS;
            var spawn = childProcesses.spawn;
            for (var i = 0; i < phantomJSinstances; i++) {
                var curProcess = spawn(path, args, {
                    stdio: "pipe"
                });
                curProcess.stdout.pipe(process.stdout);
                curProcess.stderr.pipe(process.stderr);
            }
        });
    }

    var browsers = argv.browser;
    if (browsers) {
        if (!Array.isArray(browsers)) {
            browsers = [browsers];
        }
        campaign.on('result-serverAttached', function (event) {
            var args = [event.slaveURL];
            var spawn = childProcesses.spawn;
            process.stdout.setMaxListeners(256); // so that phantomJSinstances can be > 10
            process.stderr.setMaxListeners(256);
            for (var i = 0, l = browsers.length; i < l; i++) {
                var curProcess = spawn(browsers[i], args, {
                    stdio: "pipe"
                });
                curProcess.stdout.pipe(process.stdout);
                curProcess.stderr.pipe(process.stderr);
            }
        });
    }

    campaign.on('finished', function () {
        writeReports({
            test: configData['test-reports'],
            coverage: configData['coverage-reports']
        }, {
            test: jsonReport,
            coverage: campaign.getCoverageResult()
        }, function (err) {
            if (err) {
                logger.logError('An error occurred while writing reports: %s', err);
                endProcess();
                return;
            }
            var ignoreErrors = argv['ignore-errors'];
            var ignoreFailures = argv['ignore-failures'];
            var stats = jsonReport.stats;
            var success = (ignoreErrors || stats.errors === 0) && (ignoreFailures || stats.failures === 0);
            logger.logInfo('Tests run: %d, Failures: %d, Errors: %d, Skipped: %d', [stats.testCases, stats.failures, stats.errors, stats.tasksIgnored]);
            endProcess(success);
        });
    });

    campaign.init(function () {
        testServer = new TestServer({
            frozen: argv['server-only']
        }, logger);
        testServer.server.on('error', function (error) {
            testServer.logger.logError('Web server error: %s', [error]);
            endProcess();
        });
        testServer.server.listen(argv.port, function () {
            testServer.addCampaign(campaign);
        });
    });

};

module.exports = run;<commit_msg>Fixing node warnings if >10 instances of PhantomJS launched.<commit_after>/*
 * Copyright 2012 Amadeus s.a.s.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var TestCampaign = require('./test-campaign/campaign.js');
var TestServer = require('./test-server/server.js');
var optimist = require('optimist');
var fs = require('fs');
var yaml = require('js-yaml');
var Logger = require('./logging/logger.js');
var ConsoleLogger = require('./logging/console-logger.js');
var ConsoleReport = require('./reports/console-report.js');
var JsonConsole = require('./reports/json-console.js');
var JsonReport = require('./reports/json-report.js');
var JsonLogReport = require('./reports/json-log-report.js');
var colors = require('colors');
var writeReports = require('./reports/write-reports.js');
var merge = require('./merge.js');
var childProcesses = require('./child-processes');
var exitProcess = require('./exit-process.js');

var readConfigFile = function (configFile, logger) {
    var configFileContent;
    try {
        configFileContent = fs.readFileSync(configFile, "utf8");
    } catch (e) {
        logger.logError("Error while opening the configuration file: %s", [e]);
        return false;
    }
    try {
        return (/\.ya?ml$/i).test(configFile) ? yaml.load(configFileContent) : JSON.parse(configFileContent);
    } catch (e) {
        logger.logError("Unable to parse configuration file %s : %s", [configFile, e]);
        return false;
    }
};

var run = function () {
    var opt = optimist.usage('Usage: $0 [options] [config.yml|config.json]').boolean(['json-console', 'help', 'server-only', 'version', 'colors', 'ignore-errors', 'ignore-failures']).string(['phantomjs-path']).describe({
        'log-level': 'Level of logging: integer from 0 (no logging) to 4 (debug).',
        'port': 'Port used for the web server. If set to 0, an available port is automatically selected.',
        'json-console': 'When enabled, JSON objects will be sent to stdout to provide information about tests.',
        'heartbeats': 'Delay (in ms) for heartbeats messages sent when --json-console is enabled. Use 0 to disable them.',
        'server-only': 'Only starts the web server, and configure it for the test campaign but do not start the campaign.',
        'phantomjs-instances': 'Number of instances of PhantomJS to start.',
        'phantomjs-path': 'Path to PhantomJS executable.',
        'browser': 'Path to any browser executable to execute the tests. Can be repeated multiple times.',
        'ignore-errors': 'When enabled, test errors (not including failures) will not cause this process to return a non-zero value.',
        'ignore-failures': 'When enabled, test failures (anticipated errors) will not cause this process to return a non-zero value.',
        'help': 'Displays this help message and exits.',
        'colors': 'Uses colors (disable with --no-colors).',
        'version': 'Displays the version number and exits.'
    }).alias({
        'j': 'json-console',
        'p': 'port'
    })['default']({
        'heartbeats': 2000,
        'port': 0,
        'log-level': 3,
        'colors': true,
        'phantomjs-instances': process.env.npm_package_config_phantomjsInstances || 0,
        'phantomjs-path': 'phantomjs',
        'ignore-errors': false,
        'ignore-failures': false
    });
    var argv = opt.argv;
    var reports = [];
    if (argv.help) {
        opt.showHelp();
        exitProcess(0);
        return;
    }
    if (argv.version) {
        console.log(require('../package.json').version);
        exitProcess(0);
        return;
    }

    var testServer = null;
    var endProcess = function (success) {
        if (testServer) {
            testServer.close();
        }
        childProcesses.closeAll();
        exitProcess(success ? 0 : 1);
    };

    if (argv['json-console']) {
        var jsonConsole = new JsonConsole(process.stdout, argv.heartbeats);
        process.stdout.on('error', function () {
            // the process listening on this stream was closed
            endProcess();
        });
        process.stdout = process.stderr;
        console.log = console.warn;
        reports.push(jsonConsole);
    }
    colors.mode = argv.colors ? "console" : "none";

    var logger = new Logger("attester");
    logger.logLevels['.'] = argv['log-level'];
    var consoleLogger = new ConsoleLogger(process.stdout);
    consoleLogger.attach(logger);

    var configData = {
        'coverage': null,
        'resources': {
            '/': []
        },
        'test-reports': {
            'json-log-file': [],
            'json-file': [],
            'xml-file': [],
            'xml-directory': []
        },
        'coverage-reports': {
            'json-file': [],
            'lcov-file': []
        }
    };
    var configFile = argv._[0];
    if (configFile) {
        configFile = readConfigFile(configFile, logger);
        if (configFile === false) {
            return;
        }
        merge(configData, configFile);
    }

    if (argv.config) {
        var argvResources = argv.config.resources;
        if (argvResources) { // "array-ify" entries in resources so they can get merged properly
            for (var key in argvResources) {
                if (argvResources.hasOwnProperty(key) && !Array.isArray(argvResources[key])) {
                    argvResources[key] = [argvResources[key]];
                }
            }
        }

        merge(configData, argv.config);
    }

    var campaign = new TestCampaign(configData, logger);

    var jsonReport = new JsonReport();
    reports.push(jsonReport);
    reports.push(new ConsoleReport(logger));
    var logReports = configData['test-reports']['json-log-file'];
    var i, l;
    for (i = 0, l = logReports.length; i < l; i++) {
        reports.push(new JsonLogReport(logReports[i]));
    }

    for (i = 0, l = reports.length; i < l; i++) {
        var curReport = reports[i];
        campaign.on('result', curReport.addResult.bind(curReport));
    }

    // so that (phantomjs-instances + the number of browsers) can be > 10:
    process.stdout.setMaxListeners(256);
    process.stderr.setMaxListeners(256);

    var phantomJSinstances = argv['phantomjs-instances'];
    if (phantomJSinstances > 0) {
        campaign.on('result-serverAttached', function (event) {
            var path = argv['phantomjs-path'];
            var args = event.phantomJS;
            var spawn = childProcesses.spawn;
            for (var i = 0; i < phantomJSinstances; i++) {
                var curProcess = spawn(path, args, {
                    stdio: "pipe"
                });
                curProcess.stdout.pipe(process.stdout);
                curProcess.stderr.pipe(process.stderr);
            }
        });
    }

    var browsers = argv.browser;
    if (browsers) {
        if (!Array.isArray(browsers)) {
            browsers = [browsers];
        }
        campaign.on('result-serverAttached', function (event) {
            var args = [event.slaveURL];
            var spawn = childProcesses.spawn;
            for (var i = 0, l = browsers.length; i < l; i++) {
                var curProcess = spawn(browsers[i], args, {
                    stdio: "pipe"
                });
                curProcess.stdout.pipe(process.stdout);
                curProcess.stderr.pipe(process.stderr);
            }
        });
    }

    campaign.on('finished', function () {
        writeReports({
            test: configData['test-reports'],
            coverage: configData['coverage-reports']
        }, {
            test: jsonReport,
            coverage: campaign.getCoverageResult()
        }, function (err) {
            if (err) {
                logger.logError('An error occurred while writing reports: %s', err);
                endProcess();
                return;
            }
            var ignoreErrors = argv['ignore-errors'];
            var ignoreFailures = argv['ignore-failures'];
            var stats = jsonReport.stats;
            var success = (ignoreErrors || stats.errors === 0) && (ignoreFailures || stats.failures === 0);
            logger.logInfo('Tests run: %d, Failures: %d, Errors: %d, Skipped: %d', [stats.testCases, stats.failures, stats.errors, stats.tasksIgnored]);
            endProcess(success);
        });
    });

    campaign.init(function () {
        testServer = new TestServer({
            frozen: argv['server-only']
        }, logger);
        testServer.server.on('error', function (error) {
            testServer.logger.logError('Web server error: %s', [error]);
            endProcess();
        });
        testServer.server.listen(argv.port, function () {
            testServer.addCampaign(campaign);
        });
    });

};

module.exports = run;<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

const pkg = require('../package.json');
const scanner = require('./index.js');
const commander = require('commander');

console.log(`\n\n  (^_^) SOCIAL-SCANNER  `);

// Setup commander
commander
  .version(pkg.version)
  .name(pkg.name)
  .description('A node utility to scan various social networks against username.')
  .usage('[options] <username>')
  .arguments('<username>')
  .option('-o, --output [path]', 'Where to save the output files')
  .option('-t, --timeout [milliseconds]', 'Milliseconds to wait before killing the screenshot')
  .option('-r, --restrict [items]', 'Comma separated list of social networks to scan', val => val.split(','), [])
  .action(username => {
    console.log('\n  Scanning for:', username);
    // Run the scanner
    scanner(username, {
      output: commander.output,
      restrict: commander.restrict
    }, (err, results) => {
      if (err) {
        console.log('An error occurred while scanning:', err);
        return;
      }
      console.log('  Scanned', results.length, 'social networks.\n');
      process.exit();
    });
  })
  .parse(process.argv);
<commit_msg>List command close #5<commit_after>#!/usr/bin/env node

'use strict';

const pkg = require('../package.json');
const scanner = require('./index.js');
const rules = require('./rules.js');
const commander = require('commander');

console.log(`\n\n  (^_^) SOCIAL-SCANNER  `);

// Setup commander
commander
  .version(pkg.version)
  .name(pkg.name)
  .description('A node utility to scan various social networks against username.')
  .usage('[options] <username>')
  .arguments('<username>')
  .option('-o, --output [path]', 'Where to save the output files')
  .option('-t, --timeout [milliseconds]', 'Milliseconds to wait before killing the screenshot')
  .option('-r, --restrict [items]', 'Comma separated list of social networks to scan', val => val.split(','), [])
  .action(username => {
    console.log('\n  Scanning for:', username);
    // Run the scanner
    scanner(username, {
      output: commander.output,
      restrict: commander.restrict
    }, (err, results) => {
      if (err) {
        console.log('An error occurred while scanning:', err);
        return;
      }
      console.log('  Scanned', results.length, 'social networks.\n');
      process.exit();
    });
  });

// Print all the available rule entries
commander
  .command('list')
  .description('List all the available social networks.')
  .action(() => {
    // Group rules by category property
    const groupedRules = rules.reduce(function (rv, x) {
      (rv[x.category] = rv[x.category] || []).push(x);
      return rv;
    }, {});

    console.log('\nThere are', rules.length, 'rules right now in', Object.keys(groupedRules).length, 'categories.\n');

    // Print the grouped rules
    Object.keys(groupedRules).forEach(function (key) {
      let groupRules = groupedRules[key];
      console.log('Category:', key);
      console.log('===========================\n');
      groupRules.forEach(r => {
        console.log('Name:', r.name);
        console.log('Address:', r.url, '\n');
      });
    });
  });

// Parse arguments
commander.parse(process.argv);
<|endoftext|>


<commit_before>/**
 * The CLI of BEM hint
 * ===================
 */
var path = require('path'),
    logger = require('./logger'),
    bemhint = require('./bemhint');

/**
 * @example
 * Run the command `npm run example`
 */
module.exports = require('coa').Cmd()
    .name(process.argv[1])
    .helpful()
    .title('BEM hint')
    .opt()
        .name('version')
        .title('Shows the version number')
        /*jshint -W024 */
        .short('v').long('version')
        .flag()
        .only()
        .act(function () {
            var p = require('../package.json');
            return p.name + ' ' + p.version;
        })
        .end()
    .opt()
        .name('config')
        .title('Path to the configuration file')
        .long('config').short('c')
        .req()
        .end()
    .act(function (opts) {
        var config = require(path.resolve(opts.config));

        bemhint(config)
            .then(function (res) {
                logger.showErrors(res);
            })
            .fail(function (err) {
                console.log(err);
            });
    })
    .run(process.argv.slice(2));
<commit_msg>Update handling of errors<commit_after>/**
 * The CLI of BEM hint
 * ===================
 */
var path = require('path'),
    logger = require('./logger'),
    bemhint = require('./bemhint');

/**
 * @example
 * Run the command `npm run example`
 */
module.exports = require('coa').Cmd()
    .name(process.argv[1])
    .helpful()
    .title('BEM hint')
    .opt()
        .name('version')
        .title('Shows the version number')
        /*jshint -W024 */
        .short('v').long('version')
        .flag()
        .only()
        .act(function () {
            var p = require('../package.json');
            return p.name + ' ' + p.version;
        })
        .end()
    .opt()
        .name('config')
        .title('Path to the configuration file')
        .long('config').short('c')
        .req()
        .end()
    .act(function (opts) {
        var config = require(path.resolve(opts.config));

        return bemhint(config)
            .then(function (res) {
                logger.showErrors(res);
            })
            .fail(function (err) {
                throw err;
            });
    })
    .run(process.argv.slice(2));
<|endoftext|>


<commit_before>/*
 * InterfaceLIFT Wallpaper Auto-Downloader
 * https://github.com/stevenbenner/interfacelift-downloader
 *
 * Copyright (c) 2014 Steven Benner (http://stevenbenner.com/).
 * Released under the MIT License.
 */

'use strict';

var PageScraper = require('./pagescraper');
var Downloader = require('./downloader');
var fs = require('fs');
var path = require('path');
var resPaths = require('./respaths.json');

module.exports = {

  process: function(args) {
    var resolution = '1920x1080';
    var downloadPath = process.cwd();

    if (args.length > 4 || (args.length === 3 && args[2] === '--help')) {
      module.exports.help();
      process.exit(0);
    }

    if (args.length >= 3) {
      if (resPaths[args[2]]) {
        resolution = args[2];
      } else {
        console.log('"' + args[2] + '" is not a known resolution.');
        process.exit(1);
      }
    }

    if (args.length >= 4) {
      downloadPath = path.join(downloadPath, args[3]);
      if (!fs.existsSync(downloadPath)) {
        console.log('The path "' + args[3] + '" does not exist.');
        process.exit(1);
      }
    }

    module.exports.run(resolution, downloadPath);
  },

  run: function(resolution, downloadPath) {
    var startTime = new Date();
    var ps = new PageScraper(resolution);
    var existingFiles = 0;

    // run the page scraper
    ps.on('next', function(pageNumber) {
      console.log('Scanning Page ' + pageNumber + '...');
    });
    ps.on('end', function(downloadLinks) {
      var index = downloadLinks.length;
      var elapesdSeconds = (new Date() - startTime) / 1000;
      var dl = new Downloader(downloadLinks, downloadPath, resolution);

      dl.on('start', function() {
        console.log('Starting Download...\n');
      });
      dl.on('exist', function() {
        existingFiles++;
        index--;
      });
      dl.on('save', function(fileName) {
        console.log('[' + index + '] Saved: ' + fileName);
        index--;
      });
      dl.on('fail', function(fileName) {
        console.log('[' + index + '] Failed: ' + fileName);
        index--;
      });
      dl.on('end', function() {
        var elapesdSeconds = (new Date() - startTime) / 1000;
        console.log('Download competed in ' + elapesdSeconds + ' seconds.');
        console.log('Already had ' + existingFiles + ' images.');
      });

      console.log('Scrape completed in ' + elapesdSeconds + ' seconds. Found ' + index + ' images.');
      dl.start();
    });

    console.log('InterfaceLIFT Wallpaper Auto-Downloader\n');
    console.log([
      'Searching pages for images...',
      '(The download will begin after the page scan finishes.)'
    ].join('\n'));
    ps.start();
  },

  help: function() {
    console.log([
      'Usage: node interfacelift-downloader [resolution] [path]',
      'Resolution is the dimensions of the images you want to search for.',
      'For example: interfacelift-downloader 1920x1080'
    ].join('\n'));
  }

};
<commit_msg>Allow full path to be entered on command line.<commit_after>/*
 * InterfaceLIFT Wallpaper Auto-Downloader
 * https://github.com/stevenbenner/interfacelift-downloader
 *
 * Copyright (c) 2014 Steven Benner (http://stevenbenner.com/).
 * Released under the MIT License.
 */

'use strict';

var PageScraper = require('./pagescraper');
var Downloader = require('./downloader');
var fs = require('fs');
var path = require('path');
var resPaths = require('./respaths.json');

module.exports = {

  process: function(args) {
    var resolution = '1920x1080';
    var downloadPath = process.cwd();

    if (args.length > 4 || (args.length === 3 && args[2] === '--help')) {
      module.exports.help();
      process.exit(0);
    }

    if (args.length >= 3) {
      if (resPaths[args[2]]) {
        resolution = args[2];
      } else {
        console.log('"' + args[2] + '" is not a known resolution.');
        process.exit(1);
      }
    }

    if (args.length >= 4) {
      downloadPath = path.resolve(downloadPath, args[3]);
      if (!fs.existsSync(downloadPath)) {
        console.log('The path "' + args[3] + '" does not exist.');
        process.exit(1);
      }
    }

    module.exports.run(resolution, downloadPath);
  },

  run: function(resolution, downloadPath) {
    var startTime = new Date();
    var ps = new PageScraper(resolution);
    var existingFiles = 0;

    // run the page scraper
    ps.on('next', function(pageNumber) {
      console.log('Scanning Page ' + pageNumber + '...');
    });
    ps.on('end', function(downloadLinks) {
      var index = downloadLinks.length;
      var elapesdSeconds = (new Date() - startTime) / 1000;
      var dl = new Downloader(downloadLinks, downloadPath, resolution);

      dl.on('start', function() {
        console.log('Starting Download...\n');
      });
      dl.on('exist', function() {
        existingFiles++;
        index--;
      });
      dl.on('save', function(fileName) {
        console.log('[' + index + '] Saved: ' + fileName);
        index--;
      });
      dl.on('fail', function(fileName) {
        console.log('[' + index + '] Failed: ' + fileName);
        index--;
      });
      dl.on('end', function() {
        var elapesdSeconds = (new Date() - startTime) / 1000;
        console.log('Download competed in ' + elapesdSeconds + ' seconds.');
        console.log('Already had ' + existingFiles + ' images.');
      });

      console.log('Scrape completed in ' + elapesdSeconds + ' seconds. Found ' + index + ' images.');
      dl.start();
    });

    console.log('InterfaceLIFT Wallpaper Auto-Downloader\n');
    console.log([
      'Searching pages for images...',
      '(The download will begin after the page scan finishes.)'
    ].join('\n'));
    ps.start();
  },

  help: function() {
    console.log([
      'Usage: node interfacelift-downloader [resolution] [path]',
      'Resolution is the dimensions of the images you want to search for.',
      'For example: interfacelift-downloader 1920x1080'
    ].join('\n'));
  }

};
<|endoftext|>


<commit_before>const HtmlWebpackPlugin = require('html-webpack-plugin');
const StyleLintPlugin = require('stylelint-webpack-plugin');
const path = require('path');

function resolve(dir) {
    return path.join(__dirname, '..', dir)
}

module.exports = function (env) {
    var isProd = !!(env && env.prod);

    var config = {
        entry: {
            app: ['./tests/app/main.ts']
        },

        externals: [],

        output: {
            publicPath: '/',
            filename: 'app.js'
        },

        resolve: {
            extensions: ['.js', '.ts', '.html'],
            alias: {
                'vue$': 'vue/dist/vue.esm.js',
                '@': resolve('src')
            }
        },

        devtool: 'source-map',

        module: {
            loaders: [{
                exclude: [
                    'vue/**/*'
                ],
            }],
            rules: [{
                    enforce: 'post',
                    test: /\.css$/,
                    use: ['style-loader', 'css-loader']
                },
                {
                    enforce: 'post',
                    test: /\.scss$/,
                    use: ['style-loader',
                        'css-loader',
                        {
                            loader: 'postcss-loader',
                            options: {
                                sourceMap: true,
                                plugins: function () {
                                    return [
                                        require('autoprefixer')
                                    ];
                                }
                            }
                        }
                    ]
                },
                {
                    enforce: 'pre',
                    test: /\.scss$/,
                    loader: "sass-loader",
                    options: {
                        sourceMap: true,
                        includePaths: ["./src/styles"]
                    }
                },
                {
                    test: /\.html$/,
                    loader: 'vue-template-loader',
                    exclude: resolve('tests/app/index.html'),
                    options: {
                        scoped: true
                    }
                },
                {
                    test: /\.ts$/,
                    loader: 'awesome-typescript-loader',
                    options: {
                        configFileName: resolve(isProd ? 'tsconfig.json' : 'tsconfig.dev.json')
                    }
                },
                {
                    test: /\.ts$/,
                    enforce: 'pre',
                    loader: 'tslint-loader',
                    include: [resolve('src'), resolve('test')],
                    options: {
                        configFile: 'conf/tslint.json',
                        formatter: 'grouped',
                        formattersDirectory: 'node_modules/custom-tslint-formatters/formatters',
                        emitErrors: true,
                    }
                },
                {
                    test: /\.svg$/,
                    loader: 'svg-inline-loader',
                    options: {
                        removeTags: true,
                        removingTags: ['desc', 'defs', 'style'],
                        removeSVGTagAttrs: true
                    }
                }
            ]
        },
        plugins: [
            new StyleLintPlugin({
                configFile: '.stylelintrc',
                emitErrors: false
            })
        ]
    }

    if (!isProd) {
        config.plugins.push(new HtmlWebpackPlugin({
            filename: 'index.html',
            template: resolve('tests/app/index.html'),
            inject: 'body'
        }));
    }

    if (isProd) {
        /*config.entry = {
            'component-names': ['./src/components/component-names.ts'],
            'meta': ['./src/meta/meta.ts'],
            'meta-fr': ['./src/meta/meta-fr.ts'],
            'background-color': ['./src/directives/background-color/background-color.ts'],
            'button': ['./src/components/button/button.ts'],
            'lang': ['./src/directives/lang/lang.ts'],
            'list': ['./src/components/list/list.ts'],
            'panel': ['./src/components/panel/panel.ts'],
            'table': ['./src/components/table/table.ts'],
            'dynamic-template': ['./src/components/dynamic-template/dynamic-template.ts'],
            'i18n': ['./src/utils/i18n.ts'],
            'uuid': ['./src/utils/uuid.ts'],
            'services': ['./src/services/component-meta-impl']
        };

        config.externals = ['vue', 'vue-class-component', 'vue-property-decorator'];

        config.output = {
            path: resolve('dist'),
            publicPath: '/',
            libraryTarget: 'umd',
            filename: '[name].js'
        };*/

        console.log('Use npm run tsc instead (for the moment...)');
    }

    return config;
}
<commit_msg>Stylelint now emits errors<commit_after>const HtmlWebpackPlugin = require('html-webpack-plugin');
const StyleLintPlugin = require('stylelint-webpack-plugin');
const path = require('path');

function resolve(dir) {
    return path.join(__dirname, '..', dir)
}

module.exports = function (env) {
    var isProd = !!(env && env.prod);

    var config = {
        entry: {
            app: ['./tests/app/main.ts']
        },

        externals: [],

        output: {
            publicPath: '/',
            filename: 'app.js'
        },

        resolve: {
            extensions: ['.js', '.ts', '.html'],
            alias: {
                'vue$': 'vue/dist/vue.esm.js',
                '@': resolve('src')
            }
        },

        devtool: 'source-map',

        module: {
            loaders: [{
                exclude: [
                    'vue/**/*'
                ],
            }],
            rules: [{
                    enforce: 'post',
                    test: /\.css$/,
                    use: ['style-loader', 'css-loader']
                },
                {
                    enforce: 'post',
                    test: /\.scss$/,
                    use: ['style-loader',
                        'css-loader',
                        {
                            loader: 'postcss-loader',
                            options: {
                                sourceMap: true,
                                plugins: function () {
                                    return [
                                        require('autoprefixer')
                                    ];
                                }
                            }
                        }
                    ]
                },
                {
                    enforce: 'pre',
                    test: /\.scss$/,
                    loader: "sass-loader",
                    options: {
                        sourceMap: true,
                        includePaths: ["./src/styles"]
                    }
                },
                {
                    test: /\.html$/,
                    loader: 'vue-template-loader',
                    exclude: resolve('tests/app/index.html'),
                    options: {
                        scoped: true
                    }
                },
                {
                    test: /\.ts$/,
                    loader: 'awesome-typescript-loader',
                    options: {
                        configFileName: resolve(isProd ? 'tsconfig.json' : 'tsconfig.dev.json')
                    }
                },
                {
                    test: /\.ts$/,
                    enforce: 'pre',
                    loader: 'tslint-loader',
                    include: [resolve('src'), resolve('test')],
                    options: {
                        configFile: 'conf/tslint.json',
                        formatter: 'grouped',
                        formattersDirectory: 'node_modules/custom-tslint-formatters/formatters',
                        emitErrors: true,
                    }
                },
                {
                    test: /\.svg$/,
                    loader: 'svg-inline-loader',
                    options: {
                        removeTags: true,
                        removingTags: ['desc', 'defs', 'style'],
                        removeSVGTagAttrs: true
                    }
                }
            ]
        },
        plugins: [
            new StyleLintPlugin({
                configFile: '.stylelintrc',
                emitErrors: true
            })
        ]
    }

    if (!isProd) {
        config.plugins.push(new HtmlWebpackPlugin({
            filename: 'index.html',
            template: resolve('tests/app/index.html'),
            inject: 'body'
        }));
    }

    if (isProd) {
        /*config.entry = {
            'component-names': ['./src/components/component-names.ts'],
            'meta': ['./src/meta/meta.ts'],
            'meta-fr': ['./src/meta/meta-fr.ts'],
            'background-color': ['./src/directives/background-color/background-color.ts'],
            'button': ['./src/components/button/button.ts'],
            'lang': ['./src/directives/lang/lang.ts'],
            'list': ['./src/components/list/list.ts'],
            'panel': ['./src/components/panel/panel.ts'],
            'table': ['./src/components/table/table.ts'],
            'dynamic-template': ['./src/components/dynamic-template/dynamic-template.ts'],
            'i18n': ['./src/utils/i18n.ts'],
            'uuid': ['./src/utils/uuid.ts'],
            'services': ['./src/services/component-meta-impl']
        };

        config.externals = ['vue', 'vue-class-component', 'vue-property-decorator'];

        config.output = {
            path: resolve('dist'),
            publicPath: '/',
            libraryTarget: 'umd',
            filename: '[name].js'
        };*/

        console.log('Use npm run tsc instead (for the moment...)');
    }

    return config;
}
<|endoftext|>


<commit_before>var gulp        = require('gulp');
var uglify      = require('gulp-uglify');
var minifycss   = require('gulp-minify-css');
var rename      = require('gulp-rename');
var less        = require('gulp-less');
var concat      = require('gulp-concat');
var path        = require('path');
var del         = require('del');

var dirFeature = '../../vendor/spryker/spryker/Bundles/Gui/src/SprykerFeature/Zed/Gui/Static/Assets';
var dirPub = '../../static/public/Zed/bundles/';

var _match = /[^\/]+\/src\/SprykerFeature\/Zed\/([^\/]+)\/Static\/Public/;

function buildSource(type) {
    var source = {
        'css'    : 'styles/**/*.css',
        'js'     : 'scripts/**/*.js',
        'images' : 'images/**/*.{svg,png,jpeg,gif}',
        'fonts'  : 'fonts/**/*.{svg,woff,otf,ttf,eot}'
    };

    return [
        path.join(dirFeature, source[type])
    ];
}

function copy(directory) {
    var source = dirFeature + '/' + directory;
    var target = dirPub + '/Gui/' + directory;

    return gulp.src(source + '/**/*.*', {base: source})
        .pipe(gulp.dest(target));
}

gulp.task('compile-less', function(){
    return gulp.src(dirFeature + '/LESS/style.less')
        .pipe(less({
            paths: [ path.join(__dirname, 'less', 'includes') ]
        }))
        .pipe(concat('style-gulp-new.css'))
        //.pipe(minifycss())
        .pipe(gulp.dest(dirFeature + '/styles'))
});

gulp.task('compile-js', function(){
    var jsFiles = [
        dirFeature + '/scripts/jquery-2.1.1.js',
        dirFeature + '/scripts/jquery-ui.custom.min.js',
        dirFeature + '/scripts/bootstrap.min.js',
        dirFeature + '/scripts/inspinia.js'
    ];
    return gulp.src(jsFiles)
        //.pipe(uglify())
        .pipe(concat('resources.min.js'))
        .pipe(gulp.dest(dirPub + '/Gui/scripts/'))
    ;
});

gulp.task('copy-fonts', function(){
    return copy('fonts');
});

gulp.task('copy-img', function(){
    return copy('img');
});

gulp.task('copy-sprites', function(){
    return copy('sprite');
});

gulp.task('copy-font-awesome', function(){
    return copy('font-awesome');
});

gulp.task('copy-css', function(){
    return copy('styles');
});

gulp.task('default', [
    'compile-less'
    ,'compile-js'
    ,'copy-fonts'
    ,'copy-font-awesome'
    ,'copy-img'
    ,'copy-sprites'
    ,'copy-css'
]);
<commit_msg>copy assets and compile less, css, js<commit_after>var gulp        = require('gulp');
var uglify      = require('gulp-uglify');
var minifycss   = require('gulp-minify-css');
var rename      = require('gulp-rename');
var less        = require('gulp-less');
var concat      = require('gulp-concat');
var path        = require('path');
var del         = require('del');

var dirFeature = '../../vendor/spryker/spryker/Bundles/Gui/src/SprykerFeature/Zed/Gui/Static/Assets';
var dirPub = '../../static/public/Zed/bundles/';

function copy(directory) {
    var source = dirFeature + '/' + directory;
    var target = dirPub + '/Gui/' + directory;

    return gulp.src(source + '/**/*.*', {base: source})
        .pipe(gulp.dest(target));
}

gulp.task('compile-less', ['copy-less'], function(){
    return gulp.src(dirPub + 'Gui/LESS/style.less')
        .pipe(less({
            paths: [ path.join(__dirname, 'less', 'includes') ]
        }))
        .pipe(concat('style.min.css'))
        //.pipe(minifycss())
        .pipe(gulp.dest(dirPub + 'Gui/styles'))
});

gulp.task('compile-js', ['copy-js'], function(){
    var jsFiles = [
        dirPub + 'Gui/scripts/jquery-2.1.1.js',
        dirPub + 'Gui/scripts/bootstrap.min.js',
        dirPub + 'Gui/scripts/plugins/metisMenu/jquery.metisMenu.js',
        dirPub + 'Gui/scripts/plugins/footable/footable.all.min.js',
        dirPub + 'Gui/scripts/plugins/slimscroll/jquery.slimscroll.min.js',
        dirPub + 'Gui/scripts/inspinia.js'
    ];
    return gulp.src(jsFiles)
        .pipe(uglify())
        .pipe(concat('resources.min.js'))
        .pipe(gulp.dest(dirPub + '/Gui/scripts/'))
    ;
});

gulp.task('copy-fonts', function(){
    return copy('fonts');
});

gulp.task('copy-sprites', function(){
    return copy('sprite');
});

gulp.task('copy-js', function(){
    return copy('scripts');
});

gulp.task('copy-font-awesome', function(){
    return copy('font-awesome');
});

gulp.task('copy-css', function(){
    return copy('styles');
});

gulp.task('copy-less', function(){
    return copy('LESS');
});

//gulp.task('clean-css', function(done){
//    del(dirPub + '/Gui/styles/*', function(err, paths){
//        console.log('Deleted: ', path.join('\n'));
//    },{ force: true });
//});

gulp.task('copy-files', [
    'copy-css'
    ,'copy-less'
    ,'copy-fonts'
    ,'copy-font-awesome'
    ,'copy-sprites'
    ,'copy-js'
]);

gulp.task('clean-files', [
    'clean-css'
]);

gulp.task('do-nothing');

gulp.task('default', [
    'do-nothing'
    //,'clean-files'
    ,'copy-files'
    ,'compile-less'
    ,'compile-js'
]);
<|endoftext|>