python2rust 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- python2rust/__init__.py +8 -0
- python2rust/__main__.py +5 -0
- python2rust/_core.py +44 -0
- python2rust/agent/__init__.py +0 -0
- python2rust/agent/agents.py +333 -0
- python2rust/agent/apply.py +516 -0
- python2rust/agent/finish.py +295 -0
- python2rust/agent/fixers.py +229 -0
- python2rust/agent/loop.py +441 -0
- python2rust/agent/patches.py +1165 -0
- python2rust/agent/port.py +579 -0
- python2rust/agent/prompts/judge_v2.md +96 -0
- python2rust/agent/review.py +34 -0
- python2rust/agent/rustlex.py +232 -0
- python2rust/cli/__init__.py +0 -0
- python2rust/cli/doctor.py +62 -0
- python2rust/cli/inputs.py +105 -0
- python2rust/cli/main.py +1162 -0
- python2rust/cli/ops.py +642 -0
- python2rust/cli/workflow.py +178 -0
- python2rust/core/__init__.py +38 -0
- python2rust/core/config.py +263 -0
- python2rust/core/constructs.py +124 -0
- python2rust/core/diagnostics.py +280 -0
- python2rust/core/emit/__init__.py +5 -0
- python2rust/core/emit/crates.py +51 -0
- python2rust/core/emit/render.py +561 -0
- python2rust/core/emit/schema.py +168 -0
- python2rust/core/emit/translate.py +304 -0
- python2rust/core/frontend/__init__.py +1 -0
- python2rust/core/frontend/module.py +896 -0
- python2rust/core/frontend/names.py +129 -0
- python2rust/core/frontend/project.py +277 -0
- python2rust/core/frontend/project_imports.py +173 -0
- python2rust/core/frontend/symbols.py +132 -0
- python2rust/core/frontend/walrus.py +59 -0
- python2rust/core/ir/__init__.py +1 -0
- python2rust/core/ir/nodes.py +675 -0
- python2rust/core/ir/rtypes.py +122 -0
- python2rust/core/ir/types.py +326 -0
- python2rust/core/lower/__init__.py +1 -0
- python2rust/core/lower/calls.py +1125 -0
- python2rust/core/lower/context.py +223 -0
- python2rust/core/lower/exceptions.py +317 -0
- python2rust/core/lower/exprs.py +845 -0
- python2rust/core/lower/fstrings.py +141 -0
- python2rust/core/lower/funcs.py +276 -0
- python2rust/core/lower/lowerer.py +366 -0
- python2rust/core/lower/modelcalls.py +195 -0
- python2rust/core/lower/models.py +645 -0
- python2rust/core/lower/stmts.py +722 -0
- python2rust/core/lower/testing.py +601 -0
- python2rust/core/lower/validation.py +253 -0
- python2rust/core/passes/__init__.py +1 -0
- python2rust/core/passes/aliasing.py +311 -0
- python2rust/core/passes/analysis.py +207 -0
- python2rust/core/passes/devirt.py +329 -0
- python2rust/core/passes/ownership.py +259 -0
- python2rust/core/passes/raises.py +275 -0
- python2rust/core/rt_lib.rs +2071 -0
- python2rust/data/README.md +81 -0
- python2rust/data/py2many_builtins.toml +4744 -0
- python2rust/errors.py +28 -0
- python2rust/py.typed +0 -0
- python2rust/report/__init__.py +0 -0
- python2rust/report/constructs.py +31 -0
- python2rust/report/contract.py +688 -0
- python2rust/report/corpus.py +323 -0
- python2rust/report/explain.py +168 -0
- python2rust/report/schemas.py +914 -0
- python2rust/server/__init__.py +0 -0
- python2rust/server/mcp_server.py +289 -0
- python2rust/server/mcp_workflow.py +100 -0
- python2rust/skill/SKILL.md +214 -0
- python2rust/verify/__init__.py +0 -0
- python2rust/verify/check.py +1135 -0
- python2rust/verify/equiv/__init__.py +1264 -0
- python2rust/verify/equiv/compare.py +455 -0
- python2rust/verify/equiv/harness.py +505 -0
- python2rust/verify/equiv/judge.py +358 -0
- python2rust/verify/equiv/procs.py +255 -0
- python2rust/verify/equiv/runner.py +248 -0
- python2rust/verify/equiv/types.py +543 -0
- python2rust/verify/keystore.py +76 -0
- python2rust/verify/ladder.py +396 -0
- python2rust/verify/sandbox.py +370 -0
- python2rust/verify/testrun.py +280 -0
- python2rust/workflow/__init__.py +0 -0
- python2rust/workflow/brief.py +312 -0
- python2rust/workflow/interview.py +366 -0
- python2rust/workflow/layout.py +103 -0
- python2rust/workflow/planner.py +409 -0
- python2rust/workflow/project.py +134 -0
- python2rust/workflow/schemas.py +265 -0
- python2rust/workflow/state.py +392 -0
- python2rust/workflow/staticscan.py +209 -0
- python2rust-0.1.0.dist-info/METADATA +395 -0
- python2rust-0.1.0.dist-info/RECORD +102 -0
- python2rust-0.1.0.dist-info/WHEEL +4 -0
- python2rust-0.1.0.dist-info/entry_points.txt +4 -0
- python2rust-0.1.0.dist-info/licenses/LICENSE +21 -0
- python2rust-0.1.0.dist-info/licenses/NOTICE +65 -0
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""The CLI's review floor: areas that always need a human, whatever the core's patterns say.
|
|
2
|
+
|
|
3
|
+
`apply` never accepts a judged-only equivalence pass on `needs_review` code, so what gets flagged is a
|
|
4
|
+
safety property of the CLI. The core flags through its configurable `review_patterns`; this floor adds
|
|
5
|
+
crypto, subprocesses, file writes and permissions. It only ever adds flags, it never removes one.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
FLOOR: tuple[tuple[str, str], ...] = (
|
|
14
|
+
("crypto", r"\b(hashlib|hmac|secrets|cryptography|jwt|bcrypt)\b"),
|
|
15
|
+
("subprocess", r"\b(subprocess|os\.system|os\.popen|os\.exec\w*|os\.spawn\w*)\b"),
|
|
16
|
+
(
|
|
17
|
+
"file writes",
|
|
18
|
+
r"""\bopen\([^)]*,\s*(?:mode\s*=\s*)?['"][rbt+]*[wax+]|\.write_(?:text|bytes)\(|\bshutil\.|"""
|
|
19
|
+
r"""\bos\.(?:remove|unlink|rmdir|rename|replace|makedirs|mkdir|truncate)\b|\.unlink\(""",
|
|
20
|
+
),
|
|
21
|
+
("permissions", r"(?i)\b(chmod|chown|is_admin|grant|revoke)\b|\b\w*permission\w*"),
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def apply_floor(todo: dict[str, Any]) -> dict[str, Any]:
|
|
26
|
+
"""`todo` with `needs_review` set when its Python touches a floor area."""
|
|
27
|
+
if todo.get("needs_review"):
|
|
28
|
+
return todo
|
|
29
|
+
snippet = todo.get("python_snippet", "")
|
|
30
|
+
areas = [name for name, pattern in FLOOR if re.search(pattern, snippet)]
|
|
31
|
+
if not areas:
|
|
32
|
+
return todo
|
|
33
|
+
reason = f"review floor: touches {', '.join(areas)}"
|
|
34
|
+
return {**todo, "needs_review": True, "review_reason": reason}
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
"""A small, strict Rust lexer for the host-access scan and the anti-cheat gate.
|
|
2
|
+
|
|
3
|
+
The scanners used to blank comments and strings with regexes and then match names in what was
|
|
4
|
+
left. Any disagreement with rustc about where a string or comment ends lets code hide inside one
|
|
5
|
+
(`'r#"` is a lifetime and a quote, not a raw string) and, worse, lets the scanner read a real
|
|
6
|
+
`include_str!` as the inside of a literal. This lexer follows rustc_lexer (lifetimes against char
|
|
7
|
+
literals, raw strings with any number of hashes, byte / C / raw prefixes, nested block comments,
|
|
8
|
+
raw identifiers, raw lifetimes) and is strict: when it cannot be sure how rustc would split the
|
|
9
|
+
input (an unterminated token, a stray character, a reserved prefix such as `foo"x"`) it raises
|
|
10
|
+
`LexError` and the caller rejects the code. Valid Rust never trips it.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import re
|
|
16
|
+
import unicodedata
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from typing import Literal
|
|
19
|
+
|
|
20
|
+
Kind = Literal["ident", "lifetime", "number", "punct", "string", "char", "comment"]
|
|
21
|
+
|
|
22
|
+
# rustc treats exactly the Unicode Pattern_White_Space characters as whitespace
|
|
23
|
+
_WHITESPACE = frozenset("\t\n\v\f\r \x85\u200e\u200f\u2028\u2029")
|
|
24
|
+
_PUNCT_CHARS = frozenset("!#$%&()*+,-./:;<=>?@[]^{|}~")
|
|
25
|
+
_MULTI = ("..=", "::", "..", "=>", "->", "==", "!=", "<=", ">=", "&&", "||")
|
|
26
|
+
_STRING_PREFIX = re.compile(r"(?:br|cr|r)(#*)\"|[bc]\"")
|
|
27
|
+
_MAX_HASHES = 255
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class LexError(ValueError):
|
|
31
|
+
"""The input cannot be split into tokens with certainty; `line` is 1-based."""
|
|
32
|
+
|
|
33
|
+
def __init__(self, message: str, line: int) -> None:
|
|
34
|
+
super().__init__(f"{message} (line {line})")
|
|
35
|
+
self.message = message
|
|
36
|
+
self.line = line
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True)
|
|
40
|
+
class Token:
|
|
41
|
+
kind: Kind
|
|
42
|
+
start: int
|
|
43
|
+
end: int
|
|
44
|
+
text: str # ident: NFC-normalised name without any `r#`; literals and comments: the raw source
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _is_id_start(c: str) -> bool:
|
|
48
|
+
return c != "" and (c == "_" or c.isidentifier())
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _is_id_continue(c: str) -> bool:
|
|
52
|
+
return c != "" and ("a" + c).isidentifier()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def lex(code: str, *, strict: bool = True) -> list[Token]:
|
|
56
|
+
"""All tokens of `code`, whitespace excluded. Strict mode raises `LexError` on anything dubious;
|
|
57
|
+
lenient mode (for locating spans in output the tool generated itself) turns an unterminated
|
|
58
|
+
token into one that runs to the end of the input and skips stray characters."""
|
|
59
|
+
toks: list[Token] = []
|
|
60
|
+
n = len(code)
|
|
61
|
+
|
|
62
|
+
def line_of(pos: int) -> int:
|
|
63
|
+
return code.count("\n", 0, pos) + 1
|
|
64
|
+
|
|
65
|
+
def fail(message: str, pos: int) -> int:
|
|
66
|
+
if strict:
|
|
67
|
+
raise LexError(message, line_of(pos))
|
|
68
|
+
return n # lenient: the broken token swallows the rest
|
|
69
|
+
|
|
70
|
+
def emit(kind: Kind, start: int, end: int, text: str | None = None) -> None:
|
|
71
|
+
toks.append(Token(kind, start, end, code[start:end] if text is None else text))
|
|
72
|
+
|
|
73
|
+
def quoted(pos: int, quote: str) -> int:
|
|
74
|
+
"""End (exclusive) of a `"`/`'` literal body starting after the opener at pos; -1 if none."""
|
|
75
|
+
j = pos
|
|
76
|
+
while j < n:
|
|
77
|
+
c = code[j]
|
|
78
|
+
if c == "\\":
|
|
79
|
+
j += 2
|
|
80
|
+
elif c == quote:
|
|
81
|
+
return j + 1
|
|
82
|
+
elif c == "\n" and quote == "'":
|
|
83
|
+
return -1
|
|
84
|
+
else:
|
|
85
|
+
j += 1
|
|
86
|
+
return -1
|
|
87
|
+
|
|
88
|
+
def char_literal(start: int, body: int) -> int:
|
|
89
|
+
"""End of a char/byte literal whose body begins at `body`: one char or an escape."""
|
|
90
|
+
if body < n and code[body] == "\\":
|
|
91
|
+
end = quoted(body, "'")
|
|
92
|
+
return end if end != -1 and end - body >= 3 else -1
|
|
93
|
+
if body + 1 < n and code[body] not in "'\n" and code[body + 1] == "'":
|
|
94
|
+
return body + 2
|
|
95
|
+
return -1
|
|
96
|
+
|
|
97
|
+
i = 1 if code.startswith("\ufeff") else 0 # rustc drops a leading byte order mark
|
|
98
|
+
while i < n:
|
|
99
|
+
c = code[i]
|
|
100
|
+
if c in _WHITESPACE:
|
|
101
|
+
i += 1
|
|
102
|
+
elif code.startswith("//", i):
|
|
103
|
+
j = code.find("\n", i)
|
|
104
|
+
j = n if j < 0 else j
|
|
105
|
+
emit("comment", i, j)
|
|
106
|
+
i = j
|
|
107
|
+
elif code.startswith("/*", i):
|
|
108
|
+
depth, j = 1, i + 2
|
|
109
|
+
while j < n and depth:
|
|
110
|
+
if code.startswith("/*", j):
|
|
111
|
+
depth, j = depth + 1, j + 2
|
|
112
|
+
elif code.startswith("*/", j):
|
|
113
|
+
depth, j = depth - 1, j + 2
|
|
114
|
+
else:
|
|
115
|
+
j += 1
|
|
116
|
+
if depth:
|
|
117
|
+
j = fail("unterminated block comment", i)
|
|
118
|
+
emit("comment", i, j)
|
|
119
|
+
i = j
|
|
120
|
+
elif c == '"':
|
|
121
|
+
j = quoted(i + 1, '"')
|
|
122
|
+
if j == -1:
|
|
123
|
+
j = fail("unterminated string literal", i)
|
|
124
|
+
emit("string", i, j)
|
|
125
|
+
i = j
|
|
126
|
+
elif c == "'":
|
|
127
|
+
nxt, after = code[i + 1 : i + 2], code[i + 2 : i + 3]
|
|
128
|
+
if (_is_id_start(nxt) or (nxt.isascii() and nxt.isdecimal())) and after != "'":
|
|
129
|
+
# a lifetime, a raw lifetime (`'r#name`) or a multi-character "char" (rustc: error)
|
|
130
|
+
j = i + 1
|
|
131
|
+
if code.startswith("r#", j) and _is_id_start(code[j + 2 : j + 3]):
|
|
132
|
+
j += 2
|
|
133
|
+
while j < n and _is_id_continue(code[j]):
|
|
134
|
+
j += 1
|
|
135
|
+
if code[j : j + 1] == "'":
|
|
136
|
+
fail("a character literal holds more than one character", i)
|
|
137
|
+
j += 1 # lenient: it ends at its closing quote, as rustc lexes it
|
|
138
|
+
emit("char", i, j)
|
|
139
|
+
else:
|
|
140
|
+
emit("lifetime", i, j)
|
|
141
|
+
else:
|
|
142
|
+
j = char_literal(i, i + 1)
|
|
143
|
+
if j == -1:
|
|
144
|
+
j = fail("malformed or unterminated character literal", i)
|
|
145
|
+
emit("char", i, j)
|
|
146
|
+
i = j
|
|
147
|
+
elif _is_id_start(c):
|
|
148
|
+
if (m := _STRING_PREFIX.match(code, i)) is not None:
|
|
149
|
+
hashes = len(m.group(1) or "")
|
|
150
|
+
if hashes > _MAX_HASHES:
|
|
151
|
+
fail("raw string with too many #", i)
|
|
152
|
+
if m.group().endswith('"') and "r" in m.group()[:2]:
|
|
153
|
+
closing = '"' + "#" * hashes
|
|
154
|
+
end = code.find(closing, m.end())
|
|
155
|
+
j = n if end < 0 else end + len(closing)
|
|
156
|
+
if end < 0:
|
|
157
|
+
j = fail("unterminated raw string", i)
|
|
158
|
+
else:
|
|
159
|
+
j = quoted(m.end(), '"')
|
|
160
|
+
if j == -1:
|
|
161
|
+
j = fail("unterminated string literal", i)
|
|
162
|
+
emit("string", i, j)
|
|
163
|
+
i = j
|
|
164
|
+
elif code.startswith("b'", i):
|
|
165
|
+
j = char_literal(i, i + 2)
|
|
166
|
+
if j == -1:
|
|
167
|
+
j = fail("malformed or unterminated byte literal", i)
|
|
168
|
+
emit("char", i, j)
|
|
169
|
+
i = j
|
|
170
|
+
else:
|
|
171
|
+
raw = code.startswith("r#", i) and _is_id_start(code[i + 2 : i + 3])
|
|
172
|
+
j = i + 2 if raw else i
|
|
173
|
+
j0 = j
|
|
174
|
+
while j < n and _is_id_continue(code[j]):
|
|
175
|
+
j += 1
|
|
176
|
+
if j < n and code[j] in "\"'#":
|
|
177
|
+
# a reserved prefix (`foo"x"`, `foo#"x"#`, `br#x`): rustc 2021+ refuses it
|
|
178
|
+
j = fail("reserved prefix before a quote or #", i)
|
|
179
|
+
emit("ident", i, j, unicodedata.normalize("NFC", code[j0:j]))
|
|
180
|
+
i = j
|
|
181
|
+
elif c.isdecimal() and c.isascii():
|
|
182
|
+
j = i
|
|
183
|
+
while j < n and (_is_id_continue(code[j])):
|
|
184
|
+
j += 1
|
|
185
|
+
text = code[i:j]
|
|
186
|
+
hexlike = text[:2].lower() in ("0x", "0b", "0o")
|
|
187
|
+
if code[j : j + 1] == "." and not hexlike:
|
|
188
|
+
after = code[j + 1 : j + 2]
|
|
189
|
+
if after.isdecimal() and after.isascii():
|
|
190
|
+
j += 1
|
|
191
|
+
while j < n and _is_id_continue(code[j]):
|
|
192
|
+
j += 1
|
|
193
|
+
elif after != "." and not _is_id_start(after):
|
|
194
|
+
j += 1 # `1.` is a float
|
|
195
|
+
text = code[i:j]
|
|
196
|
+
if (
|
|
197
|
+
not hexlike
|
|
198
|
+
and text[-1:] in ("e", "E")
|
|
199
|
+
and code[j : j + 1] in ("+", "-")
|
|
200
|
+
and code[j + 1 : j + 2].isdecimal()
|
|
201
|
+
):
|
|
202
|
+
j += 1
|
|
203
|
+
while j < n and _is_id_continue(code[j]):
|
|
204
|
+
j += 1
|
|
205
|
+
emit("number", i, j)
|
|
206
|
+
i = j
|
|
207
|
+
elif c in _PUNCT_CHARS:
|
|
208
|
+
op = next((m for m in _MULTI if code.startswith(m, i)), c)
|
|
209
|
+
emit("punct", i, i + len(op))
|
|
210
|
+
i += len(op)
|
|
211
|
+
else:
|
|
212
|
+
if strict:
|
|
213
|
+
raise LexError(f"unknown start of token {c!r}", line_of(i))
|
|
214
|
+
i += 1
|
|
215
|
+
return toks
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def code_tokens(code: str, *, strict: bool = True) -> list[Token]:
|
|
219
|
+
"""The tokens that are code: no comments, string or char literals."""
|
|
220
|
+
return [t for t in lex(code, strict=strict) if t.kind not in ("comment", "string", "char")]
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def blank_noise(code: str) -> str:
|
|
224
|
+
"""`code` with comments and string/char literals replaced by spaces (newlines kept), so every
|
|
225
|
+
offset and line number of what is left is unchanged. Lenient: never raises."""
|
|
226
|
+
out = list(code)
|
|
227
|
+
for t in lex(code, strict=False):
|
|
228
|
+
if t.kind in ("comment", "string", "char"):
|
|
229
|
+
for k in range(t.start, t.end):
|
|
230
|
+
if out[k] != "\n":
|
|
231
|
+
out[k] = " "
|
|
232
|
+
return "".join(out)
|
|
File without changes
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""`doctor`: is this machine ready to run python2rust?"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib.util
|
|
6
|
+
import sys
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from python2rust._core import core_name
|
|
10
|
+
from python2rust.cli.ops import envelope, load_config
|
|
11
|
+
from python2rust.errors import EXIT_FINDINGS, EXIT_OK, InternalError
|
|
12
|
+
from python2rust.verify.check import ToolError, tool_version
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _check(name: str, status: str, detail: str, required: bool = False) -> dict[str, Any]:
|
|
16
|
+
return {"name": name, "status": status, "detail": detail, "required": required}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def doctor_doc(config_path: str | None = None) -> tuple[dict[str, Any], int]:
|
|
20
|
+
checks = []
|
|
21
|
+
v = sys.version_info
|
|
22
|
+
checks.append(
|
|
23
|
+
_check(
|
|
24
|
+
"python",
|
|
25
|
+
"ok" if v >= (3, 14) else "fail",
|
|
26
|
+
f"{v.major}.{v.minor}.{v.micro}"
|
|
27
|
+
+ ("" if v >= (3, 14) else " (python2rust needs >= 3.14)"),
|
|
28
|
+
required=True,
|
|
29
|
+
)
|
|
30
|
+
)
|
|
31
|
+
try:
|
|
32
|
+
checks.append(_check("core", "ok", core_name(), required=True))
|
|
33
|
+
except InternalError as exc:
|
|
34
|
+
checks.append(_check("core", "fail", str(exc), required=True))
|
|
35
|
+
for tool, why in (
|
|
36
|
+
("rustfmt", "formats and parse-checks the Rust"),
|
|
37
|
+
("cargo", "needed by `check` and `verify`"),
|
|
38
|
+
):
|
|
39
|
+
try:
|
|
40
|
+
version = tool_version(tool)
|
|
41
|
+
except ToolError as exc:
|
|
42
|
+
checks.append(_check(tool, "warn", f"found on PATH but failed to run: {exc}"))
|
|
43
|
+
continue
|
|
44
|
+
checks.append(
|
|
45
|
+
_check(tool, "ok" if version else "warn", version or f"not found on PATH ({why})")
|
|
46
|
+
)
|
|
47
|
+
mcp = importlib.util.find_spec("mcp") is not None
|
|
48
|
+
checks.append(
|
|
49
|
+
_check(
|
|
50
|
+
"mcp-sdk",
|
|
51
|
+
"ok" if mcp else "warn",
|
|
52
|
+
"installed" if mcp else "missing: pip install 'python2rust[mcp]'",
|
|
53
|
+
)
|
|
54
|
+
)
|
|
55
|
+
if config_path is not None:
|
|
56
|
+
try:
|
|
57
|
+
load_config(config_path)
|
|
58
|
+
checks.append(_check("config", "ok", config_path, required=True))
|
|
59
|
+
except Exception as exc:
|
|
60
|
+
checks.append(_check("config", "fail", str(exc), required=True))
|
|
61
|
+
ok = all(c["status"] != "fail" for c in checks)
|
|
62
|
+
return envelope("doctor", ok=ok, checks=checks), EXIT_OK if ok else EXIT_FINDINGS
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Turning command-line paths (files, directories, `-`) into an ordered list of sources."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import sys
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from python2rust.errors import UsageError
|
|
10
|
+
|
|
11
|
+
_SKIP_DIRS = {
|
|
12
|
+
"__pycache__",
|
|
13
|
+
"node_modules",
|
|
14
|
+
"site-packages",
|
|
15
|
+
"venv",
|
|
16
|
+
"env",
|
|
17
|
+
"build",
|
|
18
|
+
"dist",
|
|
19
|
+
"target",
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class Source:
|
|
25
|
+
display: str # stable name used in every output (posix, as given by the caller)
|
|
26
|
+
rel: str # path below the output directory (posix)
|
|
27
|
+
text: str | None # None when the file could not be read
|
|
28
|
+
read_error: str | None = None
|
|
29
|
+
root: str | None = None # the directory argument it was found under (None: a file or stdin)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _skip(part: str) -> bool:
|
|
33
|
+
return part.startswith(".") or part in _SKIP_DIRS or part.endswith(".egg-info")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _walk(root: Path, suffixes: tuple[str, ...]) -> list[Path]:
|
|
37
|
+
"""Files below `root`, never following a symlink out of it (a link could point anywhere)."""
|
|
38
|
+
real = root.resolve()
|
|
39
|
+
return sorted(
|
|
40
|
+
p
|
|
41
|
+
for p in root.rglob("*")
|
|
42
|
+
if p.suffix in suffixes
|
|
43
|
+
and not p.is_symlink()
|
|
44
|
+
and p.is_file()
|
|
45
|
+
and p.resolve().is_relative_to(real)
|
|
46
|
+
and not any(_skip(part) for part in p.relative_to(root).parts[:-1])
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _read(path: Path) -> tuple[str | None, str | None]:
|
|
51
|
+
try:
|
|
52
|
+
return path.read_text(encoding="utf-8"), None
|
|
53
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
54
|
+
return None, f"cannot read {path}: {exc}"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def collect(
|
|
58
|
+
paths: list[str], *, suffixes: tuple[str, ...] = (".py",), stdin_filename: str = "<stdin>.py"
|
|
59
|
+
) -> list[Source]:
|
|
60
|
+
"""Resolve `paths` to sources, sorted by display name, duplicates removed.
|
|
61
|
+
|
|
62
|
+
Directories are walked recursively for `suffixes` files (hidden directories, virtualenvs and
|
|
63
|
+
build output are skipped). Explicit files are accepted whatever their extension.
|
|
64
|
+
"""
|
|
65
|
+
if not paths:
|
|
66
|
+
raise UsageError("no input paths given (use a file, a directory, or - for stdin)")
|
|
67
|
+
if paths.count("-") > 1:
|
|
68
|
+
raise UsageError("stdin (-) can only be given once")
|
|
69
|
+
found: dict[str, Source] = {}
|
|
70
|
+
seen: set[Path] = set()
|
|
71
|
+
|
|
72
|
+
def add(src: Source) -> None:
|
|
73
|
+
if src.display in found:
|
|
74
|
+
raise UsageError(f"two inputs resolve to the same name: {src.display}")
|
|
75
|
+
found[src.display] = src
|
|
76
|
+
|
|
77
|
+
for raw in paths:
|
|
78
|
+
if raw == "-":
|
|
79
|
+
add(Source(stdin_filename, Path(stdin_filename).name, sys.stdin.read()))
|
|
80
|
+
continue
|
|
81
|
+
path = Path(raw)
|
|
82
|
+
if not path.exists():
|
|
83
|
+
raise UsageError(f"path does not exist: {raw}")
|
|
84
|
+
if path.is_dir():
|
|
85
|
+
files = [(f, f.relative_to(path)) for f in _walk(path, suffixes)]
|
|
86
|
+
if not files:
|
|
87
|
+
raise UsageError(f"no {'/'.join(suffixes)} files found under: {raw}")
|
|
88
|
+
else:
|
|
89
|
+
files = [(path, Path(path.name))]
|
|
90
|
+
for file, rel in files:
|
|
91
|
+
key = file.resolve()
|
|
92
|
+
if key in seen:
|
|
93
|
+
continue
|
|
94
|
+
seen.add(key)
|
|
95
|
+
text, err = _read(file)
|
|
96
|
+
add(Source(file.as_posix(), rel.as_posix(), text, err, raw if path.is_dir() else None))
|
|
97
|
+
return [found[k] for k in sorted(found)]
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def check_rel_collisions(sources: list[Source]) -> None:
|
|
101
|
+
"""With `-o DIR` two inputs must not map to the same output file."""
|
|
102
|
+
seen: dict[str, str] = {}
|
|
103
|
+
for s in sources:
|
|
104
|
+
if (other := seen.setdefault(s.rel, s.display)) != s.display:
|
|
105
|
+
raise UsageError(f"{other} and {s.display} would both be written to {s.rel}")
|