Debian Codegraph @

subprojects/pythoncapi-compat/upgrade_pythoncapi.py

raw
1 #!/usr/bin/env python3
2 import argparse
3 import os
4 import re
5 import urllib.request
6 import sys
7
8
9 MIN_PYTHON = (2, 7)
10
11
12 PYTHONCAPI_COMPAT_URL = ('https://raw.githubusercontent.com/python/'
13 'pythoncapi-compat/main/pythoncapi_compat.h')
14 PYTHONCAPI_COMPAT_H = 'pythoncapi_compat.h'
15 INCLUDE_PYTHONCAPI_COMPAT = f'#include "{PYTHONCAPI_COMPAT_H}"'
16 INCLUDE_PYTHONCAPI_COMPAT2 = f'#include <{PYTHONCAPI_COMPAT_H}>'
17
18 C_FILE_EXT = (
19 # C language
20 ".c", ".h",
21 # C++ language
22 ".cc", ".cpp", ".cxx", ".hpp",
23 )
24 IGNORE_DIRS = (".git", ".tox")
25
26
27 # Match spaces but not newline characters.
28 # Similar to \s but exclude newline characters and only look for ASCII spaces
29 SPACE_REGEX = r'[ \t\f\v]'
30 # Match the end of a line: newline characters of a single line
31 NEWLINE_REGEX = r'(?:\n|\r|\r\n)'
32 # Match the indentation at the beginning of a line
33 INDENTATION_REGEX = fr'^{SPACE_REGEX}*'
34
35
36 # Match a C identifier: 'identifier', 'var_3', 'NameCamelCase', '_var'
37 # Use \b to only match a full word: match "a_b", but not just "b" in "a_b".
38 ID_REGEX = r'\b[a-zA-Z_][a-zA-Z0-9_]*\b'
39 # Match 'array[3]'
40 SUBEXPR_REGEX = fr'{ID_REGEX}(?:\[[^]]+\])*'
41 # Match a C expression like "frame", "frame.attr", "obj->attr" or "*obj".
42 # Don't match functions calls like "func()".
43 EXPR_REGEX = (fr"\*?" # "*" prefix
44 fr"{SUBEXPR_REGEX}" # "var"
45 fr"(?:(?:->|\.){SUBEXPR_REGEX})*") # "->attr" or ".attr"
46
47 # # Match 'PyObject *var' and 'struct MyStruct* var'
48 TYPE_PTR_REGEX = fr'{ID_REGEX} *\*'
49
50 # Match '(PyObject*)' and nothing
51 OPT_CAST_REGEX = fr'(?:\({TYPE_PTR_REGEX} *\){SPACE_REGEX}*)?'
52
53
54 def same_indentation(group):
55 # the regex must have re.MULTILINE flag
56 return fr'{SPACE_REGEX}*(?:{NEWLINE_REGEX}{group})?'
57
58
59 def get_member_regex_str(member):
60 # Match "var->member".
61 return fr'\b({EXPR_REGEX}) *-> *{member}\b'
62
63
64 def get_member_regex(member):
65 # Match "var->member" (get).
66 # Don't match "var->member = value" (set).
67 # Don't match "Py_CLEAR(var->member)".
68 # Only "Py_CLEAR(" exact string is excluded.
69 regex = (r'(?<!Py_CLEAR\()'
70 + get_member_regex_str(member)
71 + r'(?!\s*=\s*)')
72 return re.compile(regex)
73
74
75 def assign_regex_str(var, expr):
76 # Match "var = expr;".
77 return fr'{var} *= *{expr}\s*;'
78
79
80 def set_member_regex(member):
81 # Match "var->member = expr;".
82 regex = assign_regex_str(get_member_regex_str(member), r'([^=].*)')
83 return re.compile(regex)
84
85
86 def call_assign_regex(name):
87 # Match "Py_TYPE(expr) = expr;".
88 # Don't match "assert(Py_TYPE(expr) == expr);".
89 # Tolerate spaces
90 regex = fr'{name} *\( *(.+) *\) *= *([^=].*) *;'
91 return re.compile(regex)
92
93
94 def is_c_filename(filename):
95 return filename.endswith(C_FILE_EXT)
96
97
98 class Operation:
99 NAME = "<name>"
100 REPLACE = ()
101 NEED_PYTHONCAPI_COMPAT = False
102
103 def __init__(self, patcher):
104 self.patcher = patcher
105
106 def patch(self, content):
107 old_content = content
108 for regex, replace in self.REPLACE:
109 content = regex.sub(replace, content)
110 if content != old_content and self.NEED_PYTHONCAPI_COMPAT:
111 content = self.patcher.add_pythoncapi_compat(content)
112 return content
113
114
115 class Py_TYPE(Operation):
116 NAME = "Py_TYPE"
117 REPLACE = (
118 (get_member_regex('ob_type'), r'Py_TYPE(\1)'),
119 )
120 # Py_TYPE() was added to Python 2.6.
121
122
123 class Py_SIZE(Operation):
124 NAME = "Py_SIZE"
125 REPLACE = (
126 (get_member_regex('ob_size'), r'Py_SIZE(\1)'),
127 )
128 # Py_SIZE() was added to Python 2.6.
129
130
131 class Py_REFCNT(Operation):
132 NAME = "Py_REFCNT"
133 REPLACE = (
134 (get_member_regex('ob_refcnt'), r'Py_REFCNT(\1)'),
135 )
136 # Py_REFCNT() was added to Python 2.6.
137
138
139 class Py_SET_TYPE(Operation):
140 NAME = "Py_SET_TYPE"
141 REPLACE = (
142 (call_assign_regex('Py_TYPE'), r'Py_SET_TYPE(\1, \2);'),
143 (set_member_regex('ob_type'), r'Py_SET_TYPE(\1, \2);'),
144 )
145 # Need Py_SET_TYPE(): new in Python 3.9.
146 NEED_PYTHONCAPI_COMPAT = (MIN_PYTHON < (3, 9))
147
148
149 class Py_SET_SIZE(Operation):
150 NAME = "Py_SET_SIZE"
151 REPLACE = (
152 (call_assign_regex('Py_SIZE'), r'Py_SET_SIZE(\1, \2);'),
153 (set_member_regex('ob_size'), r'Py_SET_SIZE(\1, \2);'),
154 )
155 # Need Py_SET_SIZE(): new in Python 3.9.
156 NEED_PYTHONCAPI_COMPAT = (MIN_PYTHON < (3, 9))
157
158
159 class Py_SET_REFCNT(Operation):
160 NAME = "Py_SET_REFCNT"
161 REPLACE = (
162 (call_assign_regex('Py_REFCNT'), r'Py_SET_REFCNT(\1, \2);'),
163 (set_member_regex('ob_refcnt'), r'Py_SET_REFCNT(\1, \2);'),
164 )
165 # Need Py_SET_REFCNT(): new in Python 3.9.
166 NEED_PYTHONCAPI_COMPAT = (MIN_PYTHON < (3, 9))
167
168
169 class PyObject_NEW(Operation):
170 NAME = "PyObject_NEW"
171 # In Python 3.9, the PyObject_NEW() macro becomes an alias to the
172 # PyObject_New() macro, and the PyObject_NEW_VAR() macro becomes an alias
173 # to the PyObject_NewVar() macro.
174 REPLACE = (
175 (re.compile(r"\bPyObject_NEW\b( *\()"), r'PyObject_New\1'),
176 (re.compile(r"\bPyObject_NEW_VAR\b( *\()"), r'PyObject_NewVar\1'),
177 )
178
179
180 class PyMem_MALLOC(Operation):
181 NAME = "PyMem_MALLOC"
182 # In Python 3.9, the PyObject_NEW() macro becomes an alias to the
183 # PyObject_New() macro, and the PyObject_NEW_VAR() macro becomes an alias
184 # to the PyObject_NewVar() macro.
185
186 REPLACE = (
187 (re.compile(r"\bPyMem_MALLOC\b( *\()"), r'PyMem_Malloc\1'),
188 (re.compile(r"\bPyMem_REALLOC\b( *\()"), r'PyMem_Realloc\1'),
189 (re.compile(r"\bPyMem_FREE\b( *\()"), r'PyMem_Free\1'),
190 (re.compile(r"\bPyMem_Del\b( *\()"), r'PyMem_Free\1'),
191 (re.compile(r"\bPyMem_DEL\b( *\()"), r'PyMem_Free\1'),
192 )
193
194
195 class PyObject_MALLOC(Operation):
196 NAME = "PyObject_MALLOC"
197 # In Python 3.9, the PyObject_NEW() macro becomes an alias to the
198 # PyObject_New() macro, and the PyObject_NEW_VAR() macro becomes an alias
199 # to the PyObject_NewVar() macro.
200
201 REPLACE = (
202 (re.compile(r"\bPyObject_MALLOC\b( *\()"), r'PyObject_Malloc\1'),
203 (re.compile(r"\bPyObject_REALLOC\b( *\()"), r'PyObject_Realloc\1'),
204 (re.compile(r"\bPyObject_FREE\b( *\()"), r'PyObject_Free\1'),
205 (re.compile(r"\bPyObject_Del\b( *\()"), r'PyObject_Free\1'),
206 (re.compile(r"\bPyObject_DEL\b( *\()"), r'PyObject_Free\1'),
207 )
208
209
210 class PyFrame_GetBack(Operation):
211 NAME = "PyFrame_GetBack"
212 REPLACE = (
213 (get_member_regex('f_back'), r'_PyFrame_GetBackBorrow(\1)'),
214 )
215 # Need _PyFrame_GetBackBorrow() (PyFrame_GetBack() is new in Python 3.9)
216 NEED_PYTHONCAPI_COMPAT = (MIN_PYTHON < (3, 9))
217
218
219 class PyFrame_GetCode(Operation):
220 NAME = "PyFrame_GetCode"
221
222 REPLACE = (
223 (get_member_regex('f_code'), r'_PyFrame_GetCodeBorrow(\1)'),
224 )
225 # Need _PyFrame_GetCodeBorrow() (PyFrame_GetCode() is new in Python 3.9)
226 NEED_PYTHONCAPI_COMPAT = (MIN_PYTHON < (3, 9))
227
228
229 class PyThreadState_GetInterpreter(Operation):
230 NAME = "PyThreadState_GetInterpreter"
231 REPLACE = (
232 (get_member_regex('interp'), r'PyThreadState_GetInterpreter(\1)'),
233 )
234 # Need PyThreadState_GetInterpreter() (new in Python 3.9)
235 NEED_PYTHONCAPI_COMPAT = (MIN_PYTHON < (3, 9))
236
237
238 class PyThreadState_GetFrame(Operation):
239 NAME = "PyThreadState_GetFrame"
240 REPLACE = (
241 (get_member_regex('frame'), r'_PyThreadState_GetFrameBorrow(\1)'),
242 )
243 # Need _PyThreadState_GetFrameBorrow()
244 # (PyThreadState_GetFrame() is new in Python 3.9)
245 NEED_PYTHONCAPI_COMPAT = (MIN_PYTHON < (3, 9))
246
247
248 class Py_NewRef(Operation):
249 NAME = "Py_NewRef"
250 REPLACE = (
251 # "Py_INCREF(x); return x;" => "return Py_NewRef(x);"
252 # "Py_XINCREF(x); return x;" => "return Py_XNewRef(x);"
253 # The two statements must be at the same indentation, otherwise the
254 # regex does not match.
255 (re.compile(fr'({INDENTATION_REGEX})'
256 + fr'Py_(X?)INCREF\(({EXPR_REGEX})\)\s*;'
257 + same_indentation(r'\1')
258 + fr'return {OPT_CAST_REGEX}\3;',
259 re.MULTILINE),
260 r'\1return Py_\2NewRef(\3);'),
261
262 # Same regex than the previous one,
263 # but the two statements are on the same line.
264 (re.compile(fr'Py_(X?)INCREF\(({EXPR_REGEX})\)\s*;'
265 + fr'{SPACE_REGEX}*'
266 + fr'return {OPT_CAST_REGEX}\2;',
267 re.MULTILINE),
268 r'return Py_\1NewRef(\2);'),
269
270 # "Py_INCREF(x); y = x;" must be replaced before
271 # "y = x; Py_INCREF(y);", to not miss consecutive
272 # "Py_INCREF; assign; Py_INCREF; assign; ..." (see unit tests).
273
274 # "Py_INCREF(x); y = x;" => "y = Py_NewRef(x)"
275 # "Py_XINCREF(x); y = x;" => "y = Py_XNewRef(x)"
276 # The two statements must have the same indentation, otherwise the
277 # regex does not match.
278 (re.compile(fr'({INDENTATION_REGEX})'
279 + fr'Py_(X?)INCREF\(({EXPR_REGEX})\);'
280 + same_indentation(r'\1')
281 + assign_regex_str(fr'({EXPR_REGEX})',
282 fr'{OPT_CAST_REGEX}\3'),
283 re.MULTILINE),
284 r'\1\4 = Py_\2NewRef(\3);'),
285
286 # Same regex than the previous one,
287 # but the two statements are on the same line.
288 (re.compile(fr'Py_(X?)INCREF\(({EXPR_REGEX})\);'
289 + fr'{SPACE_REGEX}*'
290 + assign_regex_str(fr'({EXPR_REGEX})',
291 fr'{OPT_CAST_REGEX}\2')),
292 r'\3 = Py_\1NewRef(\2);'),
293
294 # "y = x; Py_INCREF(x);" => "y = Py_NewRef(x);"
295 # "y = x; Py_INCREF(y);" => "y = Py_NewRef(x);"
296 # "y = x; Py_XINCREF(x);" => "y = Py_XNewRef(x);"
297 # "y = x; Py_XINCREF(y);" => "y = Py_XNewRef(x);"
298 # "y = (PyObject*)x; Py_XINCREF(y);" => "y = Py_XNewRef(x);"
299 # The two statements must have the same indentation, otherwise the
300 # regex does not match.
301 (re.compile(fr'({INDENTATION_REGEX})'
302 + assign_regex_str(fr'({EXPR_REGEX})',
303 fr'{OPT_CAST_REGEX}({EXPR_REGEX})')
304 + same_indentation(r'\1')
305 + r'Py_(X?)INCREF\((?:\2|\3)\);',
306 re.MULTILINE),
307 r'\1\2 = Py_\4NewRef(\3);'),
308
309 # Same regex than the previous one,
310 # but the two statements are on the same line.
311 (re.compile(assign_regex_str(fr'({EXPR_REGEX})',
312 fr'{OPT_CAST_REGEX}({EXPR_REGEX})')
313 + fr'{SPACE_REGEX}*'
314 + r'Py_(X?)INCREF\((?:\1|\2)\);'),
315 r'\1 = Py_\3NewRef(\2);'),
316
317 # "PyObject *var = x; Py_INCREF(x);" => "PyObject *var = Py_NewRef(x);"
318 # The two statements must have the same indentation, otherwise the
319 # regex does not match.
320 (re.compile(fr'({INDENTATION_REGEX})'
321 # "type* var = expr;"
322 + assign_regex_str(fr'({TYPE_PTR_REGEX} *)({EXPR_REGEX})',
323 fr'({OPT_CAST_REGEX})({EXPR_REGEX})')
324 + same_indentation(r'\1')
325 # "Py_INCREF(var);"
326 + r'Py_(X?)INCREF\((?:\3|\5)\);',
327 re.MULTILINE),
328 r'\1\2\3 = \4Py_\6NewRef(\5);'),
329
330 # "Py_INCREF(x); PyObject *var = x;" => "PyObject *var = Py_NewRef(x);"
331 # The two statements must have the same indentation, otherwise the
332 # regex does not match.
333 (re.compile(fr'({INDENTATION_REGEX})'
334 # "Py_INCREF(var);"
335 + fr'Py_(X?)INCREF\(({EXPR_REGEX})\);'
336 + same_indentation(r'\1')
337 # "type* var = expr;"
338 + assign_regex_str(fr'({TYPE_PTR_REGEX} *{EXPR_REGEX})',
339 fr'({OPT_CAST_REGEX})\3'),
340 re.MULTILINE),
341 r'\1\4 = \5Py_\2NewRef(\3);'),
342 )
343 # Need Py_NewRef(): new in Python 3.10
344 NEED_PYTHONCAPI_COMPAT = (MIN_PYTHON < (3, 10))
345
346
347 class Py_CLEAR(Operation):
348 NAME = "Py_CLEAR"
349 REPLACE = (
350 # "Py_XDECREF(x); x = NULL;" => "Py_CLEAR(x)";
351 # The two statements must have the same indentation, otherwise the
352 # regex does not match.
353 (re.compile(fr'({INDENTATION_REGEX})'
354 + fr'Py_XDECREF\(({EXPR_REGEX})\) *;'
355 + same_indentation(r'\1')
356 + assign_regex_str(r'\2', r'NULL'),
357 re.MULTILINE),
358 r'\1Py_CLEAR(\2);'),
359
360 # "Py_XDECREF(x); x = NULL;" => "Py_CLEAR(x)";
361 (re.compile(fr'Py_XDECREF\(({EXPR_REGEX})\) *;'
362 + fr'{SPACE_REGEX}*'
363 + assign_regex_str(r'\1', r'NULL')),
364 r'Py_CLEAR(\1);'),
365 )
366
367
368 SETREF_VALUE = fr'{OPT_CAST_REGEX}(?:{EXPR_REGEX}|Py_X?NewRef\({EXPR_REGEX}\))'
369
370
371 class Py_SETREF(Operation):
372 NAME = "Py_SETREF"
373 REPLACE = (
374 # "Py_INCREF(y); Py_CLEAR(x); x = y;" => "Py_XSETREF(x, y)";
375 # Statements must have the same indentation, otherwise the regex does
376 # not match.
377 (re.compile(fr'({INDENTATION_REGEX})'
378 + fr'Py_(X?)INCREF\(({EXPR_REGEX})\) *;'
379 + same_indentation(r'\1')
380 + fr'Py_CLEAR\(({EXPR_REGEX})\) *;'
381 + same_indentation(r'\1')
382 + assign_regex_str(r'\4', r'\3'),
383 re.MULTILINE),
384 r'\1Py_XSETREF(\4, Py_\2NewRef(\3));'),
385
386 # "Py_CLEAR(x); x = y;" => "Py_XSETREF(x, y)";
387 # Statements must have the same indentation, otherwise the regex does
388 # not match.
389 (re.compile(fr'({INDENTATION_REGEX})'
390 + fr'Py_CLEAR\(({EXPR_REGEX})\) *;'
391 + same_indentation(r'\1')
392 + assign_regex_str(r'\2',
393 fr'({SETREF_VALUE})'),
394 re.MULTILINE),
395 r'\1Py_XSETREF(\2, \3);'),
396
397 # "Py_INCREF(y); Py_DECREF(x); x = y;" => "Py_SETREF(x, y)";
398 # Statements must have the same indentation, otherwise the regex does
399 # not match.
400 (re.compile(fr'({INDENTATION_REGEX})'
401 + fr'Py_(X?)INCREF\(({EXPR_REGEX})\) *;'
402 + same_indentation(r'\1')
403 + fr'Py_(X?)DECREF\(({EXPR_REGEX})\) *;'
404 + same_indentation(r'\1')
405 + assign_regex_str(r'\5', r'\3'),
406 re.MULTILINE),
407 r'\1Py_\4SETREF(\5, Py_\2NewRef(\3));'),
408
409 # "Py_DECREF(x); x = y;" => "Py_SETREF(x, y)";
410 # "Py_DECREF(x); x = Py_NewRef(y);" => "Py_SETREF(x, Py_NewRef(y))";
411 # Statements must have the same indentation, otherwise the regex does
412 # not match.
413 (re.compile(fr'({INDENTATION_REGEX})'
414 + fr'Py_(X?)DECREF\(({EXPR_REGEX})\) *;'
415 + same_indentation(r'\1')
416 + assign_regex_str(r'\3',
417 fr'({SETREF_VALUE})'),
418 re.MULTILINE),
419 r'\1Py_\2SETREF(\3, \4);'),
420
421 # "old = var; var = new; Py_DECREF(old);" => "Py_SETREF(var, new);"
422 # "PyObject *old = var; var = new; Py_DECREF(old);" => "Py_SETREF(var, new);"
423 # Statements must have the same indentation, otherwise the regex does
424 # not match.
425 (re.compile(fr'({INDENTATION_REGEX})'
426 + fr'(?:{ID_REGEX} *\* *)?({ID_REGEX}) *= *{OPT_CAST_REGEX}({EXPR_REGEX}) *;'
427 + same_indentation(r'\1')
428 + assign_regex_str(r'\3',
429 fr'({SETREF_VALUE})')
430 + same_indentation(r'\1')
431 + fr'Py_(X?)DECREF\(\2\) *;',
432 re.MULTILINE),
433 r'\1Py_\5SETREF(\3, \4);'),
434 )
435 # Need Py_NewRef(): new in Python 3.5
436 NEED_PYTHONCAPI_COMPAT = (MIN_PYTHON < (3, 5))
437
438
439 class Py_Is(Operation):
440 NAME = "Py_Is"
441
442 def replace2(regs):
443 x = regs.group(1)
444 y = regs.group(2)
445 if y == 'NULL':
446 return regs.group(0)
447 return f'{x} = _Py_StealRef({y});'
448
449 REPLACE = []
450 expr = fr'({EXPR_REGEX})'
451 for name in ('None', 'True', 'False'):
452 REPLACE.extend((
453 (re.compile(fr'{expr} == Py_{name}\b'),
454 fr'Py_Is{name}(\1)'),
455 (re.compile(fr'{expr} != Py_{name}\b'),
456 fr'!Py_Is{name}(\1)'),
457 ))
458
459 # Need Py_IsNone(), Py_IsTrue(), Py_IsFalse(): new in Python 3.10
460 NEED_PYTHONCAPI_COMPAT = (MIN_PYTHON < (3, 10))
461
462
463 OPERATIONS = (
464 Py_SET_TYPE,
465 Py_SET_SIZE,
466 Py_SET_REFCNT,
467 # Py_SET_xxx must be run before Py_xxx
468 Py_TYPE,
469 Py_SIZE,
470 Py_REFCNT,
471
472 Py_Is,
473
474 PyObject_NEW,
475 PyMem_MALLOC,
476 PyObject_MALLOC,
477
478 PyFrame_GetBack,
479 PyFrame_GetCode,
480
481 PyThreadState_GetInterpreter,
482 PyThreadState_GetFrame,
483
484 # Code style: excluded from "all"
485 Py_NewRef,
486 Py_CLEAR,
487 Py_SETREF,
488 )
489
490 EXCLUDE_FROM_ALL = (
491 Py_NewRef,
492 Py_CLEAR,
493 Py_SETREF,
494 )
495
496
497 def all_operations():
498 return set(operation_class.NAME for operation_class in OPERATIONS
499 if operation_class not in EXCLUDE_FROM_ALL)
500
501
502 class Patcher:
503 def __init__(self, args=None):
504 self.exitcode = 0
505 self.pythoncapi_compat_added = 0
506 self.want_pythoncapi_compat = False
507 self.operations = None
508 self.applied_operations = set()
509
510 # Set temporarily by patch()
511 self._has_pythoncapi_compat = None
512 self._applied_operations = None
513
514 self._parse_options(args)
515
516 def log(self, msg=''):
517 print(msg, file=sys.stderr, flush=True)
518
519 def warning(self, msg):
520 self.log(f"WARNING: {msg}")
521
522 def _get_operations(self, parser):
523 args_names = self.args.operations.split(',')
524
525 wanted = set()
526 for name in args_names:
527 name = name.strip()
528 if not name:
529 continue
530
531 if name == "all":
532 wanted |= all_operations()
533 elif name.startswith("-"):
534 name = name[1:]
535 wanted.discard(name)
536 else:
537 wanted.add(name)
538
539 operations = []
540 for operation_class in OPERATIONS:
541 name = operation_class.NAME
542 if name not in wanted:
543 continue
544 wanted.discard(name)
545 operation = operation_class(self)
546 operations.append(operation)
547
548 if wanted:
549 print(f"invalid operations: {','.join(wanted)}")
550 print()
551 self.usage(parser)
552 sys.exit(1)
553
554 return operations
555
556 def add_line(self, content, line):
557 # Use the first matching newline
558 match = re.search(r'(?:\r\n|\n|\r)', content)
559 newline = match.group(0) if match else '\n'
560
561 line = line + newline
562 # FIXME: tolerate trailing spaces
563 if line not in content:
564 # FIXME: add macro after the first header comment
565 # FIXME: add macro after includes
566 # FIXME: add macro after: #define PY_SSIZE_T_CLEAN
567 return line + newline + content
568 else:
569 return content
570
571 def add_pythoncapi_compat(self, content):
572 if self._has_pythoncapi_compat:
573 return content
574 content = self.add_line(content, INCLUDE_PYTHONCAPI_COMPAT)
575 self._has_pythoncapi_compat = True
576 self.pythoncapi_compat_added += 1
577 return content
578
579 def _patch(self, content):
580 try:
581 has = (self.args.no_compat
582 or INCLUDE_PYTHONCAPI_COMPAT in content
583 or INCLUDE_PYTHONCAPI_COMPAT2 in content)
584 self._has_pythoncapi_compat = has
585 self._applied_operations = []
586 for operation in self.operations:
587 new_content = operation.patch(content)
588 if new_content != content:
589 self._applied_operations.append(operation.NAME)
590 content = new_content
591 applied_operations = self._applied_operations
592 finally:
593 self._has_pythoncapi_compat = None
594 self._applied_operations = None
595 return (content, applied_operations)
596
597 def patch(self, content):
598 return self._patch(content)[0]
599
600 def patch_file(self, filename):
601 if os.path.basename(filename) == PYTHONCAPI_COMPAT_H:
602 self.log(f"Skip {filename}")
603 return
604
605 encoding = "utf-8"
606 errors = "surrogateescape"
607
608 with open(filename, encoding=encoding, errors=errors, newline="") as fp:
609 old_contents = fp.read()
610
611 new_contents, operations = self._patch(old_contents)
612
613 if self.args.to_stdout:
614 print(new_contents, end="")
615 return (new_contents != old_contents)
616
617 # Don't rewrite if the filename for in-place replacement,
618 # to avoid changing the file modification time.
619 if new_contents == old_contents:
620 return False
621
622 if not self.args.no_backup:
623 old_filename = filename + ".old"
624 # If old_filename already exists, replace it
625 os.replace(filename, old_filename)
626
627 with open(filename, "w", encoding=encoding, errors=errors, newline="") as fp:
628 fp.write(new_contents)
629
630 self.applied_operations |= set(operations)
631 operations = ', '.join(operations)
632 self.log(f"Patched file: {filename} ({operations})")
633 return True
634
635 def _walk_dir(self, path):
636 empty = True
637
638 for dirpath, dirnames, filenames in os.walk(path):
639 # Don't walk into .tox
640 for ignore_name in IGNORE_DIRS:
641 try:
642 dirnames.remove(ignore_name)
643 except ValueError:
644 pass
645 for filename in filenames:
646 if is_c_filename(filename):
647 yield os.path.join(dirpath, filename)
648 empty = False
649
650 if empty:
651 self.warning(f"Directory {path} doesn't contain any C file")
652 self.exitcode = 1
653
654 def walk(self, paths):
655 for path in paths:
656 if os.path.isdir(path):
657 for filename in self._walk_dir(path):
658 yield filename
659 elif os.path.exists(path):
660 yield path
661 else:
662 self.warning(f"Path {path} does not exist")
663 self.exitcode = 1
664
665 def get_latest_header(self, base_dir):
666 target = os.path.join(base_dir, PYTHONCAPI_COMPAT_H)
667 self.log(f"Download the file from {PYTHONCAPI_COMPAT_URL} to {target}.")
668 urllib.request.urlretrieve(PYTHONCAPI_COMPAT_URL, target)
669
670 @staticmethod
671 def usage(parser):
672 parser.print_help()
673 print()
674 print("Operations:")
675 print()
676 for operation in sorted(OPERATIONS,
677 key=lambda operation: operation.NAME.lower()):
678 print(f"- {operation.NAME}")
679 print()
680 print("If a directory is passed, search for .c and .h files "
681 "in subdirectories.")
682
683 def _parse_dir_path(self, path):
684 if os.path.isdir(path):
685 return path
686 else:
687 raise argparse.ArgumentTypeError(f"{path} is not a valid path")
688
689 def _parse_options(self, args):
690 parser = argparse.ArgumentParser(
691 description="Upgrade C extension modules to newer Python C API")
692 parser.add_argument(
693 '-o', '--operations', action="store",
694 default="all",
695 help='Space separated list of operation names to apply')
696 parser.add_argument(
697 '-q', '--quiet', action="store_true",
698 help='Quiet mode')
699 parser.add_argument(
700 '-c', '--to-stdout', action="store_true",
701 help='Write output into stdout instead of modifying files '
702 'in-place (imply quiet mode)')
703 parser.add_argument(
704 '-B', '--no-backup', action="store_true",
705 help="Don't create .old backup files")
706 parser.add_argument(
707 '-C', '--no-compat', action="store_true",
708 help=f"Don't add: {INCLUDE_PYTHONCAPI_COMPAT}")
709 parser.add_argument(
710 '-d', '--download', metavar='PATH',
711 help=f'Download latest pythoncapi_compat.h file to designated PATH',
712 type=self._parse_dir_path)
713 parser.add_argument(
714 metavar='file_or_directory', dest="paths", nargs='*')
715
716 args = parser.parse_args(args)
717 if not args.paths and not args.download:
718 self.usage(parser)
719 sys.exit(1)
720
721 if args.to_stdout:
722 args.quiet = True
723
724 self.args = args
725 self.operations = self._get_operations(parser)
726
727 def main(self):
728 if self.args.paths:
729 for filename in self.walk(self.args.paths):
730 self.patch_file(filename)
731
732 if self.applied_operations:
733 nops = len(self.applied_operations)
734 ops = ', '.join(sorted(self.applied_operations))
735 self.log()
736 self.log(f"Applied operations ({nops}): {ops}")
737
738 if self.args.download:
739 path = self.args.download
740 self.get_latest_header(path)
741
742 if self.pythoncapi_compat_added and not self.args.quiet:
743 self.log()
744 self.log(f"{INCLUDE_PYTHONCAPI_COMPAT} added: you may have "
745 f"to copy {PYTHONCAPI_COMPAT_H} to your project")
746 self.log("Run 'python upgrade_pythoncapi.py --download <target_path>'")
747
748 sys.exit(self.exitcode)
749
750
751 if __name__ == "__main__":
752 Patcher().main()