forked from nix-community/poetry2nix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpython-requires-patch-hook.py
79 lines (59 loc) · 2 KB
/
python-requires-patch-hook.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env python
import ast
import sys
import io
# Python2 compat
if sys.version_info[0] < 3:
FileNotFoundError = IOError
# Python <= 3.8 compat
def astunparse(tree):
# Use bundled unparse by default
if hasattr(ast, "unparse"):
return ast.unparse(tree)
# Use example tool from Python sources for older interpreter versions
from poetry2nix_astunparse import Unparser
buf = io.StringIO()
up = Unparser(tree, buf)
return buf.getvalue()
class Rewriter(ast.NodeVisitor):
def __init__(self, *args, **kwargs):
super(Rewriter, self).__init__(*args, **kwargs)
self.modified = False
def visit_Call(self, node):
function_name = ""
if isinstance(node.func, ast.Name):
function_name = node.func.id
elif isinstance(node.func, ast.Attribute):
function_name = node.func.attr
else:
return
if function_name != "setup":
return
for kw in node.keywords:
if kw.arg != "python_requires":
continue
value = kw.value
if not isinstance(value, ast.Constant):
return
# Rewrite version constraints without wildcard characters.
#
# Only rewrite the file if the modified value actually differs, as we lose whitespace and comments when rewriting
# with the AST module.
python_requires = ", ".join(
[v.strip().rstrip(".*") for v in value.value.split(",")]
)
if value.value != python_requires:
value.value = python_requires
self.modified = True
if __name__ == "__main__":
sys.path.extend(sys.argv[1:])
try:
with open("setup.py", encoding="utf-8-sig") as f:
tree = ast.parse(f.read())
except FileNotFoundError:
exit(0)
r = Rewriter()
r.visit(tree)
if r.modified:
with open("setup.py", "w") as f:
f.write(astunparse(tree))