endregion region Compare sources.json with repository
161764
function compare (checkDictionary, path, pathContent) {
        var subPromises = [];
        pathContent.forEach(function (name) {
            var JS_EXT = ".js",
                JS_EXT_LENGTH = JS_EXT.length,
                contentFullName = path + name,
                contentFullNameLength = contentFullName.length;
            if (contentFullNameLength > JS_EXT_LENGTH
                && contentFullName.indexOf(JS_EXT) === contentFullNameLength - JS_EXT_LENGTH) {
                contentFullName = contentFullName.substring(START, contentFullNameLength - JS_EXT_LENGTH);
                if (checkDictionary[contentFullName] === "obsolete") {
                    checkDictionary[contentFullName] = "exists";
                } else {
                    checkDictionary[contentFullName] = "new";
                }
            } else if (name.indexOf(".") === NOT_FOUND) {
                subPromises.push(gpf.http.get("/fs/src/" + contentFullName)
                    .then(function (response) {
                        return JSON.parse(response.responseText);
                    })
                    .then(function (subPathContent) {
                        return compare(checkDictionary, contentFullName + "/", subPathContent);
                    }));
            }
        });
        if (!subPromises.length) {
            return Promise.resolve();
        }
        return Promise.all(subPromises);
    }
719715
function compareVersions(v1, v2) {
    if (semver.gt(v1.tag, v2.tag)) {
        return -1;
    }
    if (semver.lt(v1.tag, v2.tag)) {
        return 1;
    }
    return 0;
}
120279
function (source) {
            packageUrl = source;

            if (source && source.indexOf(bower.config.rhodecode.repo) != -1) {
                return true;
            }

            return Q.nfcall(registryClient.lookup.bind(registryClient), source)
                .then(function (entry) {

                    if (entry && entry.url && entry.url.indexOf(bower.config.rhodecode.repo) != -1) {
                        packageUrl = entry.url;
                        return true
                    }

                    return false;
                });

        }
488995
def get_package_sources(self):
        """"""
        # Checkout local modules
        for config in self.sources.get('local', []):
            self.fetch_local_package(config=config)
        # Checkout S3 repositories specified in config
        for config in self.sources.get('s3', []):
            self.fetch_s3_package(config=config)
        # Checkout git repositories specified in config
        for config in self.sources.get('git', []):
            self.fetch_git_package(config=config)
855296
def diff(other_snapshot)
      endpoint = "/snapshots/#{self.Name}/diff/#{other_snapshot.Name}"
      response = @connection.send(:get, endpoint)
      JSON.parse(response.body)
    end
970455
async function getRepos(token, endpoint) {
  logger.debug('getRepos(token, endpoint)');
  const opts = hostRules.find({ platform: 'bitbucket' }, { token, endpoint });
  // istanbul ignore next
  if (!opts.token) {
    throw new Error('No token found for getRepos');
  }
  hostRules.update({ ...opts, platform: 'bitbucket', default: true });
  try {
    const repos = await utils.accumulateValues(
      `/2.0/repositories/?role=contributor`
    );
    return repos.map(repo => repo.full_name);
  } catch (err) /* istanbul ignore next */ {
    logger.error({ err }, `bitbucket getRepos error`);
    throw err;
  }
}
195598
function checkPackageJson () {
        const pkg = requireFresh(path.join(project, 'package.json'));
        expect(pkg.name).toEqual(appId);
        expect(pkg.displayName).toEqual(appName);
        expect(pkg.version).toEqual(appVersion);
    }
1158590
def fetch_compare(older, newer)
      unless @compares["#{older}...#{newer}"]
        compare_data = check_github_response { @client.compare(user_project, older, newer || "HEAD") }
        raise StandardError, "Sha #{older} and sha #{newer} are not related; please file a github-changelog-generator issues and describe how to replicate this issue." if compare_data["status"] == "diverged"

        @compares["#{older}...#{newer}"] = stringify_keys_deep(compare_data.to_hash)
      end
      @compares["#{older}...#{newer}"]
    end
390831
public int compareSourceLines(BugCollection lhsCollection, BugCollection rhsCollection, SourceLineAnnotation lhs,
            SourceLineAnnotation rhs) {
        if (lhs == null || rhs == null) {
            return compareNullElements(lhs, rhs);
        }

        // Classes must match fuzzily.
        int cmp = compareClassesByName(lhsCollection, rhsCollection, lhs.getClassName(), rhs.getClassName());
        if (cmp != 0) {
            return cmp;
        }

        return 0;
    }
