Beispiel #1
0
function getProject(uri, cb) {
    var projectUri = 'git@github.com:' + uri;
    var parts = uri.split('/');
    var folderName = parts[parts.length - 1];
    var folder = path.join(process.cwd(), folderName);

    series([
        gitrun.bind(null, ['clone', projectUri], process.cwd()),
        parallel.bind(null, {
            readme: fs.readFile.bind(null,
                path.join(folder, 'README.md'), 'utf8'),
            package: fs.readFile.bind(null,
                path.join(folder, 'package.json'), 'utf8')
        })
    ], function done(err, results) {
        if (err) {
            return cb(err);
        }

        var data = results[1];

        data.package = JSON.parse(data.package);
        data.name = data.package.name;

        logger.log('got', data.name);

        rimraf(folder, function fini() {
            cb(err, data);
        });
    });
}
Beispiel #2
0
State.prototype.runUp = function(name, done) {
	if (!this.fixtures[name]) {
		return done(new Error('No such fixture: ' + name));
	}

	this.fixtures[name].load();
	if (this.fixtures[name].hasRun) {
		logger.debug('Fixture already run');
		return done(null);
	}

	// Run deps
	var fncs = this.fixtures[name].dependsOn.map(function(dep) {
		this.fixtures[name].dependencies[dep] = this.fixtures[dep];
		return function(done) {
			this.runUp.call(this, dep, done);
		}.bind(this)
	}.bind(this));

	series(fncs, function(err) {
		if (err) {
			return done(err);
		}

		// Run the main fixture
		logger.notice('Setting up fixture: ' + name);
		this.fixtures[name].up.call(this.fixtures[name], function(err) {
			if (err) {
				return done(err);
			}
			this.fixtures[name].hasRun = true;
			done(null);
		}.bind(this));
	}.bind(this));
};
Beispiel #3
0
Router.transition = function transition (state, route, params, callback) {
  var current = hookRunner(state, state.active(), state.params())
  var next = hookRunner(state, route, params)

  var fail = filter(Boolean, partial(ErrorEvent.broadcast, state))
  callback = callback || noop

  series([
    partial(current, 'leave.before'),
    partial(current, 'leave.after'),
    partial(next, 'enter.before'),
    enter
  ], done)

  function enter (callback) {
    activate(state, {
      route: route,
      params: params
    })
    callback(null)
    next('enter.after', fail)
  }

  function done (err) {
    fail(err)
    callback(err)
  }
}
Beispiel #4
0
 cancelStopOrders: function(cb) {
     let orders = [], tasks = [];
     today_orders.forEach(function(order) {
         if ((order.trigger == "stop") && (['queued', 'unconfirmed', 'confirmed', 'partially_filled'].includes(order.state))) {
             let symbol = instruments.getSymbol(order.instrument);
             if (conf.list[conf.strategy].includes(symbol)) {
                 console.log("Cancel stop order: "+order.id);
                 orders.push(order);
                 tasks.push(function(cb) {
                     if (conf.trade) {
                         global.Robinhood.cancel_order(orders.pop(), function(err, resp, body) {
                             if (err) return cb(err);
                             cb();
                         });
                     } else cb();
                 });
             }
         }
     });
     if ((orders.length > 0) && (conf.trade)) {
         tasks.push(function(cb) {
             console.log("Waiting until stop orders cancelled...");
             setTimeout(function() {
                 cb();
             }, 10000);
         })
     }
     series(tasks, function(err, results) {
         if (err) console.error(err);
         cb();
     });
 },
