Example #1
0
var qiniu = require('./qiniu');
var co = require('co');
var Post = require('../mongodb_models/post').Model;

co.wrap(function *() {
    console.log(5);
    var docs = yield Post.find().exec();
    for (var i in docs) {
        var d = docs[i];
        try {
            if (true) {
                var info = JSON.parse(yield qiniu.stat(d.pic_id));
                if (info.orientation && info.orientation == 'Right-top') {
                    d.w = info.height;
                    d.h = info.width;
                    yield d.save();
                    console.log(info.orientation);
                }
            }
        } catch(err) {
            console.log(err);
        }
    }
    //yield qiniu.pfop("6LosLa4BqzYwnef8oYVMXTUuMkf6LwHuM1GzbdMOMVm_Iq2N3ttvYwZ8pz-jM80Y");
    console.log(52);
})().then(function(data) {
}).catch(function(err) {
    console.log(err.stack);
});
Example #2
0
const ora = require('ora')
const co = require('co')
const surge = require('@webdesignio/surge-helper')
const Bluebird = require('bluebird')
const read = require('read')
const yn = require('yn')
const shortid = require('shortid')
const tar = require('tar-fs')

const { UserError } = require('../errors')
const login = require('./login')

const readAsync = Bluebird.promisify(read)
const writeFileAsync = Bluebird.promisify(writeFile)

module.exports = co.wrap(init)

function * init (ctx) {
  let { rc, argv: { _: [argv0, name], url = 'https://webdesignio.com' } } = ctx
  const spinner = ora({ spinner: 'arrow3', text: '...' })
  if (name) {
    if (!existsSync(name)) {
      spinner.start()
      spinner.text = 'Fetching and unpacking sources ...'
      yield new Promise((resolve, reject) => {
        request('https://s3.eu-central-1.amazonaws.com/webdesignio/website-boilerplate.tar.gz')
          .pipe(createGunzip())
          .pipe(tar.extract(name))
          .on('error', reject)
          .on('finish', resolve)
      })
Example #3
0
    user: heroku.get('/account/features'),
    app: context.app ? heroku.get(`/apps/${context.app}/features`) : null
  }
  // general features are managed via `features` not `labs`
  features.user = features.user.filter((f) => f.state !== 'general')
  if (features.app) features.app = features.app.filter((f) => f.state !== 'general')
  if (context.flags.json) {
    delete features.currentUser
    printJSON(features)
  } else {
    cli.styledHeader(`User Features ${cli.color.cyan(features.currentUser.email)}`)
    printFeatures(features.user)
    if (features.app) {
      cli.log()
      cli.styledHeader(`App Features ${cli.color.app(context.app)}`)
      printFeatures(features.app)
    }
  }
}

module.exports = {
  topic: 'labs',
  description: 'list experimental features',
  flags: [
    {name: 'json', description: 'display as json'}
  ],
  needsAuth: true,
  wantsApp: true,
  run: cli.command(co.wrap(run))
}
Example #4
0
    describe('with module unification', function() {
      let input, output;

      before(
        co.wrap(function*() {
          input = yield createTempDir();

          let indexContent = `
          {{rootURL}}{{content-for "head"}}
          {{content-for "head-footer"}}
          {{content-for "body"}}
          {{content-for "body-footer"}}
        `;
          input.write({
            'addon-tree-output': {},
            'the-best-app-ever': {
              'router.js': 'router.js',
              'app.js': 'app.js',
              'index.html': indexContent,
              config: {
                'environment.js': 'environment.js',
              },
              templates: {},
            },
            src: {
              ui: {
                'index.html': 'src',
              },
            },
          });
        })
      );

      after(
        co.wrap(function*() {
          yield input.dispose();
        })
      );

      afterEach(
        co.wrap(function*() {
          yield output.dispose();
        })
      );

      it(
        'prefers `src/ui/index.html` over `app/index.html`',
        co.wrap(function*() {
          let defaultPackager = new DefaultPackager({
            name: 'the-best-app-ever',
            env: 'development',

            autoRun: true,
            storeConfigInMeta: true,
            isModuleUnificationEnabled: true,
            areTestsEnabled: true,

            distPaths: {
              appHtmlFile: 'index.html',
            },

            project,
          });

          output = yield buildOutput(defaultPackager.processIndex(input.path()));

          let outputFiles = output.read();
          let indexContent = decodeURIComponent(outputFiles['index.html'].trim());

          expect(indexContent).to.equal('src');
        })
      );

      it(
        'works if only `src/ui/index.html` exists',
        co.wrap(function*() {
          input.dispose();
          input.write({
            'addon-tree-output': {},
            src: {
              ui: {
                'index.html': 'src',
              },
            },
          });
          let defaultPackager = new DefaultPackager({
            name: 'the-best-app-ever',
            env: 'development',

            autoRun: true,
            storeConfigInMeta: true,
            isModuleUnificationEnabled: true,
            areTestsEnabled: true,

            distPaths: {
              appHtmlFile: 'index.html',
            },

            project,
          });

          output = yield buildOutput(defaultPackager.processIndex(input.path()));

          let outputFiles = output.read();
          let indexContent = decodeURIComponent(outputFiles['index.html'].trim());

          expect(indexContent).to.equal('src');
        })
      );
    });
Example #5
0
  describe('with module unification layout', function() {
    let inputMU, outputMU;
    let addonPreprocessTreeHookCalled = false;
    let addonPostprocessTreeHookCalled = false;

    let MU_LAYOUT = {
      'addon-tree-output': {},
      public: {},
      tests: {},
      vendor: {},
      src: {
        'main.js': '',
        'resolver.js': '',
        'router.js': '',
        ui: {
          components: {
            'login-form': {
              'component-test.js': ' // login-form-component-test',
              'component.js': '',
              'template.hbs': '',
            },
          },
          'index.html': '',
          routes: {
            application: {
              'template.hbs': '',
            },
          },
          styles: {
            'app.css': 'html { height: 100%; }',
          },
        },
      },
    };
    before(co.wrap(function *() {
      inputMU = yield createTempDir();

      inputMU.write(MU_LAYOUT);
    }));

    after(co.wrap(function *() {
      yield inputMU.dispose();
    }));

    afterEach(co.wrap(function *() {
      yield outputMU.dispose();
    }));

    it('processes javascript according to the registry', co.wrap(function *() {
      let defaultPackager = new DefaultPackager({
        name: 'the-best-app-ever',

        distPaths: {
          appJsFile: '/assets/the-best-app-ever.js',
          appCssFile: '/assets/the-best-app-ever.css',
          vendorJsFile: '/assets/vendor.js',
        },

        registry: setupRegistry({
          js: tree => tree,
        }),

        isModuleUnificationEnabled: true,

        // avoid using `testdouble.js` here on purpose; it does not have a "proxy"
        // option, where a function call would be registered and the original
        // would be returned
        project: {
          addons: [{
            preprocessTree(type, tree) {
              expect(type).to.equal('src');
              return tree;
            },
            postprocessTree(type, tree) {
              expect(type).to.equal('src');
              return tree;
            },
          }],
        },
      });

      expect(defaultPackager._cachedProcessedSrc).to.equal(null);

      outputMU = yield buildOutput(defaultPackager.processJavascriptSrc(inputMU.path()));

      let outputFiles = outputMU.read();

      expect(outputFiles['the-best-app-ever']).to.deep.equal({
        src: {
          'main.js': '',
          'resolver.js': '',
          'router.js': '',
          ui: {
            components: {
              'login-form': {
                'component.js': '',
              },
            },
          },
        },
      });
    }));

    it('runs pre/post-process add-on hooks', co.wrap(function *() {

      addonPreprocessTreeHookCalled = false;
      addonPostprocessTreeHookCalled = false;

      let defaultPackager = new DefaultPackager({
        name: 'the-best-app-ever',

        distPaths: {
          appJsFile: '/assets/the-best-app-ever.js',
          appCssFile: '/assets/the-best-app-ever.css',
          vendorJsFile: '/assets/vendor.js',
        },

        registry: setupRegistry({
          js: tree => tree,
        }),

        isModuleUnificationEnabled: true,

        // avoid using `testdouble.js` here on purpose; it does not have a "proxy"
        // option, where a function call would be registered and the original
        // would be returned
        project: {
          addons: [{
            preprocessTree(type, tree) {
              expect(type).to.equal('src');
              addonPreprocessTreeHookCalled = true;

              return tree;
            },
            postprocessTree(type, tree) {
              expect(type).to.equal('src');
              addonPostprocessTreeHookCalled = true;

              return tree;
            },
          }],
        },
      });

      outputMU = yield buildOutput(defaultPackager.processJavascriptSrc(inputMU.path()));

      expect(addonPreprocessTreeHookCalled).to.equal(true);
      expect(addonPostprocessTreeHookCalled).to.equal(true);
    }));
  });
Example #6
0
  config = pickBy(config, (_, k) => vars[k])
  config = mapKeys(config, (_, k) => cli.color.green(k))
  cli.styledObject(config)
}