102943
function parseSource( errBuf ) {
	var parsers = {
			monolith: function(){
				return require( './monolith-parser.js' );
			},
			category: function(){
				return require( './category-parser.js' );
			},
			language: function(){
				return require( './language-parser.js' );
			}
		},
		args = argv.parseArgs(),
		file = path.resolve( path.extname( args.file ) ? args.file : args.file + '.json' ),
		source;

	if ( fs.existsSync( file ) ) {
		try {
			source = JSON.parse( fs.readFileSync( file, 'utf8' ) );
		} catch (e) {
			errBuf.push( 'Error (source): wrong format for "' + file + '"' );
			return false;
		} // try..catch

		if ( commons.validateMeta( source.meta || source, errBuf ) ) {
			return parsers[ (source.meta || source).format ]().parse( source, errBuf );
		} // if
	} else {
		errBuf.push( 'Error (source): unable to open "' + file + '"' );
		return false;
	} // if..else
}
125053
def compare(node1, node2):
    """"""
    if not os.path.isdir("a"):
        print("error: comparison feature not initialized", file=sys.stderr)
        sys.exit(4)

    print("=" * 80)
    print("WERKZEUG INTERNAL BENCHMARK -- COMPARE MODE".center(80))
    print("-" * 80)

    def _hg_update(repo, node):
        def hg(*x):
            return subprocess.call(
                ["hg"] + list(x), cwd=repo, stdout=null_out, stderr=null_out
            )

        hg("revert", "-a", "--no-backup")
        client = subprocess.Popen(
            ["hg", "status", "--unknown", "-n", "-0"], stdout=subprocess.PIPE, cwd=repo
        )
        unknown = client.communicate()[0]
        if unknown:
            client = subprocess.Popen(
                ["xargs", "-0", "rm", "-f"],
                cwd=repo,
                stdout=null_out,
                stdin=subprocess.PIPE,
            )
            client.communicate(unknown)
        hg("pull", "../..")
        hg("update", node)
        if node == "tip":
            diff = subprocess.Popen(
                ["hg", "diff"], cwd="..", stdout=subprocess.PIPE
            ).communicate()[0]
            if diff:
                client = subprocess.Popen(
                    ["hg", "import", "--no-commit", "-"],
                    cwd=repo,
                    stdout=null_out,
                    stdin=subprocess.PIPE,
                )
                client.communicate(diff)

    _hg_update("a", node1)
    _hg_update("b", node2)
    d1 = run("a", no_header=True)
    d2 = run("b", no_header=True)

    print("DIRECT COMPARISON".center(80))
    print("-" * 80)
    for key in sorted(d1):
        delta = d1[key] - d2[key]
        if abs(1 - d1[key] / d2[key]) < TOLERANCE or abs(delta) < MIN_RESOLUTION:
            delta = "=="
        else:
            delta = "%+.4f (%+d%%)" % (delta, round(d2[key] / d1[key] * 100 - 100))
        print("%36s   %.4f    %.4f    %s" % (format_func(key), d1[key], d2[key], delta))
    print("-" * 80)
