<commit_before>const _ = require('lodash');
const neodoc = require('../');
const path = require('path');
const chalk = require('chalk');
const expect = require('chai').expect;

const EXAMPLES = path.resolve(__dirname, '..', 'examples');
const GIT_EXAMPLE = path.resolve(EXAMPLES, 'git');

const { runFakeProc, exec } = require('./support');

describe('neodoc', () => {
  describe('examples - git', () => {
    const git = (args) => {
      const output = exec(GIT_EXAMPLE, args)
      return JSON.parse(output);
    }

    it('git branch -u origin master', () => {
      expect(git('branch -u origin master'))
        .to.deep.equal({
          branch: true
        , '<branchname>': ['master']
        , '-u': 'origin'
        , '--set-upstream-to': 'origin'
        });
    });

    it('git branch -D master development', () => {
      expect(git('branch -D master development'))
        .to.deep.equal({
          branch: true
        , '<branchname>': [ 'master', 'development' ]
        , '-D': true
        });
    });

    it('git clone --separate-git-dir=~/foo', () => {
      expect(git('clone --separate-git-dir=~/foo'))
        .to.deep.equal({
          '--': []
        , '--separate-git-dir': '~/foo'
        , 'clone': true
        });
    });

    it('git commit --gpg-sign=my-key', () => {
      expect(git('commit --gpg-sign=my-key'))
        .to.deep.equal({
          '--': []
        , 'commit': true
        , '--gpg-sign': 'my-key'
        , '-S': 'my-key'
        });
    });
  });

  describe('special arguments', () => {
    describe('option.helpFlags', () => {
      it('should return the help', () => {
        const help = 'usage: p [--help]';
        const out = neodoc.run(help, { dontExit: true, argv: [ '--help' ]});
        expect(out).to.deep.equal({"--help": 1, ".help": help });
      });

      it('should return the help (implicit)', () => {
        const help = 'usage: p';
        const out = neodoc.run(help, { dontExit: true, argv: [ '--help' ]});
        expect(out).to.deep.equal({"--help": 1, ".help": help });
      });

      it('should return the help (implicit w/ alias)', () => {
        const help = `\
          usage: p
          options:
            -h, --help`;
        const out = neodoc.run(help, { dontExit: true, argv: [ '-h' ]});
        expect(out).to.deep.equal({"--help": 1, "-h": 1, ".help": help });
      });

      it('should accept custom helpFlags (implicit)', () => {
        const help = 'usage: p'
        const out = neodoc.run(help, { dontExit: true, argv: [ '-h' ], helpFlags: [ '-h' ]});
        expect(out).to.deep.equal({"-h": 1, ".help": help });
      });
    });

    describe('option.versionFlags', () => {
      it('should return the version', () => {
        const version = '1.0.0';
        const help = 'usage: p [--version]';
        const out = neodoc.run(help, { dontExit: true, argv: [ '--version' ], version });
        expect(out).to.deep.equal({"--version": 1, ".version": version });
      });

      it('should return the version (implicit)', () => {
        const version = '1.0.0';
        const help = 'usage: p';
        const out = neodoc.run(help, { dontExit: true, argv: [ '--version' ], version});
        expect(out).to.deep.equal({"--version": 1, ".version": version });
      });

      it('should return the version (implicit w/ alias)', () => {
        const version = '1.0.0';
        const help = `\
          usage: p
          options:
            -v, --version`;
        const out = neodoc.run(help, { dontExit: true, argv: [ '-v' ], version});
        expect(out).to.deep.equal({"--version": 1, "-v": 1, ".version": version });
      });

      it('should accept custom versionFlags (implicit)', () => {
        const version = '1.0.0';
        const help = 'usage: p'
        const out = neodoc.run(help, { dontExit: true, argv: [ '-v' ], versionFlags: [ '-v' ], version});
        expect(out).to.deep.equal({"-v": 1, ".version": version });
      });
    });
  });

  describe('special arguments (via cli)', () => {
    describe('option.helpFlags', () => {
      it('should print help', () => {
        for (let flag of ['-h', '--help', '-?']) {
          const result = runFakeProc(() => {
            console.log(JSON.stringify(neodoc.run(`\
              usage: prog -h
              options:
                -?, -h, --help
            `, { argv: [flag] }
            )))
          });
          expect(result).to.deep.equal({
            code: 0
          , stderr: ''
          , stdout: `\
              usage: prog -h
              options:
                -?, -h, --help`
          });
        }
      });
    });

    describe('option.versionFlags', () => {
      it('should print help', () => {
        for (let flag of ['-v', '--version']) {
          const result = runFakeProc(() => {
            console.log(JSON.stringify(neodoc.run(`\
              usage: prog -v
              options:
                -v, --version
            `, { argv: [flag], version: '1.0.0' }
            )))
          });
          expect(result).to.deep.equal({
            code: 0
          , stderr: ''
          , stdout: '1.0.0'
          });
        }
      });

      describe('#73 - false positive check of special flags', () => {
        it('should not trigger on negative fallback', () => {
          for (let [ help, args, expected ] of [
            [ '', [], {} ]
          , [ '[-h]', [], {} ]
          , [ '[-xh]', [], {} ]
          , [ '[-xh]', ['-x'], {'-x': true} ]
          , [ '[-xh]', ['-h=false'], 'option takes no argument' ]
          ]) {
            const result = runFakeProc(() => {
              console.log(JSON.stringify(neodoc.run(`
                usage: prog ${help}
                options:
                  -h, --help
              `, { argv: args }
              )))
            });
            if (typeof expected === 'string') {
              expect(_.omit(result, 'stderr')).to.deep.equal({
                code: 1
              , stdout: ''
              });
              expect(result.stderr).to.contains(expected);
            } else {
              expect(result).to.deep.equal({
                code: 0
              , stderr: ''
              , stdout: JSON.stringify(expected)
              });
            }
          }
        });
      });
    });
  });

  describe('transform hooks', () => {
    describe('presolve hooks', () => {
      it('should get called once per run', () => {
        let i = 0, k = 0;
        const args = neodoc.run(`\
          usage: prog -a -b -c
        `, {
          dontExit: true
        , argv: ['-a', '-b', '-c']
        , transforms: {
            presolve: [
              spec => {
                i += 1;
                return spec;
              }
            , spec => {
                k += 1;
                return spec;
              }
            ]
          }
        });

        expect({ i, k }).to.deep.equal({ i: 1, k: 1 });
        expect(args).to.deep.equal({
          '-a': true
        , '-b': true
        , '-c': true
        });
      });

      it('should be able to change the spec', () => {
        const args = neodoc.run(`\
          usage: prog foo
        `, {
          dontExit: true
        , argv: []
        , transforms: {
            presolve: [
              spec => {
                spec.layouts = [];
                return spec;
              }
            ]
          }
        });
      });
    });

    describe('postsolve hooks', () => {
      it('should get called once per run', () => {
        let i = 0, k = 0;
        const args = neodoc.run(`\
          usage: prog -a -b -c
        `, {
          dontExit: true
        , argv: ['-a', '-b', '-c']
        , transforms: {
            presolve: [
              spec => {
                i += 1;
                return spec;
              }
            , spec => {
                k += 1;
                return spec;
              }
            ]
          }
        });

        expect({ i, k }).to.deep.equal({ i: 1, k: 1 });
        expect(args).to.deep.equal({
          '-a': true
        , '-b': true
        , '-c': true
        });
      });

      it('should be able to change the spec', () => {
        const args = neodoc.run(`\
          usage: prog foo
        `, {
          dontExit: true
        , argv: []
        , transforms: {
            presolve: [
              spec => {
                spec.layouts = [];
                return spec;
              }
            ]
          }
        });
      });
    });
  });

  describe('issues', () => {
    describe('#71 - remove left & right trimming', () => {
      it('should not trim the help text', () => {
        const result = runFakeProc(() => {
          neodoc.run(`\
            ${chalk.inverse(' THIMBLE ')} A scaffolding system that grows with you.
            ${chalk.blue('I. Usage:')}
              thimble <command> [<args>...]
              thimble -h | --help
              thimble --version
          `, { argv: [ '--help' ] });
        });
        expect(result).to.deep.equal({
          code: 0
        , stderr: ''
        , stdout: `\
            ${chalk.inverse(' THIMBLE ')} A scaffolding system that grows with you.
            ${chalk.blue('I. Usage:')}
              thimble <command> [<args>...]
              thimble -h | --help
              thimble --version`
        });
      });
    });
  });
});
<commit_msg>Add another test for sanity<commit_after>const _ = require('lodash');
const neodoc = require('../');
const path = require('path');
const chalk = require('chalk');
const expect = require('chai').expect;

const EXAMPLES = path.resolve(__dirname, '..', 'examples');
const GIT_EXAMPLE = path.resolve(EXAMPLES, 'git');

const { runFakeProc, exec } = require('./support');