let cmd = {
  topic: 'config',
  command: 'set',
  description: 'set one or more config vars',
  help: `Examples:

 $ heroku config:set RAILS_ENV=staging
 Setting config vars and restarting example... done, v10
 RAILS_ENV: staging

 $ heroku config:set RAILS_ENV=staging RACK_ENV=staging
 Setting config vars and restarting example... done, v11
 RAILS_ENV: staging
 RACK_ENV:  staging
 `,
  needsApp: true,
  needsAuth: true,
  variableArgs: true,
  run: cli.command({preauth: true}, co.wrap(run))
}

module.exports.set = cmd
module.exports.add = Object.assign({}, cmd)
module.exports.add.command = 'add'
Example #7
0
test.onFinish = function onFinish (fn) {
  return tape.onFinish(co.wrap(fn))
}
Example #8
0
var co = require('co')
  , fs = require('fs');

var read = co.wrap(fs.readFile);

co(function* (){
  try{
    var content = yield read(
                    __dirname + '/ong6.txt'
                    , {encoding: 'utf-8'}
                  );
    console.log('generator: ', content);
  }
  catch(e){
    console.log(e);
  }
});
Example #9
0
describe('Acceptance: ember new', function() {
  this.timeout(10000);
  let ORIGINAL_PROCESS_ENV_CI;

  beforeEach(co.wrap(function *() {
    yield tmp.setup(tmpDir);
    process.chdir(tmpDir);
    ORIGINAL_PROCESS_ENV_CI = process.env.CI;
  }));

  afterEach(function() {
    if (ORIGINAL_PROCESS_ENV_CI === undefined) {
      delete process.env.CI;
    } else {
      process.env.CI = ORIGINAL_PROCESS_ENV_CI;
    }
    return tmp.teardown(tmpDir);
  });

  function confirmBlueprintedForDir(dir) {
    let blueprintPath = path.join(root, dir, 'files');
    let expected = walkSync(blueprintPath);
    let actual = walkSync('.').sort();
    let directory = path.basename(process.cwd());

    forEach(Blueprint.renamedFiles, function(destFile, srcFile) {
      expected[expected.indexOf(srcFile)] = destFile;
    });

    expected.sort();

    expect(directory).to.equal('foo');
    expect(expected)
      .to.deep.equal(actual, `${EOL} expected: ${util.inspect(expected)}${EOL} but got: ${util.inspect(actual)}`);
  }

  function confirmBlueprintedApp() {
    if (isExperimentEnabled('MODULE_UNIFICATION')) {
      return confirmBlueprintedForDir('blueprints/module-unification-app');
    }
    return confirmBlueprintedForDir('blueprints/app');
  }

  if (isExperimentEnabled('MODULE_UNIFICATION')) {
    it('EMBER_CLI_MODULE_UNIFICATION: ember addon foo works', co.wrap(function *() {
      yield ember([
        'addon',
        'foo',
        '--skip-npm',
        '--skip-bower',
      ]);

      // the fixture files are now out of sync because
      // this only tests file count and names, not contents
      let expectedFiles = walkSync(path.join(__dirname, '../fixtures', 'module-unification-addon'))
        .sort()
        .filter(e => e !== '.DS_Store');
      let actualFiles = walkSync('.').sort().filter(e => e !== '.DS_Store');
      expect(actualFiles).to.deep.equal(expectedFiles);
    }));
  } else {
    // TODO: this should pass in both MU and classic
    it('ember new adds ember-welcome-page by default', co.wrap(function *() {
      yield ember([
        'new',
        'foo',
        '--skip-npm',
        '--skip-bower',
        '--skip-git',
      ]);

      expect(file('package.json'))
        .to.match(/"ember-welcome-page"/);

      expect(file('app/templates/application.hbs'))
        .to.contain("{{welcome-page}}");
    }));

    // TODO: this should pass in both MU and classic
    it('ember new --no-welcome skips installation of ember-welcome-page', co.wrap(function *() {
      yield ember([
        'new',
        'foo',
        '--skip-npm',
        '--skip-bower',
        '--skip-git',
        '--no-welcome',
      ]);

      expect(file('package.json'))
        .not.to.match(/"ember-welcome-page"/);

      expect(file('app/templates/application.hbs'))
        .to.contain("Welcome to Ember");
    }));
  }

  it('ember new foo, where foo does not yet exist, works', co.wrap(function *() {
    yield ember([
      'new',
      'foo',
      '--skip-npm',
      '--skip-bower',
    ]);

    confirmBlueprintedApp();
  }));

  it('ember new foo, blueprint targets match the default ember-cli targets', co.wrap(function *() {
    yield ember([
      'new',
      'foo',
      '--skip-npm',
      '--skip-bower',
    ]);

    process.env.CI = true;
    const defaultTargets = require('../../lib/utilities/default-targets').browsers;
    const blueprintTargets = require(path.resolve('config/targets.js')).browsers;
    expect(blueprintTargets).to.have.same.deep.members(defaultTargets);
  }));

  it('ember new with empty app name fails with a warning', co.wrap(function *() {
    let err = yield expect(ember([
      'new',
      '',
    ])).to.be.rejected;

    expect(err.name).to.equal('SilentError');
    expect(err.message).to.contain('The `ember new` command requires a name to be specified.');
  }));

  it('ember new without app name fails with a warning', co.wrap(function *() {
    let err = yield expect(ember([
      'new',
    ])).to.be.rejected;

    expect(err.name).to.equal('SilentError');
    expect(err.message).to.contain('The `ember new` command requires a name to be specified.');
  }));

  it('ember new with app name creates new directory and has a dasherized package name', co.wrap(function *() {
    yield ember([
      'new',
      'FooApp',
      '--skip-npm',
      '--skip-bower',
      '--skip-git',
    ]);

    expect(dir('FooApp')).to.not.exist;
    expect(file('package.json')).to.exist;

    let pkgJson = fs.readJsonSync('package.json');
    expect(pkgJson.name).to.equal('foo-app');
  }));

  it('Can create new ember project in an existing empty directory', co.wrap(function *() {
    fs.mkdirsSync('bar');

    yield ember([
      'new',
      'foo',
      '--skip-npm',
      '--skip-bower',
      '--skip-git',
      '--directory=bar',
    ]);
  }));

  it('Cannot create new ember project in a populated directory', co.wrap(function *() {
    fs.mkdirsSync('bar');
    fs.writeFileSync(path.join('bar', 'package.json'), '{}');

    let error = yield expect(ember([
      'new',
      'foo',
      '--skip-npm',
      '--skip-bower',
      '--skip-git',
      '--directory=bar',
    ])).to.be.rejected;

    expect(error.name).to.equal('SilentError');
    expect(error.message).to.equal('Directory \'bar\' already exists.');
  }));

  it('Cannot run ember new, inside of ember-cli project', co.wrap(function *() {
    yield ember([
      'new',
      'foo',
      '--skip-npm',
      '--skip-bower',
      '--skip-git',
    ]);

    let error = yield expect(ember([
      'new',
      'foo',
      '--skip-npm',
      '--skip-bower',
      '--skip-git',
    ])).to.be.rejected;

    expect(dir('foo')).to.not.exist;
    expect(error.name).to.equal('SilentError');
    expect(error.message).to.equal(`You cannot use the ${chalk.green('new')} command inside an ember-cli project.`);

    confirmBlueprintedApp();
  }));

  it('ember new with blueprint uses the specified blueprint directory with a relative path', co.wrap(function *() {
    fs.mkdirsSync('my_blueprint/files');
    fs.writeFileSync('my_blueprint/files/gitignore');

    yield ember([
      'new',
      'foo',
      '--skip-npm',
      '--skip-bower',
      '--skip-git',
      '--blueprint=./my_blueprint',
    ]);

    confirmBlueprintedForDir(path.join(tmpDir, 'my_blueprint'));
  }));

  it('ember new with blueprint uses the specified blueprint directory with an absolute path', co.wrap(function *() {
    fs.mkdirsSync('my_blueprint/files');
    fs.writeFileSync('my_blueprint/files/gitignore');

    yield ember([
      'new',
      'foo',
      '--skip-npm',
      '--skip-bower',
      '--skip-git',
      `--blueprint=${path.resolve(process.cwd(), 'my_blueprint')}`,
    ]);

    confirmBlueprintedForDir(path.join(tmpDir, 'my_blueprint'));
  }));

  it('ember new with git blueprint checks out the blueprint and uses it', co.wrap(function *() {
    this.timeout(20000); // relies on GH network stuff

    yield ember([
      'new',
      'foo',
      '--skip-npm',
      '--skip-bower',
      '--skip-git',
      '--blueprint=https://github.com/ember-cli/app-blueprint-test.git',
    ]);

    expect(file('.ember-cli')).to.exist;
  }));

  it('ember new passes blueprint options through to blueprint', co.wrap(function *() {
    fs.mkdirsSync('my_blueprint/files');
    fs.writeFileSync('my_blueprint/index.js', [
      'module.exports = {',
      '  availableOptions: [ { name: \'custom-option\' } ],',
      '  locals(options) {',
      '    return {',
      '      customOption: options.customOption',
      '    };',
      '  }',
      '};',
    ].join('\n'));
    fs.writeFileSync('my_blueprint/files/gitignore', '<%= customOption %>');

    yield ember([
      'new',
      'foo',
      '--skip-npm',
      '--skip-bower',
      '--skip-git',
      '--blueprint=./my_blueprint',
      '--custom-option=customValue',
    ]);

    expect(file('.gitignore')).to.contain('customValue');
  }));

  it('ember new uses yarn when blueprint has yarn.lock', co.wrap(function *() {
    if (!hasGlobalYarn) {
      this.skip();
    }

    fs.mkdirsSync('my_blueprint/files');
    fs.writeFileSync('my_blueprint/index.js', 'module.exports = {};');
    fs.writeFileSync('my_blueprint/files/package.json', '{ "name": "foo", "dependencies": { "fs-extra": "*" }}');
    fs.writeFileSync('my_blueprint/files/yarn.lock', '');

    yield ember([
      'new',
      'foo',
      '--skip-git',
      '--blueprint=./my_blueprint',
    ]);

    expect(file('yarn.lock')).to.not.be.empty;
    expect(dir('node_modules/fs-extra')).to.not.be.empty;
  }));

  it('ember new without skip-git flag creates .git dir', co.wrap(function *() {
    yield ember([
      'new',
      'foo',
      '--skip-npm',
      '--skip-bower',
    ], {
      skipGit: false,
    });

    expect(dir('.git')).to.exist;
  }));

  it('ember new cleans up after itself on error', co.wrap(function *() {
    fs.mkdirsSync('my_blueprint');
    fs.writeFileSync('my_blueprint/index.js', 'throw("this will break");');

    yield ember([
      'new',
      'foo',
      '--skip-npm',
      '--skip-bower',
      '--skip-git',
      '--blueprint=./my_blueprint',
    ]);

    expect(dir('foo')).to.not.exist;
  }));

  it('ember new with --dry-run does not create new directory', co.wrap(function *() {
    yield ember([
      'new',
      'foo',
      '--dry-run',
    ]);

    expect(process.cwd()).to.not.match(/foo/, 'does not change cwd to foo in a dry run');
    expect(dir('foo')).to.not.exist;
    expect(dir('.git')).to.not.exist;
  }));

  it('ember new with --directory uses given directory name and has correct package name', co.wrap(function *() {
    let workdir = process.cwd();

    yield ember([
      'new',
      'foo',
      '--skip-npm',
      '--skip-bower',
      '--skip-git',
      '--directory=bar',
    ]);

    expect(dir(path.join(workdir, 'foo'))).to.not.exist;
    expect(dir(path.join(workdir, 'bar'))).to.exist;

    let cwd = process.cwd();
    expect(cwd).to.not.match(/foo/, 'does not use app name for directory name');
    expect(cwd).to.match(/bar/, 'uses given directory name');

    let pkgJson = fs.readJsonSync('package.json');
    expect(pkgJson.name).to.equal('foo', 'uses app name for package name');
  }));

  it('ember addon with --directory uses given directory name and has correct package name', co.wrap(function *() {
    let workdir = process.cwd();

    yield ember([
      'addon',
      'foo',
      '--skip-npm',
      '--skip-bower',
      '--skip-git',
      '--directory=bar',
    ]);

    expect(dir(path.join(workdir, 'foo'))).to.not.exist;
    expect(dir(path.join(workdir, 'bar'))).to.exist;

    let cwd = process.cwd();
    expect(cwd).to.not.match(/foo/, 'does not use addon name for directory name');
    expect(cwd).to.match(/bar/, 'uses given directory name');

    let pkgJson = fs.readJsonSync('package.json');
    expect(pkgJson.name).to.equal('foo', 'uses addon name for package name');
  }));

  describe('verify fixtures', function() {
    function checkPackageJson(fixtureName) {
      let currentVersion = require('../../package').version;
      let fixturePath = path.join(__dirname, '../fixtures', fixtureName, 'package.json');
      let fixtureContents = fs.readFileSync(fixturePath, { encoding: 'utf-8' })
        .replace("<%= emberCLIVersion %>", currentVersion);

      expect(file('package.json'))
        .to.equal(fixtureContents);
    }

    it('module-unification-app + npm + !welcome', co.wrap(function *() {
      yield ember([
        'new',
        'foo',
        '--blueprint',
        'module-unification-app',
        '--skip-npm',
        '--skip-bower',
        '--skip-git',
        '--no-welcome',
      ]);

      let fixturePath = 'module-unification-app/npm';
      [
        'src/ui/routes/application/template.hbs',
        '.travis.yml',
        'README.md',
        '.eslintrc.js',
      ].forEach(filePath => {
        expect(file(filePath))
          .to.equal(file(path.join(__dirname, '../fixtures', fixturePath, filePath)));
      });

      checkPackageJson(fixturePath);
    }));

    it('module-unification-app + yarn + welcome', co.wrap(function *() {
      yield ember([
        'new',
        'foo',
        '--blueprint',
        'module-unification-app',
        '--skip-npm',
        '--skip-bower',
        '--skip-git',
        '--yarn',
      ]);

      let fixturePath = 'module-unification-app/yarn';
      [
        'src/ui/routes/application/template.hbs',
        '.travis.yml',
        'README.md',
        '.eslintrc.js',
      ].forEach(filePath => {
        expect(file(filePath))
          .to.equal(file(path.join(__dirname, '../fixtures', fixturePath, filePath)));
      });

      checkPackageJson(fixturePath);
    }));

    if (!isExperimentEnabled('MODULE_UNIFICATION')) {
      it('app + npm + !welcome', co.wrap(function *() {
        yield ember([
          'new',
          'foo',
          '--skip-npm',
          '--skip-bower',
          '--skip-git',
          '--no-welcome',
        ]);

        let fixturePath = 'app/npm';
        [
          'app/templates/application.hbs',
          '.travis.yml',
          'README.md',
          '.eslintrc.js',
        ].forEach(filePath => {
          expect(file(filePath))
            .to.equal(file(path.join(__dirname, '../fixtures', fixturePath, filePath)));
        });

        checkPackageJson(fixturePath);
      }));

      it('app + yarn + welcome', co.wrap(function *() {
        yield ember([
          'new',
          'foo',
          '--skip-npm',
          '--skip-bower',
          '--skip-git',
          '--yarn',
        ]);

        let fixturePath = 'app/yarn';
        [
          'app/templates/application.hbs',
          '.travis.yml',
          'README.md',
          '.eslintrc.js',
        ].forEach(filePath => {
          expect(file(filePath))
            .to.equal(file(path.join(__dirname, '../fixtures', fixturePath, filePath)));
        });

        checkPackageJson(fixturePath);
      }));

      it('addon + npm + !welcome', co.wrap(function *() {
        yield ember([
          'addon',
          'foo',
          '--skip-npm',
          '--skip-bower',
          '--skip-git',
        ]);

        let fixturePath = 'addon/npm';
        [
          'config/ember-try.js',
          'tests/dummy/app/templates/application.hbs',
          '.travis.yml',
          'README.md',
          '.eslintrc.js',
        ].forEach(filePath => {
          expect(file(filePath))
            .to.equal(file(path.join(__dirname, '../fixtures', fixturePath, filePath)));
        });

        checkPackageJson(fixturePath);
      }));

      it('addon + yarn + welcome', co.wrap(function *() {
        yield ember([
          'addon',
          'foo',
          '--skip-npm',
          '--skip-bower',
          '--skip-git',
          '--yarn',
          '--welcome',
        ]);

        let fixturePath = 'addon/yarn';
        [
          'config/ember-try.js',
          'tests/dummy/app/templates/application.hbs',
          '.travis.yml',
          'README.md',
          '.eslintrc.js',
        ].forEach(filePath => {
          expect(file(filePath))
            .to.equal(file(path.join(__dirname, '../fixtures', fixturePath, filePath)));
        });

        checkPackageJson(fixturePath);
      }));
    }
  });

  describe('verify dependencies', function() {
    it('are locked down for pre-1.0 versions', co.wrap(function *() {
      yield ember([
        'new',
        'foo',
        '--skip-npm',
        '--skip-bower',
        '--skip-git',
        '--yarn',
        '--welcome',
      ]);

      let pkg = fs.readJsonSync('package.json');

      assertVersionLock(pkg.dependencies);
      assertVersionLock(pkg.devDependencies);
    }));
  });
});
Example #10
0
/**
 * Checks if the provided path is a file or directory.
 * If it is a file, it returns file details object.
 * Otherwise it returns undefined.
 */
