Convert a Bitbucket PR to a PR representation
@param {BitbucketServerPullRequest} bbPr - the API response from a Bitbucket API looking for a PR
@returns {PullRequest} a pull request in standard format
190495
function convertPr (bbPr) {
  return {
    description: bbPr.description,
    headSha: bbPr.fromRef.latestCommit,
    number: bbPr.id,
    url: bbPr.links.self[0].href
  }
}
856899
function get(id, callback) {
        _getSHA(id, function(err, sha) {
            if (err) return callback(err);
            repo.git.blobs(sha).fetch(function(err, res) {
                if (err) return callback(err);
                callback(err, JSON.parse(atob(res.content)));
            });
        });
    }
1061602
function () {
    const oThis = this;

    return oThis.asyncPerform()
      .catch(function (error) {
        if (responseHelper.isCustomResult(error)) {
          return error;
        } else {
          logger.error('openst-platform::services/approve/branded_token.js::perform::catch');
          logger.error(error);

          return responseHelper.error({
            internal_error_identifier: 's_a_bt_1',
            api_error_identifier: 'unhandled_error',
            error_config: basicHelper.fetchErrorConfig()
          });
        }
      });
  }
93942
function getAuthToken () {
  console.log('You have hit the rate limit for unauthenticated requests, please log in to raise your rate limit:\n'.red);

  program.prompt('GitHub Username: ', function (user) {

    console.log('\nAfter entering your password, hit return' + ' twice.\n'.green);
    var authProcess = spawn('curl', [
      '-u',
      user,
      '-d',
      '{"scopes":["repo"],"note":"mdlint"}',
      '-s',
      'https://api.github.com/authorizations'
    ], {
      stdio: [process.stdin, 'pipe', process.stderr]
    });

    authProcess.stdout.setEncoding('utf8');
    authProcess.stdout.on('data', function (data) {
      var response = JSON.parse(data);
      if (response.message) {
        console.log(response.message.red + '\n');
        process.exit();
      } else {
        fs.writeFileSync(tokenFile, response.token);
        console.log('Authenticated :). Now try your lint again. \n'.green);
        process.exit();
      }
    });
  });
}
782903
async function getPrFiles(prNo) {
  logger.debug(`getPrFiles(${prNo})`);
  if (!prNo) {
    return [];
  }

  // GET /rest/api/1.0/projects/{projectKey}/repos/{repositorySlug}/pull-requests/{pullRequestId}/changes
  const values = await utils.accumulateValues(
    `./rest/api/1.0/projects/${config.projectKey}/repos/${
      config.repositorySlug
    }/pull-requests/${prNo}/changes?withComments=false`
  );
  return values.map(f => f.path.toString);
}
1311930
function getPinDateMapFromBoardRssGetResponse(response, board, callback) {
    parseString(response, function (err, result) {
        if (err) {
            // Don't throw because pinterest either does not have RSS feeds for boards with special characters
            // or we just haven't been able to figure out how they are handling special characters.
            // Either way, the response will be HTML in predictable cases like this, so we don't want to throw.
            console.error('Error getting RSS feed for board ' + board + '. Unable to retrieve publish dates. This is expected to happen if the board name contains an escaped character');
            callback({});
            return;
        }
        callback(createPinDateMapFromRssXmlObject(result));
        return;
    });
}
586973
function requireAuthorization(handler) {
  return function(request, response, store, parameters) {
    var handlerArguments = arguments
    var publisher = parameters.publisher
    var authorization = request.headers.authorization
    if (authorization) {
      var parsed = parseAuthorization(authorization)
      if (parsed === false || parsed.user !== publisher) {
        respond401(response) }
      else {
        checkPassword(publisher, parsed.password, function(error, valid) {
          if (error) {
            respond500(request, response, error) }
          else {
            if (valid) {
              handler.apply(this, handlerArguments) }
            else {
              respond401(response) } } }) } }
    else {
      respond401(response) } } }
