Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/distlib/markers.py: 77%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# -*- coding: utf-8 -*-
2#
3# Copyright (C) 2012-2023 Vinay Sajip.
4# Licensed to the Python Software Foundation under a contributor agreement.
5# See LICENSE.txt and CONTRIBUTORS.txt.
6#
7"""
8Parser for the environment markers micro-language defined in PEP 508.
9"""
11# Note: In PEP 345, the micro-language was Python compatible, so the ast
12# module could be used to parse it. However, PEP 508 introduced operators such
13# as ~= and === which aren't in Python, necessitating a different approach.
15import os
16import re
17import sys
18import platform
20from .compat import string_types
21from .util import in_venv, parse_marker
22from .version import LegacyVersion as LV
23from .version import NormalizedVersion as NV
25__all__ = ['interpret']
27_VERSION_PATTERN = re.compile(r'((\d+(\.\d+)*\w*)|\'(\d+(\.\d+)*\w*)\'|\"(\d+(\.\d+)*\w*)\")')
28_VERSION_MARKERS = {'python_version', 'python_full_version', 'implementation_version'}
31def _is_version_marker(s):
32 return isinstance(s, string_types) and s in _VERSION_MARKERS
35def _is_literal(o):
36 if not isinstance(o, string_types) or not o:
37 return False
38 return o[0] in '\'"'
41def _get_versions(s):
42 return {LV(m.groups()[0]) for m in _VERSION_PATTERN.finditer(s)}
45def _match_compatible(lhs, rhs):
46 version, constraint = NV(str(lhs)), NV(str(rhs))
47 prefix = constraint._release_clause[:-1]
48 release = version._release_clause + (0, ) * len(prefix)
49 return (version >= constraint and version._parts[0] == constraint._parts[0] and release[:len(prefix)] == prefix)
52class Evaluator(object):
53 """
54 This class is used to evaluate marker expressions.
55 """
57 operations = {
58 '==': lambda x, y: x == y,
59 '===': lambda x, y: x == y,
60 '~=': _match_compatible,
61 '!=': lambda x, y: x != y,
62 '<': lambda x, y: x < y,
63 '<=': lambda x, y: x == y or x < y,
64 '>': lambda x, y: x > y,
65 '>=': lambda x, y: x == y or x > y,
66 'and': lambda x, y: x and y,
67 'or': lambda x, y: x or y,
68 'in': lambda x, y: x in y,
69 'not in': lambda x, y: x not in y,
70 }
72 def evaluate(self, expr, context):
73 """
74 Evaluate a marker expression returned by the :func:`parse_requirement`
75 function in the specified context.
76 """
77 if isinstance(expr, string_types):
78 if expr[0] in '\'"':
79 result = expr[1:-1]
80 else:
81 if expr not in context:
82 raise SyntaxError('unknown variable: %s' % expr)
83 result = context[expr]
84 else:
85 assert isinstance(expr, dict)
86 op = expr['op']
87 if op not in self.operations:
88 raise NotImplementedError('op not implemented: %s' % op)
89 elhs = expr['lhs']
90 erhs = expr['rhs']
91 if _is_literal(expr['lhs']) and _is_literal(expr['rhs']):
92 raise SyntaxError('invalid comparison: %s %s %s' % (elhs, op, erhs))
94 lhs = self.evaluate(elhs, context)
95 rhs = self.evaluate(erhs, context)
96 if ((_is_version_marker(elhs) or _is_version_marker(erhs)) and
97 op in ('<', '<=', '>', '>=', '===', '==', '!=', '~=')):
98 lhs = LV(lhs)
99 rhs = LV(rhs)
100 elif _is_version_marker(elhs) and op in ('in', 'not in'):
101 lhs = LV(lhs)
102 rhs = _get_versions(rhs)
103 result = self.operations[op](lhs, rhs)
104 return result
107_DIGITS = re.compile(r'\d+\.\d+')
110def default_context():
112 def format_full_version(info):
113 version = '%s.%s.%s' % (info.major, info.minor, info.micro)
114 kind = info.releaselevel
115 if kind != 'final':
116 version += kind[0] + str(info.serial)
117 return version
119 if hasattr(sys, 'implementation'):
120 implementation_version = format_full_version(sys.implementation.version)
121 implementation_name = sys.implementation.name
122 else:
123 implementation_version = '0'
124 implementation_name = ''
126 ppv = platform.python_version()
127 m = _DIGITS.match(ppv)
128 pv = m.group(0)
129 result = {
130 'implementation_name': implementation_name,
131 'implementation_version': implementation_version,
132 'os_name': os.name,
133 'platform_machine': platform.machine(),
134 'platform_python_implementation': platform.python_implementation(),
135 'platform_release': platform.release(),
136 'platform_system': platform.system(),
137 'platform_version': platform.version(),
138 'platform_in_venv': str(in_venv()),
139 'python_full_version': ppv,
140 'python_version': pv,
141 'sys_platform': sys.platform,
142 }
143 return result
146DEFAULT_CONTEXT = default_context()
147del default_context
149evaluator = Evaluator()
151def interpret_parsed(expr, execution_context=None):
152 context = dict(DEFAULT_CONTEXT)
153 if execution_context:
154 context.update(execution_context)
155 return evaluator.evaluate(expr, context)
157def interpret(marker, execution_context=None):
158 """
159 Interpret a marker and return a result depending on environment.
161 :param marker: The marker to interpret.
162 :type marker: str
163 :param execution_context: The context used for name lookup.
164 :type execution_context: mapping
165 """
166 try:
167 expr, rest = parse_marker(marker)
168 except Exception as e:
169 raise SyntaxError('Unable to interpret marker syntax: %s: %s' % (marker, e))
170 if rest and rest[0] != '#':
171 raise SyntaxError('unexpected trailing data in marker: %s: %s' % (marker, rest))
172 return interpret_parsed(expr, execution_context)