export const readFile = co.wrap(function *(filepath, cwd, gzipFiles) {
  var stat = fs.statSync(filepath);
  if(stat.isFile()) {
    let fileContents = yield fs.readFile(filepath, {encoding: null});

    if(gzipFiles) {
      fileContents = zlib.gzipSync(fileContents);
    }

    return {
      stat: stat,
      contents: fileContents,
      base: path.join(process.cwd(), cwd),
      path: path.join(process.cwd(), filepath)
    };
  }

  return undefined;
});

/**
 * Handles a path, by obtaining file details for a provided path,
 * checking if file is already in AWS bucket and needs updates,
 * and uploading files that are not there yet, or do need an update.
 */
Example #11
0
exports.builder = {};
exports.handler = co.wrap(function* (argv) {
  const options = {};

  if (argv.u) { options.baseUrl = argv.u; }
  if (argv.token) { options.token = argv.token; }
  if (argv.timeout) { options.timeout = argv.timeout; }
  if (argv.insecure) { options.strictSSL = false; }

  let list;
  try {
    list = yield ezmesure.indices.list(options);
  } catch (err) {
    console.error(err.statusCode === 401 ? 'Invalid token' : err.message);
    process.exit(1);
  }

  if (list.length === 0) {
    return console.log('No indices');
  }

  // Getting the size of the longest name for pretty indentation
  const maxChars = list.reduce((prev, cur) => Math.max(prev, cur.name.length), 6);

  console.log(`Index ${' '.repeat(maxChars - 4)} Documents`);

  list.forEach(index => {
    const spacing = '-'.repeat(maxChars - index.name.length + 1);
    console.log(`${index.name} ${spacing} ${index.docs}`);
  });
});
Example #12
0
 */