95760
function (bidRequests, bidderRequest) {
    let normalizedBids = bidRequests.map((bidRequest) => {
      return getNormalizedBidRequest(bidRequest);
    });

    let idClient = new ImproveDigitalAdServerJSClient('hb');
    let requestParameters = {
      singleRequestMode: (config.getConfig('improvedigital.singleRequest') === true),
      returnObjType: idClient.CONSTANTS.RETURN_OBJ_TYPE.URL_PARAMS_SPLIT,
      libVersion: this.version
    };

    if (bidderRequest && bidderRequest.gdprConsent && bidderRequest.gdprConsent.consentString) {
      requestParameters.gdpr = bidderRequest.gdprConsent.consentString;
    }

    let requestObj = idClient.createRequest(
      normalizedBids, // requestObject
      requestParameters
    );

    if (requestObj.errors && requestObj.errors.length > 0) {
      utils.logError('ID WARNING 0x01');
    }

    return requestObj.requests;
  }
800050
function getDiffForPR(pr) {
  print(['Get diff for PR ', clc.yellow.bold(`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`)], debug);
  return new Promise((resolve) => {
    github.repos.compareCommits({
      user: pr.head.user.login,
      repo: pr.head.repo.name,
      head: pr.head.ref,
      base: pr.base.ref
    }, (err, diff) => {
      if (err && debug) {
        print(['Error fetching diffs for PR ', clc.red.bold`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`], debug);
      }
      diff.user = pr.head.user.login;
      diff.repo = pr.head.repo.name;
      diff.title = pr.title;
      diff.number = pr.number;
      diff.link = pr._links.html.href;
      diff.createdAt = pr.created_at;
      diff.createdAt = pr.updated_at;
      diff.labels = pr.labels;
      return resolve(extractDiffData(diff));
    });
  });
}
625629
function pullcatalog(opts, cb) {
  opts.path = APIM_CATALOG_ENDP +
              '?' + // filter parms
              APIM_CLIENT_ID_EQ + opts.clientid + '&' +
              APIM_TYPE_EQ + APIM_TYPE_FILTER;
  opts.prefix = 'catalogs-';
  opts.suffix = '.json';
  fetch(opts, function(err, result) {
    if (err) {
      cb(err);
    } else if (typeof result === 'object') {
      response.catalogs = result.file;
      var models = [];
      models.push(new ModelType('products', 'products-', APIM_PRODUCTS_ENDP));
      models.push(new ModelType('apis', 'apis-', APIM_APIS_ENDP));
      models.push(new ModelType('subscriptions', 'subs-', APIM_SUBS_ENDP));
      models.push(new ModelType('tlsprofiles', 'tlsprofs-', APIM_TLS_ENDP));
      models.push(new ModelType('registries', 'registries-', APIM_REGISTRIES_ENDP));
      models.forEach(
        function(model) {
          response[model.name] = [];
        }
      );
      var catalogsJSON;
      try {
        catalogsJSON = JSON.parse(result.contents);
      } catch (e) {
        cb(e);
        return;
      }
      var catalogs = [];
      catalogsJSON.forEach(function(obj) {
        catalogs.push({
          org: obj.organization.id,
          cat: obj.id });
      });
      cb(null, catalogs, models);
    } else {
      var error = new Error('Unexpected type returned from catalog fetch');
      cb(error);
    }
  });
}
545986
function(validBidRequests, bidderRequest) {
    return validBidRequests.map(bidRequest => {
      let gjid = Math.floor(Math.random() * 99999999);
      let sizes = generateSizeParam(bidRequest.sizes);
      let configId = bidRequest.params.placementId || '';
      let minCPM = bidRequest.params.minCPM || 0.0;
      let minCPC = bidRequest.params.minCPC || 0.0;
      let allowExplicit = bidRequest.params.explicit || 0;
      const body = {
        gjid: gjid,
        sizes: sizes,
        configId: configId,
        minCPM: minCPM,
        minCPC: minCPC,
        allowExplicit: allowExplicit,
        referrer: utils.getTopWindowUrl(),
        requestid: bidRequest.bidderRequestId,
        bidid: bidRequest.bidId
      };
      if (document.referrer) {
        body.referrer = document.referrer;
      }
      if (bidderRequest && bidderRequest.gdprConsent) {
        body.consent_string = bidderRequest.gdprConsent.consentString;
        body.consent_required = (typeof bidderRequest.gdprConsent.gdprApplies === 'boolean') ? bidderRequest.gdprConsent.gdprApplies : true;
      }
      return {
        method: 'GET',
        url: ENDPOINT_URL,
        data: body
      };
    });
  }
