Wrap github calls in to promises
975540
function qG(options) {
  var defer = q.defer();
  var compiledData = [];

  // Recursive call to paginate
  function qGCall(pageLink) {
    var methodCall;

    // Callback
    function callback(error, data) {
      if (error) {
        defer.reject(new Error(error));
      }
      else {
        compiledData = compiledData.concat(data);
        if (github.hasNextPage(data)) {
          qGCall(data);
        }
        else {
          defer.resolve(compiledData);
        }
      }
    }

    // If the call is a link to another page, use that.
    if (pageLink) {
      method = github.getNextPage(pageLink, callback);
    }
    else {
      githubAuth()[options.obj][options.method](options, callback);
    }
  }
  qGCall();

  return defer.promise;
}
327163
function chain_requests(ml, url) {
  return (batches) => {
    let promise = new Promise((resolve, reject) => resolve(new MonkeyLearnResponse()));

    // attach requests for all the batches sequentially to the original promise and return _that_
    return batches.reduce((promise, batch) =>
      promise.then((response) =>

        request(ml, {
          url: url,
          method: 'POST',
          body: batch,
          parse_response: false
        })

        .then(raw_response => {
          response._add_raw_response(raw_response);
          return response;
        })

        .catch(error => {
          if (error.hasOwnProperty('response')) {
            response._add_raw_response(error.response);
            error.response = response;
          } else {
            // if it's not a MonkeyLearn Error (so, some other js runtime error),
            // return as-is but add the response
            // not the cleanest solution but I don't want the error to lose the context
            error.response = response;
            error.error_code = '';
          }
          throw error;
        })
      )
    , promise)
  }
}
31688
function(url, method = 'get', body = undefined) {
		var deferred = Q.defer();
		let self = this;

		try {
			let req = undefined;

			// Create request object
			switch (method.toLowerCase().trim()) {
				case 'post': {
					req = request.post(url).send(body);
					break;
				}
				case 'patch': {
					req = request.patch(url).send(body);
					break;
				}
				case 'put': {
					req = request.put(url).send(body);
					break;
				}
				case 'delete': {
					req = request.delete(url);
					break;
				}
				case 'get': {
					req = request.get(url);
					break;
				}
				default: {
					throw new Error(`Unsupported HTTP verb: ${method}`);
				}
			}

			self.requestCount++;

			// Set standard stuff and handle response
			req
				.set('Authorization', 'token ' + config.token)
				.then(function(res) {
					self.logRequestSuccess(res);
					deferred.resolve({
						body: res.body,
						headers: res.headers
					});
				}, 
				function(err) {
					// TODO: handle rate limiting (github sends a 403, not a 429)
					// https://developer.github.com/v3/#rate-limiting
					log.error(err);
					deferred.reject(err);
				});
		} catch(err) {
			log.error(err);
			deferred.reject(err);
		}

		return deferred.promise;
	}