exports.executeableSubcommand = co.wrap(function *(args) {
    // TODO:
    // - abort
    // - continue

    const colors = require("colors");

    const CherryPick = require("../util/cherrypick");
    const GitUtil    = require("../util/git_util");
    const Status     = require("../util/status");

    const repo = yield GitUtil.getCurrentRepo();
    yield Status.ensureCleanAndConsistent(repo);

    for (let i = 0; i < args.commits.length; ++i) {
        let commitish = args.commits[i];
        let result = yield GitUtil.resolveCommitish(repo, commitish);
        if (null === result) {
            console.error(`Could not resolve ${colors.red(commitish)} to a \
commit.`);
            process.exit(-1);
        }
        else {
            console.log(`Cherry-picking commit ${colors.green(result.id())}.`);
            let commit = yield repo.getCommit(result.id());
            yield CherryPick.cherryPick(repo, commit);
        }
    }
});
Example #13
0
module.exports = co.wrap(function *() {
  const task = new Task();
  const taskData = yield task.getExpectedOne();

  if (!taskData) {
    logger.debug('no queue');
    return;
  }

  const project = new Project();
  const projectData = yield project.getById(taskData.projectId);

  if (!projectData) {
    logger.debug('no projectData');
    return;
  }

  let body = projectData.repositoryUrl;

  body += `#${projectData.repositoryBranch}`;

  process.send({
    message: 'dispatch',
    data: {
      body: body,
      taskId: taskData._id,
      type: 'task'
    }
  });
});
Example #14
0
}

export function writeStrTo(fpath, fcontent) {
  return writeFile(fpath, fcontent, 'utf8');
}

export const watch = (pattern) => Observable.create((observer) => {
  const watcher = chokidar.watch(pattern, {
    ignored: /[\/\\]\./, // Don't care dotfiles
    persistent: true,
  });

  watcher.on('all', (event, file) => observer.onNext(file));

  return () => watcher.close();
});

export const readAsset = wrap(function *(name) {
  const fpath = getAssetPath(name);
  try {
    yield access(fpath, R_OK);
    return yield readToStr(fpath);
  } catch (err) {
    return null;
  }
});

export function readAssetSync(name) {
  return readFileSync(getAssetPath(name), 'utf8');
}
Example #15
0
const co = require('co')
const cli = require('heroku-cli-util')
const disambiguate = require('../../lib/disambiguate')

module.exports = {
  topic: 'pipelines',
  command: 'rename',
  description: 'rename a pipeline',
  examples: `$ heroku pipelines:rename example www
Renaming example pipeline to www... done`,
  needsApp: false,
  needsAuth: true,
  args: [
    { name: 'pipeline', description: 'current name of pipeline', optional: false },
    { name: 'name', description: 'new name of pipeline', optional: false }
  ],
  run: cli.command(co.wrap(function * (context, heroku) {
    const pipeline = yield disambiguate(heroku, context.args.pipeline)

    const promise = heroku.request({
      method: 'PATCH',
      path: `/pipelines/${pipeline.id}`,
      body: { name: context.args.name },
      headers: { 'Accept': 'application/vnd.heroku+json; version=3' }
    }) // heroku.pipelines(pipeline).update(body);

    yield cli.action(`Renaming ${cli.color.pipeline(pipeline.name)} pipeline to ${cli.color.pipeline(context.args.name)}`, promise)
  }))
}
Example #16
0
  describe('verify fixtures', function() {
    function checkPackageJson(fixtureName) {
      let currentVersion = require('../../package').version;
      let fixturePath = path.join(__dirname, '../fixtures', fixtureName, 'package.json');
      let fixtureContents = fs.readFileSync(fixturePath, { encoding: 'utf-8' })
        .replace("<%= emberCLIVersion %>", currentVersion);

      expect(file('package.json'))
        .to.equal(fixtureContents);
    }

    it('module-unification-app + npm + !welcome', co.wrap(function *() {
      yield ember([
        'new',
        'foo',
        '--blueprint',
        'module-unification-app',
        '--skip-npm',
        '--skip-bower',
        '--skip-git',
        '--no-welcome',
      ]);

      let fixturePath = 'module-unification-app/npm';
      [
        'src/ui/routes/application/template.hbs',
        '.travis.yml',
        'README.md',
        '.eslintrc.js',
      ].forEach(filePath => {
        expect(file(filePath))
          .to.equal(file(path.join(__dirname, '../fixtures', fixturePath, filePath)));
      });

      checkPackageJson(fixturePath);
    }));

    it('module-unification-app + yarn + welcome', co.wrap(function *() {
      yield ember([
        'new',
        'foo',
        '--blueprint',
        'module-unification-app',
        '--skip-npm',
        '--skip-bower',
        '--skip-git',
        '--yarn',
      ]);

      let fixturePath = 'module-unification-app/yarn';
      [
        'src/ui/routes/application/template.hbs',
        '.travis.yml',
        'README.md',
        '.eslintrc.js',
      ].forEach(filePath => {
        expect(file(filePath))
          .to.equal(file(path.join(__dirname, '../fixtures', fixturePath, filePath)));
      });

      checkPackageJson(fixturePath);
    }));

    if (!isExperimentEnabled('MODULE_UNIFICATION')) {
      it('app + npm + !welcome', co.wrap(function *() {
        yield ember([
          'new',
          'foo',
          '--skip-npm',
          '--skip-bower',
          '--skip-git',
          '--no-welcome',
        ]);

        let fixturePath = 'app/npm';
        [
          'app/templates/application.hbs',
          '.travis.yml',
          'README.md',
          '.eslintrc.js',
        ].forEach(filePath => {
          expect(file(filePath))
            .to.equal(file(path.join(__dirname, '../fixtures', fixturePath, filePath)));
        });

        checkPackageJson(fixturePath);
      }));

      it('app + yarn + welcome', co.wrap(function *() {
        yield ember([
          'new',
          'foo',
          '--skip-npm',
          '--skip-bower',
          '--skip-git',
          '--yarn',
        ]);

        let fixturePath = 'app/yarn';
        [
          'app/templates/application.hbs',
          '.travis.yml',
          'README.md',
          '.eslintrc.js',
        ].forEach(filePath => {
          expect(file(filePath))
            .to.equal(file(path.join(__dirname, '../fixtures', fixturePath, filePath)));
        });

        checkPackageJson(fixturePath);
      }));

      it('addon + npm + !welcome', co.wrap(function *() {
        yield ember([
          'addon',
          'foo',
          '--skip-npm',
          '--skip-bower',
          '--skip-git',
        ]);

        let fixturePath = 'addon/npm';
        [
          'config/ember-try.js',
          'tests/dummy/app/templates/application.hbs',
          '.travis.yml',
          'README.md',
          '.eslintrc.js',
        ].forEach(filePath => {
          expect(file(filePath))
            .to.equal(file(path.join(__dirname, '../fixtures', fixturePath, filePath)));
        });

        checkPackageJson(fixturePath);
      }));

      it('addon + yarn + welcome', co.wrap(function *() {
        yield ember([
          'addon',
          'foo',
          '--skip-npm',
          '--skip-bower',
          '--skip-git',
          '--yarn',
          '--welcome',
        ]);

        let fixturePath = 'addon/yarn';
        [
          'config/ember-try.js',
          'tests/dummy/app/templates/application.hbs',
          '.travis.yml',
          'README.md',
          '.eslintrc.js',
        ].forEach(filePath => {
          expect(file(filePath))
            .to.equal(file(path.join(__dirname, '../fixtures', fixturePath, filePath)));
        });

        checkPackageJson(fixturePath);
      }));
    }
  });