630743
async function saveAsPullRequest(chainedResult) {
	const {owner, repo, title, branch, message} = chainedResult
	//probably want to write in the cwrc-git /// application tag,
	const doesBranchExist = await checkForBranch({owner, repo, branch});
	if (! doesBranchExist) {
		await createBranchFromMaster({owner, repo, branch})
	}
	const resultOfSave = await saveDoc(chainedResult)
	const doesPullRequestExist = await checkForPullRequest({owner, repo, branch})
	// there can be only one PR per branch */
	if (! doesPullRequestExist) {
		const prArgs = {
			owner,
			repo,
			title,
			head: branch,
			base: 'master',
			body: message
		}
		const prResult = await github.pullRequests.create(prArgs)
	}

	return {...chainedResult, sha: resultOfSave.sha}
}
687318
function makeRequest(params) {
    var QPromiseFactory = function(resolver) {
      return q.Promise(resolver);
    };
    params.retryStrategy = loggingRetryStrategy;
    params.promiseFactory = QPromiseFactory;
    return request(params)
      .then(function (response) {
        if (response.statusCode !== 200) {
          throw new Error('HTTP error (' + response.statusCode + ')');
        }
        return response.body;
      })
      .fail(function (error) {
        throw new WrapperError([
          params.method,
          params.url,
          'failed.'
        ].join(' '), error);
      });
  }
112983
function getBrClientRect(brNode) {
        var doc = brNode.ownerDocument,
          rng = createRange(doc),
          nbsp = doc.createTextNode('\u00a0'),
          parentNode = brNode.parentNode,
          clientRect;

        parentNode.insertBefore(nbsp, brNode);
        rng.setStart(nbsp, 0);
        rng.setEnd(nbsp, 1);
        clientRect = ClientRect.clone(rng.getBoundingClientRect());
        parentNode.removeChild(nbsp);

        return clientRect;
      }
472521
async function getPr(prNo) {
  const pr = (await api.get(
    `/2.0/repositories/${config.repository}/pullrequests/${prNo}`
  )).body;

  // istanbul ignore if
  if (!pr) {
    return null;
  }

  const res = {
    displayNumber: `Pull Request #${pr.id}`,
    ...utils.prInfo(pr),
  };

  if (utils.prStates.open.includes(pr.state)) {
    res.isConflicted = await isPrConflicted(prNo);
    const commits = await utils.accumulateValues(pr.links.commits.href);
    if (commits.length === 1) {
      res.canRebase = true;
    }
  }
  if (await branchExists(pr.source.branch.name)) {
    res.isStale = await isBranchStale(pr.source.branch.name);
  }

  return res;
}
278539
private static BinaryMemcacheRequest handleReplicaGetRequest(final ReplicaGetRequest msg) {
        byte[] key = msg.keyBytes();
        short keyLength = (short) key.length;
        BinaryMemcacheRequest request = new DefaultBinaryMemcacheRequest(key);

        request.setOpcode(OP_GET_REPLICA)
            .setKeyLength(keyLength)
            .setTotalBodyLength(keyLength);
        return request;
    }