Beispiel #5
0
function programDevice(){
  $('#runBtn').prop('disabled', true);
  $('#programBtn').prop('disabled', true);

  var serial = new SerialPort(serialSelect.state.selectedDevice, {
    baudrate: baud
  }, false);

  var programmer = new stk500(serial);

  series([
    programmer.connect.bind(programmer),
    programmer.reset.bind(programmer, delay1, delay2),
    programmer.sync.bind(programmer, 5),
    programmer.verifySignature.bind(programmer, signature),
    programmer.setOptions.bind(programmer, options),
    programmer.enterProgrammingMode.bind(programmer),
    programmer.upload.bind(programmer, hex, pageSize),
    programmer.exitProgrammingMode.bind(programmer),
    programmer.disconnect.bind(programmer)
  ], function(error){
    $('#runBtn').prop('disabled', false);
    $('#programBtn').prop('disabled', false);

    if(error){
      console.log("programing FAILED: " + error);
      return;
    }

    console.log("programing SUCCESS!");
  });
}
Beispiel #6
0
    plugins[plugin] = function (pluginOptions, cb) {
      var tasks = options[plugin].map(function (step) {
        return _exports.normalize(step, './plugin-noop').bind(null, pluginOptions);
      });

      series(tasks, cb);
    };
Beispiel #7
0
}, function t(cluster, assert) {

    series([
        cluster.idlGet.bind(cluster, 'init'),
        cluster.inspectLocalApp.bind(cluster)
    ], onResults);

    function onResults(err, results) {
        if (err) {
            assert.ifError(err);
        }
        var local = results[1];

        var expected = [
            'typedef string UUID',
            'typedef i64 Timestamp',
            '',
            'service Idl {',
            '    UUID echo(',
            '        1: UUID uuid',
            '    )',
            '}',
            ''
        ].join('\n');

        assert.equal(
            local.idl['github.com']['uber-node'].idl['idl.thrift'],
            expected,
            'Correct IDL file contents at the correct path'
        );

        assert.end();
    }
});
Beispiel #8
0
}, function t(cluster, assert) {

    var now = Date.now();

    series([
        publishRemote(cluster, 'A', now + 1000, false),
        publishRemote(cluster, 'Z', now + 2000, false)
    ], onResults);

    function onResults(err, results) {
        if (err) {
            assert.ifError(err);
        }

        var filepath = 'idl/github.com/org/z/service.thrift';
        assert.false(
            results[1].upstream.files.hasOwnProperty(filepath),
            'No published thrift file for service Z'
        );
        assert.equal(
            results[1].upstream.meta.version,
            now + 1000,
            'Correct version (unchanged)'
        );
        assert.equal(
            results[1].stderr.message,
            'Directory not found: ./idl/github.com/org/z'
        );

        tk.reset();
        assert.end();
    }
});
Beispiel #9
0
testSetup('healthy goes unhealthy with partial success', function t(cluster, assert) {
    var peer = cluster.client.peers.get(cluster.hosts[1]);

    series([
        function checkIt(done) {
            assert.equals(peer.state.shouldRequest(), 1.0, 'expected fully connected score');
            assert.equals(peer.state.type, 'tchannel.healthy', 'still healthy');
            done();
        },

        function sendIt(done) {
            // 1ok : 2nok
            parallel([
                cluster.send('glad'),
                cluster.send('sad'),
                cluster.send('sad'),
            ], done);
        },

        function checkItAgain(done) {
            peer.channel.timers.advance(1000);
            assert.equals(peer.state.shouldRequest(), 0.0, 'expected unhealthy score');
            assert.equals(peer.state.type, 'tchannel.unhealthy', 'expected unhealthy');
            done();
        }
    ], assert.end);
});
  before((done) => {
    const repoData = []
    repoContext.keys().forEach((key) => {
      repoData.push({
        key: key.replace('./', ''),
        value: repoContext(key)
      })
    })

    const mainBlob = store('ipfs')
    const blocksBlob = store('ipfs/blocks')

    series(repoData.map((file) => (cb) => {
      if (_.startsWith(file.key, 'datastore/')) {
        return cb()
      }

      const blocks = _.startsWith(file.key, 'blocks/')
      const blob = blocks ? blocksBlob : mainBlob

      const key = blocks ? file.key.replace(/^blocks\//, '') : file.key

      blob.createWriteStream({
        key: key
      }).end(file.value, cb)
    }), done)
  })
Beispiel #11
0
  return function runner (type, callback) {
    series([run(state, params), run(route, params)], callback)

    function run (key, arg) {
      return partial(hooks.get(type, key), arg)
    }
  }
Beispiel #12
0
testSetup('consecutive success during unhealthy periods restores health', function t(cluster, assert) {
    var peer = cluster.client.peers.get(cluster.hosts[1]);

    var Steps = [
        function failIt(done) {
            parallel([
                cluster.send('sad'),
                cluster.send('sad')
            ], done);
        },

        function checkIt(done) {
            peer.channel.timers.advance(1000);
            assert.equals(peer.state.shouldRequest(), 0.0, 'expected unhealthy score');
            assert.equals(peer.state.type, 'tchannel.unhealthy', 'expected unhealthy');

            done();
        }
    ];

    [1, 2, 3, 4, 5].forEach(function each(trial) {Steps.push(

        function checkBefore(done) {
            peer.channel.timers.advance(1000);
            assert.equals(peer.state.shouldRequest(), 1.0, 'expected probe score before try ' + trial);
            assert.equals(peer.state.type, 'tchannel.unhealthy', 'unhealthy before try ' + trial);

            done();
        },

        cluster.send('glad'),

        function checkAfter(done) {
            assert.equals(peer.state.shouldRequest(), 0.0, 'expected unhealthy score after try ' + trial);
            assert.equals(peer.state.type, 'tchannel.unhealthy', 'unhealthy after try ' + trial);

            done();
        }

    );});

    Steps.push(
        function fastForward(done) {
            peer.channel.timers.advance(1000);
            done();
        },

        cluster.send('glad'),
        cluster.send('glad'),

        function checkFinal(done) {
            assert.equals(peer.state.shouldRequest(), 1.0, 'expected healthy score', 'expected healthy score');
            assert.equals(peer.state.type, 'tchannel.healthy', 'probed back to health');

            done();
        });

    series(Steps, assert.end);

});
Beispiel #13
0
testSetup('stays healthy with partial success', function t(cluster, assert) {
    var peer = cluster.client.peers.get(cluster.hosts[1]);

    series([
        function checkIt(done) {
            assert.equals(peer.state.shouldRequest(), 1.0, 'expected fully connected score');
            assert.equals(peer.state.type, 'tchannel.healthy', 'still healthy');
            done();
        },

        function sendIt(done) {
            parallel([
                // 50%ok/50%nok is ultimately okay with a threshold of .5
                cluster.send('glad'),
                cluster.send('sad'),
                cluster.send('glad'),
                cluster.send('sad'),
                cluster.send('glad'),
                cluster.send('sad'),
            ], done);
        },

        function checkItAgain(done) {
            peer.channel.timers.advance(1000);
            assert.equals(peer.state.shouldRequest(), 1.0, 'expected fully connected score');
            assert.equals(peer.state.type, 'tchannel.healthy', 'still healthy');
            done();
        }
    ], assert.end);
});
Beispiel #14
0
 function createApp (comboOpts) {
   var buildParentDir
   if (useTempDir) {
     buildParentDir = tempBase
   } else {
     buildParentDir = opts.out || process.cwd()
   }
   var buildDir = path.join(buildParentDir, `${platform}-${arch}-template`)
   console.error(`Packaging app for platform ${platform} ${arch} using electron v${version}`)
   series([
     function (cb) {
       fs.mkdirs(buildDir, cb)
     },
     function (cb) {
       extract(zipPath, {dir: buildDir}, cb)
     },
     function (cb) {
       if (!opts.afterExtract || !Array.isArray(opts.afterExtract)) {
         cb()
       } else {
         var newFunctions = opts.afterExtract.map(function (fn) {
           return fn.bind(this, buildDir, version, platform, arch)
         })
         series(newFunctions, cb)
       }
     }
   ], function () {
     require(supportedPlatforms[platform]).createApp(comboOpts, buildDir, callback)
   })
 }
Beispiel #15
0
testSetup('one check per period while unhealthy', function t(cluster, assert) {
    var peer = cluster.client.peers.get(cluster.hosts[1]);

    series([

        function failIt(done) {
            parallel([
                cluster.send('sad'),
                cluster.send('sad')
            ], done);
        },

        function checkIt(done) {
            peer.channel.timers.advance(1000);
            assert.equals(peer.state.shouldRequest(), 0.0, 'expected unhealthy score');
            assert.equals(peer.state.type, 'tchannel.unhealthy', 'expected unhealthy');

            peer.channel.timers.advance(1000);
            assert.equals(peer.state.shouldRequest(), 1.0, 'expected probe score');
            assert.ok(peer.state.shouldRequest(), 'first request allowed');

            done();
        },

        cluster.send('glad'),

        function checkFirst(done) {
            assert.equals(peer.state.type, 'tchannel.unhealthy');
            assert.equals(peer.state.shouldRequest(), 0.0, 'expected unhealthy score');

            done();
        }

    ], assert.end);
});
Beispiel #16
0
function flatApplication (opts, callback) {
  var operations = []

  var args = [
    '--component', opts.app, opts.install,
    '--sign', opts.identity,
    opts.pkg
  ]
  if (opts.keychain) {
    args.unshift('--keychain', opts.keychain)
  }

  // Call productbuild
  operations.push(function (cb) {
    child.execFile('productbuild', args, function (err, stdout, stderr) {
      if (err) return cb(err)
      cb()
    })
    debuglog('Flattening with productbuild...')
  })

  series(operations, function (err) {
    if (err) return callback(err)
    callback()
  })
}
Beispiel #17
0
exports.downloadAll = function downloadAll (version, callback) {
  series(combinations.map(function (combination) {
    return function (cb) {
      download(combination, cb)
    }
  }), callback)
}
Beispiel #18
0
    common.initializeApp(opts, templatePath, path.join('resources', 'app'), function buildWinApp (err, tempPath) {
      if (err) return callback(err)

      let newExeName = `${common.sanitizeAppName(opts.name)}.exe`
      var operations = [
        function (cb) {
          common.rename(tempPath, 'electron.exe', newExeName, cb)
        }
      ]

      const rcOpts = generateRceditOptionsSansIcon(opts)

      if (opts.icon || opts.win32metadata || opts['version-string'] || opts.appCopyright || opts.appVersion || opts.buildVersion) {
        operations.push(function (cb) {
          common.normalizeExt(opts.icon, '.ico', function (err, icon) {
            // Icon might be omitted or only exist in one OS's format, so skip it if normalizeExt reports an error
            if (!err) {
              rcOpts.icon = icon
            }

            debug(`Running rcedit with the options ${JSON.stringify(rcOpts)}`)
            require('rcedit')(path.join(tempPath, newExeName), rcOpts, function (err) {
              cb(updateWineMissingException(err))
            })
          })
        })
      }

      series(operations, function (err) {
        if (err) return callback(err)
        common.moveApp(opts, tempPath, callback)
      })
    })
Beispiel #19
0
function blockStatement(node, meta, callback) {
    var tasks = node.body.map(function (node) {
        return verify.bind(null, node, meta)
    })

    series(tasks, callback)
}
Beispiel #20
0
    common.initializeApp(opts, templatePath, path.join('resources', 'app'), function buildWinApp (err, tempPath) {
      if (err) return callback(err)

      var newExePath = path.join(tempPath, opts.name + '.exe')
      var operations = [
        function (cb) {
          mv(path.join(tempPath, 'electron.exe'), newExePath, cb)
        }
      ]

      if (opts.icon || opts['version-string']) {
        operations.push(function (cb) {
          common.normalizeExt(opts.icon, '.ico', function (err, icon) {
            var rcOpts = {}
            if (opts['version-string']) rcOpts['version-string'] = opts['version-string']

            // Icon might be omitted or only exist in one OS's format, so skip it if normalizeExt reports an error
            if (!err) {
              rcOpts.icon = icon
            }

            require('rcedit')(newExePath, rcOpts, cb)
          })
        })
      }

      series(operations, function (err) {
        if (err) return callback(err)
        common.moveApp(opts, tempPath, callback)
      })
    })
Beispiel #21
0
function hooks (fns, req, res, callback) {
  if (!fns) return callback()

  series(
    fns.map((fn) => partial(fn, req, res)),
    callback
  )
}
 fs.readdir(file, function (err, _files) {
   if (err) return cb(err)
   series(_files.map(function (_file) {
     return function (cb2) {
       consume(join(file, _file), null, cb2)
     }
   }), cb)
 })
Beispiel #23
0
/**
 * Build an Inferno app.
 */
export default function buildInfernoApp(args, cb) {
  let dist = args._[2] || 'dist'

  runSeries([
    (cb) => cleanApp({_: ['clean-app', dist]}, cb),
    (cb) => webpackBuild('Inferno app', args, buildConfig, cb),
  ], cb)
}
Beispiel #24
0
  initializeApp: function initializeApp (opts, templatePath, appRelativePath, callback) {
    // Performs the following initial operations for an app:
    // * Creates temporary directory
    // * Copies template into temporary directory
    // * Copies user's app into temporary directory
    // * Prunes non-production node_modules (if opts.prune is set)
    // * Creates an asar (if opts.asar is set)

    var tempPath
    if (opts.tmpdir === false) {
      tempPath = generateFinalPath(opts)
    } else {
      tempPath = path.join(opts.tmpdir || os.tmpdir(), 'electron-packager', opts.platform + '-' + opts.arch, generateFinalBasename(opts))
    }

    // Path to `app` directory
    var appPath = path.join(tempPath, appRelativePath)
    var resourcesPath = path.resolve(appPath, '..')

    var operations = [
      function (cb) {
        fs.move(templatePath, tempPath, {clobber: true}, cb)
      },
      function (cb) {
        fs.copy(opts.dir, appPath, {filter: userIgnoreFilter(opts), dereference: true}, cb)
      },
      function (cb) {
        rimraf(path.join(resourcesPath, 'default_app'), cb)
      }
    ]

    // Prune and asar are now performed before platform-specific logic, primarily so that
    // appPath is predictable (e.g. before .app is renamed for mac)
    if (opts.prune) {
      operations.push(function (cb) {
        child.exec('npm prune --production', {cwd: appPath}, cb)
      })
    }

    if (opts.asar) {
      operations.push(function (cb) {
        var options = {}
        if (opts['asar-unpack']) {
          options['unpack'] = opts['asar-unpack']
        }
        if (opts['asar-unpack-dir']) {
          options['unpackDir'] = opts['asar-unpack-dir']
        }
        asarApp(path.join(appPath), options, cb)
      })
    }

    series(operations, function (err) {
      if (err) return callback(err)
      // Resolve to path to temporary app folder for platform-specific processes to use
      callback(null, tempPath)
    })
  },
test('handler can reject events', function (t) {
  var acceptableEvents   = {
          'undefined'                     : undefined
        , 'a string equal to the event'   : 'bogus'
        , 'a string equal to *'           : '*'
        , 'an array containing the event' : ['bogus']
        , 'an array containing *'         : ['not-bogus', '*']
      }
    , unacceptableEvents = {
          'a string not equal to the event or *'   : 'not-bogus'
        , 'an array not containing the event or *' : ['not-bogus']
      }
    , acceptable         = Object.keys(acceptableEvents)
    , unacceptable       = Object.keys(unacceptableEvents)
    , acceptableTests    = acceptable.map(function (events) {
        return acceptableReq.bind(null, events)
      })
    , unacceptableTests  = unacceptable.map(function (events) {
        return unacceptableReq.bind(null, events)
      })

  t.plan(acceptable.length + unacceptable.length)
  series(acceptableTests.concat(unacceptableTests))

  function acceptableReq (events, callback) {
    var h = handler({
        path    : '/some/url'
      , secret  : 'bogus'
      , events  : acceptableEvents[events]
    })

    h(mkReq('/some/url'), mkRes(), function (err) {
      t.error(err)
      t.fail(false, 'should not call')
    })

    setTimeout(function () {
      t.ok(true, 'accepted because options.events was ' + events)
      callback()
    })
  }

  function unacceptableReq (events, callback) {
    var h = handler({
        path    : '/some/url'
      , secret  : 'bogus'
      , events  : unacceptableEvents[events]
    })

    h.on('error', function () {})

    h(mkReq('/some/url'), mkRes(), function (err) {
      t.ok(err, 'rejected because options.events was ' + events)
      callback()
    })
  }
})
Beispiel #26
0
/*  must verify call expression.

    Fetch the type of the identifier that is being called.

    verify that all arguments are valid types

    return the type of the result of the function to the
        callback
*/
function callExpression(node, meta, callback) {
    var callee = node.callee.name;

    var identifiers = meta.currentMeta.identifiers;

    /* istanbul ignore if */
    if (!identifiers[callee]) {
        console.warn('skipping call expression', callee);
        return callback(null);
    }

    var funcType = identifiers[callee].jsig;

    var tasks = node.arguments.map(function verifyArg(arg) {
        return verify.bind(null, arg, meta);
    });
    series(tasks, onargs);

    function onargs(err, args) {
        if (err) {
            return callback(err);
        }

        // TODO allow optional arguments
        if (funcType.args.length !== args.length) {
            return callback(InvalidCallArgCountError({
                count: funcType.args.length,
                invalidCount: args.length
            }));
        }

        var errors = args.map(function checkArg(type, index) {
            if (!type) {
                return new Error('could not get type for ' +
                    node.arguments[index].type);
            }

            return checkSubType(funcType.args[index], type);
        }).filter(Boolean);

        if (errors.length) {
            return callback(errors[0]);
        }

        if (!funcType.isNodeRequireToken) {
            return callback(null, funcType.result);
        }

        // special case for require. The require function has a
        // return value of Any but we can find the real type by
        // loading the source and analyzing it either by loading
        // the correct jsig definition file or
        // by doing type inference
        inferTypeFromRequire(node, meta, callback);
    }
}
Beispiel #27
0
 function (cb) {
   if (!opts.afterExtract || !Array.isArray(opts.afterExtract)) {
     cb()
   } else {
     var newFunctions = opts.afterExtract.map(function (fn) {
       return fn.bind(this, buildDir, version, platform, arch)
     })
     series(newFunctions, cb)
   }
 }
Beispiel #28
0
 function connectNodes (node1, node2, done) {
   series([
     (cb) => connectNodesSingle(node1, node2, cb),
     (cb) => setTimeout(() => {
       // need timeout so we wait for identify to happen
       // in the browsers
       connectNodesSingle(node2, node1, cb)
     }, 100)
   ], done)
 }
Beispiel #29
0
/**
 * Serve a standalone React entry module, component or element.
 */
export default function serveReact(args, cb) {
  if (args._.length === 1) {
    return cb(new UserError('An entry module must be specified.'))
  }

  runSeries([
    (cb) => install(['react', 'react-dom'], {args, check: true}, cb),
    (cb) => webpackServer(args, buildConfig, cb),
  ], cb)
}
Beispiel #30
0
 var server = http.createServer(function (req, res) {
   var tasks = routes.map((route) => {
     return (done) => route(req, res, done)
   })
   series(tasks, function (err) {
     if (err) console.error(err)
     res.statusCode = 404
     res.end('Not Found')
   })
 })