setTimeout(function () {
  var ctx = new Object();
  var fn = co.wrap(main);
  fn.call(ctx).catch(onerror);
}, 800);
Example #18
0
     */
    get commit() {
        return this.d_commit;
    }
}

/**
 * @async
 * Return the metaOriginUrl used to resolve relative sub URLs.
 * @return {String|null}
 */
SubmoduleFetcher.prototype.getMetaOriginUrl = co.wrap(function *() {
    // If we haven't computed the URL yet, it will be `undefined`.  Null
    // indicates that no URL was provided and there is no origin.

    if (undefined === this.d_metaOriginUrl) {
        this.d_metaOriginUrl = yield GitUtil.getOriginUrl(this.d_repo);
    }
    return this.d_metaOriginUrl;
});

/**
 * @async
 * Return the submodule URL configured in the meta-repo on the specified
 * commit for the submodule having the specified `name`.  Throw a user error if
 * the submodule does  not have a configured URL for `this.commit`.
 * @param {String} name
 */
SubmoduleFetcher.prototype.getSubmoduleUrl = co.wrap(function *(name) {
    assert.isString(name);
    if (null === this.d_urls) {
Example #19
0
const api = require('./api');
const co = require('co');

module.exports = co.wrap(function *(id, user){
  try{
    const result = yield api.buy(id, user);
    if(result.success){
      return result;
    }else{
      console.error(result.errorMessage);
      throw "oops, noe gikk veldig galt";
    }
  }catch(error){
    throw "Hmm, har du husket å registrere deg?\nprøv `isbot jeg er <ansattnummer>`";
  }
});
Example #20
0
describe('Acceptance: ember generate pod', function() {
  this.timeout(60000);

  let tmpdir;

  before(function() {
    BlueprintNpmTask.disableNPM(Blueprint);
  });

  after(function() {
    BlueprintNpmTask.restoreNPM(Blueprint);
  });

  beforeEach(co.wrap(function *() {
    tmpdir = yield mkTmpDirIn(tmproot);
    process.chdir(tmpdir);
  }));

  afterEach(function() {
    process.chdir(root);
    return remove(tmproot);
  });

  function initApp() {
    return ember([
      'init',
      '--name=my-app',
      '--skip-npm',
      '--skip-bower',
    ]).then(addJSHint);
  }

  function addJSHint() {
    let pkg = fs.readJsonSync('package.json');
    pkg.devDependencies['ember-cli-jshint'] = '*';
    fs.writeJsonSync('package.json', pkg);
  }

  function generate(args) {
    let generateArgs = ['generate'].concat(args);

    return initApp().then(function() {
      return ember(generateArgs);
    });
  }

  function generateWithPrefix(args) {
    let generateArgs = ['generate'].concat(args);

    return initApp().then(function() {
      replaceFile('config/environment.js', "(var|let|const) ENV = {", "$1 ENV = {\npodModulePrefix: 'app/pods', \n");
      return ember(generateArgs);
    });
  }

  it('blueprint foo --pod', co.wrap(function *() {
    yield generate(['blueprint', 'foo', '--pod']);

    expect(file('blueprints/foo/index.js'))
      .to.contain("module.exports = {\n" +
                  "  description: ''\n" +
                  "\n" +
                  "  // locals(options) {\n" +
                  "  //   // Return custom template variables here.\n" +
                  "  //   return {\n" +
                  "  //     foo: options.entity.options.foo\n" +
                  "  //   };\n" +
                  "  // }\n" +
                  "\n" +
                  "  // afterInstall(options) {\n" +
                  "  //   // Perform extra work here.\n" +
                  "  // }\n" +
                  "};");
  }));

  it('blueprint foo/bar --pod', co.wrap(function *() {
    yield generate(['blueprint', 'foo/bar', '--pod']);

    expect(file('blueprints/foo/bar/index.js'))
      .to.contain("module.exports = {\n" +
                  "  description: ''\n" +
                  "\n" +
                  "  // locals(options) {\n" +
                  "  //   // Return custom template variables here.\n" +
                  "  //   return {\n" +
                  "  //     foo: options.entity.options.foo\n" +
                  "  //   };\n" +
                  "  // }\n" +
                  "\n" +
                  "  // afterInstall(options) {\n" +
                  "  //   // Perform extra work here.\n" +
                  "  // }\n" +
                  "};");
  }));

  it('http-mock foo --pod', co.wrap(function *() {
    yield generate(['http-mock', 'foo', '--pod']);

    expect(file('server/index.js'))
      .to.contain("mocks.forEach(route => route(app));");

    expect(file('server/mocks/foo.js'))
      .to.contain("module.exports = function(app) {\n" +
                  "  const express = require('express');\n" +
                  "  let fooRouter = express.Router();\n" +
                  "\n" +
                  "  fooRouter.get('/', function(req, res) {\n" +
                  "    res.send({\n" +
                  "      'foo': []\n" +
                  "    });\n" +
                  "  });\n" +
                  "\n" +
                  "  fooRouter.post('/', function(req, res) {\n" +
                  "    res.status(201).end();\n" +
                  "  });\n" +
                  "\n" +
                  "  fooRouter.get('/:id', function(req, res) {\n" +
                  "    res.send({\n" +
                  "      'foo': {\n" +
                  "        id: req.params.id\n" +
                  "      }\n" +
                  "    });\n" +
                  "  });\n" +
                  "\n" +
                  "  fooRouter.put('/:id', function(req, res) {\n" +
                  "    res.send({\n" +
                  "      'foo': {\n" +
                  "        id: req.params.id\n" +
                  "      }\n" +
                  "    });\n" +
                  "  });\n" +
                  "\n" +
                  "  fooRouter.delete('/:id', function(req, res) {\n" +
                  "    res.status(204).end();\n" +
                  "  });\n" +
                  "\n" +
                  "  // The POST and PUT call will not contain a request body\n" +
                  "  // because the body-parser is not included by default.\n" +
                  "  // To use req.body, run:\n" +
                  "\n" +
                  "  //    npm install --save-dev body-parser\n" +
                  "\n" +
                  "  // After installing, you need to `use` the body-parser for\n" +
                  "  // this mock uncommenting the following line:\n" +
                  "  //\n" +
                  "  //app.use('/api/foo', require('body-parser').json());\n" +
                  "  app.use('/api/foo', fooRouter);\n" +
                  "};");

    expect(file('server/.jshintrc'))
      .to.contain('{\n  "node": true\n}');
  }));

  it('http-mock foo-bar --pod', co.wrap(function *() {
    yield generate(['http-mock', 'foo-bar', '--pod']);

    expect(file('server/index.js'))
      .to.contain("mocks.forEach(route => route(app));");

    expect(file('server/mocks/foo-bar.js'))
      .to.contain("module.exports = function(app) {\n" +
                  "  const express = require('express');\n" +
                  "  let fooBarRouter = express.Router();\n" +
                  "\n" +
                  "  fooBarRouter.get('/', function(req, res) {\n" +
                  "    res.send({\n" +
                  "      'foo-bar': []\n" +
                  "    });\n" +
                  "  });\n" +
                  "\n" +
                  "  fooBarRouter.post('/', function(req, res) {\n" +
                  "    res.status(201).end();\n" +
                  "  });\n" +
                  "\n" +
                  "  fooBarRouter.get('/:id', function(req, res) {\n" +
                  "    res.send({\n" +
                  "      'foo-bar': {\n" +
                  "        id: req.params.id\n" +
                  "      }\n" +
                  "    });\n" +
                  "  });\n" +
                  "\n" +
                  "  fooBarRouter.put('/:id', function(req, res) {\n" +
                  "    res.send({\n" +
                  "      'foo-bar': {\n" +
                  "        id: req.params.id\n" +
                  "      }\n" +
                  "    });\n" +
                  "  });\n" +
                  "\n" +
                  "  fooBarRouter.delete('/:id', function(req, res) {\n" +
                  "    res.status(204).end();\n" +
                  "  });\n" +
                  "\n" +
                  "  // The POST and PUT call will not contain a request body\n" +
                  "  // because the body-parser is not included by default.\n" +
                  "  // To use req.body, run:\n" +
                  "\n" +
                  "  //    npm install --save-dev body-parser\n" +
                  "\n" +
                  "  // After installing, you need to `use` the body-parser for\n" +
                  "  // this mock uncommenting the following line:\n" +
                  "  //\n" +
                  "  //app.use('/api/foo-bar', require('body-parser').json());\n" +
                  "  app.use('/api/foo-bar', fooBarRouter);\n" +
                  "};");

    expect(file('server/.jshintrc'))
      .to.contain('{\n  "node": true\n}');
  }));

  it('http-proxy foo --pod', co.wrap(function *() {
    yield generate(['http-proxy', 'foo', 'http://localhost:5000', '--pod']);

    expect(file('server/index.js'))
      .to.contain("proxies.forEach(route => route(app));");

    expect(file('server/proxies/foo.js'))
      .to.contain("const proxyPath = '/foo';\n" +
                  "\n" +
                  "module.exports = function(app) {\n" +
                  "  // For options, see:\n" +
                  "  // https://github.com/nodejitsu/node-http-proxy\n" +
                  "  let proxy = require('http-proxy').createProxyServer({});\n" +
                  "\n" +
                  "  proxy.on('error', function(err, req) {\n" +
                  "    console.error(err, req.url);\n" +
                  "  });\n" +
                  "\n" +
                  "  app.use(proxyPath, function(req, res, next){\n" +
                  "    // include root path in proxied request\n" +
                  "    req.url = proxyPath + '/' + req.url;\n" +
                  "    proxy.web(req, res, { target: 'http://localhost:5000' });\n" +
                  "  });\n" +
                  "};");

    expect(file('server/.jshintrc'))
      .to.contain('{\n  "node": true\n}');
  }));

  it('uses blueprints from the project directory', co.wrap(function *() {
    yield initApp();
    yield outputFile(
      'blueprints/foo/files/app/foos/__name__.js',
      "import Ember from 'ember';\n" +
      'export default Ember.Object.extend({ foo: true });\n'
    );

    yield ember(['generate', 'foo', 'bar', '--pod']);

    expect(file('app/foos/bar.js')).to.contain('foo: true');
  }));

  it('allows custom blueprints to override built-ins', co.wrap(function *() {
    yield initApp();
    yield outputFile(
      'blueprints/controller/files/app/__path__/__name__.js',
      "import Ember from 'ember';\n\n" +
      "export default Ember.Controller.extend({ custom: true });\n"
    );

    yield ember(['generate', 'controller', 'foo', '--pod']);

    expect(file('app/foo/controller.js')).to.contain('custom: true');
  }));

  it('passes custom cli arguments to blueprint options', co.wrap(function *() {
    yield initApp();
    yield outputFile(
      'blueprints/customblue/files/app/__name__.js',
      "Q: Can I has custom command? A: <%= hasCustomCommand %>"
    );

    yield outputFile(
      'blueprints/customblue/index.js',
      "module.exports = {\n" +
      "  fileMapTokens(options) {\n" +
      "    return {\n" +
      "      __name__(options) {\n" +
      "         return options.dasherizedModuleName;\n" +
      "      }\n" +
      "    };\n" +
      "  },\n" +
      "  locals(options) {\n" +
      "    var loc = {};\n" +
      "    loc.hasCustomCommand = (options.customCommand) ? 'Yes!' : 'No. :C';\n" +
      "    return loc;\n" +
      "  },\n" +
      "};\n"
    );

    yield ember(['generate', 'customblue', 'foo', '--custom-command', '--pod']);

    expect(file('app/foo.js')).to.contain('A: Yes!');
  }));

  it('correctly identifies the root of the project', co.wrap(function *() {
    yield initApp();
    yield outputFile(
      'blueprints/controller/files/app/__path__/__name__.js',
      "import Ember from 'ember';\n\n" +
      "export default Ember.Controller.extend({ custom: true });\n"
    );

    process.chdir(path.join(tmpdir, 'app'));
    yield ember(['generate', 'controller', 'foo', '--pod']);

    process.chdir(tmpdir);
    expect(file('app/foo/controller.js')).to.contain('custom: true');
  }));

  // Skip until podModulePrefix is deprecated
  it.skip('podModulePrefix deprecation warning', co.wrap(function *() {
    let result = yield generateWithPrefix(['controller', 'foo', '--pod']);

    expect(result.outputStream.join()).to.include("`podModulePrefix` is deprecated and will be" +
      " removed from future versions of ember-cli. Please move existing pods from" +
      " 'app/pods/' to 'app/'.");
  }));
});
Example #21
0
describe('Default Packager: Index', function() {
  let input, output;

  let project = {
    configPath() {
      return `${input.path()}/the-best-app-ever/config/environment`;
    },

    config() {
      return {
        rootURL: 'best-url-ever',
        modulePrefix: 'the-best-app-ever',
      };
    },

    addons: [],
  };

  let META_TAG =
    '/best-url-ever/\n<meta name="the-best-app-ever/config/environment" content="{"rootURL":"/best-url-ever/","modulePrefix":"the-best-app-ever"}" />';

  before(
    co.wrap(function*() {
      input = yield createTempDir();

      let indexContent = `
      {{rootURL}}{{content-for "head"}}
      {{content-for "head-footer"}}
      {{content-for "body"}}
      {{content-for "body-footer"}}
    `;
      input.write({
        'addon-tree-output': {},
        'the-best-app-ever': {
          'router.js': 'router.js',
          'app.js': 'app.js',
          'index.html': indexContent,
          config: {
            'environment.js': 'environment.js',
          },
          templates: {},
        },
      });
    })
  );

  after(
    co.wrap(function*() {
      yield input.dispose();
    })
  );

  afterEach(
    co.wrap(function*() {
      yield output.dispose();
    })
  );

  it(
    'caches processed index tree',
    co.wrap(function*() {
      let defaultPackager = new DefaultPackager({
        name: 'the-best-app-ever',
        env: 'development',

        autoRun: true,
        storeConfigInMeta: true,
        isModuleUnificationEnabled: false,
        areTestsEnabled: true,

        distPaths: {
          appHtmlFile: 'index.html',
        },

        project,
      });

      expect(defaultPackager._cachedProcessedIndex).to.equal(null);

      output = yield buildOutput(defaultPackager.processIndex(input.path()));

      expect(defaultPackager._cachedProcessedIndex).to.not.equal(null);
    })
  );

  it(
    'works with a custom path',
    co.wrap(function*() {
      let defaultPackager = new DefaultPackager({
        name: 'the-best-app-ever',
        env: 'development',

        autoRun: true,
        storeConfigInMeta: true,
        isModuleUnificationEnabled: false,
        areTestsEnabled: true,

        distPaths: {
          appHtmlFile: 'custom/index.html',
        },

        project,
      });

      expect(defaultPackager._cachedProcessedIndex).to.equal(null);

      output = yield buildOutput(defaultPackager.processIndex(input.path()));

      let outputFiles = output.read();
      let indexContent = decodeURIComponent(outputFiles.custom['index.html'].trim());

      expect(indexContent).to.equal(META_TAG);
    })
  );

  it(
    'populates `index.html` according to settings',
    co.wrap(function*() {
      let defaultPackager = new DefaultPackager({
        name: 'the-best-app-ever',
        env: 'development',

        autoRun: true,
        storeConfigInMeta: true,
        isModuleUnificationEnabled: false,
        areTestsEnabled: true,

        distPaths: {
          appHtmlFile: 'index.html',
        },

        project,
      });

      expect(defaultPackager._cachedProcessedIndex).to.equal(null);

      output = yield buildOutput(defaultPackager.processIndex(input.path()));

      let outputFiles = output.read();
      let indexContent = decodeURIComponent(outputFiles['index.html'].trim());

      expect(indexContent).to.equal(META_TAG);
    })
  );

  if (isExperimentEnabled('MODULE_UNIFICATION')) {
    describe('with module unification', function() {
      let input, output;

      before(
        co.wrap(function*() {
          input = yield createTempDir();

          let indexContent = `
          {{rootURL}}{{content-for "head"}}
          {{content-for "head-footer"}}
          {{content-for "body"}}
          {{content-for "body-footer"}}
        `;
          input.write({
            'addon-tree-output': {},
            'the-best-app-ever': {
              'router.js': 'router.js',
              'app.js': 'app.js',
              'index.html': indexContent,
              config: {
                'environment.js': 'environment.js',
              },
              templates: {},
            },
            src: {
              ui: {
                'index.html': 'src',
              },
            },
          });
        })
      );

      after(
        co.wrap(function*() {
          yield input.dispose();
        })
      );

      afterEach(
        co.wrap(function*() {
          yield output.dispose();
        })
      );

      it(
        'prefers `src/ui/index.html` over `app/index.html`',
        co.wrap(function*() {
          let defaultPackager = new DefaultPackager({
            name: 'the-best-app-ever',
            env: 'development',

            autoRun: true,
            storeConfigInMeta: true,
            isModuleUnificationEnabled: true,
            areTestsEnabled: true,

            distPaths: {
              appHtmlFile: 'index.html',
            },

            project,
          });

          output = yield buildOutput(defaultPackager.processIndex(input.path()));

          let outputFiles = output.read();
          let indexContent = decodeURIComponent(outputFiles['index.html'].trim());

          expect(indexContent).to.equal('src');
        })
      );

      it(
        'works if only `src/ui/index.html` exists',
        co.wrap(function*() {
          input.dispose();
          input.write({
            'addon-tree-output': {},
            src: {
              ui: {
                'index.html': 'src',
              },
            },
          });
          let defaultPackager = new DefaultPackager({
            name: 'the-best-app-ever',
            env: 'development',

            autoRun: true,
            storeConfigInMeta: true,
            isModuleUnificationEnabled: true,
            areTestsEnabled: true,

            distPaths: {
              appHtmlFile: 'index.html',
            },

            project,
          });

          output = yield buildOutput(defaultPackager.processIndex(input.path()));

          let outputFiles = output.read();
          let indexContent = decodeURIComponent(outputFiles['index.html'].trim());

          expect(indexContent).to.equal('src');
        })
      );
    });
  }
});
Example #22
0
module.exports = function (fileTree, source) {

    const data            = require('../data');
    const build = co.wrap(function* (dir, parent) {

        let collection;
        const children    = dir.children || [];
        const files       = children.filter(item => item.isFile);
        const directories = children.filter(item => item.isDirectory);
        const matched     = {
            directories: directories,
            files:       files,
            views:       files.filter(f => source.isView(f)),
            varViews:    files.filter(f => source.isVarView(f)),
            configs:     files.filter(f => source.isConfig(f)),
            readmes:     files.filter(f => source.isReadme(f)),
            assets:      files.filter(f => source.isAsset(f)),
        };

        const dirConfig = yield data.getConfig(_.find(matched.configs, f => f.name.startsWith(dir.name)), {
            name:     dir.name,
            isHidden: dir.isHidden,
            order:    dir.order,
            dir:      dir.path,
            collated: dir.collated
        });
        dirConfig.parent = parent;

        // first figure out if it's a component directory or not...

        const view = _.find(matched.views, { name: dir.name });
        if (view) { // it is a component
            const nameMatch    = `${dir.name}`;
            dirConfig.view     = view.base;
            dirConfig.viewName = dir.name;
            dirConfig.viewPath = view.path;
            dirConfig.source   = source;
            const assets       = new AssetCollection({}, matched.assets.map(f => new Asset(f)));
            return Component.create(dirConfig, {
                view:     view,
                readme:   matched.readmes[0],
                varViews: _.filter(matched.varViews, f => f.name.startsWith(nameMatch))
            }, assets);
        }

        // not a component, so go through the items and group into components and collections

        if (!parent) {
            collection = source;
            source.setProps(dirConfig);
        } else {
            collection = new Collection(dirConfig, []);
            collection._source = source;
        }

        const collections = yield matched.directories.map(item => build(item, collection));
        const components  = yield matched.views.map(view => {
            const nameMatch = `${view.name}`;
            const configFile = _.find(matched.configs, f => f.name.startsWith(nameMatch));
            const conf    = data.getConfig(configFile, {
                name:     view.name,
                order:    view.order,
                isHidden: view.isHidden,
                view:     view.base,
                viewName: view.name,
                viewPath: view.path,
                dir:      dir.path,
            });
            return conf.then(c => {
                c.parent = collection;
                c.source = source;
                return Component.create(c, {
                    view: view,
                    readme: null,
                    varViews: matched.varViews.filter(f => f.name.startsWith(nameMatch)),
                }, new AssetCollection({}, []));
            });
        });

        const items = yield (_.concat(components, collections));
        collection.setItems(_.orderBy(items, ['order', 'name']));
        return collection;
    });

    return build(fileTree);
};
Example #23
0
describe('Default Packager: Javascript', function() {
  let input, output;

  let scriptOutputFiles = {
    '/assets/vendor.js': [
      'vendor/ember-cli/vendor-prefix.js',
      'vendor/loader/loader.js',
      'vendor/ember/jquery/jquery.js',
      'vendor/ember-cli-shims/app-shims.js',
      'vendor/ember-resolver/legacy-shims.js',
      'vendor/ember/ember.debug.js',
    ],
  };
  let MODULES = {
    'addon-tree-output': {
      'ember-ajax': {
        'request.js': '',
      },
      'ember-cli-app-version': {
        'initializer-factory.js': '',
      },
      'modules': {
        'ember-data': {
          'transform.js': '',
          'store.js': '',
        },
      },
    },
    'the-best-app-ever': {
      'router.js': 'router.js',
      'app.js': 'app.js',
      'components': {
        'x-foo.js': 'export default class {}',
      },
      'routes': {
        'application.js': 'export default class {}',
      },
      'config': {
        'environment.js': 'environment.js',
      },
      'templates': {},
    },
    'vendor': {
      'loader': {
        'loader.js': '',
      },
      'ember': {
        'jquery': {
          'jquery.js': '',
        },
        'ember.debug.js': '',
      },
      'ember-cli': {
        'app-boot.js': 'app-boot.js',
        'app-config.js': 'app-config.js',
        'app-prefix.js': 'app-prefix.js',
        'app-suffix.js': 'app-suffix.js',
        'test-support-prefix.js': 'test-support-prefix.js',
        'test-support-suffix.js': 'test-support-suffix.js',
        'tests-prefix.js': 'tests-prefix.js',
        'tests-suffix.js': 'tests-suffix.js',
        'vendor-prefix.js': 'vendor-prefix.js',
        'vendor-suffix.js': 'vendor-suffix.js',
      },
      'ember-cli-shims': {
        'app-shims.js': '',
      },
      'ember-resolver': {
        'legacy-shims.js': '',
      },
    },
  };
  let project = {
    configPath() {
      return `${input.path()}/the-best-app-ever/config/environment`;
    },

    config() {
      return { a: 1 };
    },

    registry: setupRegistryFor('template', function(tree) {
      return new Funnel(tree, {
        getDestinationPath(relativePath) {
          return relativePath.replace(/hbs$/g, 'js');
        },
      });
    }),

    addons: [],
  };

  before(co.wrap(function *() {
    input = yield createTempDir();

    input.write(MODULES);
  }));

  after(co.wrap(function *() {
    yield input.dispose();
  }));

  afterEach(co.wrap(function *() {
    yield output.dispose();
  }));

  it('caches packaged javascript tree', co.wrap(function *() {
    let defaultPackager = new DefaultPackager({
      name: 'the-best-app-ever',
      env: 'development',

      distPaths: {
        appJsFile: '/assets/the-best-app-ever.js',
        vendorJsFile: '/assets/vendor.js',
      },

      registry: setupRegistryFor('template', function(tree) {
        return new Funnel(tree, {
          getDestinationPath(relativePath) {
            return relativePath.replace(/hbs$/g, 'js');
          },
        });
      }),

      customTransformsMap: new Map(),

      scriptOutputFiles,
      project,
    });

    expect(defaultPackager._cachedJavascript).to.equal(null);

    output = yield buildOutput(defaultPackager.packageJavascript(input.path()));

    expect(defaultPackager._cachedJavascript).to.not.equal(null);
    expect(defaultPackager._cachedJavascript._annotation).to.equal('Packaged Javascript');
  }));

  it('packages javascript files with sourcemaps on', co.wrap(function *() {
    let defaultPackager = new DefaultPackager({
      name: 'the-best-app-ever',
      env: 'development',

      distPaths: {
        appJsFile: '/assets/the-best-app-ever.js',
        vendorJsFile: '/assets/vendor.js',
      },

      registry: setupRegistryFor('template', function(tree) {
        return new Funnel(tree, {
          getDestinationPath(relativePath) {
            return relativePath.replace(/hbs$/g, 'js');
          },
        });
      }),

      customTransformsMap: new Map(),

      scriptOutputFiles,
      project,
    });

    output = yield buildOutput(defaultPackager.packageJavascript(input.path()));

    let outputFiles = output.read();

    expect(Object.keys(outputFiles.assets)).to.deep.equal([
      'the-best-app-ever.js',
      'the-best-app-ever.map',
      'vendor.js',
      'vendor.map',
    ]);
  }));

  it('packages javascript files with sourcemaps off', co.wrap(function *() {
    let defaultPackager = new DefaultPackager({
      name: 'the-best-app-ever',
      env: 'development',

      distPaths: {
        appJsFile: '/assets/the-best-app-ever.js',
        vendorJsFile: '/assets/vendor.js',
      },

      registry: setupRegistryFor('template', function(tree) {
        return new Funnel(tree, {
          getDestinationPath(relativePath) {
            return relativePath.replace(/hbs$/g, 'js');
          },
        });
      }),

      sourcemaps: {
        enabled: false,
      },

      customTransformsMap: new Map(),

      scriptOutputFiles,
      project,
    });

    output = yield buildOutput(defaultPackager.packageJavascript(input.path()));

    let outputFiles = output.read();

    expect(Object.keys(outputFiles.assets)).to.deep.equal([
      'the-best-app-ever.js',
      'vendor.js',
    ]);
  }));

  it('processes javascript according to the registry', co.wrap(function *() {
    let defaultPackager = new DefaultPackager({
      name: 'the-best-app-ever',

      registry: setupRegistryFor('js', function(tree) {
        return new Funnel(tree, {
          getDestinationPath(relativePath) {
            return relativePath.replace(/js/g, 'jsx');
          },
        });
      }),

      project: { addons: [] },
    });

    expect(defaultPackager._cachedProcessedJavascript).to.equal(null);

    output = yield buildOutput(defaultPackager.processJavascript(input.path()));

    let outputFiles = output.read();

    expect(outputFiles['the-best-app-ever']).to.deep.equal({
      'app.jsx': 'app.js',
      components: {
        'x-foo.jsx': 'export default class {}',
      },
      routes: {
        'application.jsx': 'export default class {}',
      },
      config: {
        'environment.jsx': 'environment.js',
      },
      'router.jsx': 'router.js',
    });
  }));

  it('runs pre/post-process add-on hooks', co.wrap(function *() {
    let addonPreprocessTreeHookCalled = false;
    let addonPostprocessTreeHookCalled = false;

    let defaultPackager = new DefaultPackager({
      name: 'the-best-app-ever',

      registry: setupRegistryFor('js', tree => tree),

      // avoid using `testdouble.js` here on purpose; it does not have a "proxy"
      // option, where a function call would be registered and the original
      // would be returned
      project: {
        addons: [{
          preprocessTree(type, tree) {
            addonPreprocessTreeHookCalled = true;

            return tree;
          },
          postprocessTree(type, tree) {
            addonPostprocessTreeHookCalled = true;

            return tree;
          },
        }],
      },
    });

    expect(defaultPackager._cachedProcessedJavascript).to.equal(null);

    output = yield buildOutput(defaultPackager.processJavascript(input.path()));

    expect(addonPreprocessTreeHookCalled).to.equal(true);
    expect(addonPostprocessTreeHookCalled).to.equal(true);
  }));

});
const co = require('co');
const {Receipt} = require('../../models');

module.exports = {
  up: co.wrap(function*(migration, Sequelize) {
    yield migration.addColumn(Receipt.tableName, 'discount', {
      type: Sequelize.INTEGER,
      defaultValue: 0
    });

    yield migration.addColumn(Receipt.tableName, 'selfPaid', {
      type: Sequelize.BOOLEAN,
      defaultValue: false
    });
  }),

  down: co.wrap(function*(migration, Sequelize) {
    yield migration.removeColumn(Receipt.tableName, 'discount');
    yield migration.removeColumn(Receipt.tableName, 'selfPaid');
  })
};
Example #25
0
var co = require('co');
var mongo = require('../lib/mongo-extend');


exports.getById = co.wrap(function * (id, select) {
	if (!select) select = {};

	id = parseInt(id);
	return yield mongo.findOne('Solution', { _id: id }, { select: select });
});

exports.update = co.wrap(function * (solution) {
	var id = parseInt(solution._id);
	return yield mongo.findOneAndUpdate('Solution', { _id: id }, { $set: solution});
});

exports.create = co.wrap(function * (solution) {
	solution._id = parseInt(solution._id);
	return yield mongo.insert('Solution', solution);
});



Example #26
0
'use strict';

const grpc = require('grpc');
const auth = grpc.load(__dirname + '/userAuth.proto').auth;
const co = require('co');
const pify = require('promise.ify');
const _ = require('lodash');
const c = new auth.AuthService('127.0.0.1:5200', grpc.credentials.createInsecure());
c.getAuthResultAsync = pify(c.getAuthResult, c);

const main = co.wrap(function*() {
  console.time('rpc');
  for (let i = 0; i < 10000; i++) {
    const result = yield c.getAuthResultAsync({
      token: 'hello world'
    });
    // console.log(result);
  }
  console.timeEnd('rpc');
});

main().catch(e => console.error(e.stack || e));
Example #27
0
  const queryStr = stringify({
    client_id: CLIENT_ID,
    redirect_uri: CALLBACK_URL,
    state: Date.now(),
  });
  return `https://github.com/login/oauth/authorize?${queryStr}`;
}

const handleLoginCallback = wrap(function *({code, state}) {
  const { access_token } = yield rp({
    method: 'POST',
    uri: 'https://github.com/login/oauth/access_token',
    body: {
      client_id: CLIENT_ID,
      client_secret: CLIENT_SECRET,
      redirect_uri: CALLBACK_URL,
      code,
      state,
    },
    json: true,
  });

  return access_token;
});

export {
  github as default,
  createLoginUrl,
  handleLoginCallback,
};
Example #28
0
'use strict'

const kue = require('kue')
const {wrap} = require('co')
const {createClient, sharedClient: redis} = require('./redis')
const log = require('./log')

const queue = kue.createQueue({
  redis: {
    createClientFactory: createClient
  }
})

const enqueueSyncStarsJob = wrap(function *(userId) {
  const key = `{uniq-job:sync-stars}:user_id:${userId}`
  const result = yield redis.getset(key, Date.now().toString())
  log.info({value: result}, 'ENQUEUE_UNIQUE_JOB_CHECK')
  // result will be `null` when first time "getset"
  if (result !== null) {
    return
  }
  queue.create('sync-stars', {user_id: userId}).save()
  yield redis.expire(key, 30) // 30 sec
})

module.exports = {
  enqueueSyncStarsJob
}
Example #29
0
 start: () => {
   logger.info('[WORKER.opendata.paris] Starting');
   /* eslint no-new: 0 */ /* Everyday at 4AM */
   new CronJob('00 00 04 * * *', co.wrap(update), null, true, 'Europe/Paris');
 },
Example #30
0
            }

            resolve();
        });
    });
}

const dumpConfig = co.wrap(function* dumpConfig(records) {
    let config = '';

    for (const [ip, domains] of records.entries()) {
        config += ip;

        for (const domain of domains) {
            config += ` ${domain}`;
        }

        config += '\n';
    }

    yield writeFile(hostsFile, config);

    process.kill(yield generatePid(), 'SIGHUP');
});

const addRecord = co.wrap(function* addRecord(records, ip, domain) {
    if (!records.has(ip)) {
        records.set(ip, new Set());
    }

    records.get(ip).add(domain);