1129503
function fetch(name, spec, options) {
  if (typeof spec === 'object' && options === undefined) {
    options = spec
    spec = undefined
  }
  spec = spec || '*'

  var p = url.parse(spec) || {}

  switch (p.protocol) {
    case 'http:':
    case 'https:':
      return exports.tarball(name, spec, options)
    case "git:":
    case "git+http:":
    case "git+https:":
    case "git+rsync:":
    case "git+ftp:":
    case "git+ssh:":
      return exports.git(name, spec, options)
    default:
      var result = new PassThrough()
      fs.stat(spec, function (err, stat) {
        if (err === null && stat.isDirectory()) {
          exports.local.dir(name, spec, options)
            .on('end', result.end.bind(result))
            .syphon(result)
        } else if (err === null && stat.isFile()) {
          exports.local.file(name, spec, options)
            .on('end', result.end.bind(result))
            .syphon(result)
        } else if (/^([^\/]+)\/([^\/#]+)(?:#(.+))?$/.test(spec)) {
          exports.github(name, spec, options)
            .on('end', result.end.bind(result))
            .syphon(result)
        } else {
          exports.npm(name, spec, options)
            .on('end', result.end.bind(result))
            .syphon(result)
        }
      })
      return result
  }
}
497889
function cloneRepo(item){

      var deferred = Q.defer();
      var repoURL = item.repo;
      var path = item.path;

      deleteOldFiles(path).
      then(function(){
        return performCmd(repoURL, path);
      }).then(function(success){
        return npmInstall(path, success);
      }).then(function(success){
        return bowerInstall(path, success);
      }).then(function(){
        deferred.resolve();
      });

      return deferred.promise;

    }
1318638
function wrap(func) {
      return function wrappedParsePromise() {
        var args = Array.prototype.slice.call(arguments, 0);
        var parsePromise = func.apply(this, args);
        var promise = $q(parsePromise.then.bind(parsePromise));
        wrapParsePromise(promise, parsePromise);
        return promise;
      };
    }
218061
function main (argv, conf) {
  if (!conf.repo) {
    console.error("[Github-Todos] Mandatory option 'repo' not set, where am I supposed to create issues?");
    console.error("[Github-Todos] Run 'github-todos config repo \"<GITHUB USER OR ORG>/<REPOSITORY>\"' to enable hook");
    process.exit(1);
  }

  if (argv.range) {

    // Extract target SHA
    var targetCommit = _.last(argv.range.split(".."));
    return git.run("rev-parse '" + targetCommit + "'").then(function (sha) {
      return analyzeRange(argv.range, sha.trim(), conf);
    });

  } else {

    // Receive git-hook data from stdin
    return new Promise(function (resolve, reject) {
      var analyzing = [];

      process.stdin.on("data", function (chunk) {
        var info = chunk.toString("utf8").split(/\s+/);
        var promise = onCommitRange(info[1], info[3], conf);
        analyzing.push(promise);
      });

      process.stdin.on("close", function () {
        Promise.all(analyzing).then(resolve, reject);
      });
    });

  }
}
890485
function CurlApi (ids, callback, errback, waitFor) {
		var then, ctx;
		ctx = core.createContext(userCfg, undef, [].concat(ids));
		this['then'] = then = function (resolved, rejected) {
			when(ctx,
				// return the dependencies as arguments, not an array
				function (deps) {
					if (resolved) resolved.apply(undef, deps);
				},
				// just throw if the dev didn't specify an error handler
				function (ex) {
					if (rejected) rejected(ex); else throw ex;
				}
			);
			return this;
		};
		this['next'] = function (ids, cb, eb) {
			// chain api
			return new CurlApi(ids, cb, eb, ctx);
		};
		this['config'] = _config;
		if (callback || errback) then(callback, errback);
		when(waitFor, function () { core.getDeps(ctx); });
	}
171244
function promisify(op) {
    var args = slice.call(arguments, 1);
    return new Promise(function(resolver) {
      op.apply(null, args.concat(function(err, value) {
        if(err) {
          resolver.reject(err);
        }
        else {
          resolver.resolve(value);
        }
      }));
    });
  }
79862
function github(url, destination) {
  return new Promise((resolve, reject) => {
    (0, _downloadGithubRepo2.default)(url, destination, err => {
      if (err) {
        reject(err);
      } else {
        resolve();
      }
    });
  });
}
377786
def _map_promise(map_fn, all_inputs):
  """"""
  all_promises = utils.map_nested(map_fn, all_inputs)  # Apply the function
  res = utils.map_nested(_wait_on_promise, all_promises)
  return res
169305
async function initRepo({
  repository,
  endpoint,
  gitPrivateKey,
  gitFs,
  localDir,
}) {
  logger.debug(
    `initRepo("${JSON.stringify(
      { repository, endpoint, gitFs, localDir },
      null,
      2
    )}")`
  );
  const opts = hostRules.find({ platform }, { endpoint });
  // istanbul ignore if
  if (!(opts.username && opts.password)) {
    throw new Error(
      `No username/password found for Bitbucket repository ${repository}`
    );
  }
  // istanbul ignore if
  if (!opts.endpoint) {
    throw new Error(`No endpoint found for Bitbucket Server`);
  }
  hostRules.update({ ...opts, platform, default: true });
  api.reset();

  const [projectKey, repositorySlug] = repository.split('/');
  config = { projectKey, repositorySlug, gitPrivateKey };

  // Always gitFs
  const { host, pathname } = url.parse(opts.endpoint);
  const gitUrl = GitStorage.getUrl({
    gitFs: gitFs || 'https',
    auth: `${opts.username}:${opts.password}`,
    host: `${host}${pathname}${pathname.endsWith('/') ? '' : '/'}scm`,
    repository,
  });

  config.storage = new GitStorage();
  await config.storage.initRepo({
    ...config,
    localDir,
    url: gitUrl,
  });

  const platformConfig = {};

  try {
    const info = (await api.get(
      `./rest/api/1.0/projects/${config.projectKey}/repos/${
        config.repositorySlug
      }`
    )).body;
    platformConfig.privateRepo = info.is_private;
    platformConfig.isFork = !!info.parent;
    platformConfig.repoFullName = info.name;
    config.owner = info.project.key;
    logger.debug(`${repository} owner = ${config.owner}`);
    config.defaultBranch = (await api.get(
      `./rest/api/1.0/projects/${config.projectKey}/repos/${
        config.repositorySlug
      }/branches/default`
    )).body.displayId;
    config.baseBranch = config.defaultBranch;
    config.mergeMethod = 'merge';
  } catch (err) /* istanbul ignore next */ {
    logger.debug(err);
    if (err.statusCode === 404) {
      throw new Error('not-found');
    }
    logger.info({ err }, 'Unknown Bitbucket initRepo error');
    throw err;
  }
  delete config.prList;
  delete config.fileList;
  logger.debug(
    { platformConfig },
    `platformConfig for ${config.projectKey}/${config.repositorySlug}`
  );
  return platformConfig;
}
1220063
function(context, pkg){
		var deps = crawl.getDependencyMap(context.loader, pkg, true);

		var pluginsPromise = crawl.loadPlugins(context, pkg, true, deps, true);
		var stealPromise = crawl.loadSteal(context, pkg, true, deps);

		return Promise.all([pluginsPromise, stealPromise]);
	}
607564
function eval$call(params) {
  var func = typeof params.$call == 'string'
              ? this.getFunc(params.$call)
              : params.$call;
  // TODO params.$args is object
  return Promise.resolve(func.apply(null, params.$args));
}
244393
function pull() {
  var tasks = [],
      cwd = process.cwd();

  findRepos(function(err, repos) {
    if (err) return console.log(err);
    repos.forEach(function(repo) {
      tasks.push(function(done) {
        repo.status(function(err, status) {
          var name = status.repo.path.replace(cwd + '/', '');
          if (!status.clean) {
            console.log('Skipped '.red + name.bold + ' (not clean)'.grey);
            done();
          }
          else {
            console.log('Pulling '.green + name.bold);
            process.chdir(status.repo.path);
            exec('git fetch', function(err, stdout, stderr) {
              if (err) return done(stderr);
              if (stdout && argv.v) console.log(indent(stdout));
              exec('git rebase', function(err, stdout, stderr) {
                if (err) return done(stderr);
                if (stdout && argv.v) console.log(indent(stdout));
                done(null);
              });
            });
          }
        });
      });
    });

    async.series(tasks, function(err, results) {
      if (err) {
        console.log('Error:'.red);
        console.log(err);
      }
      else {
        console.log('Done!');
      }
    });
  });
}
668146
function promisify(f, args) {
  return new Promise((resolve, reject) => f.apply(this, args.concat((err, x) => err ? reject(err) : resolve(x))));
}
969021
function middleware(doIt, req, res) {
  const originalEnd = res.end;

  return new Promise(resolve => {
    res.end = function end(...args) {
      originalEnd.apply(this, args);
      resolve(0);
    };
    doIt(req, res, () => {
      resolve(1);
    });
  });
}