986067
async function initRepo({
  repository,
  token,
  endpoint,
  forkMode,
  forkToken,
  gitPrivateKey,
  gitFs,
  localDir,
  includeForks,
}) {
  logger.debug(`initRepo("${repository}")`);
  const opts = hostRules.find({ platform: 'github' }, { token, endpoint });
  if (!opts.token) {
    throw new Error(`No token found for GitHub repository ${repository}`);
  }
  hostRules.update({ ...opts, platform: 'github', default: true });
  logger.info('Authenticated as user: ' + (await getRenovateUsername()));
  logger.info('Using renovate version: ' + global.renovateVersion);
  // config is used by the platform api itself, not necessary for the app layer to know
  cleanRepo();
  config.isGhe = endpoint && !endpoint.startsWith('https://api.github.com');
  config.localDir = localDir;
  config.platform = 'github';
  config.repository = repository;
  [config.repositoryOwner, config.repositoryName] = repository.split('/');
  config.gitPrivateKey = gitPrivateKey;
  // platformConfig is passed back to the app layer and contains info about the platform they require
  const platformConfig = {};
  let res;
  try {
    res = await get(`repos/${repository}`);
    logger.trace({ repositoryDetails: res.body }, 'Repository details');
    // istanbul ignore if
    if (res.body.fork && gitFs && !includeForks) {
      try {
        const renovateConfig = JSON.parse(
          Buffer.from(
            (await get(
              `repos/${config.repository}/contents/${defaultConfigFile}`
            )).body.content,
            'base64'
          ).toString()
        );
        if (!renovateConfig.includeForks) {
          throw new Error();
        }
      } catch (err) {
        throw new Error('fork');
      }
    }
    // istanbul ignore if
    if (res.body.full_name && res.body.full_name !== repository) {
      logger.info(
        { repository, this_repository: res.body.full_name },
        'Repository has been renamed'
      );
      throw new Error('renamed');
    }
    if (res.body.archived) {
      logger.info(
        'Repository is archived - throwing error to abort renovation'
      );
      throw new Error('archived');
    }
    platformConfig.privateRepo = res.body.private === true;
    platformConfig.isFork = res.body.fork === true;
    const owner = res.body.owner.login;
    logger.debug(`${repository} owner = ${owner}`);
    // Use default branch as PR target unless later overridden.
    config.defaultBranch = res.body.default_branch;
    // Base branch may be configured but defaultBranch is always fixed
    config.baseBranch = config.defaultBranch;
    logger.debug(`${repository} default branch = ${config.baseBranch}`);
    // GitHub allows administrators to block certain types of merge, so we need to check it
    if (res.body.allow_rebase_merge) {
      config.mergeMethod = 'rebase';
    } else if (res.body.allow_squash_merge) {
      config.mergeMethod = 'squash';
    } else if (res.body.allow_merge_commit) {
      config.mergeMethod = 'merge';
    } else {
      // This happens if we don't have Administrator read access, it is not a critical error
      logger.info('Could not find allowed merge methods for repo');
    }
  } catch (err) /* istanbul ignore next */ {
    logger.debug('Caught initRepo error');
    if (err.message === 'archived' || err.message === 'renamed') {
      throw err;
    }
    if (err.statusCode === 403) {
      throw new Error('forbidden');
    }
    if (err.statusCode === 404) {
      throw new Error('not-found');
    }
    if (err.message.startsWith('Repository access blocked')) {
      throw new Error('blocked');
    }
    if (err.message === 'fork') {
      throw err;
    }
    logger.info({ err }, 'Unknown GitHub initRepo error');
    throw err;
  }
  // This shouldn't be necessary, but occasional strange errors happened until it was added
  config.issueList = null;
  config.prList = null;
  config.openPrList = null;
  config.closedPrList = null;
  config.storage = new Storage();
  await config.storage.initRepo(config);
  if (forkMode) {
    logger.info('Bot is in forkMode');
    config.forkToken = forkToken;
    // Save parent SHA then delete
    const parentSha = await getBaseCommitSHA();
    config.baseCommitSHA = null;
    // save parent name then delete
    config.parentRepo = config.repository;
    config.repository = null;
    // Get list of existing repos
    const existingRepos = (await get('user/repos?per_page=100', {
      token: forkToken || opts.token,
      paginate: true,
    })).body.map(r => r.full_name);
    try {
      config.repository = (await get.post(`repos/${repository}/forks`, {
        token: forkToken || opts.token,
      })).body.full_name;
    } catch (err) /* istanbul ignore next */ {
      logger.info({ err }, 'Error forking repository');
      throw new Error('cannot-fork');
    }
    if (existingRepos.includes(config.repository)) {
      logger.info(
        { repository_fork: config.repository },
        'Found existing fork'
      );
      // Need to update base branch
      logger.debug(
        { baseBranch: config.baseBranch, parentSha },
        'Setting baseBranch ref in fork'
      );
      // This is a lovely "hack" by GitHub that lets us force update our fork's master
      // with the base commit from the parent repository
      try {
        await get.patch(
          `repos/${config.repository}/git/refs/heads/${config.baseBranch}`,
          {
            body: {
              sha: parentSha,
              force: true,
            },
            token: forkToken || opts.token,
          }
        );
      } catch (err) /* istanbul ignore next */ {
        if (
          err.statusCode === 422 &&
          err.message.startsWith('Object does not exist')
        ) {
          throw new Error('repository-changed');
        }
      }
    } else {
      logger.info({ repository_fork: config.repository }, 'Created fork');
      // Wait an arbitrary 30s to hopefully give GitHub enough time for forking to complete
      await delay(30000);
    }
    await config.storage.initRepo(config);
  }

  // istanbul ignore if
  if (gitFs) {
    logger.debug('Enabling Git FS');
    let { host } = URL.parse(opts.endpoint);
    if (host === 'api.github.com') {
      host = null;
    }
    host = host || 'github.com';
    const url = GitStorage.getUrl({
      gitFs,
      auth:
        config.forkToken ||
        (global.appMode ? `x-access-token:${opts.token}` : opts.token),
      hostname: host,
      repository: config.repository,
    });
    config.storage = new GitStorage();
    await config.storage.initRepo({
      ...config,
      url,
    });
  }

  return platformConfig;
}
770689
@GwtIncompatible("Unnecessary")
  private List<SourceFile> createSourceInputs(
      List<JsModuleSpec> jsModuleSpecs,
      List<FlagEntry<JsSourceType>> files,
      List<JsonFileSpec> jsonFiles,
      List<String> moduleRoots)
      throws IOException {
    if (isInTestMode()) {
      return inputsSupplierForTesting != null ? inputsSupplierForTesting.get()
          : null;
    }
    if (files.isEmpty() && jsonFiles == null) {
      // Request to read from stdin.
      files = ImmutableList.of(new FlagEntry<JsSourceType>(JsSourceType.JS, "-"));
    }

    for (JSError error : deduplicateIjsFiles(files, moduleRoots, !jsModuleSpecs.isEmpty())) {
      compiler.report(error);
    }

    try {
      if (jsonFiles != null) {
        return createInputs(files, jsonFiles, jsModuleSpecs);
      } else {
        return createInputs(files, true, jsModuleSpecs);
      }
    } catch (FlagUsageException e) {
      throw new FlagUsageException("Bad --js flag. " + e.getMessage());
    }
  }
