-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibcst.py
More file actions
200 lines (156 loc) · 5.48 KB
/
libcst.py
File metadata and controls
200 lines (156 loc) · 5.48 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
from __future__ import annotations
from collections.abc import Sequence
from dataclasses import dataclass
from subprocess import CalledProcessError, check_output
from typing import assert_never, override
from libcst import (
AsName,
Attribute,
BaseExpression,
FormattedString,
FormattedStringExpression,
FormattedStringText,
Import,
ImportAlias,
ImportFrom,
ImportStar,
Module,
Name,
)
from utilities.errors import ImpossibleCaseError
def generate_f_string(var: str, suffix: str, /) -> FormattedString:
"""Generate an f-string."""
return FormattedString([
FormattedStringExpression(expression=Name(var)),
FormattedStringText(suffix),
])
def generate_import(module: str, /, *, asname: str | None = None) -> Import:
"""Generate an `Import` object."""
alias = ImportAlias(
name=split_dotted_str(module), asname=AsName(Name(asname)) if asname else None
)
return Import(names=[alias])
def generate_import_from(
module: str, name: str, /, *, asname: str | None = None
) -> ImportFrom:
"""Generate an `ImportFrom` object."""
match name, asname:
case "*", None:
names = ImportStar()
case "*", str():
raise GenerateImportFromError(module=module, asname=asname)
case _, None:
alias = ImportAlias(name=Name(name))
names = [alias]
case _, str():
alias = ImportAlias(name=Name(name), asname=AsName(Name(asname)))
names = [alias]
case never:
assert_never(never)
return ImportFrom(module=split_dotted_str(module), names=names)
@dataclass(kw_only=True, slots=True)
class GenerateImportFromError(Exception):
module: str
asname: str | None = None
@override
def __str__(self) -> str:
return f"Invalid import: 'from {self.module} import * as {self.asname}'"
##
@dataclass(order=True, unsafe_hash=True, kw_only=True, slots=True)
class _ParseImportOutput:
module: str
name: str | None = None
def parse_import(import_: Import | ImportFrom, /) -> Sequence[_ParseImportOutput]:
"""Parse an import."""
match import_:
case Import():
return [_parse_import_one(n) for n in import_.names]
case ImportFrom():
if (attr_or_name := import_.module) is None:
raise _ParseImportEmptyModuleError(import_=import_)
module = join_dotted_str(attr_or_name)
match import_.names:
case Sequence() as names:
return [_parse_import_from_one(module, n) for n in names]
case ImportStar():
return [_ParseImportOutput(module=module, name="*")]
case never:
assert_never(never)
case never:
assert_never(never)
def _parse_import_one(alias: ImportAlias, /) -> _ParseImportOutput:
return _ParseImportOutput(module=join_dotted_str(alias.name))
def _parse_import_from_one(module: str, alias: ImportAlias, /) -> _ParseImportOutput:
match alias.name:
case Name(name):
return _ParseImportOutput(module=module, name=name)
case Attribute() as attr:
raise _ParseImportAliasError(module=module, attr=attr)
case never:
assert_never(never)
@dataclass(kw_only=True, slots=True)
class ParseImportError(Exception): ...
@dataclass(kw_only=True, slots=True)
class _ParseImportEmptyModuleError(ParseImportError):
import_: ImportFrom
@override
def __str__(self) -> str:
return f"Module must not be None; got {self.import_}"
@dataclass(kw_only=True, slots=True)
class _ParseImportAliasError(ParseImportError):
module: str
attr: Attribute
@override
def __str__(self) -> str:
attr = self.attr
return f"Invalid alias name; got module {self.module!r} and attribute '{attr.value}.{attr.attr}'"
##
def split_dotted_str(dotted: str, /) -> Name | Attribute:
"""Split a dotted string into a name/attribute."""
parts = dotted.split(".")
node = Name(parts[0])
for part in parts[1:]:
node = Attribute(value=node, attr=Name(part))
return node
def join_dotted_str(name_or_attr: Name | Attribute, /) -> str:
"""Join a dotted from from a name/attribute."""
parts: list[str] = []
curr: BaseExpression | Name | Attribute = name_or_attr
while True:
match curr:
case Name(value=value):
parts.append(value)
break
case Attribute(value=value, attr=Name(value=attr_value)):
parts.append(attr_value)
curr = value
case BaseExpression(): # pragma: no cover
raise ImpossibleCaseError(case=[f"{curr=}"])
case never:
assert_never(never)
return ".".join(reversed(parts))
##
def render_module(source: str | Module, /) -> str:
"""Render a module."""
match source: # skipif-ci
case str() as text:
try:
return check_output(["ruff", "format", "-"], input=text, text=True)
except CalledProcessError: # pragma: no cover
return text
case Module() as module:
return render_module(module.code)
case never:
assert_never(never)
##
__all__ = [
"GenerateImportFromError",
"ParseImportError",
"generate_f_string",
"generate_import",
"generate_import_from",
"join_dotted_str",
"parse_import",
"render_module",
"split_dotted_str",
]