Debian Codegraph @

tasks/deps/_parse.py

raw symbols SCIP
1 # -*- coding: ascii -*-
2 #
3 # Copyright 2018 - 2025
4 # Andr\xe9 Malo or his licensors, as applicable
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 """
18 Regular expressions
19 ~~~~~~~~~~~~~~~~~~~
20
21 :See: https://www.python.org/dev/peps/pep-0508/
22 """
23 import functools as _ft
24 import re as _re
25
26 # pylint: disable = import-outside-toplevel
27
28
29 class regex(object):
30 """Collection of regexes"""
31
32 wsp = r"[^\S\r\n]"
33 idre = r"([a-zA-Z\d]+(?:[._-]+[a-zA-Z\d]+)*)"
34 extra = r"""(?: \[
35 %(wsp)s* %(idre)s+ %(wsp)s*
36 (?:,%(wsp)s* %(idre)s %(wsp)s*)*
37 \] )""" % dict(
38 idre=idre, wsp=wsp
39 )
40
41 version_cmp = r"(?:===|[<!=>~]=|[<>])"
42 version_str = r"[a-zA-Z0-9_.*+!-]+"
43 version_release = r"""(?x)(?:
44 ([vV]? (?:[0-9]+!)?)
45 ([0-9]+(?:\.[0-9]+)*)
46 )"""
47 version1 = r"(?: %(cmp)s %(wsp)s* %(version)s )" % dict(
48 cmp=version_cmp, wsp=wsp, version=version_str
49 )
50 version = r"""(?:
51 %(version1)s %(wsp)s*
52 (?:, %(wsp)s* %(version1)s %(wsp)s* )*
53 )""" % dict(
54 version1=version1, wsp=wsp
55 )
56
57 marker = r"""(?:
58 (?: ; %(wsp)s*
59 (?:
60 [a-zA-Z0-9"'<>=~!().{}_*#\\:,/?[\]`@$%%^&+|-]+
61 %(wsp)s*
62 )+
63 )+
64 )""" % dict(
65 wsp=wsp
66 )
67
68 # the # character is enclosed in a character class, so it can be used
69 # with re.X
70 line_comment = r"(?:[#][^\r\n]*)"
71
72 py_str_double = r'(?:"[^"\\\r\n]*(?:\\(?:[^\r\n]|\r?\n|\r)[^"\\\r\n]*)*")'
73 py_mstr_double = r'(?:"""[^"\\]*(?:(?:\\.|""?[^"])[^"\\]*)*""")'
74 py_str_single = r"(?:'[^'\\\r\n]*(?:\\(?:[^\r\n]|\r?\n|\r)[^'\\\r\n]*)*')"
75 py_mstr_single = r"(?:'''[^'\\]*(?:(?:\\.|''?[^'])[^'\\]*)*''')"
76
77 toml_str_double = py_str_double
78 toml_mstr_double = (
79 r'(?:"""[^"\\]*(?:(?:\\.|""(?!"""")|"(?!"""""))[^"\\]*)*""")'
80 )
81 toml_str_single = r"(?:'[^'\r\n]*(?:[^'\r\n]*)*')"
82 toml_mstr_single = r"(?:'''[^']*(?:''?[^'][^']*)*''')"
83
84 @classmethod
85 def full_spec(cls, name=None, require_version=False):
86 """
87 Full version spec regex
88
89 Parameters:
90 name (str):
91 The package name to match against. If omitted or ``None`` all
92 valid names are matched
93
94 require_version (bool):
95 Require the version to be present?
96
97 Returns:
98 str: The regex
99 """
100 return r"""(?xm)
101 (?P<space> %(wsp)s* )
102 (?P<spec>
103 (?P<name> %(name)s )
104 (?P<extra> (?: %(wsp)s* %(extra)s ) ? )
105 (?P<version> (?: %(wsp)s* %(version)s ) %(opt_version)s )
106 (?P<marker> (?: %(wsp)s* %(marker)s ) ? )
107 )
108 """ % dict(
109 wsp=cls.wsp,
110 name=cls.idre if name is None else name_as_regex(name),
111 extra=cls.extra,
112 version=cls.version,
113 opt_version="" if require_version else "?",
114 marker=cls.marker,
115 )
116
117
118 def name_as_regex(name):
119 """
120 Transform package name into a regex
121
122 Letters will be matched case insensitively and interpunction chars will be
123 matched as a sequence.
124
125 >>> name_as_regex("foo-b4r")
126 '(?<![a-zA-Z0-9_.-])[fF][oO][oO][_.-]+[bB]4[rR](?![a-zA-Z0-9_.-])'
127
128 Parameters:
129 name (str):
130 The name to transform
131
132 Returns:
133 str: The name as regex
134 """
135 # pylint: disable = unnecessary-lambda-assignment
136
137 # escape control characters
138 name = _re.sub(r"([^a-zA-Z0-9_.-])", r"\\\1", name)
139
140 # replace interpunction sequences with matches of interpunction sequences
141 name = _re.sub(r"[_.-]+", "[_.-]+", name)
142
143 # match all letters CI
144 ci_match = lambda m: "[%s%s]" % (m.group(1).lower(), m.group(1).upper())
145 name = _re.sub(r"([a-zA-Z])", ci_match, name)
146
147 # make sure we're matching the full name
148 name = r"(?<![a-zA-Z0-9_.-])%s(?![a-zA-Z0-9_.-])" % (name,)
149
150 return name
151
152
153 # group(1) is the match, group(2) the comment (if it is a comment match)
154 find_py_str_or_comment = _re.compile(
155 r"""(?s) (
156 (%(line_comment)s)
157 | %(py_mstr_double)s
158 | %(py_mstr_single)s
159 | %(py_str_double)s
160 | %(py_str_single)s
161 ) """
162 % vars(regex),
163 _re.X,
164 ).finditer
165
166 find_toml_str_or_comment = _re.compile(
167 r"""(?s) (
168 (%(line_comment)s)
169 | %(toml_mstr_double)s
170 | %(toml_mstr_single)s
171 | %(toml_str_double)s
172 | %(toml_str_single)s
173 ) """
174 % vars(regex),
175 _re.X,
176 ).finditer
177
178
179 safe_extra_sub = _ft.partial(_re.compile(r"[^A-Za-z0-9.-]+").sub, "_")
180 name_clean_sub = _ft.partial(_re.compile(r"[-_.]+").sub, "-")
181
182
183 def safe_extra(value):
184 """
185 Convert string to safe extra name
186
187 Parameters:
188 value (str):
189 The string to sanitize
190
191 Returns:
192 str: The safe extra
193 """
194 return safe_extra_sub(value).lower()
195
196
197 def normalize(name):
198 """
199 Normalize package name
200
201 Parameters:
202 name (str):
203 The name to normalize
204
205 Returns:
206 str: The normalized name
207 """
208 return name_clean_sub(name).lower()
209
210
211 def _make_req_parse():
212 """
213 Pick requirement parser
214
215 Returns:
216 callable: Parser call
217 """
218 try:
219 import packaging.requirements
220 except ImportError:
221 import pkg_resources
222 else:
223 return packaging.requirements.Requirement
224 return pkg_resources.Requirement.parse
225
226
227 requirement = _make_req_parse()
228
229
230 def _make_ver_parse():
231 """
232 Pick version parser
233
234 Returns:
235 callable: Parser call
236 """
237 try:
238 import packaging.version
239 except ImportError:
240 import pkg_resources
241 else:
242 return packaging.version.Version
243 return pkg_resources.parse_version
244
245
246 version = _make_ver_parse()