describe('neodoc', () => {
  describe('examples - git', () => {
    const git = (args) => {
      const output = exec(GIT_EXAMPLE, args)
      return JSON.parse(output);
    }

    it('git branch -u origin master', () => {
      expect(git('branch -u origin master'))
        .to.deep.equal({
          branch: true
        , '<branchname>': ['master']
        , '-u': 'origin'
        , '--set-upstream-to': 'origin'
        });
    });

    it('git branch -D master development', () => {
      expect(git('branch -D master development'))
        .to.deep.equal({
          branch: true
        , '<branchname>': [ 'master', 'development' ]
        , '-D': true
        });
    });

    it('git clone --separate-git-dir=~/foo', () => {
      expect(git('clone --separate-git-dir=~/foo'))
        .to.deep.equal({
          '--': []
        , '--separate-git-dir': '~/foo'
        , 'clone': true
        });
    });

    it('git commit --gpg-sign=my-key', () => {
      expect(git('commit --gpg-sign=my-key'))
        .to.deep.equal({
          '--': []
        , 'commit': true
        , '--gpg-sign': 'my-key'
        , '-S': 'my-key'
        });
    });
  });

  describe('special arguments', () => {
    describe('option.helpFlags', () => {
      it('should return the help', () => {
        const help = 'usage: p [--help]';
        const out = neodoc.run(help, { dontExit: true, argv: [ '--help' ]});
        expect(out).to.deep.equal({"--help": 1, ".help": help });
      });

      it('should return the help (implicit)', () => {
        const help = 'usage: p';
        const out = neodoc.run(help, { dontExit: true, argv: [ '--help' ]});
        expect(out).to.deep.equal({"--help": 1, ".help": help });
      });

      it('should return the help (implicit, should not fail)', () => {
        const help = 'usage: p <word>';
        const out = neodoc.run(help, { dontExit: true, argv: [ '--help' ]});
        expect(out).to.deep.equal({"--help": 1, ".help": help });
      });

      it('should return the help (implicit w/ alias)', () => {
        const help = `\
          usage: p
          options:
            -h, --help`;
        const out = neodoc.run(help, { dontExit: true, argv: [ '-h' ]});
        expect(out).to.deep.equal({"--help": 1, "-h": 1, ".help": help });
      });

      it('should accept custom helpFlags (implicit)', () => {
        const help = 'usage: p'
        const out = neodoc.run(help, { dontExit: true, argv: [ '-h' ], helpFlags: [ '-h' ]});
        expect(out).to.deep.equal({"-h": 1, ".help": help });
      });
    });

    describe('option.versionFlags', () => {
      it('should return the version', () => {
        const version = '1.0.0';
        const help = 'usage: p [--version]';
        const out = neodoc.run(help, { dontExit: true, argv: [ '--version' ], version });
        expect(out).to.deep.equal({"--version": 1, ".version": version });
      });

      it('should return the version (implicit)', () => {
        const version = '1.0.0';
        const help = 'usage: p';
        const out = neodoc.run(help, { dontExit: true, argv: [ '--version' ], version});
        expect(out).to.deep.equal({"--version": 1, ".version": version });
      });

      it('should return the version (implicit w/ alias)', () => {
        const version = '1.0.0';
        const help = `\
          usage: p
          options:
            -v, --version`;
        const out = neodoc.run(help, { dontExit: true, argv: [ '-v' ], version});
        expect(out).to.deep.equal({"--version": 1, "-v": 1, ".version": version });
      });

      it('should accept custom versionFlags (implicit)', () => {
        const version = '1.0.0';
        const help = 'usage: p'
        const out = neodoc.run(help, { dontExit: true, argv: [ '-v' ], versionFlags: [ '-v' ], version});
        expect(out).to.deep.equal({"-v": 1, ".version": version });
      });
    });
  });

  describe('special arguments (via cli)', () => {
    describe('option.helpFlags', () => {
      it('should print help', () => {
        for (let flag of ['-h', '--help', '-?']) {
          const result = runFakeProc(() => {
            console.log(JSON.stringify(neodoc.run(`\
              usage: prog -h
              options:
                -?, -h, --help
            `, { argv: [flag] }
            )))
          });
          expect(result).to.deep.equal({
            code: 0
          , stderr: ''
          , stdout: `\
              usage: prog -h
              options:
                -?, -h, --help`
          });
        }
      });
    });

    describe('option.versionFlags', () => {
      it('should print help', () => {
        for (let flag of ['-v', '--version']) {
          const result = runFakeProc(() => {
            console.log(JSON.stringify(neodoc.run(`\
              usage: prog -v
              options:
                -v, --version
            `, { argv: [flag], version: '1.0.0' }
            )))
          });
          expect(result).to.deep.equal({
            code: 0
          , stderr: ''
          , stdout: '1.0.0'
          });
        }
      });

      describe('#73 - false positive check of special flags', () => {
        it('should not trigger on negative fallback', () => {
          for (let [ help, args, expected ] of [
            [ '', [], {} ]
          , [ '[-h]', [], {} ]
          , [ '[-xh]', [], {} ]
          , [ '[-xh]', ['-x'], {'-x': true} ]
          , [ '[-xh]', ['-h=false'], 'option takes no argument' ]
          ]) {
            const result = runFakeProc(() => {
              console.log(JSON.stringify(neodoc.run(`
                usage: prog ${help}
                options:
                  -h, --help
              `, { argv: args }
              )))
            });
            if (typeof expected === 'string') {
              expect(_.omit(result, 'stderr')).to.deep.equal({
                code: 1
              , stdout: ''
              });
              expect(result.stderr).to.contains(expected);
            } else {
              expect(result).to.deep.equal({
                code: 0
              , stderr: ''
              , stdout: JSON.stringify(expected)
              });
            }
          }
        });
      });
    });
  });

  describe('transform hooks', () => {
    describe('presolve hooks', () => {
      it('should get called once per run', () => {
        let i = 0, k = 0;
        const args = neodoc.run(`\
          usage: prog -a -b -c
        `, {
          dontExit: true
        , argv: ['-a', '-b', '-c']
        , transforms: {
            presolve: [
              spec => {
                i += 1;
                return spec;
              }
            , spec => {
                k += 1;
                return spec;
              }
            ]
          }
        });

        expect({ i, k }).to.deep.equal({ i: 1, k: 1 });
        expect(args).to.deep.equal({
          '-a': true
        , '-b': true
        , '-c': true
        });
      });

      it('should be able to change the spec', () => {
        const args = neodoc.run(`\
          usage: prog foo
        `, {
          dontExit: true
        , argv: []
        , transforms: {
            presolve: [
              spec => {
                spec.layouts = [];
                return spec;
              }
            ]
          }
        });
      });
    });

    describe('postsolve hooks', () => {
      it('should get called once per run', () => {
        let i = 0, k = 0;
        const args = neodoc.run(`\
          usage: prog -a -b -c
        `, {
          dontExit: true
        , argv: ['-a', '-b', '-c']
        , transforms: {
            presolve: [
              spec => {
                i += 1;
                return spec;
              }
            , spec => {
                k += 1;
                return spec;
              }
            ]
          }
        });

        expect({ i, k }).to.deep.equal({ i: 1, k: 1 });
        expect(args).to.deep.equal({
          '-a': true
        , '-b': true
        , '-c': true
        });
      });

      it('should be able to change the spec', () => {
        const args = neodoc.run(`\
          usage: prog foo
        `, {
          dontExit: true
        , argv: []
        , transforms: {
            presolve: [
              spec => {
                spec.layouts = [];
                return spec;
              }
            ]
          }
        });
      });
    });
  });

  describe('issues', () => {
    describe('#71 - remove left & right trimming', () => {
      it('should not trim the help text', () => {
        const result = runFakeProc(() => {
          neodoc.run(`\
            ${chalk.inverse(' THIMBLE ')} A scaffolding system that grows with you.
            ${chalk.blue('I. Usage:')}
              thimble <command> [<args>...]
              thimble -h | --help
              thimble --version
          `, { argv: [ '--help' ] });
        });
        expect(result).to.deep.equal({
          code: 0
        , stderr: ''
        , stdout: `\
            ${chalk.inverse(' THIMBLE ')} A scaffolding system that grows with you.
            ${chalk.blue('I. Usage:')}
              thimble <command> [<args>...]
              thimble -h | --help
              thimble --version`
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>var fs = require("fs");
var _  = require("lodash");

var humanise = function (val) {
  return val.replace(/-/g, " ");
};

var readFile = exports.readFile = function (filename) {
  if (fs.existsSync(filename)) {
    var file = fs.readFileSync(filename, "utf8").trim();
    file = file.replace(/\r\n/g, "\n");
    return file;
  } else {
    return "";
  }
};

exports.get = function (entryName) {
  if (exports.cache[entryName]) return exports.cache[entryName];

  var suites = [];
  var entryLoc = __dirname + "/fixtures/" + entryName;

  _.each(fs.readdirSync(entryLoc), function (suiteName) {
    if (suiteName[0] === ".") return;

    var suite = {
      options: {},
      tests: [],
      title: humanise(suiteName),
      filename: entryLoc + "/" + suiteName
    };
    suites.push(suite);

    var suiteOptsLoc = suite.filename + "/options.json";
    if (fs.existsSync(suiteOptsLoc)) suite.options = require(suiteOptsLoc);

    _.each(fs.readdirSync(suite.filename), function (taskName) {
      var taskDir = suite.filename + "/" + taskName;
      if (fs.statSync(taskDir).isFile()) return;

      var actualLocAlias = suiteName + "/" + taskName + "/actual.js";
      var expectLocAlias = suiteName + "/" + taskName + "/expected.js";
      var execLocAlias   = suiteName + "/" + taskName + "/exec.js";

      var actualLoc = taskDir + "/actual.js";
      var expectLoc = taskDir + "/expected.js";
      var execLoc   = taskDir + "/exec.js";

      var taskOpts = _.merge({
        sourceFileName: actualLocAlias,
        sourceMapName:  expectLocAlias
      }, _.cloneDeep(suite.options));

      var taskOptsLoc = taskDir + "/options.json";
      if (fs.existsSync(taskOptsLoc)) _.merge(taskOpts, require(taskOptsLoc));

      var test = {
        title: humanise(taskName),
        disabled: taskName[0] === ".",
        options: taskOpts,
        exec: {
          code: readFile(execLoc),
          filename: execLocAlias,
        },
        actual: {
          loc: actualLoc,
          code: readFile(actualLoc),
          filename: actualLocAlias,
        },
        expect: {
          loc: expectLoc,
          code: readFile(expectLoc),
          filename: expectLocAlias
        }
      };

      suite.tests.push(test);

      var sourceMappingsLoc = taskDir + "/source-mappings.json";
      if (fs.existsSync(sourceMappingsLoc)) {
        test.options.sourceMap = true;
        test.sourceMappings = require(sourceMappingsLoc);
      }

      var sourceMap = taskDir + "/source-map.json";
      if (fs.existsSync(sourceMap)) {
        test.options.sourceMap = true;
        test.sourceMap = require(sourceMap);
      }
    });
  });

  return exports.cache[entryName] = suites;
};

try {
  exports.cache = require("../tests.json");
} catch (err) {
  if (err.code !== "MODULE_NOT_FOUND") throw err;

  var cache = exports.cache = {};
  cache.transformation = exports.get("transformation");
  cache.generation     = exports.get("generation");
}
<commit_msg>add loc option to exec test<commit_after>var fs = require("fs");
var _  = require("lodash");

var humanise = function (val) {
  return val.replace(/-/g, " ");
};

var readFile = exports.readFile = function (filename) {
  if (fs.existsSync(filename)) {
    var file = fs.readFileSync(filename, "utf8").trim();
    file = file.replace(/\r\n/g, "\n");
    return file;
  } else {
    return "";
  }
};

exports.get = function (entryName) {
  if (exports.cache[entryName]) return exports.cache[entryName];

  var suites = [];
  var entryLoc = __dirname + "/fixtures/" + entryName;

  _.each(fs.readdirSync(entryLoc), function (suiteName) {
    if (suiteName[0] === ".") return;

    var suite = {
      options: {},
      tests: [],
      title: humanise(suiteName),
      filename: entryLoc + "/" + suiteName
    };
    suites.push(suite);

    var suiteOptsLoc = suite.filename + "/options.json";
    if (fs.existsSync(suiteOptsLoc)) suite.options = require(suiteOptsLoc);

    _.each(fs.readdirSync(suite.filename), function (taskName) {
      var taskDir = suite.filename + "/" + taskName;
      if (fs.statSync(taskDir).isFile()) return;

      var actualLocAlias = suiteName + "/" + taskName + "/actual.js";
      var expectLocAlias = suiteName + "/" + taskName + "/expected.js";
      var execLocAlias   = suiteName + "/" + taskName + "/exec.js";

      var actualLoc = taskDir + "/actual.js";
      var expectLoc = taskDir + "/expected.js";
      var execLoc   = taskDir + "/exec.js";

      var taskOpts = _.merge({
        sourceFileName: actualLocAlias,
        sourceMapName:  expectLocAlias
      }, _.cloneDeep(suite.options));

      var taskOptsLoc = taskDir + "/options.json";
      if (fs.existsSync(taskOptsLoc)) _.merge(taskOpts, require(taskOptsLoc));

      var test = {
        title: humanise(taskName),
        disabled: taskName[0] === ".",
        options: taskOpts,
        exec: {
          loc: execLoc,
          code: readFile(execLoc),
          filename: execLocAlias,
        },
        actual: {
          loc: actualLoc,
          code: readFile(actualLoc),
          filename: actualLocAlias,
        },
        expect: {
          loc: expectLoc,
          code: readFile(expectLoc),
          filename: expectLocAlias
        }
      };

      suite.tests.push(test);

      var sourceMappingsLoc = taskDir + "/source-mappings.json";
      if (fs.existsSync(sourceMappingsLoc)) {
        test.options.sourceMap = true;
        test.sourceMappings = require(sourceMappingsLoc);
      }

      var sourceMap = taskDir + "/source-map.json";
      if (fs.existsSync(sourceMap)) {
        test.options.sourceMap = true;
        test.sourceMap = require(sourceMap);
      }
    });
  });

  return exports.cache[entryName] = suites;
};

try {
  exports.cache = require("../tests.json");
} catch (err) {
  if (err.code !== "MODULE_NOT_FOUND") throw err;

  var cache = exports.cache = {};
  cache.transformation = exports.get("transformation");
  cache.generation     = exports.get("generation");
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

var fs = require('fs');
var path = require('path');
var execSync = require('child_process').execSync;
var resolveCwd = require('resolve-cwd');
var validatePackageName = require('validate-npm-package-name');

var packageManifest = require('./package.json');

var getLocalCliPath = function () {
  try {
    return resolveCwd('hops-local-cli');
  } catch (error) {
    return null;
  }
};

var PACKAGES_TO_INSTALL = [
  'hops-local-cli'
];

function globalCLI (argv) {
  return require('yargs')
    .version(packageManifest.version)
    .usage('Usage: $0 <command> [options]')
    .command('init <project-name>', 'Generates a new project with the ' +
      'specified name')
    .option('template', {
      type: 'string',
      describe: 'Use this with the npm package name of a template to ' +
        'initialize with a different template',
      default: 'hops-template-react'
    })
    .option('hops-version', {
      type: 'string',
      describe: 'Which version (or npm dist-tag) of hops-local-cli to use',
      default: 'latest'
    })
    .option('verbose', {
      type: 'boolean',
      describe: 'Increase verbosity of command',
      default: false
    })
    .option('npm', {
      type: 'boolean',
      describe: 'Force usage of `npm` instead of yarn',
      default: false
    })
    .example(
      '$0 init my-project',
      'Creates the folder my-project inside the current directory and ' +
        'initializes a sample hops react project inside it.'
    )
    .example(
      '$0 init --template hops-template-minimal my-project',
      'Creates the folder my-project inside the current directory and ' +
        'initializes a minimal hops example inside it.'
    )
    .help('h')
    .alias('h', 'help')
    .demandCommand()
    .wrap(72)
    .parse(argv);
}

function validateName (name) {
  var validationResult = validatePackageName(name);
  if (!validationResult.validForNewPackages) {
    console.error(
      'Cannot create a project with the name:',
      name,
      'because of the following npm restrictions:'
    );
    if (validationResult.errors) {
      validationResult.errors.forEach(function (msg) { console.error(msg); });
    }
    if (validationResult.warnings) {
      validationResult.warnings.forEach(function (msg) { console.warn(msg); });
    }
    process.exit(1);
  }
}

function createDirectory (root) {
  if (fs.existsSync(root)) {
    console.error(
      'A directory with the name:',
      name,
      'already exists in:',
      process.cwd(),
      '\nPlease remove this directory or choose a different project-name.'
    );
    process.exit(1);
  }

  fs.mkdirSync(root);
}

function writePackageManifest (root) {
  fs.writeFileSync(
    path.join(root, 'package.json'),
    JSON.stringify({
      name: name,
      version: '1.0.0',
      private: true
    }, null, 2)
  );
}

function isYarnAvailable () {
  try {
    execSync('yarn --version', { stdio: 'ignore' });
    return true;
  } catch (error) {
    return false;
  }
}

function installPackages (packages, options) {
  var command = null;
  var shouldUseYarn = isYarnAvailable() && !options.npm;
  if (shouldUseYarn) {
    command = [
      'yarn',
      'add',
      '--exact'
    ];
  } else {
    command = [
      'npm',
      'install',
      '--save',
      '--save-exact'
    ];
  }
  if (options.verbose) {
    command.push('--verbose');
  }
  Array.prototype.push.apply(command, packages);

  try {
    if (options.verbose) {
      console.log('Executing command: "', command.join(' '), '"');
    }
    execSync(command.join(' '), { stdio: 'inherit' });
  } catch (error) {
    console.error(error.message);
    if (options.verbose) {
      console.error(error);
      console.error('Command: "', command.join(' '), '" has failed.');
    }
    process.exit(1);
  }
}

var localCliPath = getLocalCliPath();
var argv = process.argv.slice(2);

var isInsideHopsProject = false;
try {
  var manifest = require(path.resolve(process.cwd(), 'package.json'));
  if (manifest.dependencies) {
    isInsideHopsProject = Boolean(manifest.dependencies['hops-local-cli']);
  }
} catch (error) {
  isInsideHopsProject = false;
}

if (isInsideHopsProject) {
  if (localCliPath) {
    require(localCliPath).run(argv);
  } else {
    console.error(
      'It appears that we are inside a hops project but the dependencies have',
      'not been installed.\n',
      'Please execute "' + (isYarnAvailable() ? 'yarn' : 'npm') + ' install"',
      'and retry.'
    );
    process.exit(1);
  }
} else {
  var options = globalCLI(argv);
  var name = options.projectName;
  var root = process.cwd();
  var versionedPackages = PACKAGES_TO_INSTALL.map(function (name) {
    return name + '@' + options.hopsVersion;
  });

  validateName(name);
  createDirectory(path.resolve(root, name));
  writePackageManifest(path.resolve(root, name));
  process.chdir(path.resolve(root, name));
  installPackages(versionedPackages, options);
  require(getLocalCliPath()).init(root, name, options);
}
<commit_msg>fix(cli): lookup "hops-local-cli" in dependencies + devDependencies<commit_after>#!/usr/bin/env node
'use strict';

var fs = require('fs');
var path = require('path');
var execSync = require('child_process').execSync;
var resolveCwd = require('resolve-cwd');
var validatePackageName = require('validate-npm-package-name');

var packageManifest = require('./package.json');

var getLocalCliPath = function () {
  try {
    return resolveCwd('hops-local-cli');
  } catch (error) {
    return null;
  }
};

var PACKAGES_TO_INSTALL = [
  'hops-local-cli'
];

function globalCLI (argv) {
  return require('yargs')
    .version(packageManifest.version)
    .usage('Usage: $0 <command> [options]')
    .command('init <project-name>', 'Generates a new project with the ' +
      'specified name')
    .option('template', {
      type: 'string',
      describe: 'Use this with the npm package name of a template to ' +
        'initialize with a different template',
      default: 'hops-template-react'
    })
    .option('hops-version', {
      type: 'string',
      describe: 'Which version (or npm dist-tag) of hops-local-cli to use',
      default: 'latest'
    })
    .option('verbose', {
      type: 'boolean',
      describe: 'Increase verbosity of command',
      default: false
    })
    .option('npm', {
      type: 'boolean',
      describe: 'Force usage of `npm` instead of yarn',
      default: false
    })
    .example(
      '$0 init my-project',
      'Creates the folder my-project inside the current directory and ' +
        'initializes a sample hops react project inside it.'
    )
    .example(
      '$0 init --template hops-template-minimal my-project',
      'Creates the folder my-project inside the current directory and ' +
        'initializes a minimal hops example inside it.'
    )
    .help('h')
    .alias('h', 'help')
    .demandCommand()
    .wrap(72)
    .parse(argv);
}

function validateName (name) {
  var validationResult = validatePackageName(name);
  if (!validationResult.validForNewPackages) {
    console.error(
      'Cannot create a project with the name:',
      name,
      'because of the following npm restrictions:'
    );
    if (validationResult.errors) {
      validationResult.errors.forEach(function (msg) { console.error(msg); });
    }
    if (validationResult.warnings) {
      validationResult.warnings.forEach(function (msg) { console.warn(msg); });
    }
    process.exit(1);
  }
}

function createDirectory (root) {
  if (fs.existsSync(root)) {
    console.error(
      'A directory with the name:',
      name,
      'already exists in:',
      process.cwd(),
      '\nPlease remove this directory or choose a different project-name.'
    );
    process.exit(1);
  }

  fs.mkdirSync(root);
}

function writePackageManifest (root) {
  fs.writeFileSync(
    path.join(root, 'package.json'),
    JSON.stringify({
      name: name,
      version: '1.0.0',
      private: true
    }, null, 2)
  );
}

function isYarnAvailable () {
  try {
    execSync('yarn --version', { stdio: 'ignore' });
    return true;
  } catch (error) {
    return false;
  }
}

function installPackages (packages, options) {
  var command = null;
  var shouldUseYarn = isYarnAvailable() && !options.npm;
  if (shouldUseYarn) {
    command = [
      'yarn',
      'add',
      '--exact'
    ];
  } else {
    command = [
      'npm',
      'install',
      '--save',
      '--save-exact'
    ];
  }
  if (options.verbose) {
    command.push('--verbose');
  }
  Array.prototype.push.apply(command, packages);

  try {
    if (options.verbose) {
      console.log('Executing command: "', command.join(' '), '"');
    }
    execSync(command.join(' '), { stdio: 'inherit' });
  } catch (error) {
    console.error(error.message);
    if (options.verbose) {
      console.error(error);
      console.error('Command: "', command.join(' '), '" has failed.');
    }
    process.exit(1);
  }
}

var localCliPath = getLocalCliPath();
var argv = process.argv.slice(2);

var isInsideHopsProject = false;
try {
  var manifest = require(path.resolve(process.cwd(), 'package.json'));
  var dependencies = Object.keys(manifest.dependencies || {})
    .concat(Object.keys(manifest.devDependencies || {}));
  isInsideHopsProject = dependencies.indexOf('hops-local-cli') > -1;
} catch (error) {
  isInsideHopsProject = false;
}

if (isInsideHopsProject) {
  if (localCliPath) {
    require(localCliPath).run(argv);
  } else {
    console.error(
      'It appears that we are inside a hops project but the dependencies have',
      'not been installed.\n',
      'Please execute "' + (isYarnAvailable() ? 'yarn' : 'npm') + ' install"',
      'and retry.'
    );
    process.exit(1);
  }
} else {
  var options = globalCLI(argv);
  var name = options.projectName;
  var root = process.cwd();
  var versionedPackages = PACKAGES_TO_INSTALL.map(function (name) {
    return name + '@' + options.hopsVersion;
  });

  validateName(name);
  createDirectory(path.resolve(root, name));
  writePackageManifest(path.resolve(root, name));
  process.chdir(path.resolve(root, name));
  installPackages(versionedPackages, options);
  require(getLocalCliPath()).init(root, name, options);
}
<|endoftext|>


<commit_before>// @flow
/**
 * Part of GDL gdl-frontend.
 * Copyright (C) 2017 GDL
 *
 * See LICENSE
 */

import * as React from 'react';
import { DateFormat, Trans } from '@lingui/react';
import { MdTranslate } from 'react-icons/lib/md';

import styled from 'react-emotion';
import config from '../../config';
import { fetchBook, fetchSimilarBooks } from '../../fetch';
import type { Book, RemoteData, Context } from '../../types';
import defaultPage from '../../hocs/defaultPage';
import { Link } from '../../routes';
import Box from '../../components/Box';
import Flex from '../../components/Flex';
import Layout from '../../components/Layout';
import Ribbon from '../../components/Ribbon';
import A from '../../components/A';
import H3 from '../../components/H3';
import H1 from '../../components/H1';
import H6 from '../../components/H6';
import P from '../../components/P';
import Card from '../../components/Card';
import BookCover from '../../components/BookCover';
import Button from '../../components/Button';
import Container from '../../components/Container';
import Head from '../../components/Head';
import BookList from '../../components/BookList';
import media from '../../style/media';
import theme from '../../style/theme';
import { flexColumnCentered } from '../../style/flex';

type Props = {
  book: RemoteData<Book>,
  similar: RemoteData<{
    results: Array<Book>
  }>
};

const CoverWrap = styled('div')`
  ${media.mobile`
    position: absolute;
    top: -120px;
    z-index: 10;
    left: 50%;
    transform: translateX(-50%);
    width: 150px;
  `} height: 190px;

  ${media.tablet`
    height: 365px;
    flex: 0 0 260px;
    margin-right: 20px;
  `};
`;

const Hr = styled('hr')`
  height: 1px;
  background-color: ${theme.colors.grayLight};
  border-style: none;
  margin: 0;
  ${media.mobile`
    margin-left: -15px;
    margin-right: -15px;
  `};
`;

const HeroCard = styled(Card)`
  ${flexColumnCentered};
`;

class BookPage extends React.Component<Props> {
  static async getInitialProps({ query, accessToken }: Context) {
    const [book, similar] = await Promise.all([
      fetchBook(query.id, query.lang)(accessToken),
      fetchSimilarBooks(query.id, query.lang)(accessToken)
    ]);

    return {
      book,
      similar
    };
  }

  render() {
    const { similar, book } = this.props;

    const contributors = book.contributors
      .map(contributor => {contributor.name})
      .map((item, index) => [index > 0 && ', ', item]);

    const categories = book.categories
      .map(category => {category.name})
      .map((item, index) => [index > 0 && ', ', item]);

    return (
      <Layout
        crumbs={[
          <Link route="books" params={{ lang: book.language.code }}>
            {book.language.name}
          </Link>,
          book.title
        ]}
        language={book.language}
      >

        <Container pt={[15, 20]}>
          <Flex mt={[120, 0]} style={{ position: 'relative' }}>
            <CoverWrap>
              <BookCover coverPhoto={book.coverPhoto} width={[150, 260]} />
            </CoverWrap>
            <HeroCard textAlign="center" p={[15, 20]} pt={[80, 20]} flex="1">

{book.title}

                <Trans>
                  from {book.publisher.name}
                </Trans>

                {book.description}

              <Link
                route="read"
                passHref
                params={{ id: book.id, lang: book.language.code }}
                prefetch
              >
                <Button color="green">
                  <Trans>Read Book</Trans>
                </Button>
              </Link>
              <Box mt={[15, 20]}>

                  <Trans>Download book</Trans>

              </Box>
            </HeroCard>
          </Flex>
        </Container>
        <Container pb={[15, 20]}>
          <Box ml={[0, 'auto']} w={['auto', 438]}>
            <Box p={[15, 20]} fontSize={[14, 16]}>
              <Ribbon level={book.readingLevel} />
              {book.datePublished && (
                <Box mb={15}>

                    <Trans>Published</Trans>

                  <DateFormat value={new Date(book.datePublished)} />
                </Box>
              )}
              <Box mb={15}>

                  <Trans>Authors</Trans>

                {contributors}
              </Box>
              <Box>

                  <Trans>License</Trans>

                {book.license.description}
              </Box>
              {book.categories.length > 0 && (
                <Box mb={15}>

                    <Trans>categories</Trans>

,
                  {categories},
                </Box>
              )}
            </Box>
            {config.TRANSLATION_PAGES &&
              book.supportsTranslation && (
                <React.Fragment>

                  <Box my={[15, 20]} textAlign="center">
                    <Link
                      route="translate"
                      passHref
                      params={{ id: book.id, lang: book.language.code }}
                    >
                      <Button>
                        <MdTranslate /> <Trans>Translate book</Trans>
                      </Button>
                    </Link>
                  </Box>
                </React.Fragment>
              )}
          </Box>

            <Trans>Similar</Trans>

          <BookList books={similar.results} mt={20} />
        </Container>
      </Layout>
    );
  }
}

export default defaultPage(BookPage);
<commit_msg>Hide similar books if the list is empty<commit_after>// @flow
/**
 * Part of GDL gdl-frontend.
 * Copyright (C) 2017 GDL
 *
 * See LICENSE
 */

import * as React from 'react';
import { DateFormat, Trans } from '@lingui/react';
import { MdTranslate } from 'react-icons/lib/md';

import styled from 'react-emotion';
import config from '../../config';
import { fetchBook, fetchSimilarBooks } from '../../fetch';
import type { Book, RemoteData, Context } from '../../types';
import defaultPage from '../../hocs/defaultPage';
import { Link } from '../../routes';
import Box from '../../components/Box';
import Flex from '../../components/Flex';
import Layout from '../../components/Layout';
import Ribbon from '../../components/Ribbon';
import A from '../../components/A';
import H3 from '../../components/H3';
import H1 from '../../components/H1';
import H6 from '../../components/H6';
import P from '../../components/P';
import Card from '../../components/Card';
import BookCover from '../../components/BookCover';
import Button from '../../components/Button';
import Container from '../../components/Container';
import Head from '../../components/Head';
import BookList from '../../components/BookList';
import media from '../../style/media';
import theme from '../../style/theme';
import { flexColumnCentered } from '../../style/flex';

type Props = {
  book: RemoteData<Book>,
  similar: RemoteData<{
    results: Array<Book>
  }>
};

const CoverWrap = styled('div')`
  ${media.mobile`
    position: absolute;
    top: -120px;
    z-index: 10;
    left: 50%;
    transform: translateX(-50%);
    width: 150px;
  `} height: 190px;

  ${media.tablet`
    height: 365px;
    flex: 0 0 260px;
    margin-right: 20px;
  `};
`;

const Hr = styled('hr')`
  height: 1px;
  background-color: ${theme.colors.grayLight};
  border-style: none;
  margin: 0;
  ${media.mobile`
    margin-left: -15px;
    margin-right: -15px;
  `};
`;

const HeroCard = styled(Card)`
  ${flexColumnCentered};
`;

class BookPage extends React.Component<Props> {
  static async getInitialProps({ query, accessToken }: Context) {
    const [book, similar] = await Promise.all([
      fetchBook(query.id, query.lang)(accessToken),
      fetchSimilarBooks(query.id, query.lang)(accessToken)
    ]);

    return {
      book,
      similar
    };
  }

  render() {
    const { similar, book } = this.props;

    const contributors = book.contributors
      .map(contributor => {contributor.name})
      .map((item, index) => [index > 0 && ', ', item]);

    const categories = book.categories
      .map(category => {category.name})
      .map((item, index) => [index > 0 && ', ', item]);

    return (
      <Layout
        crumbs={[
          <Link route="books" params={{ lang: book.language.code }}>
            {book.language.name}
          </Link>,
          book.title
        ]}
        language={book.language}
      >

        <Container pt={[15, 20]}>
          <Flex mt={[120, 0]} style={{ position: 'relative' }}>
            <CoverWrap>
              <BookCover coverPhoto={book.coverPhoto} width={[150, 260]} />
            </CoverWrap>
            <HeroCard textAlign="center" p={[15, 20]} pt={[80, 20]} flex="1">

{book.title}

                <Trans>
                  from {book.publisher.name}
                </Trans>

                {book.description}

              <Link
                route="read"
                passHref
                params={{ id: book.id, lang: book.language.code }}
                prefetch
              >
                <Button color="green">
                  <Trans>Read Book</Trans>
                </Button>
              </Link>
              <Box mt={[15, 20]}>

                  <Trans>Download book</Trans>

              </Box>
            </HeroCard>
          </Flex>
        </Container>
        <Container pb={[15, 20]}>
          <Box ml={[0, 'auto']} w={['auto', 438]}>
            <Box p={[15, 20]} fontSize={[14, 16]}>
              <Ribbon level={book.readingLevel} />
              {book.datePublished && (
                <Box mb={15}>

                    <Trans>Published</Trans>

                  <DateFormat value={new Date(book.datePublished)} />
                </Box>
              )}
              <Box mb={15}>

                  <Trans>Authors</Trans>

                {contributors}
              </Box>
              <Box>

                  <Trans>License</Trans>

                {book.license.description}
              </Box>
              {book.categories.length > 0 && (
                <Box mb={15}>

                    <Trans>categories</Trans>

,
                  {categories},
                </Box>
              )}
            </Box>
            {config.TRANSLATION_PAGES &&
              book.supportsTranslation && (
                <React.Fragment>

                  <Box my={[15, 20]} textAlign="center">
                    <Link
                      route="translate"
                      passHref
                      params={{ id: book.id, lang: book.language.code }}
                    >
                      <Button>
                        <MdTranslate /> <Trans>Translate book</Trans>
                      </Button>
                    </Link>
                  </Box>
                </React.Fragment>
              )}
          </Box>
          {similar &&
            similar.results.length > 0 && (
              <React.Fragment>

                  <Trans>Similar</Trans>

                <BookList books={similar.results} mt={20} />
              </React.Fragment>
            )}
        </Container>
      </Layout>
    );
  }
}

export default defaultPage(BookPage);
<|endoftext|>


<commit_before>exports.create = function () {

    var page = new tabris.Page({
        title: "Barcode scanner",
        topLevel: false
    }).on('backButtonPressed', function () {
        require("./devices.js").create('devices.js').open();
    });

    new tabris.Button({
        layoutData: {left: 10, centerY: 0, right: 10},
        text: "Scan Barcode"
    }).on("select", scanBarcode).appendTo(page);

    var resultView = new tabris.TextView({
        layoutData: {top: "prev() 20", left: 20, right: 20},
        markupEnabled: true
    }).appendTo(page);

    function scanBarcode() {
        cordova.plugins.barcodeScanner.scan(function (result) {
            resultView.set("text", result.cancelled ?
                "Scan cancelled" :
            "Scan result: " + result.text + " (" + result.format + ")");
        }, function (error) {
            resultView.set("text", "Error: " + error);
        });
    }

    return page;
};<commit_msg>Register a device<commit_after>exports.create = function () {

	var page = new tabris.Page({
        title: "Add a Device",
        topLevel: false
    }).on('backButtonPressed', function () {
        require("./devices.js").create('devices.js').open();
    });

	new tabris.Button({
        layoutData: {left: 10, top: 150, right: 10},
        text: "Scan Barcode"
    }).on("select", scanBarcode).appendTo(page);

	var resultView = new tabris.TextView({
        id: "result",
        layoutData: {top: "prev() 20", left: 20, right: 20},
        markupEnabled: true
    }).appendTo(page);

    new tabris.TextView({
        id: "submitto",
        layoutData: {top: 19, left: 15},
        text: "Submit to",
        font: "15px"
    }).appendTo(page);

	var lists = [
        {
            id: "first",
            name: "List 1"
        },
        {
            id: "second",
            name: "List 2"
        }
    ];

    new tabris.Picker({
        layoutData: {left: "#submitto 15", right: 12, top: 10, height: 38},
        items: lists,
        itemText: function (list) {
            return list.name;
        },
        selection: lists[0]
    }).on("change:selection", function (picker, item) {
        console.log("Selected " + item.id);
    }).appendTo(page);

	new tabris.Button({
        id: "submit",
        text: "Submit",
        layoutData: {centerX: 0, top: "#result 20"}
    }).on("tap", function () {
        reDirect();
    }).appendTo(page);

	function reDirect() {

        var b = globalResult.text;
        if (/DuraMax/.test(b)) {
            require("./duramax.js").create("duramax.js").open();
        }else if(/HANDYSURF/.test(b)){
			require("./handysurf.js").create("handysurf.js").open();
		}else if(/O-INSPECT/.test(b)){
			require("./oinspect.js").create("oinspect.js").open();
		}else if(/SURFCOM/.test(b)){
			require("./surfcom.js").create("surfcom.js").open();
		}
    }

    var globalResult;

    function scanBarcode() {
        cordova.plugins.barcodeScanner.scan(function (result) {
                globalResult = result;
                resultView.set("text", result.cancelled ?
                    "Scan cancelled" :
                "Scan result: " + result.text + " (" + result.format + ")");
            },
            function (error) {
                resultView.set("text", "Error: " + error);
            });
    }

    function scanBarcode() {
        cordova.plugins.barcodeScanner.scan(function (result) {
            resultView.set("text", result.cancelled ?
                "Scan cancelled" :
            "Scan result: " + result.text + " (" + result.format + ")");
        }, function (error) {
            resultView.set("text", "Error: " + error);
        });
    }

    return page;
};<|endoftext|>


<commit_before>"use strict";

Option.saveOptions = function() {
  Option.all.forEach(function(option) {
    option.save();
  });
};

Option.needSaveOptions = function() {
  return !Option.all.every(function(option) {
    return option.areEqual(option.readValueFromElement(), option.previous);
  });
};

function NumberOption() {
  NumberOption.__super__.constructor.apply(this, arguments);
  this.element.addEventListener("input", this.onUpdated);
}
__extends(NumberOption, Option);

NumberOption.prototype.populateElement = function(value) {
  return this.element.value = value;
};

NumberOption.prototype.readValueFromElement = function() {
  return parseFloat(this.element.value);
};

function TextOption() {
  TextOption.__super__.constructor.apply(this, arguments);
  this.element.addEventListener("input", this.onUpdated);
}
__extends(TextOption, Option);

TextOption.prototype.populateElement = function(value) {
  return this.element.value = value.replace(/\n /g, '\n\xa0');
};

TextOption.prototype.readValueFromElement = function() {
  return this.element.value.trim().replace(/\xa0/g, ' ');
};

function NonEmptyTextOption(element) {
  NonEmptyTextOption.__super__.constructor.apply(this, arguments);
}
__extends(NonEmptyTextOption, TextOption);

NonEmptyTextOption.prototype.readValueFromElement = function() {
  var value = NonEmptyTextOption.__super__.readValueFromElement.call(this);
  if (!value) {
    value = bgSettings.defaults[this.field];
    this.populateElement(value);
  }
  return value;
};

function JSONOption() {
  JSONOption.__super__.constructor.apply(this, arguments);
}
__extends(JSONOption, TextOption);

JSONOption.prototype.populateElement = function(obj) {
  return JSONOption.__super__.populateElement.call(this, JSON.stringify(obj));
};

JSONOption.prototype.readValueFromElement = function() {
  var value = JSONOption.__super__.readValueFromElement.call(this), obj, std;
  obj = std = bgSettings.defaults[this.field];
  if (value) {
    try {
      obj = JSON.parse(value);
      if (JSON.stringify(obj) == JSON.stringify(std)) {
        obj = std;
      }
    } catch (e) {}
  } else {
    this.populateElement(obj);
  }
  return obj;
};

function CheckBoxOption() {
  CheckBoxOption.__super__.constructor.apply(this, arguments);
  this.element.addEventListener("change", this.onUpdated);
}
__extends(CheckBoxOption, Option);

CheckBoxOption.prototype.populateElement = function(value) {
  return this.element.checked = value;
};

CheckBoxOption.prototype.readValueFromElement = function() {
  return this.element.checked;
};

(function() {
  var advancedMode, element, name, onUpdated, saveOptions, type, _i, _ref, status = 0;

  onUpdated = function() {
    var saveBtn;
    if (this.areEqual(this.readValueFromElement(), this.previous)) {
      if (status == 1 && !Option.needSaveOptions()) {
        saveBtn = $("saveOptions");
        saveBtn.disabled = true;
        saveBtn.textContent = "No Changes";
        $("exportButton").disabled = false;
        status = 0;
      }
      return;
    } else if (status == 1) {
      return;
    }
    status = 1;
    saveBtn = $("saveOptions");
    saveBtn.disabled = false;
    saveBtn.textContent = "Save Changes";
    $("exportButton").disabled = true;
  };

  $("showCommands").onclick = function(event) {
    var node;
    DomUtils.suppressEvent(event);
    if (node = document.querySelector('.HelpCommandName')) {
      node.click();
      return;
    }
    MainPort.sendMessage({
      handler: "initHelp",
      unbound: true,
      names: true,
      title: "Command Listing"
    }, function(response) {
      if (node = $("HelpDialog")) {
        MainPort.Listener({
          name: "execute",
          command: "showHelp",
          count: 1
        });
      }
      MainPort.Listener(response);
    });
  };

  saveOptions = function(virtually) {
    var btn = $("saveOptions"), toSync;
    if (virtually !== false) {
      Option.saveOptions();
    }
    toSync = Option.syncToFrontend;
    Option.syncToFrontend = [];
    btn.disabled = true;
    btn.textContent = "No Changes";
    $("exportButton").disabled = false;
    status = 0;
    setTimeout(function () {
      var event = new FocusEvent("focus"), i, key, ref;
      window.dispatchEvent(event);
      i = toSync.length;
      if (i === 0) { return; }
      bgSettings.postUpdate("bufferToLoad", null);
      var i, key, ref = bgSettings.bufferToLoad, obj = {name: "settingsUpdate"};
      while (0 <= --i) {
        key = toSync[i];
        obj[key] = ref[key];
      }
      bgSettings.postUpdate("broadcast", obj);
    }, 100);
  };
  $("saveOptions").onclick = saveOptions;

  _ref = document.getElementsByClassName("nonEmptyTextOption");
  for (_i = _ref.length; 0 <= --_i; ) {
    element = _ref[_i];
    element.className = element.className + " example info";
    element.textContent = "Leave empty to reset this option.";
  }

  window.onbeforeunload = function() {
    if (status !== 0 && Option.needSaveOptions()) {
      return "You have unsaved changes to options.";
    }
  };
  document.addEventListener("keyup", function(event) {
    if (event.ctrlKey && event.keyCode === 13) {
      var element = document.activeElement;
      if (element && element.blur) {
        element.blur();
      }
      if (status != 0) {
        saveOptions();
      }
    }
  });

  _ref = document.querySelectorAll("[data-model]");
  for (_i = _ref.length; 0 <= --_i; ) {
    element = _ref[_i];
    type = window[element.getAttribute("data-model") + "Option"];
    new type(element, onUpdated);
  }

  advancedMode = bgSettings.get("showAdvancedOptions");
  element = $("advancedOptionsButton");
  element.onclick = function(_0, init) {
    if (!init) {
      advancedMode = !advancedMode;
      bgSettings.set("showAdvancedOptions", advancedMode);
    }
    if (advancedMode) {
      $("advancedOptions").style.display = "";
      this.textContent = "Hide Advanced Options";
    } else {
      $("advancedOptions").style.display = "none";
      this.textContent = "Show Advanced Options";
    }
  };
  element.onclick(null, true);

  element = null;
})();

var formatDate = function(time) {
  return new Date(time - new Date().getTimezoneOffset() * 1000 * 60
    ).toJSON().substring(0, 19).replace('T', ' ');
};

$("exportButton").onclick = function() {
  var exported_object, exported_data, file_name, force2, d, nodeA;
  exported_object = {__proto__: null, name: "Vimium++", time: 0};
  (function() {
    var storage = localStorage, i, len, key, mark_head, all = bgSettings.defaults
      , strArr = bgSettings.NonJSON, arr1;
    mark_head = BG.Marks.getMarkKey("");
    for (i = 0, len = storage.length; i < len; i++) {
      key = storage.key(i);
      if (key === "name" || key === "time" || key.startsWith(mark_head)) {
        continue;
      }
      exported_object[key] = (key in strArr) && storage.getItem(key).indexOf("\n") > 0
        ? storage.getItem(key).split("\n")
        : (key in all) ? bgSettings.get(key) : storage.getItem(key);
    }
  })();
  delete exported_object.findModeRawQuery;
  delete exported_object.newTabUrl_f;
  d = new Date();
  exported_object.time = d.getTime();
  exported_data = JSON.stringify(exported_object, null, '\t');
  exported_object = null;
  force2 = function(i) { return ((i <= 9) ? '0'  : '') + i; }
  file_name = 'vimium++_' + d.getFullYear() + force2(d.getMonth() + 1) + force2(d.getDate())
    + '_' + force2(d.getHours()) + force2(d.getMinutes()) + force2(d.getSeconds()) + '.json';

  nodeA = document.createElement("a");
  nodeA.download = file_name;
  nodeA.href = URL.createObjectURL(new Blob([exported_data]));
  nodeA.click();
  URL.revokeObjectURL(nodeA.href);
  console.log("EXPORT settings to", file_name, "at", formatDate(d));
};

var importSettings = function() {
  var new_data;
  try {
    new_data = JSON.parse(this.result);
  } catch (e) {}
  if (!new_data || new_data.name !== "Vimium++" || !(new_data.time > 10000)) {
    VHUD.showForDuration("No settings data found!", 2000);
    return;
  } else if (!confirm(
    "You are loading a settings copy exported at:\n        "
    + formatDate(new_data.time)
    + "\n\nAre you sure you want to continue?"
  )) {
    VHUD.showForDuration("You cancelled importing.", 1000);
    return;
  }

  var storage = localStorage, i, key, new_value, func, all = bgSettings.defaults
    , strArr = bgSettings.NonJSON;
  func = function(val) {
    return typeof val !== "string" || val.length <= 72 ? val
      : val.substring(0, 68).trimRight() + " ...";
  };
  console.log("IMPORT settings at", new Date(new_data.time));
  delete new_data.name;
  delete new_data.time;
  delete new_data.findModeRawQuery;
  delete new_data.newTabUrl_f;
  Utils.setNullProto(new_data);
  for (i = storage.length; 0 <= --i; ) {
    key = storage.key(i);
    if (!(key in new_data)) {
      new_data[key] = null;
    }
  }
  Option.all.forEach(function(item) {
    var key = item.field, new_value = new_data[key];
    delete new_data[key];
    if (new_value == null) {
      new_value = all[key];
    } else if (new_value.join && (key in strArr)) {
      new_value = new_value.join("\n");
    }
    if (!item.areEqual(bgSettings.get(key), new_value)) {
      console.log("import", key, func(new_value));
      bgSettings.set(key, new_value);
      if (key in bgSettings.bufferToLoad) {
        Option.syncToFrontend.push(key);
      }
    }
    item.fetch();
  });
  bgSettings.postUpdate("newTabUrl");
  for (key in new_data) {
    new_value = new_data[key];
    if (new_value == null) {
      if (key in all) {
        new_value = all[key];
        if (bgSettings.get(key) !== new_value) {
          bgSettings.set(key, new_value);
          console.log("reset", key, func(new_value));
          continue;
        }
        new_value = bgSettings.get(key);
      } else {
        new_value = storage.getItem(key);
      }
      storage.removeItem(key);
      console.log("remove", key, "<=", func(new_value));
      continue;
    }
    if (new_value.join && (key in strArr)) {
      new_value = new_value.join("\n");
    }
    if (key in all) {
      if (bgSettings.get(key) !== new_value) {
        bgSettings.set(key, new_value);
        console.log("update", key, func(new_value));
      }
    } else {
      storage.setItem(key, new_value);
      console.log("save", key, func(new_value));
    }
  }
  var btn = $("saveOptions");
  btn.onclick(false);
  VHUD.showForDuration("Import settings data: OK!", 1000);
};

$("settingsFile").onchange = function() {
  var file = this.files[0], reader;
  this.value = "";
  if (!file) { return; }
  reader = new FileReader();
  reader.onload = importSettings;
  reader.readAsText(file);
};
$("importButton").onclick = function() {
  $("settingsFile").click();
};

(function() {
  var arr = document.querySelectorAll("[data-auto-scale]"), i, func;
  func = function() {
    var target = $(this.getAttribute("data-auto-scale"));
    if (target.scrollHeight <= target.clientHeight) { return; }
    target.style.overflow = "hidden";
    target.style.maxWidth = Math.max(window.innerWidth, 920) - 520 + "px";
    target.style.width  = target.scrollWidth  + 6 + "px";
    target.style.height = target.scrollHeight + 3 + "px";
    target.style.overflow = "";
  };
  for (i = arr.length; 0 <= --i; ) {
    arr[i].onclick = func;
  }
})();
<commit_msg>a small change to log info<commit_after>"use strict";

Option.saveOptions = function() {
  Option.all.forEach(function(option) {
    option.save();
  });
};

Option.needSaveOptions = function() {
  return !Option.all.every(function(option) {
    return option.areEqual(option.readValueFromElement(), option.previous);
  });
};

function NumberOption() {
  NumberOption.__super__.constructor.apply(this, arguments);
  this.element.addEventListener("input", this.onUpdated);
}
__extends(NumberOption, Option);

NumberOption.prototype.populateElement = function(value) {
  return this.element.value = value;
};

NumberOption.prototype.readValueFromElement = function() {
  return parseFloat(this.element.value);
};

function TextOption() {
  TextOption.__super__.constructor.apply(this, arguments);
  this.element.addEventListener("input", this.onUpdated);
}
__extends(TextOption, Option);

TextOption.prototype.populateElement = function(value) {
  return this.element.value = value.replace(/\n /g, '\n\xa0');
};

TextOption.prototype.readValueFromElement = function() {
  return this.element.value.trim().replace(/\xa0/g, ' ');
};

function NonEmptyTextOption(element) {
  NonEmptyTextOption.__super__.constructor.apply(this, arguments);
}
__extends(NonEmptyTextOption, TextOption);

NonEmptyTextOption.prototype.readValueFromElement = function() {
  var value = NonEmptyTextOption.__super__.readValueFromElement.call(this);
  if (!value) {
    value = bgSettings.defaults[this.field];
    this.populateElement(value);
  }
  return value;
};

function JSONOption() {
  JSONOption.__super__.constructor.apply(this, arguments);
}
__extends(JSONOption, TextOption);

JSONOption.prototype.populateElement = function(obj) {
  return JSONOption.__super__.populateElement.call(this, JSON.stringify(obj));
};

JSONOption.prototype.readValueFromElement = function() {
  var value = JSONOption.__super__.readValueFromElement.call(this), obj, std;
  obj = std = bgSettings.defaults[this.field];
  if (value) {
    try {
      obj = JSON.parse(value);
      if (JSON.stringify(obj) == JSON.stringify(std)) {
        obj = std;
      }
    } catch (e) {}
  } else {
    this.populateElement(obj);
  }
  return obj;
};

function CheckBoxOption() {
  CheckBoxOption.__super__.constructor.apply(this, arguments);
  this.element.addEventListener("change", this.onUpdated);
}
__extends(CheckBoxOption, Option);

CheckBoxOption.prototype.populateElement = function(value) {
  return this.element.checked = value;
};

CheckBoxOption.prototype.readValueFromElement = function() {
  return this.element.checked;
};

(function() {
  var advancedMode, element, name, onUpdated, saveOptions, type, _i, _ref, status = 0;

  onUpdated = function() {
    var saveBtn;
    if (this.areEqual(this.readValueFromElement(), this.previous)) {
      if (status == 1 && !Option.needSaveOptions()) {
        saveBtn = $("saveOptions");
        saveBtn.disabled = true;
        saveBtn.textContent = "No Changes";
        $("exportButton").disabled = false;
        status = 0;
      }
      return;
    } else if (status == 1) {
      return;
    }
    status = 1;
    saveBtn = $("saveOptions");
    saveBtn.disabled = false;
    saveBtn.textContent = "Save Changes";
    $("exportButton").disabled = true;
  };

  $("showCommands").onclick = function(event) {
    var node;
    DomUtils.suppressEvent(event);
    if (node = document.querySelector('.HelpCommandName')) {
      node.click();
      return;
    }
    MainPort.sendMessage({
      handler: "initHelp",
      unbound: true,
      names: true,
      title: "Command Listing"
    }, function(response) {
      if (node = $("HelpDialog")) {
        MainPort.Listener({
          name: "execute",
          command: "showHelp",
          count: 1
        });
      }
      MainPort.Listener(response);
    });
  };

  saveOptions = function(virtually) {
    var btn = $("saveOptions"), toSync;
    if (virtually !== false) {
      Option.saveOptions();
    }
    toSync = Option.syncToFrontend;
    Option.syncToFrontend = [];
    btn.disabled = true;
    btn.textContent = "No Changes";
    $("exportButton").disabled = false;
    status = 0;
    setTimeout(function () {
      var event = new FocusEvent("focus"), i, key, ref;
      window.dispatchEvent(event);
      i = toSync.length;
      if (i === 0) { return; }
      bgSettings.postUpdate("bufferToLoad", null);
      var i, key, ref = bgSettings.bufferToLoad, obj = {name: "settingsUpdate"};
      while (0 <= --i) {
        key = toSync[i];
        obj[key] = ref[key];
      }
      bgSettings.postUpdate("broadcast", obj);
    }, 100);
  };
  $("saveOptions").onclick = saveOptions;

  _ref = document.getElementsByClassName("nonEmptyTextOption");
  for (_i = _ref.length; 0 <= --_i; ) {
    element = _ref[_i];
    element.className = element.className + " example info";
    element.textContent = "Leave empty to reset this option.";
  }

  window.onbeforeunload = function() {
    if (status !== 0 && Option.needSaveOptions()) {
      return "You have unsaved changes to options.";
    }
  };
  document.addEventListener("keyup", function(event) {
    if (event.ctrlKey && event.keyCode === 13) {
      var element = document.activeElement;
      if (element && element.blur) {
        element.blur();
      }
      if (status != 0) {
        saveOptions();
      }
    }
  });

  _ref = document.querySelectorAll("[data-model]");
  for (_i = _ref.length; 0 <= --_i; ) {
    element = _ref[_i];
    type = window[element.getAttribute("data-model") + "Option"];
    new type(element, onUpdated);
  }

  advancedMode = bgSettings.get("showAdvancedOptions");
  element = $("advancedOptionsButton");
  element.onclick = function(_0, init) {
    if (!init) {
      advancedMode = !advancedMode;
      bgSettings.set("showAdvancedOptions", advancedMode);
    }
    if (advancedMode) {
      $("advancedOptions").style.display = "";
      this.textContent = "Hide Advanced Options";
    } else {
      $("advancedOptions").style.display = "none";
      this.textContent = "Show Advanced Options";
    }
  };
  element.onclick(null, true);

  element = null;
})();

var formatDate = function(time) {
  return new Date(time - new Date().getTimezoneOffset() * 1000 * 60
    ).toJSON().substring(0, 19).replace('T', ' ');
};

$("exportButton").onclick = function() {
  var exported_object, exported_data, file_name, force2, d, nodeA;
  exported_object = {__proto__: null, name: "Vimium++", time: 0};
  (function() {
    var storage = localStorage, i, len, key, mark_head, all = bgSettings.defaults
      , strArr = bgSettings.NonJSON, arr1;
    mark_head = BG.Marks.getMarkKey("");
    for (i = 0, len = storage.length; i < len; i++) {
      key = storage.key(i);
      if (key === "name" || key === "time" || key.startsWith(mark_head)) {
        continue;
      }
      exported_object[key] = (key in strArr) && storage.getItem(key).indexOf("\n") > 0
        ? storage.getItem(key).split("\n")
        : (key in all) ? bgSettings.get(key) : storage.getItem(key);
    }
  })();
  delete exported_object.findModeRawQuery;
  delete exported_object.newTabUrl_f;
  d = new Date();
  exported_object.time = d.getTime();
  exported_data = JSON.stringify(exported_object, null, '\t');
  exported_object = null;
  force2 = function(i) { return ((i <= 9) ? '0'  : '') + i; }
  file_name = 'vimium++_' + d.getFullYear() + force2(d.getMonth() + 1) + force2(d.getDate())
    + '_' + force2(d.getHours()) + force2(d.getMinutes()) + force2(d.getSeconds()) + '.json';

  nodeA = document.createElement("a");
  nodeA.download = file_name;
  nodeA.href = URL.createObjectURL(new Blob([exported_data]));
  nodeA.click();
  URL.revokeObjectURL(nodeA.href);
  console.log("EXPORT settings to", file_name, "at", formatDate(d));
};

var importSettings = function() {
  var new_data;
  try {
    new_data = JSON.parse(this.result);
  } catch (e) {}
  if (!new_data || new_data.name !== "Vimium++" || !(new_data.time > 10000)) {
    VHUD.showForDuration("No settings data found!", 2000);
    return;
  } else if (!confirm(
    "You are loading a settings copy exported at:\n        "
    + formatDate(new_data.time)
    + "\n\nAre you sure you want to continue?"
  )) {
    VHUD.showForDuration("You cancelled importing.", 1000);
    return;
  }

  var storage = localStorage, i, key, new_value, func, all = bgSettings.defaults
    , strArr = bgSettings.NonJSON;
  func = function(val) {
    return typeof val !== "string" || val.length <= 72 ? val
      : val.substring(0, 68).trimRight() + " ...";
  };
  console.log("IMPORT settings at", new Date(new_data.time));
  delete new_data.name;
  delete new_data.time;
  delete new_data.findModeRawQuery;
  delete new_data.newTabUrl_f;
  Utils.setNullProto(new_data);
  for (i = storage.length; 0 <= --i; ) {
    key = storage.key(i);
    if (!(key in new_data)) {
      new_data[key] = null;
    }
  }
  Option.all.forEach(function(item) {
    var key = item.field, new_value = new_data[key];
    delete new_data[key];
    if (new_value == null) {
      new_value = all[key];
    } else if (new_value.join && (key in strArr)) {
      new_value = new_value.join("\n");
    }
    if (!item.areEqual(bgSettings.get(key), new_value)) {
      console.log("import", key, func(new_value));
      bgSettings.set(key, new_value);
      if (key in bgSettings.bufferToLoad) {
        Option.syncToFrontend.push(key);
      }
    }
    item.fetch();
  });
  bgSettings.postUpdate("newTabUrl");
  for (key in new_data) {
    new_value = new_data[key];
    if (new_value == null) {
      if (key in all) {
        new_value = all[key];
        if (bgSettings.get(key) !== new_value) {
          bgSettings.set(key, new_value);
          console.log("reset", key, func(new_value));
          continue;
        }
        new_value = bgSettings.get(key);
      } else {
        new_value = storage.getItem(key);
      }
      storage.removeItem(key);
      console.log("remove", key, ":=", func(new_value));
      continue;
    }
    if (new_value.join && (key in strArr)) {
      new_value = new_value.join("\n");
    }
    if (key in all) {
      if (bgSettings.get(key) !== new_value) {
        bgSettings.set(key, new_value);
        console.log("update", key, func(new_value));
      }
    } else {
      storage.setItem(key, new_value);
      console.log("save", key, func(new_value));
    }
  }
  var btn = $("saveOptions");
  btn.onclick(false);
  VHUD.showForDuration("Import settings data: OK!", 1000);
};

$("settingsFile").onchange = function() {
  var file = this.files[0], reader;
  this.value = "";
  if (!file) { return; }
  reader = new FileReader();
  reader.onload = importSettings;
  reader.readAsText(file);
};
$("importButton").onclick = function() {
  $("settingsFile").click();
};

(function() {
  var arr = document.querySelectorAll("[data-auto-scale]"), i, func;
  func = function() {
    var target = $(this.getAttribute("data-auto-scale"));
    if (target.scrollHeight <= target.clientHeight) { return; }
    target.style.overflow = "hidden";
    target.style.maxWidth = Math.max(window.innerWidth, 920) - 520 + "px";
    target.style.width  = target.scrollWidth  + 6 + "px";
    target.style.height = target.scrollHeight + 3 + "px";
    target.style.overflow = "";
  };
  for (i = arr.length; 0 <= --i; ) {
    arr[i].onclick = func;
  }
})();
<|endoftext|>


<commit_before>self.deprecationWorkflow = self.deprecationWorkflow || {};
self.deprecationWorkflow.config = {
  workflow: [
    { handler: "silence", matchId: "ember-runtime.deprecate-copy-copyable" },
    { handler: "silence", matchId: "ember-data:method-calls-on-destroyed-store" },
    { handler: "silence", matchId: "ember-component.send-action" }
  ]
};
<commit_msg>update deprecation workflow<commit_after>self.deprecationWorkflow = self.deprecationWorkflow || {};
self.deprecationWorkflow.config = {
  workflow: [
    { handler: "silence", matchId: "deprecate-router-events" },
    { handler: "silence", matchId: "ember-runtime.deprecate-copy-copyable" },
    { handler: "silence", matchId: "ember-polyfills.deprecate-merge" },
    { handler: "silence", matchId: "ember-data:method-calls-on-destroyed-store" },
    { handler: "silence", matchId: "ember-component.send-action" }
  ]
};
<|endoftext|>


<commit_before>'use strict';

var _ = require ('lodash');
var mongoose      = require('mongoose');
var Stream        = mongoose.model('Stream');
var PhaseBase     = mongoose.model('PhaseBase');
var MilestoneBase = mongoose.model('MilestoneBase');
var ActivityBase  = mongoose.model('ActivityBase');
var Prom = require('promise');

var baseObjects = {
	activities: [{
		code: 'edit',
		name: 'Edit Artifact',
		description: 'Edit Artifact',
		state: 'p.artifact.edit'
	},{
		code: 'review',
		name: 'Review Artifact',
		description: 'Review Artifact',
		state: 'p.artifact.review'
	},{
		code: 'approve',
		name: 'Approve Artifact',
		description: 'Approve Artifact',
		state: 'p.artifact.approve'
	},{
		code: 'executive',
		name: 'Executive Approve Artifact',
		description: 'Executive Approve Artifact',
		state: 'p.artifact.executive'
	},{
		code: 'publish',
		name: 'Publish Artifact',
		description: 'Publish Artifact',
		state: 'p.artifact.publish'
	},{
		code: 'notify',
		name: 'Notify Artifact',
		description: 'Notify Artifact',
		state: 'p.artifact.notify'
	}],
	"milestones": [{
	    code: 'project-description',
	    name: 'Project Description',
	    description: 'Project Description',
	    artifactType: 'Project Description'
	},{
	    code: 'section-10-1-a-order',
	    name: 'Section 10(1)(a) Order',
	    description: 'Section 10(1)(a) Order',
	    artifactType: 'Section 10(1)(a) Order'
	},{
	    code: 'section-10-1-b-order',
	    name: 'Section 10(1)(b) Order',
	    description: 'Section 10(1)(b) Order',
	    artifactType: 'Section 10(1)(b) Order'
	},{
	    code: 'section-10-1-c-order',
	    name: 'Section 10(1)(c) Order',
	    description: 'Section 10(1)(c) Order',
	    artifactType: 'Section 10(1)(c) Order'
	},{
	    code: 'section-11-order',
	    name: 'Section 11 Order',
	    description: 'Section 11 Order',
	    artifactType: 'Section 11 Order'
	},{
	    code: 'section-7-3-order',
	    name: 'Section 7(3) Order',
	    description: 'Section 7(3) Order',
	    artifactType: 'Section 7(3) Order'
	},{
	    code: 'valued-component',
	    name: 'Valued Component',
	    description: 'Valued Component',
	    artifactType: 'Valued Component'
	},{
		code: 'schedule-a',
		name: 'Schedule A',
		description: 'Schedule A',
		artifactType: 'Schedule A'
	}],
	"phases": [
		{
			"description": "Pre-Submission",
			"name": "Pre-submission",
			"code": "pre-submission",
		},
		{
			"description": "Pre-Application Preparation",
			"name": "Pre-EA",
			"code": "pre-ea",
		},
		{
			"description": "Pre-Application",
			"name": "Pre-Application",
			"code": "pre-application",
		},
		{
			"description": "EAO Evaluation",
			"name": "Evaluation",
			"code": "evaluation",
		},
		{
			"description": "EAO Review",
			"name": "Review",
			"code": "review",
		},
		{
			"description": "Decision",
			"name": "Decision",
			"code": "decision",
		},
		{
			"description": "Post Certification Processes",
			"name": "Post-Certification",
			"code": "post-certification",
		}
	],
	streams: [{
	code: '10-1-c',
	name: '10-1-c',
	description: 'This is the set of phases most commonly assigned to an assessment',
	phases: [
		"pre-ea",
		"pre-application",
		"evaluation",
		"review",
		"decision",
		"post-certification"
	]

	}]
};
var basePermissions = {
	"default_pro_watch": ['admin'],
	"default_pro_submit": ['admin'],
	"default_pro_write": ['editor'],
	"default_pro_read": ['member'],
	"default_eao_watch": ['admin'],
	"default_eao_submit": ['admin'],
	"default_eao_write": ['editor'],
	"default_eao_read": ['member']
};

module.exports = function (clear) {
	return new Prom (function (resolve, reject) {
	console.log ('Running configuration seeding');
	var p;
	if (clear) {
		console.log ('\t removing existing configuration objects');
		p = Stream.remove ({}).exec()
		.then (PhaseBase.remove ({}).exec())
		.then (MilestoneBase.remove ({}).exec())
		.then (ActivityBase.remove ({}).exec());
	} else {
		p = Prom.resolve();
	}
	p.then (function () {
		console.log ('\t adding phases');
		return Prom.all (baseObjects.phases.map (function (o) {
			var m = new PhaseBase (_.extend ({},o,basePermissions));
			return m.save ();
		}));
	})
	.then (function () {
		console.log ('\t adding milestones');
		return Prom.all (baseObjects.milestones.map (function (o) {
			var m = new MilestoneBase (_.extend ({},o,basePermissions));
			return m.save ();
		}));
	})
	.then (function () {
		console.log ('\t adding activities');
		return Prom.all (baseObjects.activities.map (function (o) {
			var m = new ActivityBase (_.extend ({},o,basePermissions));
			return m.save ();
		}));
	})
	.then (function () {
		console.log ('\t adding streams');
		return Prom.all (baseObjects.streams.map (function (o) {
			var m = new Stream (_.extend ({},o,basePermissions));
			return m.save ();
		}));
	})
	.then (resolve, reject);
	});
};

<commit_msg>Change phase seed<commit_after>'use strict';

var _ = require ('lodash');
var mongoose      = require('mongoose');
var Stream        = mongoose.model('Stream');
var PhaseBase     = mongoose.model('PhaseBase');
var MilestoneBase = mongoose.model('MilestoneBase');
var ActivityBase  = mongoose.model('ActivityBase');
var Prom = require('promise');

var baseObjects = {
	activities: [{
		code: 'edit',
		name: 'Edit Artifact',
		description: 'Edit Artifact',
		state: 'p.artifact.edit'
	},{
		code: 'review',
		name: 'Review Artifact',
		description: 'Review Artifact',
		state: 'p.artifact.review'
	},{
		code: 'approve',
		name: 'Approve Artifact',
		description: 'Approve Artifact',
		state: 'p.artifact.approve'
	},{
		code: 'executive',
		name: 'Executive Approve Artifact',
		description: 'Executive Approve Artifact',
		state: 'p.artifact.executive'
	},{
		code: 'publish',
		name: 'Publish Artifact',
		description: 'Publish Artifact',
		state: 'p.artifact.publish'
	},{
		code: 'notify',
		name: 'Notify Artifact',
		description: 'Notify Artifact',
		state: 'p.artifact.notify'
	}],
	"milestones": [{
	    code: 'project-description',
	    name: 'Project Description',
	    description: 'Project Description',
	    artifactType: 'Project Description'
	},{
	    code: 'section-10-1-a-order',
	    name: 'Section 10(1)(a) Order',
	    description: 'Section 10(1)(a) Order',
	    artifactType: 'Section 10(1)(a) Order'
	},{
	    code: 'section-10-1-b-order',
	    name: 'Section 10(1)(b) Order',
	    description: 'Section 10(1)(b) Order',
	    artifactType: 'Section 10(1)(b) Order'
	},{
	    code: 'section-10-1-c-order',
	    name: 'Section 10(1)(c) Order',
	    description: 'Section 10(1)(c) Order',
	    artifactType: 'Section 10(1)(c) Order'
	},{
	    code: 'section-11-order',
	    name: 'Section 11 Order',
	    description: 'Section 11 Order',
	    artifactType: 'Section 11 Order'
	},{
	    code: 'section-7-3-order',
	    name: 'Section 7(3) Order',
	    description: 'Section 7(3) Order',
	    artifactType: 'Section 7(3) Order'
	},{
	    code: 'valued-component',
	    name: 'Valued Component',
	    description: 'Valued Component',
	    artifactType: 'Valued Component'
	},{
		code: 'schedule-a',
		name: 'Schedule A',
		description: 'Schedule A',
		artifactType: 'Schedule A'
	}],
	"phases": [
		{
			"description": "Pre-Submission",
			"name": "Pre-submission",
			"code": "pre-submission",
		},
		{
			"description": "Pre-Application Preparation",
			"name": "Pre-EA",
			"code": "pre-ea",
		},
		{
			"description": "Pre-Application",
			"name": "Pre-App",
			"code": "pre-app",
		},
		{
			"description": "EAO Evaluation",
			"name": "Evaluation",
			"code": "evaluation",
		},
		{
			"description": "Application Review",
			"name": "Application Review",
			"code": "application-review",
		},
		{
			"description": "Decision",
			"name": "Decision",
			"code": "decision",
		},
		{
			"description": "Post Certification Processes",
			"name": "Post-Certification",
			"code": "post-certification",
		},
		{
			"description": "Completed",
			"name": "Completed",
			"code": "completed",
		}
	],
	streams: [{
	code: '10-1-c',
	name: '10-1-c',
	description: 'This is the set of phases most commonly assigned to an assessment',
	phases: [
		"pre-ea",
		"pre-application",
		"evaluation",
		"review",
		"decision",
		"post-certification"
	]

	}]
};
var basePermissions = {
	"default_pro_watch": ['admin'],
	"default_pro_submit": ['admin'],
	"default_pro_write": ['editor'],
	"default_pro_read": ['member'],
	"default_eao_watch": ['admin'],
	"default_eao_submit": ['admin'],
	"default_eao_write": ['editor'],
	"default_eao_read": ['member']
};

module.exports = function (clear) {
	return new Prom (function (resolve, reject) {
	console.log ('Running configuration seeding');
	var p;
	if (clear) {
		console.log ('\t removing existing configuration objects');
		p = Stream.remove ({}).exec()
		.then (PhaseBase.remove ({}).exec())
		.then (MilestoneBase.remove ({}).exec())
		.then (ActivityBase.remove ({}).exec());
	} else {
		p = Prom.resolve();
	}
	p.then (function () {
		console.log ('\t adding phases');
		return Prom.all (baseObjects.phases.map (function (o) {
			var m = new PhaseBase (_.extend ({},o,basePermissions));
			return m.save ();
		}));
	})
	.then (function () {
		console.log ('\t adding milestones');
		return Prom.all (baseObjects.milestones.map (function (o) {
			var m = new MilestoneBase (_.extend ({},o,basePermissions));
			return m.save ();
		}));
	})
	.then (function () {
		console.log ('\t adding activities');
		return Prom.all (baseObjects.activities.map (function (o) {
			var m = new ActivityBase (_.extend ({},o,basePermissions));
			return m.save ();
		}));
	})
	.then (function () {
		console.log ('\t adding streams');
		return Prom.all (baseObjects.streams.map (function (o) {
			var m = new Stream (_.extend ({},o,basePermissions));
			return m.save ();
		}));
	})
	.then (resolve, reject);
	});
};

<|endoftext|>


<commit_before>var bag = require('bagofholding'),
  buster = require('buster'),
  Breaker = require('../lib/breaker'),
  fsx = require('fs.extra');

buster.testCase('breaker - init', {
  'should copy sample .breaker.json file to current directory when init is called': function (done) {
    this.stub(fsx, 'copy', function (src, dest, cb) {
      assert.isTrue(src.match(/\/examples\/.breaker.json$/).length === 1);
      assert.equals(dest, '.breaker.json');
      cb();
    });
    var breaker = new Breaker();
    breaker.init(function (err, result) {
      assert.equals(err, undefined);
      done();
    });
  }
});

buster.testCase('breaker - format', {
  setUp: function () {
    this.mockConsole = this.mock(console);
  },
  'should use specified typed formatter and log output': function (done) {
    this.mockConsole.expects('log').once().withExactArgs('clusters = dev\n\ndev = dev1.com');
    var breaker = new Breaker();
    breaker._config = function () {
      return [{ host: 'dev1.com', labels: ['dev'] }];
    };
    breaker.format('clusterssh', function (err, result) {
      assert.equals(err, undefined);
      done();
    });
  }
});

buster.testCase('breaker - ssh', {
  setUp: function () {
    this.mockCli = this.mock(bag.cli);
    this.mockConsole = this.mock(console);
  },
  'should exec ssh command to hosts': function (done) {
    this.mockCli.expects('exec').once().withArgs('ssh -i id_rsa1 user1@dev1.com:22 \'df -kh;\'', true).callsArgWith(2);
    this.mockCli.expects('exec').once().withArgs('ssh -i id_rsa2 user2@dev2.com:22 \'df -kh;\'', true).callsArgWith(2);
    this.mockCli.expects('exec').once().withArgs('ssh -i id_rsa3 user3@dev3.com:22 \'df -kh;\'', true).callsArgWith(2);
    this.mockConsole.expects('log').once().withExactArgs('+ %s', 'dev1.com');
    this.mockConsole.expects('log').once().withExactArgs('+ %s', 'dev2.com');
    this.mockConsole.expects('log').once().withExactArgs('+ %s', 'dev3.com');
    var breaker = new Breaker();
    breaker._config = function () {
      return [
        { "host": "dev1.com", "port": 22, "user": "user1", "key": "id_rsa1", "labels": "dev1" },
        { "host": "dev2.com", "port": 22, "user": "user2", "key": "id_rsa2", "labels": "dev2" },
        { "host": "dev3.com", "port": 22, "user": "user3", "key": "id_rsa3", "labels": "dev3" }
        ];
    };
    breaker.ssh('df -kh;', function (err, results) {
      assert.isNull(err);
      done();
    });
  },
  'should create ssh command without key, with default user, and no port': function (done) {
    this.mockCli.expects('exec').once().withArgs('ssh  dev1.com \'df -kh;\'', true).callsArgWith(2);
    this.mockConsole.expects('log').once().withExactArgs('+ %s', 'dev1.com');
    var breaker = new Breaker();
    breaker._config = function () {
      return [
        { "host": "dev1.com", "labels": "dev1" }
        ];
    };
    breaker.ssh('df -kh;', function (err, results) {
      assert.isNull(err);
      done();
    });
  }
});

buster.testCase('breaker - _config', {
  setUp: function () {
    this.mockCli = this.mock(bag.cli);
  },
  'should return only config with specified label': function () {
    this.mockCli.expects('lookupFile').once().returns('[' +
      '{"host":"dev1.com","labels":["dev"]},' +
      '{"host":"prod1.com","labels":["prod"]},' +
      '{"host":"dev2.com","labels":["dev","build"]},' +
      '{"host":"test1.com","labels":["test"]}]');
    var filtered = new Breaker({ labels: ['prod'] })._config();
    assert.equals(filtered.length, 1);
    assert.equals(filtered[0].host, 'prod1.com');
  },
  'should return only config with specified label when there are multiple labels': function () {
    this.mockCli.expects('lookupFile').once().returns('[' +
      '{"host":"dev1.com","labels":["dev"]},' +
      '{"host":"prod1.com","labels":["prod"]},' +
      '{"host":"dev2.com","labels":["dev","build"]},' +
      '{"host":"test1.com","labels":["test"]}]');
    var filtered = new Breaker({ labels: ['prod', 'test'] })._config();
    assert.equals(filtered.length, 2);
    assert.equals(filtered[0].host, 'prod1.com');
    assert.equals(filtered[1].host, 'test1.com');
  },
  'should return all config when there is no label': function () {
    this.mockCli.expects('lookupFile').once().returns('[' +
      '{"host":"dev1.com","labels":["dev"]},' +
      '{"host":"prod1.com","labels":["prod"]},' +
      '{"host":"dev2.com","labels":["dev","build"]},' +
      '{"host":"test1.com","labels":["test"]}]');
    var filtered = new Breaker()._config();
    assert.equals(filtered.length, 4);
    assert.equals(filtered[0].host, 'dev1.com');
    assert.equals(filtered[1].host, 'prod1.com');
    assert.equals(filtered[2].host, 'dev2.com');
    assert.equals(filtered[3].host, 'test1.com');
  },
  'should return empty array when config is empty': function () {
    this.mockCli.expects('lookupFile').once().returns('[]');
    var filtered = new Breaker()._config();
    assert.equals(filtered.length, 0);
  },
  'should remove filtered out labels': function () {
    this.mockCli.expects('lookupFile').once().returns('[' +
      '{"host":"dev1.com","labels":["dev"]},' +
      '{"host":"prod1.com","labels":["prod","live"]},' +
      '{"host":"dev2.com","labels":["dev","build"]},' +
      '{"host":"test1.com","labels":["ci","test","qa"]}]');
    var filtered = new Breaker({ labels: ['prod', 'test'] })._config();
    assert.equals(filtered.length, 2);
    assert.equals(filtered[0].host, 'prod1.com');
    assert.equals(filtered[0].labels.length, 1);
    assert.equals(filtered[0].labels[0], 'prod');
    assert.equals(filtered[1].host, 'test1.com');
    assert.equals(filtered[1].labels.length, 1);
    assert.equals(filtered[1].labels[0], 'test');
  }
});<commit_msg>Add test scenario with multi filtered labels.<commit_after>var bag = require('bagofholding'),
  buster = require('buster'),
  Breaker = require('../lib/breaker'),
  fsx = require('fs.extra');

buster.testCase('breaker - init', {
  'should copy sample .breaker.json file to current directory when init is called': function (done) {
    this.stub(fsx, 'copy', function (src, dest, cb) {
      assert.isTrue(src.match(/\/examples\/.breaker.json$/).length === 1);
      assert.equals(dest, '.breaker.json');
      cb();
    });
    var breaker = new Breaker();
    breaker.init(function (err, result) {
      assert.equals(err, undefined);
      done();
    });
  }
});

buster.testCase('breaker - format', {
  setUp: function () {
    this.mockConsole = this.mock(console);
  },
  'should use specified typed formatter and log output': function (done) {
    this.mockConsole.expects('log').once().withExactArgs('clusters = dev\n\ndev = dev1.com');
    var breaker = new Breaker();
    breaker._config = function () {
      return [{ host: 'dev1.com', labels: ['dev'] }];
    };
    breaker.format('clusterssh', function (err, result) {
      assert.equals(err, undefined);
      done();
    });
  }
});

buster.testCase('breaker - ssh', {
  setUp: function () {
    this.mockCli = this.mock(bag.cli);
    this.mockConsole = this.mock(console);
  },
  'should exec ssh command to hosts': function (done) {
    this.mockCli.expects('exec').once().withArgs('ssh -i id_rsa1 user1@dev1.com:22 \'df -kh;\'', true).callsArgWith(2);
    this.mockCli.expects('exec').once().withArgs('ssh -i id_rsa2 user2@dev2.com:22 \'df -kh;\'', true).callsArgWith(2);
    this.mockCli.expects('exec').once().withArgs('ssh -i id_rsa3 user3@dev3.com:22 \'df -kh;\'', true).callsArgWith(2);
    this.mockConsole.expects('log').once().withExactArgs('+ %s', 'dev1.com');
    this.mockConsole.expects('log').once().withExactArgs('+ %s', 'dev2.com');
    this.mockConsole.expects('log').once().withExactArgs('+ %s', 'dev3.com');
    var breaker = new Breaker();
    breaker._config = function () {
      return [
        { "host": "dev1.com", "port": 22, "user": "user1", "key": "id_rsa1", "labels": "dev1" },
        { "host": "dev2.com", "port": 22, "user": "user2", "key": "id_rsa2", "labels": "dev2" },
        { "host": "dev3.com", "port": 22, "user": "user3", "key": "id_rsa3", "labels": "dev3" }
        ];
    };
    breaker.ssh('df -kh;', function (err, results) {
      assert.isNull(err);
      done();
    });
  },
  'should create ssh command without key, with default user, and no port': function (done) {
    this.mockCli.expects('exec').once().withArgs('ssh  dev1.com \'df -kh;\'', true).callsArgWith(2);
    this.mockConsole.expects('log').once().withExactArgs('+ %s', 'dev1.com');
    var breaker = new Breaker();
    breaker._config = function () {
      return [
        { "host": "dev1.com", "labels": "dev1" }
        ];
    };
    breaker.ssh('df -kh;', function (err, results) {
      assert.isNull(err);
      done();
    });
  }
});

buster.testCase('breaker - _config', {
  setUp: function () {
    this.mockCli = this.mock(bag.cli);
  },
  'should return only config with specified label': function () {
    this.mockCli.expects('lookupFile').once().returns('[' +
      '{"host":"dev1.com","labels":["dev"]},' +
      '{"host":"prod1.com","labels":["prod"]},' +
      '{"host":"dev2.com","labels":["dev","build"]},' +
      '{"host":"test1.com","labels":["test"]}]');
    var filtered = new Breaker({ labels: ['prod'] })._config();
    assert.equals(filtered.length, 1);
    assert.equals(filtered[0].host, 'prod1.com');
  },
  'should return only config with specified label when there are multiple labels': function () {
    this.mockCli.expects('lookupFile').once().returns('[' +
      '{"host":"dev1.com","labels":["dev"]},' +
      '{"host":"prod1.com","labels":["prod"]},' +
      '{"host":"dev2.com","labels":["dev","build"]},' +
      '{"host":"test1.com","labels":["test"]}]');
    var filtered = new Breaker({ labels: ['prod', 'test'] })._config();
    assert.equals(filtered.length, 2);
    assert.equals(filtered[0].host, 'prod1.com');
    assert.equals(filtered[1].host, 'test1.com');
  },
  'should return all config when there is no label': function () {
    this.mockCli.expects('lookupFile').once().returns('[' +
      '{"host":"dev1.com","labels":["dev"]},' +
      '{"host":"prod1.com","labels":["prod"]},' +
      '{"host":"dev2.com","labels":["dev","build"]},' +
      '{"host":"test1.com","labels":["test"]}]');
    var filtered = new Breaker()._config();
    assert.equals(filtered.length, 4);
    assert.equals(filtered[0].host, 'dev1.com');
    assert.equals(filtered[1].host, 'prod1.com');
    assert.equals(filtered[2].host, 'dev2.com');
    assert.equals(filtered[3].host, 'test1.com');
  },
  'should return empty array when config is empty': function () {
    this.mockCli.expects('lookupFile').once().returns('[]');
    var filtered = new Breaker()._config();
    assert.equals(filtered.length, 0);
  },
  'should remove filtered out labels': function () {
    this.mockCli.expects('lookupFile').once().returns('[' +
      '{"host":"dev1.com","labels":["dev"]},' +
      '{"host":"prod1.com","labels":["prod","live"]},' +
      '{"host":"dev2.com","labels":["dev","build"]},' +
      '{"host":"xyz.com","labels":["prod","test","dev","build"]},' +
      '{"host":"test1.com","labels":["ci","test","qa"]}]');
    var filtered = new Breaker({ labels: ['prod', 'test'] })._config();
    assert.equals(filtered.length, 3);
    assert.equals(filtered[0].host, 'prod1.com');
    assert.equals(filtered[0].labels.length, 1);
    assert.equals(filtered[0].labels[0], 'prod');
    assert.equals(filtered[1].host, 'xyz.com');
    assert.equals(filtered[1].labels.length, 2);
    assert.equals(filtered[1].labels[0], 'prod');
    assert.equals(filtered[1].labels[1], 'test');
    assert.equals(filtered[2].host, 'test1.com');
    assert.equals(filtered[2].labels.length, 1);
    assert.equals(filtered[2].labels[0], 'test');
  }
});<|endoftext|>


<commit_before>var test = require('tape').test
  , runnelExport = require('..')
  , runnelkey = require.resolve('..')
  ;

function setup() {
  // remove runnel from require cache to force re-require for each test
  delete require.cache[runnelkey];
}

test('no window or define exist', function (t) {
  t.plan(1);
  setup();
  var runnel = require('..');

  t.equal(runnel.toString(), runnelExport.toString(), 'runnel is exported');

  t.end();
});
<commit_msg>removing module dance tests all together<commit_after><|endoftext|>