"""
This module represents the various types of requirement that can be specified for
a project. It is somewhat redundant to re-implement here as we could use
`pip.req.InstallRequirement`, but that would require depending on pip which is not
easy to do since it will usually be installed by the user at a specific version.
Additionally, the pip implementation has a lot of extra features that we don't need -
we don't expect relative file paths to exist, for example. Note that the parsing here
is also intentionally more lenient - it is not our job to validate the requirements
list.
"""
import os
import re
from pathlib import Path
from typing import Optional
from urllib import parse
from packaging.requirements import Requirement
def _is_filepath(req):
# this is (probably) a file
return os.path.sep in req or req.startswith(".")
def _parse_egg_name(url_fragment):
"""
>>> _parse_egg_name('egg=fish&cake=lala')
fish
>>> _parse_egg_name('something_spurious')
None
"""
if "=" not in url_fragment:
return None
parts = parse.parse_qs(url_fragment)
if "egg" not in parts:
return None
return parts["egg"][0] # taking the first value mimics pip's behaviour
def _strip_fragment(urlparts):
new_urlparts = (
urlparts.scheme,
urlparts.netloc,
urlparts.path,
urlparts.params,
urlparts.query,
None,
)
return parse.urlunparse(new_urlparts)
class DetectedRequirement:
def __init__(
self, name: str = None, url: str = None, requirement: Requirement = None, location_defined: Path = None
):
if requirement is not None:
self.name = requirement.name
self.requirement = requirement
self.version_specs = [(s.operator, s.version) for s in requirement.specifier]
self.url = None
else:
self.name = name
self.version_specs = []
self.url = url
self.requirement = None
self.location_defined = location_defined
def _format_specs(self) -> str:
return ",".join(["%s%s" % (comp, version) for comp, version in self.version_specs])
def pip_format(self) -> str:
if self.url:
if self.name:
return "%s#egg=%s" % (self.url, self.name)
return self.url
if self.name:
if self.version_specs:
return "%s%s" % (self.name, self._format_specs())
return self.name
raise ValueError(f"Cannot convert {self} to pip format, no name or URL")
def __str__(self):
rep = self.name or "Unknown"
if self.version_specs:
specs = ",".join(["%s%s" % (comp, ver) for comp, ver in self.version_specs])
rep = "%s%s" % (rep, specs)
if self.url:
rep = "%s (%s)" % (rep, self.url)
return rep
def __hash__(self):
return hash(str(self.name) + str(self.url) + str(self.version_specs))
def __repr__(self):
return "