442266
async function ensurePr(prConfig) {
  const config = { ...prConfig };

  logger.trace({ config }, 'ensurePr');
  // If there is a group, it will use the config of the first upgrade in the array
  const { branchName, prTitle, upgrades } = config;
  // Check if existing PR exists
  const existingPr = await platform.getBranchPr(branchName);
  if (existingPr) {
    logger.debug('Found existing PR');
  }
  config.upgrades = [];

  if (config.artifactErrors && config.artifactErrors.length) {
    logger.debug('Forcing PR because of artifact errors');
    config.forcePr = true;
  }

  let branchStatus;
  async function getBranchStatus() {
    if (!branchStatus) {
      branchStatus = await platform.getBranchStatus(
        branchName,
        config.requiredStatusChecks
      );
      logger.debug({ branchStatus, branchName }, 'getBranchStatus() result');
    }
    return branchStatus;
  }

  // Only create a PR if a branch automerge has failed
  if (
    config.automerge === true &&
    config.automergeType.startsWith('branch') &&
    !config.forcePr
  ) {
    logger.debug(
      `Branch is configured for branch automerge, branch status) is: ${await getBranchStatus()}`
    );
    if (
      (await getBranchStatus()) === 'pending' ||
      (await getBranchStatus()) === 'running'
    ) {
      logger.debug('Checking how long this branch has been pending');
      const lastCommitTime = await platform.getBranchLastCommitTime(branchName);
      const currentTime = new Date();
      const millisecondsPerHour = 1000 * 60 * 60;
      const elapsedHours = Math.round(
        (currentTime.getTime() - lastCommitTime.getTime()) / millisecondsPerHour
      );
      if (elapsedHours >= config.prNotPendingHours) {
        logger.info('Branch exceeds prNotPending hours - forcing PR creation');
        config.forcePr = true;
      }
    }
    if (config.forcePr || (await getBranchStatus()) === 'failure') {
      logger.debug(`Branch tests failed, so will create PR`);
    } else {
      return null;
    }
  }
  if (config.prCreation === 'status-success') {
    logger.debug('Checking branch combined status');
    if ((await getBranchStatus()) !== 'success') {
      logger.debug(
        `Branch status is "${await getBranchStatus()}" - not creating PR`
      );
      return null;
    }
    logger.debug('Branch status success');
  } else if (
    config.prCreation === 'not-pending' &&
    !existingPr &&
    !config.forcePr
  ) {
    logger.debug('Checking branch combined status');
    if (
      (await getBranchStatus()) === 'pending' ||
      (await getBranchStatus()) === 'running'
    ) {
      logger.debug(
        `Branch status is "${await getBranchStatus()}" - checking timeout`
      );
      const lastCommitTime = await platform.getBranchLastCommitTime(branchName);
      const currentTime = new Date();
      const millisecondsPerHour = 1000 * 60 * 60;
      const elapsedHours = Math.round(
        (currentTime.getTime() - lastCommitTime.getTime()) / millisecondsPerHour
      );
      if (elapsedHours < config.prNotPendingHours) {
        logger.debug(
          `Branch is ${elapsedHours} hours old - skipping PR creation`
        );
        return null;
      }
      logger.debug(
        `prNotPendingHours=${
          config.prNotPendingHours
        } threshold hit - creating PR`
      );
    }
    logger.debug('Branch status success');
  }

  const processedUpgrades = [];
  const commitRepos = [];

  // Get changelog and then generate template strings
  for (const upgrade of upgrades) {
    const upgradeKey = `${upgrade.depType}-${upgrade.depName}-${
      upgrade.manager
    }-${upgrade.fromVersion || upgrade.currentValue}-${upgrade.toVersion}`;
    if (processedUpgrades.includes(upgradeKey)) {
      continue; // eslint-disable-line no-continue
    }
    processedUpgrades.push(upgradeKey);
    upgrade.hasUrls = !!(upgrade.sourceUrl || upgrade.homepage);

    const logJSON = await changelogHelper.getChangeLogJSON({
      manager: upgrade.manager,
      versionScheme: upgrade.versionScheme,
      depType: upgrade.depType,
      depName: upgrade.depName,
      fromVersion: upgrade.fromVersion,
      toVersion: upgrade.toVersion,
      sourceUrl: upgrade.sourceUrl,
      releases: upgrade.releases,
    });

    if (logJSON) {
      upgrade.githubName = logJSON.project ? logJSON.project.github : undefined;
      upgrade.hasReleaseNotes = logJSON.hasReleaseNotes;
      upgrade.releases = [];
      if (
        upgrade.hasReleaseNotes &&
        upgrade.githubName &&
        !commitRepos.includes(upgrade.githubName)
      ) {
        commitRepos.push(upgrade.githubName);
        logJSON.versions.forEach(version => {
          const release = { ...version };
          upgrade.releases.push(release);
        });
      }
    }
    config.upgrades.push(upgrade);
  }

  // Update the config object
  Object.assign(config, upgrades[0]);
  config.hasReleaseNotes = config.upgrades.some(upg => upg.hasReleaseNotes);

  const releaseNoteRepos = [];
  for (const upgrade of config.upgrades) {
    if (upgrade.hasReleaseNotes) {
      if (releaseNoteRepos.includes(upgrade.sourceUrl)) {
        logger.debug(
          { depName: upgrade.depName },
          'Removing duplicate release notes'
        );
        upgrade.hasReleaseNotes = false;
      } else {
        releaseNoteRepos.push(upgrade.sourceUrl);
      }
    }
  }

  const prBody = await getPrBody(config);

  try {
    if (existingPr) {
      logger.debug('Processing existing PR');
      // istanbul ignore if
      if (
        config.automerge &&
        ['failure', 'error', 'failed'].includes(await getBranchStatus())
      ) {
        logger.debug(`Setting assignees and reviewers as status checks failed`);
        await addAssigneesReviewers(config, existingPr);
      }
      // Check if existing PR needs updating
      const reviewableIndex = existingPr.body.indexOf(
        '<!-- Reviewable:start -->'
      );
      let existingPrBody = existingPr.body;
      if (reviewableIndex > -1) {
        logger.debug('Stripping Reviewable content');
        existingPrBody = existingPrBody.slice(0, reviewableIndex);
      }
      existingPrBody = existingPrBody.trim();
      if (
        existingPr.title === prTitle &&
        noWhitespace(existingPrBody) === noWhitespace(prBody)
      ) {
        logger.debug(`${existingPr.displayNumber} does not need updating`);
        return existingPr;
      }
      // PR must need updating
      if (existingPr.title !== prTitle) {
        logger.info(
          {
            branchName,
            oldPrTitle: existingPr.title,
            newPrTitle: prTitle,
          },
          'PR title changed'
        );
      } else if (!config.committedFiles) {
        logger.debug(
          {
            prTitle,
            oldPrBody: existingPrBody,
            newPrBody: prBody,
          },
          'PR body changed'
        );
      }
      // istanbul ignore if
      if (config.dryRun) {
        logger.info('DRY-RUN: Would update PR #' + existingPr.number);
      } else {
        await platform.updatePr(existingPr.number, prTitle, prBody);
        logger.info(
          { committedFiles: config.committedFiles, pr: existingPr.number },
          `PR updated`
        );
      }
      return existingPr;
    }
    logger.debug({ branch: branchName, prTitle }, `Creating PR`);
    // istanbul ignore if
    if (config.updateType === 'rollback') {
      logger.info('Creating Rollback PR');
    }
    let pr;
    try {
      // istanbul ignore if
      if (config.dryRun) {
        logger.info('DRY-RUN: Would create PR: ' + prTitle);
        pr = { number: 0, displayNumber: 'Dry run PR' };
      } else {
        pr = await platform.createPr(
          branchName,
          prTitle,
          prBody,
          config.labels,
          false,
          config.statusCheckVerify
        );
        logger.info({ branch: branchName, pr: pr.number }, 'PR created');
      }
    } catch (err) /* istanbul ignore next */ {
      if (err.message === 'Validation Failed (422)') {
        logger.info({ branch: branchName }, 'Deleting invalid branch');
        // istanbul ignore if
        if (config.dryRun) {
          logger.info('DRY-RUN: Would delete branch: ' + config.branchName);
        } else {
          await platform.deleteBranch(branchName);
        }
        return null;
      }
      logger.warn({ err }, `Failed to create PR`);
      if (err.statusCode === 502) {
        logger.info(
          { branch: branchName },
          'Deleting branch due to server error'
        );
        // istanbul ignore if
        if (config.dryRun) {
          logger.info('DRY-RUN: Would delete branch: ' + config.branchName);
        } else {
          await platform.deleteBranch(branchName);
        }
      }
      return null;
    }
    if (
      config.branchAutomergeFailureMessage &&
      !config.suppressNotifications.includes('branchAutomergeFailure')
    ) {
      const subject = 'Branch automerge failure';
      let content =
        'This PR was configured for branch automerge, however this is not possible so it has been raised as a PR instead.';
      if (config.branchAutomergeFailureMessage === 'branch status error') {
        content += '\n___\n * Branch has one or more failed status checks';
      }
      logger.info('Adding branch automerge failure message to PR');
      // istanbul ignore if
      if (config.dryRun) {
        logger.info('Would add comment to PR #' + pr.number);
      } else {
        await platform.ensureComment(pr.number, subject, content);
      }
    }
    // Skip assign and review if automerging PR
    if (
      config.automerge &&
      !['failure', 'error', 'failed'].includes(await getBranchStatus())
    ) {
      logger.debug(
        `Skipping assignees and reviewers as automerge=${config.automerge}`
      );
    } else {
      await addAssigneesReviewers(config, pr);
    }
    logger.info(`Created ${pr.displayNumber}`);
    return pr;
  } catch (err) {
    // istanbul ignore if
    if (
      err.message === 'repository-changed' ||
      err.message === 'rate-limit-exceeded' ||
      err.message === 'platform-failure' ||
      err.message === 'integration-unauthorized'
    ) {
      logger.debug('Passing error up');
      throw err;
    }
    logger.error({ err }, 'Failed to ensure PR:', err);
  }
  return null;
}