本文整理匯總了Python中packaging.specifiers.SpecifierSet方法的典型用法代碼示例。如果您正苦於以下問題:Python specifiers.SpecifierSet方法的具體用法?Python specifiers.SpecifierSet怎麽用?Python specifiers.SpecifierSet使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類packaging.specifiers
的用法示例。
在下文中一共展示了specifiers.SpecifierSet方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: Pip6UserAgent
# 需要導入模塊: from packaging import specifiers [as 別名]
# 或者: from packaging.specifiers import SpecifierSet [as 別名]
def Pip6UserAgent(user_agent):
# We're only concerned about pip user agents.
if not user_agent.startswith("pip/"):
raise UnableToParse
# This format was brand new in pip 6.0, so we'll need to restrict it
# to only versions of pip newer than that.
version_str = user_agent.split()[0].split("/", 1)[1]
version = packaging.version.parse(version_str)
if version not in SpecifierSet(">=6", prereleases=True):
raise UnableToParse
try:
return json.loads(user_agent.split(maxsplit=1)[1])
except (json.JSONDecodeError, UnicodeDecodeError, IndexError):
raise UnableToParse from None
示例2: Pip1_4UserAgent
# 需要導入模塊: from packaging import specifiers [as 別名]
# 或者: from packaging.specifiers import SpecifierSet [as 別名]
def Pip1_4UserAgent(*, version, impl_name, impl_version, system_name, system_release):
# This format was brand new in pip 1.4, and went away in pip 6.0, so
# we'll need to restrict it to only versions of pip between 1.4 and 6.0.
if version not in SpecifierSet(">=1.4,<6", prereleases=True):
raise UnableToParse
data = {"installer": {"name": "pip", "version": version}}
if impl_name.lower() != "unknown":
data.setdefault("implementation", {})["name"] = impl_name
if impl_version.lower() != "unknown":
data.setdefault("implementation", {})["version"] = impl_version
if system_name.lower() != "unknown":
data.setdefault("system", {})["name"] = system_name
if system_release.lower() != "unknown":
data.setdefault("system", {})["release"] = system_release
if impl_name.lower() == "cpython":
data["python"] = impl_version
return data
示例3: test_filter
# 需要導入模塊: from packaging import specifiers [as 別名]
# 或者: from packaging.specifiers import SpecifierSet [as 別名]
def test_filter(self):
from packaging.specifiers import SpecifierSet
r = Requirement.parse("Django==1.7.6", 0)
self.assertEqual(r.filter, False)
r = Requirement.parse("Django==1.7.6 # pyup: < 1.7.8", 0)
self.assertEqual(r.filter, SpecifierSet("<1.7.8"))
req = Requirement.parse("some-package==1.9.3 # rq.filter: <1.10 #some comment here", 0)
self.assertEqual(req.filter, SpecifierSet("<1.10"))
r = Requirement.parse("django==1.7.1 # pyup: <1.7.6", 0)
r = Requirement.parse("Django==1.7.6 # pyup: < 1.7.8, > 1.7.2", 0)
self.assertEqual(
sorted([s._spec for s in r.filter._specs], key=lambda r: r[1]),
sorted([("<", "1.7.8"), (">", "1.7.2")], key=lambda r: r[1])
)
r = Requirement.parse("Django==1.7.6 # pyup:< 1.7.8", 0)
self.assertEqual(r.filter, SpecifierSet("<1.7.8"))
示例4: create
# 需要導入模塊: from packaging import specifiers [as 別名]
# 或者: from packaging.specifiers import SpecifierSet [as 別名]
def create(
cls,
project_name, # type: str
target_python=None, # type: Optional[TargetPython]
prefer_binary=False, # type: bool
allow_all_prereleases=False, # type: bool
specifier=None, # type: Optional[specifiers.BaseSpecifier]
hashes=None, # type: Optional[Any]
):
if target_python is None:
target_python = TargetPython()
if specifier is None:
specifier = specifiers.SpecifierSet()
supported_tags = target_python.get_tags()
return cls(
project_name=project_name,
supported_tags=supported_tags,
specifier=specifier,
prefer_binary=prefer_binary,
allow_all_prereleases=allow_all_prereleases,
hashes=hashes,
)
示例5: clean_requires_python
# 需要導入模塊: from packaging import specifiers [as 別名]
# 或者: from packaging.specifiers import SpecifierSet [as 別名]
def clean_requires_python(candidates):
"""Get a cleaned list of all the candidates with valid specifiers in the `requires_python` attributes."""
all_candidates = []
sys_version = ".".join(map(str, sys.version_info[:3]))
from packaging.version import parse as parse_version
py_version = parse_version(os.environ.get("PIP_PYTHON_VERSION", sys_version))
for c in candidates:
requires_python = _get_requires_python(c)
if requires_python:
# Old specifications had people setting this to single digits
# which is effectively the same as '>=digit,<digit+1'
if requires_python.isdigit():
requires_python = ">={0},<{1}".format(
requires_python, int(requires_python) + 1
)
try:
specifierset = SpecifierSet(requires_python)
except InvalidSpecifier:
continue
else:
if not specifierset.contains(py_version):
continue
all_candidates.append(c)
return all_candidates
示例6: fix_requires_python_marker
# 需要導入模塊: from packaging import specifiers [as 別名]
# 或者: from packaging.specifiers import SpecifierSet [as 別名]
def fix_requires_python_marker(requires_python):
from packaging.requirements import Requirement as PackagingRequirement
marker_str = ""
if any(requires_python.startswith(op) for op in Specifier._operators.keys()):
spec_dict = defaultdict(set)
# We are checking first if we have leading specifier operator
# if not, we can assume we should be doing a == comparison
specifierset = list(SpecifierSet(requires_python))
# for multiple specifiers, the correct way to represent that in
# a specifierset is `Requirement('fakepkg; python_version<"3.0,>=2.6"')`
marker_key = Variable("python_version")
for spec in specifierset:
operator, val = spec._spec
cleaned_val = Value(val).serialize().replace('"', "")
spec_dict[Op(operator).serialize()].add(cleaned_val)
marker_str = " and ".join(
[
"{0}{1}'{2}'".format(marker_key.serialize(), op, ",".join(vals))
for op, vals in spec_dict.items()
]
)
marker_to_add = PackagingRequirement("fakepkg; {0}".format(marker_str)).marker
return marker_to_add
示例7: get_versions
# 需要導入模塊: from packaging import specifiers [as 別名]
# 或者: from packaging.specifiers import SpecifierSet [as 別名]
def get_versions(specset, group_by_operator=True):
# type: (Union[Set[Specifier], SpecifierSet], bool) -> List[Tuple[STRING_TYPE, STRING_TYPE]]
specs = [_get_specs(x) for x in list(tuple(specset))]
initial_sort_key = lambda k: (k[0], k[1])
initial_grouping_key = operator.itemgetter(0)
if not group_by_operator:
initial_grouping_key = operator.itemgetter(1)
initial_sort_key = operator.itemgetter(1)
version_tuples = sorted(
set((op, version) for spec in specs for op, version in spec), key=initial_sort_key
)
version_tuples = [fix_version_tuple(t) for t in version_tuples]
op_groups = [
(grp, list(map(operator.itemgetter(1), keys)))
for grp, keys in itertools.groupby(version_tuples, key=initial_grouping_key)
]
versions = [
(op, packaging.version.parse(".".join(str(v) for v in val)))
for op, vals in op_groups
for val in vals
]
return sorted(versions, key=operator.itemgetter(1))
示例8: read_spec
# 需要導入模塊: from packaging import specifiers [as 別名]
# 或者: from packaging.specifiers import SpecifierSet [as 別名]
def read_spec(lines):
candidates = {}
latest = None
for line in lines:
if not line or line.startswith("#"):
continue
if not line.startswith(" "):
name, version = splitstrip(line, 2)
version = Version(version)
latest = Candidate(name, version)
candidates[latest] = set()
else:
if latest is None:
raise RuntimeError(
"Spec has dependencies before first candidate"
)
name, specifier = splitstrip(line, 2)
specifier = SpecifierSet(specifier)
candidates[latest].add(Requirement(name, specifier))
return candidates
示例9: test_pipfile
# 需要導入模塊: from packaging import specifiers [as 別名]
# 或者: from packaging.specifiers import SpecifierSet [as 別名]
def test_pipfile():
content = """[[source]]
url = "http://some.pypi.mirror.server.org/simple"
verify_ssl = false
name = "pypi"
[packages]
django = "==2.0"
djangorestframework = "*"
django-allauth = "*"
[dev-packages]
toml = "*"
"""
dep_file = parse(content, file_type=filetypes.pipfile)
assert len(dep_file.dependencies) == 4
assert dep_file.dependencies[0].name == 'django'
assert dep_file.dependencies[0].specs == SpecifierSet('==2.0')
assert dep_file.dependencies[1].name == 'djangorestframework'
assert dep_file.dependencies[1].specs == SpecifierSet()
示例10: initialize_plugin
# 需要導入模塊: from packaging import specifiers [as 別名]
# 或者: from packaging.specifiers import SpecifierSet [as 別名]
def initialize_plugin(self) -> None:
"""
Initialize the plugin reading version ranges from the config.
"""
try:
config: SectionProxy = self.configuration[
"version_range_release_file_metadata"
]
except KeyError:
return
else:
if not self.initilized:
for k in config:
# self.specifiers[k] = SpecifierSet(config[k])
self.specifiers[k] = [
parse(ver) for ver in config[k].split("\n") if ver
]
logger.info(
f"Initialized version_range_release_file_metadata plugin with {self.specifiers}" # noqa: E501
)
self.initilized = True
示例11: merge_dependencies
# 需要導入模塊: from packaging import specifiers [as 別名]
# 或者: from packaging.specifiers import SpecifierSet [as 別名]
def merge_dependencies(dep1: Dependencies, dep2: Dependencies) -> Dependencies:
"""
Merge two groups of dependencies.
If some of them are not "simple" (see above), we just filter them out.
:param dep1: the first operand
:param dep2: the second operand.
:return: the merged dependencies.
"""
result: Dependencies
result = {pkg_name: info for pkg_name, info in dep1.items() if is_simple_dep(info)}
for pkg_name, info in dep2.items():
if not is_simple_dep(info):
continue
new_specifier = SpecifierSet(info.get("version", ""))
old_specifier = SpecifierSet(result.get(pkg_name, {}).get("version", ""))
combined_specifier = and_(new_specifier, old_specifier)
result[pkg_name] = {"version": str(combined_specifier)}
return result
示例12: pin_dependencies
# 需要導入模塊: from packaging import specifiers [as 別名]
# 或者: from packaging.specifiers import SpecifierSet [as 別名]
def pin_dependencies(self, include_extras=None):
# type: (Optional[List[str]]) -> Tuple[List["Package"], Dict[str, List[SpecifierSet]]]
deps = []
if include_extras:
include_extras = list(sorted(set(include_extras)))
else:
include_extras = []
constraints = defaultdict(list)
for dep in self.dependencies:
if dep.from_extras and dep.from_extras not in include_extras:
continue
if dep.specifier:
constraints[dep.name].append(dep.specifier)
try:
pinned = dep.pin()
except requests.exceptions.HTTPError:
continue
deps.append(pinned)
return deps, constraints
示例13: parse_requirement
# 需要導入模塊: from packaging import specifiers [as 別名]
# 或者: from packaging.specifiers import SpecifierSet [as 別名]
def parse_requirement(text):
"""
Parse a requirement such as 'foo>=1.0'.
Returns a (name, specifier) named tuple.
"""
from packaging.specifiers import SpecifierSet
match = REQUIREMENT_RE.match(text)
if not match:
raise ValueError("Invalid requirement: %s" % text)
name = match.group('name').strip()
spec = SpecifierSet(match.group('specifier') or '')
return Requirement(name, spec)
示例14: __init__
# 需要導入模塊: from packaging import specifiers [as 別名]
# 或者: from packaging.specifiers import SpecifierSet [as 別名]
def __init__(self, name, specs, line, lineno, extras, file_type):
self.name = name
self.key = name.lower()
self.specs = specs
self.line = line
self.lineno = lineno
self.index_server = None
self.extras = extras
self.pull_request = None
self.hashes = []
self._fetched_package = False
self._package = None
self.file_type = file_type
self.pipfile = None
self.hashCmp = (
self.key,
self.specs,
frozenset(self.extras),
)
self._is_insecure = None
self._changelog = None
if len(self.specs._specs) == 1 and next(iter(self.specs._specs))._spec[0] == "~=":
# convert compatible releases to something more easily consumed,
# e.g. '~=1.2.3' is equivalent to '>=1.2.3,<1.3.0', while '~=1.2'
# is equivalent to '>=1.2,<2.0'
min_version = next(iter(self.specs._specs))._spec[1]
max_version = list(parse_version(min_version).release)
max_version[-1] = 0
max_version[-2] = max_version[-2] + 1
max_version = '.'.join(str(x) for x in max_version)
self.specs = SpecifierSet('>=%s,<%s' % (min_version, max_version))
示例15: version
# 需要導入模塊: from packaging import specifiers [as 別名]
# 或者: from packaging.specifiers import SpecifierSet [as 別名]
def version(self):
if self.is_pinned:
return next(iter(self.specs._specs))._spec[1]
specs = self.specs
if self.filter:
specs = SpecifierSet(
",".join(["".join(s._spec) for s in list(specs._specs) + list(self.filter._specs)])
)
return self.get_latest_version_within_specs(
specs,
versions=self.package.versions,
prereleases=self.prereleases
)