'Try to find a Link matching req
Expects req, an InstallRequirement and upgrade, a boolean
Returns a Link if found,
Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise'

def find_requirement(self, req, upgrade):

    all_candidates = self.find_all_candidates(req.name)
    compatible_versions = set(req.specifier.filter([str(c.version) for c in all_candidates], prereleases=(self.allow_all_prereleases if self.allow_all_prereleases else None)))
    applicable_candidates = [c for c in all_candidates if (str(c.version) in compatible_versions)]
    if applicable_candidates:
        best_candidate = max(applicable_candidates, key=self._candidate_sort_key)
    else:
        best_candidate = None
    if (req.satisfied_by is not None):
        installed_version = parse_version(req.satisfied_by.version)
    else:
        installed_version = None
    if ((installed_version is None) and (best_candidate is None)):
        logger.critical('Could    not    find    a    version    that    satisfies    the    requirement    %s    (from    versions:    %s)', req, ',    '.join(sorted(set((str(c.version) for c in all_candidates)), key=parse_version)))
        raise DistributionNotFound(('No    matching    distribution    found    for    %s' % req))
    best_installed = False
    if (installed_version and ((best_candidate is None) or (best_candidate.version <= installed_version))):
        best_installed = True
    if ((not upgrade) and (installed_version is not None)):
        if best_installed:
            logger.debug('Existing    installed    version    (%s)    is    most    up-to-date    and    satisfies    requirement', installed_version)
        else:
            logger.debug('Existing    installed    version    (%s)    satisfies    requirement    (most    up-to-date    version    is    %s)', installed_version, best_candidate.version)
        return None
    if best_installed:
        logger.debug('Installed    version    (%s)    is    most    up-to-date    (past    versions:    %s)', installed_version, (',    '.join(sorted(compatible_versions, key=parse_version)) or 'none'))
        raise BestVersionAlreadyInstalled
    logger.debug('Using    version    %s    (newest    of    versions:    %s)', best_candidate.version, ',    '.join(sorted(compatible_versions, key=parse_version)))
    return best_candidate.location