575418
def repository_has_cookiecutter_json(repo_directory):
    
    repo_directory_exists = os.path.isdir(repo_directory)

    repo_config_exists = os.path.isfile(
        os.path.join(repo_directory, 'cookiecutter.json')
    )
    return repo_directory_exists and repo_config_exists
1147822
function getTypingNamesFromJson(jsonPath, filesToWatch) {
                if (host.fileExists(jsonPath)) {
                    filesToWatch.push(jsonPath);
                }
                var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); });
                if (result.config) {
                    var jsonConfig = result.config;
                    if (jsonConfig.dependencies) {
                        mergeTypings(ts.getOwnKeys(jsonConfig.dependencies));
                    }
                    if (jsonConfig.devDependencies) {
                        mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies));
                    }
                    if (jsonConfig.optionalDependencies) {
                        mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies));
                    }
                    if (jsonConfig.peerDependencies) {
                        mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies));
                    }
                }
            }
232160
@Override
    public Collection<CodeReviewAuditResponse> getPeerReviewResponses(String repoUrl, String repoBranch, String scmName,
                                                                      long beginDt, long endDt) {
        Collector githubCollector = collectorRepository.findByName(!StringUtils.isEmpty(scmName) ? scmName : "GitHub");
        CollectorItem collectorItem = collectorItemRepository.findRepoByUrlAndBranch(githubCollector.getId(), repoUrl, repoBranch, true);

        // This is the list of repos in the database with the same repoUrl, but a different branch.
        List<CollectorItem> filteredCollectorItemList = new ArrayList<>();
        if ((collectorItem != null) && (collectorItem.isPushed())) {
            List<ObjectId> collectorIdList = new ArrayList<>();
            collectorIdList.add(githubCollector.getId());

            Iterable<CollectorItem> collectorItemIterable
                    = collectorItemRepository.findAllByOptionNameValueAndCollectorIdsIn(REPO_URL, repoUrl, collectorIdList);

            for (CollectorItem ci : collectorItemIterable) {
                if (repoBranch.equalsIgnoreCase((String) ci.getOptions().get(BRANCH))) { continue; }

                filteredCollectorItemList.add(ci);
            }

            return codeReviewEvaluatorLegacy.evaluate(collectorItem, filteredCollectorItemList, beginDt, endDt, null);
        }

        return codeReviewEvaluatorLegacy.evaluate(collectorItem, beginDt, endDt, null);
    }
1339644
def as_json(options = {})
      result = self.attributes
      result['organization'] = self.organization.try(:name)
      result['environments'] = environments.map { |e| e.try(:name) }
      result['versions'] = versions.map(&:version)
      result['versions_details'] = versions.map do |v|
        {
          :version => v.version,
          :published => v.created_at.to_s,
          :environments => v.environments.map { |e| e.name }
        }
      end

      if options && options[:environment].present?
        result['repositories'] = repos(options[:environment]).map(&:name)
      end

      result
    end