remold 0.1.0__tar.gz

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.
@@ -0,0 +1,6 @@
1
+ <!-- do not remove -->
2
+
3
+ ## 0.1.0
4
+
5
+ - Init commit
6
+
remold-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,3 @@
1
+ include README.md
2
+ include LICENSE
3
+ include CHANGELOG.md
remold-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,171 @@
1
+ Metadata-Version: 2.4
2
+ Name: remold
3
+ Version: 0.1.0
4
+ Summary: Reshape Python source with LibCST: structure in the tree, comments and whitespace as plain text
5
+ Author: remold contributors
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/AnswerDotAI/remold
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3 :: Only
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: libcst
14
+ Requires-Dist: ast-grep-py
15
+ Provides-Extra: dev
16
+ Requires-Dist: fastship; extra == "dev"
17
+ Requires-Dist: build; extra == "dev"
18
+ Requires-Dist: twine; extra == "dev"
19
+ Dynamic: license-file
20
+
21
+ # remold
22
+
23
+ Concisely reshape Python code with [LibCST](https://github.com/Instagram/LibCST) or [ast-grep](https://ast-grep.github.io/).
24
+
25
+ ```bash
26
+ pip install remold
27
+ ```
28
+
29
+ Tools like `ast` throw comments away, and regex rewrites break on real code. remold keeps the source intact and gives you two ways to build composable `str -> str` transforms:
30
+
31
+ - `astmap(*rules)` applies ast-grep pattern rules. Use it when you can write the rewrite as a before pattern and an after template. Only the matched span is replaced, so comments elsewhere are untouched.
32
+ - `cstmap(matcher, fn, trivia='keep')` takes a [LibCST matcher](https://libcst.readthedocs.io/en/latest/matchers.html) and a function, for everything patterns can't express, including transforms that only change comments and whitespace. `fn(node, caps)` returns `None` (leave it), a string (reparsed in place, so the output is guaranteed to parse), or a CST node (full surgery).
33
+
34
+ The idea behind `cstmap` is to match structure in the tree, where matching is easy, and to write the new code as a plain string, where comments and whitespace are just characters. Two helpers make that workable. `code(node)` renders any node back to source text, trivia included. `whereis(src, *frags)` tells you where LibCST keeps things, so you don't have to search the node docs.
35
+
36
+ `from remold import *` gives you all four plus `cst` (libcst) and `m` (libcst.matchers).
37
+
38
+ ## Pattern rules
39
+
40
+ Turn `test_fail(lambda: f(x), contains='boom')` into `with expect_fail(Exception, 'boom'): f(x)`:
41
+
42
+ ```python
43
+ from remold import *
44
+
45
+ fix_tests = astmap(
46
+ ("test_fail(lambda: $BODY, contains=$MSG)", "with expect_fail(Exception, $MSG): $BODY"),
47
+ ("test_fail(lambda: $BODY)", "with expect_fail(Exception): $BODY"))
48
+
49
+ print(fix_tests("test_fail(lambda: f(x), contains='boom') # tricky case\n"))
50
+ # with expect_fail(Exception, 'boom'): f(x) # tricky case
51
+ ```
52
+
53
+ Rules are applied in order, with a reparse between each, so later rules see the output of earlier ones. A replacement can also be a `callable(match) -> str` when the new text needs computing. Code that matches no pattern (like `test_fail(divide, args=(1,0))`) is left alone, and an unknown `$VAR` in a template raises a `KeyError`.
54
+
55
+ ## The same transform with matchers
56
+
57
+ For rewrites patterns can't express, write a LibCST matcher and a function. Here is the same transform in that form:
58
+
59
+ ```python
60
+ tf = m.SimpleStatementLine(body=[m.Expr(m.Call(
61
+ func=m.Name('test_fail'),
62
+ args=[m.Arg(m.Lambda(body=m.SaveMatchedNode(m.DoNotCare(), 'body'))),
63
+ m.Arg(keyword=m.Name('contains'), value=m.SaveMatchedNode(m.DoNotCare(), 'msg'))]))])
64
+
65
+ def fix(node, caps): return f"with expect_fail(Exception, {code(caps['msg'])}): {code(caps['body'])}"
66
+
67
+ fix_tests = cstmap(tf, fix)
68
+ print(fix_tests("test_fail(lambda: f(x), contains='boom') # tricky case\n"))
69
+ # with expect_fail(Exception, 'boom'): f(x) # tricky case
70
+ ```
71
+
72
+ The trailing comment is kept because `trivia='keep'` (the default) copies the matched statement's leading lines and trailing comment onto whatever `fn` returns. The matcher also acts as a guard. A `test_fail(f, args=(1,0))` call doesn't match the arg spec, so it isn't changed.
73
+
74
+ ## Example: move a comment
75
+
76
+ With `trivia='given'`, the string you return is used exactly as given, so to move a comment you write it where you want it:
77
+
78
+ ```python
79
+ def fix(node, caps):
80
+ c = node.trailing_whitespace.comment
81
+ new = f"with expect_fail(Exception, {code(caps['msg'])}): {code(caps['body'])}"
82
+ return f"{code(c)}\n{new}" if c else new
83
+
84
+ print(cstmap(tf, fix, trivia='given')("test_fail(lambda: f(), contains='x') # ho\n"))
85
+ # # ho
86
+ # with expect_fail(Exception, 'x'): f()
87
+ ```
88
+
89
+ A multi-line string becomes multiple statements, and returning `''` deletes the statement.
90
+
91
+ ## Example: reformat a signature
92
+
93
+ Here the code itself doesn't change; only the comments and line layout do. The pieces are read from the tree, and the new layout is built with ordinary string operations:
94
+
95
+ ```python
96
+ def fix(fd, _):
97
+ ps = [code(p).strip() for p in fd.params.params] # each param arrives with its comment attached
98
+ c = fd.body.header.comment # a comment after ':' lives on the body header
99
+ if c: ps[-1] = f"{ps[-1]} {code(c)}"
100
+ return f"def {fd.name.value}(\n " + "\n ".join(ps) + "\n):" + code(fd.body.with_changes(header=cst.TrailingWhitespace()))
101
+
102
+ src = """def f(foo, # hey
103
+ bam, # gg
104
+ bar): # ho
105
+ pass
106
+ """
107
+ print(cstmap(m.FunctionDef(), fix, trivia='given')(src))
108
+ # def f(
109
+ # foo, # hey
110
+ # bam, # gg
111
+ # bar # ho
112
+ # ):
113
+ # pass
114
+ ```
115
+
116
+ ## Moving code across depths
117
+
118
+ Indentation in LibCST is contextual, not literal. Statement lines, continuation lines inside brackets, and comment lines all record "indent goes here" rather than a column number, and the indent size comes from the target module's `default_indent`. Since `cstmap` parses your returned string as its own little module and splices the resulting statements into the real one, code written at one depth renders correctly at whatever depth it lands, in the target file's indent style. The one thing never re-indented is the content of multiline strings, since changing that would change the program.
119
+
120
+ This makes depth-changing transforms work without any bookkeeping. Here a method is pulled out of its class and turned into a top-level fastcore `@patch` function. Note the trick: matching the `FunctionDef` would replace the method in place, still inside the class, so to *move* code you match the enclosing `ClassDef` and return the whole new arrangement. A multi-line replacement becomes several sibling statements.
121
+
122
+ ```python
123
+ def fix(cd, _):
124
+ fs = [s for s in cd.body.body if m.matches(s, m.FunctionDef(name=m.Name('f')))]
125
+ if not fs: return None
126
+ fd = fs[0]
127
+ rest = cd.with_changes(body=cd.body.with_changes(body=[s for s in cd.body.body if s is not fd]))
128
+ p1 = code(fd.params.params[0]).strip().rstrip(',')
129
+ ps = ', '.join([f'{p1}:{cd.name.value}'] + [code(p).strip().rstrip(',') for p in fd.params.params[1:]])
130
+ return f"{code(rest)}\n@patch\ndef {fd.name.value}({ps}):{code(fd.body)}"
131
+
132
+ src = """class A:
133
+ def __init__(self): self.x = 1
134
+
135
+ def f(self, n): # add `n` to `x`
136
+ y = self.x+n
137
+ return y
138
+ """
139
+ print(cstmap(m.ClassDef(), fix, trivia='given')(src))
140
+ # class A:
141
+ # def __init__(self): self.x = 1
142
+ #
143
+ # @patch
144
+ # def f(self:A, n): # add `n` to `x`
145
+ # y = self.x+n
146
+ # return y
147
+ ```
148
+
149
+ The method body was written at depth 2 and lands at depth 1; `code(fd.body)` carried it along with its comment, and the render re-indented it. The `self` parameter picks up the class as its type annotation, which is how `@patch` knows what to patch.
150
+
151
+ ## whereis
152
+
153
+ How did that example know a comment after the colon is `fd.body.header.comment`? Ask:
154
+
155
+ ```python
156
+ whereis(src, 'foo', '# ho', '# hey')
157
+ # {'foo': ['.body[0].params.params[0].name'],
158
+ # '# ho': ['.body[0].body.header.comment', ...],
159
+ # '# hey': ['.body[0].params.params[0].comma.whitespace_after.first_line.comment', ...]}
160
+ ```
161
+
162
+ Paste a representative snippet, ask for the fragments you care about, and copy the paths into your `fn`. Multiple entries per fragment list the node itself first, then its containers. `contains=True` matches fragments inside larger nodes.
163
+
164
+ ## Development
165
+
166
+ ```bash
167
+ pip install -e .[dev]
168
+ pytest -q
169
+ ```
170
+
171
+ Version lives in `remold/__init__.py` as `__version__`; bump with `ship-bump`. Release with `ship-gh` and `ship-pypi`.
remold-0.1.0/README.md ADDED
@@ -0,0 +1,151 @@
1
+ # remold
2
+
3
+ Concisely reshape Python code with [LibCST](https://github.com/Instagram/LibCST) or [ast-grep](https://ast-grep.github.io/).
4
+
5
+ ```bash
6
+ pip install remold
7
+ ```
8
+
9
+ Tools like `ast` throw comments away, and regex rewrites break on real code. remold keeps the source intact and gives you two ways to build composable `str -> str` transforms:
10
+
11
+ - `astmap(*rules)` applies ast-grep pattern rules. Use it when you can write the rewrite as a before pattern and an after template. Only the matched span is replaced, so comments elsewhere are untouched.
12
+ - `cstmap(matcher, fn, trivia='keep')` takes a [LibCST matcher](https://libcst.readthedocs.io/en/latest/matchers.html) and a function, for everything patterns can't express, including transforms that only change comments and whitespace. `fn(node, caps)` returns `None` (leave it), a string (reparsed in place, so the output is guaranteed to parse), or a CST node (full surgery).
13
+
14
+ The idea behind `cstmap` is to match structure in the tree, where matching is easy, and to write the new code as a plain string, where comments and whitespace are just characters. Two helpers make that workable. `code(node)` renders any node back to source text, trivia included. `whereis(src, *frags)` tells you where LibCST keeps things, so you don't have to search the node docs.
15
+
16
+ `from remold import *` gives you all four plus `cst` (libcst) and `m` (libcst.matchers).
17
+
18
+ ## Pattern rules
19
+
20
+ Turn `test_fail(lambda: f(x), contains='boom')` into `with expect_fail(Exception, 'boom'): f(x)`:
21
+
22
+ ```python
23
+ from remold import *
24
+
25
+ fix_tests = astmap(
26
+ ("test_fail(lambda: $BODY, contains=$MSG)", "with expect_fail(Exception, $MSG): $BODY"),
27
+ ("test_fail(lambda: $BODY)", "with expect_fail(Exception): $BODY"))
28
+
29
+ print(fix_tests("test_fail(lambda: f(x), contains='boom') # tricky case\n"))
30
+ # with expect_fail(Exception, 'boom'): f(x) # tricky case
31
+ ```
32
+
33
+ Rules are applied in order, with a reparse between each, so later rules see the output of earlier ones. A replacement can also be a `callable(match) -> str` when the new text needs computing. Code that matches no pattern (like `test_fail(divide, args=(1,0))`) is left alone, and an unknown `$VAR` in a template raises a `KeyError`.
34
+
35
+ ## The same transform with matchers
36
+
37
+ For rewrites patterns can't express, write a LibCST matcher and a function. Here is the same transform in that form:
38
+
39
+ ```python
40
+ tf = m.SimpleStatementLine(body=[m.Expr(m.Call(
41
+ func=m.Name('test_fail'),
42
+ args=[m.Arg(m.Lambda(body=m.SaveMatchedNode(m.DoNotCare(), 'body'))),
43
+ m.Arg(keyword=m.Name('contains'), value=m.SaveMatchedNode(m.DoNotCare(), 'msg'))]))])
44
+
45
+ def fix(node, caps): return f"with expect_fail(Exception, {code(caps['msg'])}): {code(caps['body'])}"
46
+
47
+ fix_tests = cstmap(tf, fix)
48
+ print(fix_tests("test_fail(lambda: f(x), contains='boom') # tricky case\n"))
49
+ # with expect_fail(Exception, 'boom'): f(x) # tricky case
50
+ ```
51
+
52
+ The trailing comment is kept because `trivia='keep'` (the default) copies the matched statement's leading lines and trailing comment onto whatever `fn` returns. The matcher also acts as a guard. A `test_fail(f, args=(1,0))` call doesn't match the arg spec, so it isn't changed.
53
+
54
+ ## Example: move a comment
55
+
56
+ With `trivia='given'`, the string you return is used exactly as given, so to move a comment you write it where you want it:
57
+
58
+ ```python
59
+ def fix(node, caps):
60
+ c = node.trailing_whitespace.comment
61
+ new = f"with expect_fail(Exception, {code(caps['msg'])}): {code(caps['body'])}"
62
+ return f"{code(c)}\n{new}" if c else new
63
+
64
+ print(cstmap(tf, fix, trivia='given')("test_fail(lambda: f(), contains='x') # ho\n"))
65
+ # # ho
66
+ # with expect_fail(Exception, 'x'): f()
67
+ ```
68
+
69
+ A multi-line string becomes multiple statements, and returning `''` deletes the statement.
70
+
71
+ ## Example: reformat a signature
72
+
73
+ Here the code itself doesn't change; only the comments and line layout do. The pieces are read from the tree, and the new layout is built with ordinary string operations:
74
+
75
+ ```python
76
+ def fix(fd, _):
77
+ ps = [code(p).strip() for p in fd.params.params] # each param arrives with its comment attached
78
+ c = fd.body.header.comment # a comment after ':' lives on the body header
79
+ if c: ps[-1] = f"{ps[-1]} {code(c)}"
80
+ return f"def {fd.name.value}(\n " + "\n ".join(ps) + "\n):" + code(fd.body.with_changes(header=cst.TrailingWhitespace()))
81
+
82
+ src = """def f(foo, # hey
83
+ bam, # gg
84
+ bar): # ho
85
+ pass
86
+ """
87
+ print(cstmap(m.FunctionDef(), fix, trivia='given')(src))
88
+ # def f(
89
+ # foo, # hey
90
+ # bam, # gg
91
+ # bar # ho
92
+ # ):
93
+ # pass
94
+ ```
95
+
96
+ ## Moving code across depths
97
+
98
+ Indentation in LibCST is contextual, not literal. Statement lines, continuation lines inside brackets, and comment lines all record "indent goes here" rather than a column number, and the indent size comes from the target module's `default_indent`. Since `cstmap` parses your returned string as its own little module and splices the resulting statements into the real one, code written at one depth renders correctly at whatever depth it lands, in the target file's indent style. The one thing never re-indented is the content of multiline strings, since changing that would change the program.
99
+
100
+ This makes depth-changing transforms work without any bookkeeping. Here a method is pulled out of its class and turned into a top-level fastcore `@patch` function. Note the trick: matching the `FunctionDef` would replace the method in place, still inside the class, so to *move* code you match the enclosing `ClassDef` and return the whole new arrangement. A multi-line replacement becomes several sibling statements.
101
+
102
+ ```python
103
+ def fix(cd, _):
104
+ fs = [s for s in cd.body.body if m.matches(s, m.FunctionDef(name=m.Name('f')))]
105
+ if not fs: return None
106
+ fd = fs[0]
107
+ rest = cd.with_changes(body=cd.body.with_changes(body=[s for s in cd.body.body if s is not fd]))
108
+ p1 = code(fd.params.params[0]).strip().rstrip(',')
109
+ ps = ', '.join([f'{p1}:{cd.name.value}'] + [code(p).strip().rstrip(',') for p in fd.params.params[1:]])
110
+ return f"{code(rest)}\n@patch\ndef {fd.name.value}({ps}):{code(fd.body)}"
111
+
112
+ src = """class A:
113
+ def __init__(self): self.x = 1
114
+
115
+ def f(self, n): # add `n` to `x`
116
+ y = self.x+n
117
+ return y
118
+ """
119
+ print(cstmap(m.ClassDef(), fix, trivia='given')(src))
120
+ # class A:
121
+ # def __init__(self): self.x = 1
122
+ #
123
+ # @patch
124
+ # def f(self:A, n): # add `n` to `x`
125
+ # y = self.x+n
126
+ # return y
127
+ ```
128
+
129
+ The method body was written at depth 2 and lands at depth 1; `code(fd.body)` carried it along with its comment, and the render re-indented it. The `self` parameter picks up the class as its type annotation, which is how `@patch` knows what to patch.
130
+
131
+ ## whereis
132
+
133
+ How did that example know a comment after the colon is `fd.body.header.comment`? Ask:
134
+
135
+ ```python
136
+ whereis(src, 'foo', '# ho', '# hey')
137
+ # {'foo': ['.body[0].params.params[0].name'],
138
+ # '# ho': ['.body[0].body.header.comment', ...],
139
+ # '# hey': ['.body[0].params.params[0].comma.whitespace_after.first_line.comment', ...]}
140
+ ```
141
+
142
+ Paste a representative snippet, ask for the fragments you care about, and copy the paths into your `fn`. Multiple entries per fragment list the node itself first, then its containers. `contains=True` matches fragments inside larger nodes.
143
+
144
+ ## Development
145
+
146
+ ```bash
147
+ pip install -e .[dev]
148
+ pytest -q
149
+ ```
150
+
151
+ Version lives in `remold/__init__.py` as `__version__`; bump with `ship-bump`. Release with `ship-gh` and `ship-pypi`.
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "remold"
7
+ dynamic = ["version"]
8
+ description = "Reshape Python source with LibCST: structure in the tree, comments and whitespace as plain text"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "Apache-2.0" }
12
+ authors = [{ name = "remold contributors" }]
13
+ classifiers = [
14
+ "Programming Language :: Python :: 3",
15
+ "Programming Language :: Python :: 3 :: Only",
16
+ ]
17
+
18
+ dependencies = ["libcst", "ast-grep-py"]
19
+
20
+ [project.optional-dependencies]
21
+ dev = [
22
+ "fastship",
23
+ "build",
24
+ "twine",
25
+ ]
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/AnswerDotAI/remold"
29
+
30
+ [tool.setuptools.dynamic]
31
+ version = { attr = "remold.__version__" }
32
+
33
+ [tool.setuptools.packages.find]
34
+ include = ["remold"]
@@ -0,0 +1,125 @@
1
+ """Reshape Python source with LibCST: match structure in the tree, write the new code as plain text, and comments and whitespace come along as ordinary characters."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ import re
6
+ from dataclasses import fields
7
+
8
+ import libcst as cst
9
+ import libcst.matchers as m
10
+ from ast_grep_py import SgRoot
11
+
12
+ __all__ = ['cst', 'm', 'astmap', 'cstmap', 'code', 'whereis']
13
+
14
+ def _expand(tmpl, mch):
15
+ "Fill `$VAR` holes in `tmpl` from ast-grep match `mch`"
16
+ def _sub(mo):
17
+ node = mch.get_match(mo.group(1))
18
+ if node is None: raise KeyError(f'${mo.group(1)} not captured by the pattern')
19
+ return node.text()
20
+ return re.sub(r'\$([A-Z_][A-Z0-9_]*)', _sub, tmpl)
21
+
22
+ def astmap(
23
+ *rules # (pattern, repl) pairs; repl is a `$VAR` template or a callable(match)->str
24
+ ):
25
+ "A `str->str` source transform: apply ast-grep pattern rules in order, reparsing between rules"
26
+ def _f(src):
27
+ for pat,repl in rules:
28
+ root = SgRoot(src, 'python').root()
29
+ edits = [mch.replace(repl(mch) if callable(repl) else _expand(repl, mch))
30
+ for mch in root.find_all(pattern=pat)]
31
+ if edits: src = root.commit_edits(edits)
32
+ return src
33
+ return _f
34
+
35
+ _render = cst.Module([]).code_for_node
36
+
37
+ def code(node):
38
+ "Source text for `node`, trivia included"
39
+ return _render(node)
40
+
41
+ def _reparse(node, s):
42
+ "Parse `s` as whatever fits where `node` sits"
43
+ if isinstance(node, (cst.SimpleStatementLine, cst.BaseCompoundStatement)):
44
+ mod = cst.parse_module(s)
45
+ stmts = list(mod.body)
46
+ if any(l.comment for l in mod.footer):
47
+ raise ValueError(f'{s!r} ends with a comment after its last statement, which no statement node can carry; put it before or inline')
48
+ if not stmts: return cst.RemovalSentinel.REMOVE
49
+ if mod.header: stmts[0] = stmts[0].with_changes(leading_lines=[*mod.header, *stmts[0].leading_lines])
50
+ return stmts[0] if len(stmts)==1 else cst.FlattenSentinel(stmts)
51
+ if isinstance(node, cst.BaseSmallStatement):
52
+ stmts = cst.parse_module(s).body
53
+ if len(stmts)==1 and isinstance(stmts[0], cst.SimpleStatementLine) and len(stmts[0].body)==1: return stmts[0].body[0]
54
+ raise ValueError(f'{s!r} is not a single small statement, which is what {type(node).__name__} sits as')
55
+ if isinstance(node, cst.BaseExpression): return cst.parse_expression(s)
56
+ raise TypeError(f"Can't reparse a str in place of {type(node).__name__}; return a CST node instead")
57
+
58
+ def _trailing(n):
59
+ "The `TrailingWhitespace` of statement `n`, or None"
60
+ if isinstance(n, cst.SimpleStatementLine): return n.trailing_whitespace
61
+ if isinstance(n, cst.BaseCompoundStatement):
62
+ if isinstance(n.body, cst.SimpleStatementSuite): return n.body.trailing_whitespace
63
+ if isinstance(n.body, cst.IndentedBlock): return n.body.header
64
+ return None
65
+
66
+ def _set_trailing(n, tw):
67
+ if isinstance(n, cst.SimpleStatementLine): return n.with_changes(trailing_whitespace=tw)
68
+ if isinstance(n, cst.BaseCompoundStatement):
69
+ if isinstance(n.body, cst.SimpleStatementSuite): return n.with_changes(body=n.body.with_changes(trailing_whitespace=tw))
70
+ if isinstance(n.body, cst.IndentedBlock): return n.with_changes(body=n.body.with_changes(header=tw))
71
+ return n
72
+
73
+ def _keep_trivia(old, new):
74
+ "Carry `old`'s leading lines and trailing comment onto `new`"
75
+ nodes = list(new.nodes) if isinstance(new, cst.FlattenSentinel) else [new]
76
+ if hasattr(old, 'leading_lines') and hasattr(nodes[0], 'leading_lines'):
77
+ nodes[0] = nodes[0].with_changes(leading_lines=old.leading_lines)
78
+ tw = _trailing(old)
79
+ if tw is not None and tw.comment is not None: nodes[-1] = _set_trailing(nodes[-1], tw)
80
+ return cst.FlattenSentinel(nodes) if isinstance(new, cst.FlattenSentinel) else nodes[0]
81
+
82
+ class _Mapper(cst.CSTTransformer):
83
+ def __init__(self, matcher, fn, trivia):
84
+ super().__init__()
85
+ self.matcher,self.fn,self.trivia = matcher,fn,trivia
86
+
87
+ def on_leave(self, orig, updated):
88
+ caps = m.extract(updated, self.matcher)
89
+ if caps is None: return updated
90
+ res = self.fn(updated, caps)
91
+ if res is None: return updated
92
+ if isinstance(res, str): res = _reparse(updated, res)
93
+ if self.trivia=='keep' and not isinstance(res, cst.RemovalSentinel): res = _keep_trivia(updated, res)
94
+ return res
95
+
96
+ def cstmap(
97
+ matcher, # A `libcst.matchers` matcher; `m.SaveMatchedNode` captures arrive in `fn`'s second arg
98
+ fn, # `fn(node, caps)` returning None (leave unchanged), a str (reparsed in context), or a CST node
99
+ trivia:str='keep' # 'keep' carries the matched node's leading lines and trailing comment; 'given' means fn's output is everything
100
+ ):
101
+ "A `str->str` source transform: replace every node matching `matcher` with `fn`'s result"
102
+ def _f(src): return cst.parse_module(src).visit(_Mapper(matcher, fn, trivia)).code
103
+ return _f
104
+
105
+ def _walk(node, path=''):
106
+ yield path, node
107
+ for f in fields(node):
108
+ v = getattr(node, f.name)
109
+ if isinstance(v, cst.CSTNode): yield from _walk(v, f'{path}.{f.name}')
110
+ elif isinstance(v, (tuple, list)):
111
+ for i,x in enumerate(v):
112
+ if isinstance(x, cst.CSTNode): yield from _walk(x, f'{path}.{f.name}[{i}]')
113
+
114
+ def whereis(
115
+ src:str, # Source snippet to interrogate
116
+ *frags:str, # Fragments to locate, e.g. 'foo', '# ho'
117
+ contains:bool=False # Match nodes containing the fragment, not just equal to it
118
+ ) -> dict:
119
+ "For each fragment, the attribute paths where LibCST keeps it, deepest node first"
120
+ mod = cst.parse_module(src)
121
+ def _hit(n, frag):
122
+ c = _render(n).strip()
123
+ return frag in c if contains else c==frag
124
+ return {frag: [p for p,n in sorted(((p,n) for p,n in _walk(mod) if p and _hit(n, frag)), key=lambda o: -len(o[0]))]
125
+ for frag in frags}
@@ -0,0 +1,171 @@
1
+ Metadata-Version: 2.4
2
+ Name: remold
3
+ Version: 0.1.0
4
+ Summary: Reshape Python source with LibCST: structure in the tree, comments and whitespace as plain text
5
+ Author: remold contributors
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/AnswerDotAI/remold
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3 :: Only
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: libcst
14
+ Requires-Dist: ast-grep-py
15
+ Provides-Extra: dev
16
+ Requires-Dist: fastship; extra == "dev"
17
+ Requires-Dist: build; extra == "dev"
18
+ Requires-Dist: twine; extra == "dev"
19
+ Dynamic: license-file
20
+
21
+ # remold
22
+
23
+ Concisely reshape Python code with [LibCST](https://github.com/Instagram/LibCST) or [ast-grep](https://ast-grep.github.io/).
24
+
25
+ ```bash
26
+ pip install remold
27
+ ```
28
+
29
+ Tools like `ast` throw comments away, and regex rewrites break on real code. remold keeps the source intact and gives you two ways to build composable `str -> str` transforms:
30
+
31
+ - `astmap(*rules)` applies ast-grep pattern rules. Use it when you can write the rewrite as a before pattern and an after template. Only the matched span is replaced, so comments elsewhere are untouched.
32
+ - `cstmap(matcher, fn, trivia='keep')` takes a [LibCST matcher](https://libcst.readthedocs.io/en/latest/matchers.html) and a function, for everything patterns can't express, including transforms that only change comments and whitespace. `fn(node, caps)` returns `None` (leave it), a string (reparsed in place, so the output is guaranteed to parse), or a CST node (full surgery).
33
+
34
+ The idea behind `cstmap` is to match structure in the tree, where matching is easy, and to write the new code as a plain string, where comments and whitespace are just characters. Two helpers make that workable. `code(node)` renders any node back to source text, trivia included. `whereis(src, *frags)` tells you where LibCST keeps things, so you don't have to search the node docs.
35
+
36
+ `from remold import *` gives you all four plus `cst` (libcst) and `m` (libcst.matchers).
37
+
38
+ ## Pattern rules
39
+
40
+ Turn `test_fail(lambda: f(x), contains='boom')` into `with expect_fail(Exception, 'boom'): f(x)`:
41
+
42
+ ```python
43
+ from remold import *
44
+
45
+ fix_tests = astmap(
46
+ ("test_fail(lambda: $BODY, contains=$MSG)", "with expect_fail(Exception, $MSG): $BODY"),
47
+ ("test_fail(lambda: $BODY)", "with expect_fail(Exception): $BODY"))
48
+
49
+ print(fix_tests("test_fail(lambda: f(x), contains='boom') # tricky case\n"))
50
+ # with expect_fail(Exception, 'boom'): f(x) # tricky case
51
+ ```
52
+
53
+ Rules are applied in order, with a reparse between each, so later rules see the output of earlier ones. A replacement can also be a `callable(match) -> str` when the new text needs computing. Code that matches no pattern (like `test_fail(divide, args=(1,0))`) is left alone, and an unknown `$VAR` in a template raises a `KeyError`.
54
+
55
+ ## The same transform with matchers
56
+
57
+ For rewrites patterns can't express, write a LibCST matcher and a function. Here is the same transform in that form:
58
+
59
+ ```python
60
+ tf = m.SimpleStatementLine(body=[m.Expr(m.Call(
61
+ func=m.Name('test_fail'),
62
+ args=[m.Arg(m.Lambda(body=m.SaveMatchedNode(m.DoNotCare(), 'body'))),
63
+ m.Arg(keyword=m.Name('contains'), value=m.SaveMatchedNode(m.DoNotCare(), 'msg'))]))])
64
+
65
+ def fix(node, caps): return f"with expect_fail(Exception, {code(caps['msg'])}): {code(caps['body'])}"
66
+
67
+ fix_tests = cstmap(tf, fix)
68
+ print(fix_tests("test_fail(lambda: f(x), contains='boom') # tricky case\n"))
69
+ # with expect_fail(Exception, 'boom'): f(x) # tricky case
70
+ ```
71
+
72
+ The trailing comment is kept because `trivia='keep'` (the default) copies the matched statement's leading lines and trailing comment onto whatever `fn` returns. The matcher also acts as a guard. A `test_fail(f, args=(1,0))` call doesn't match the arg spec, so it isn't changed.
73
+
74
+ ## Example: move a comment
75
+
76
+ With `trivia='given'`, the string you return is used exactly as given, so to move a comment you write it where you want it:
77
+
78
+ ```python
79
+ def fix(node, caps):
80
+ c = node.trailing_whitespace.comment
81
+ new = f"with expect_fail(Exception, {code(caps['msg'])}): {code(caps['body'])}"
82
+ return f"{code(c)}\n{new}" if c else new
83
+
84
+ print(cstmap(tf, fix, trivia='given')("test_fail(lambda: f(), contains='x') # ho\n"))
85
+ # # ho
86
+ # with expect_fail(Exception, 'x'): f()
87
+ ```
88
+
89
+ A multi-line string becomes multiple statements, and returning `''` deletes the statement.
90
+
91
+ ## Example: reformat a signature
92
+
93
+ Here the code itself doesn't change; only the comments and line layout do. The pieces are read from the tree, and the new layout is built with ordinary string operations:
94
+
95
+ ```python
96
+ def fix(fd, _):
97
+ ps = [code(p).strip() for p in fd.params.params] # each param arrives with its comment attached
98
+ c = fd.body.header.comment # a comment after ':' lives on the body header
99
+ if c: ps[-1] = f"{ps[-1]} {code(c)}"
100
+ return f"def {fd.name.value}(\n " + "\n ".join(ps) + "\n):" + code(fd.body.with_changes(header=cst.TrailingWhitespace()))
101
+
102
+ src = """def f(foo, # hey
103
+ bam, # gg
104
+ bar): # ho
105
+ pass
106
+ """
107
+ print(cstmap(m.FunctionDef(), fix, trivia='given')(src))
108
+ # def f(
109
+ # foo, # hey
110
+ # bam, # gg
111
+ # bar # ho
112
+ # ):
113
+ # pass
114
+ ```
115
+
116
+ ## Moving code across depths
117
+
118
+ Indentation in LibCST is contextual, not literal. Statement lines, continuation lines inside brackets, and comment lines all record "indent goes here" rather than a column number, and the indent size comes from the target module's `default_indent`. Since `cstmap` parses your returned string as its own little module and splices the resulting statements into the real one, code written at one depth renders correctly at whatever depth it lands, in the target file's indent style. The one thing never re-indented is the content of multiline strings, since changing that would change the program.
119
+
120
+ This makes depth-changing transforms work without any bookkeeping. Here a method is pulled out of its class and turned into a top-level fastcore `@patch` function. Note the trick: matching the `FunctionDef` would replace the method in place, still inside the class, so to *move* code you match the enclosing `ClassDef` and return the whole new arrangement. A multi-line replacement becomes several sibling statements.
121
+
122
+ ```python
123
+ def fix(cd, _):
124
+ fs = [s for s in cd.body.body if m.matches(s, m.FunctionDef(name=m.Name('f')))]
125
+ if not fs: return None
126
+ fd = fs[0]
127
+ rest = cd.with_changes(body=cd.body.with_changes(body=[s for s in cd.body.body if s is not fd]))
128
+ p1 = code(fd.params.params[0]).strip().rstrip(',')
129
+ ps = ', '.join([f'{p1}:{cd.name.value}'] + [code(p).strip().rstrip(',') for p in fd.params.params[1:]])
130
+ return f"{code(rest)}\n@patch\ndef {fd.name.value}({ps}):{code(fd.body)}"
131
+
132
+ src = """class A:
133
+ def __init__(self): self.x = 1
134
+
135
+ def f(self, n): # add `n` to `x`
136
+ y = self.x+n
137
+ return y
138
+ """
139
+ print(cstmap(m.ClassDef(), fix, trivia='given')(src))
140
+ # class A:
141
+ # def __init__(self): self.x = 1
142
+ #
143
+ # @patch
144
+ # def f(self:A, n): # add `n` to `x`
145
+ # y = self.x+n
146
+ # return y
147
+ ```
148
+
149
+ The method body was written at depth 2 and lands at depth 1; `code(fd.body)` carried it along with its comment, and the render re-indented it. The `self` parameter picks up the class as its type annotation, which is how `@patch` knows what to patch.
150
+
151
+ ## whereis
152
+
153
+ How did that example know a comment after the colon is `fd.body.header.comment`? Ask:
154
+
155
+ ```python
156
+ whereis(src, 'foo', '# ho', '# hey')
157
+ # {'foo': ['.body[0].params.params[0].name'],
158
+ # '# ho': ['.body[0].body.header.comment', ...],
159
+ # '# hey': ['.body[0].params.params[0].comma.whitespace_after.first_line.comment', ...]}
160
+ ```
161
+
162
+ Paste a representative snippet, ask for the fragments you care about, and copy the paths into your `fn`. Multiple entries per fragment list the node itself first, then its containers. `contains=True` matches fragments inside larger nodes.
163
+
164
+ ## Development
165
+
166
+ ```bash
167
+ pip install -e .[dev]
168
+ pytest -q
169
+ ```
170
+
171
+ Version lives in `remold/__init__.py` as `__version__`; bump with `ship-bump`. Release with `ship-gh` and `ship-pypi`.
@@ -0,0 +1,12 @@
1
+ CHANGELOG.md
2
+ LICENSE
3
+ MANIFEST.in
4
+ README.md
5
+ pyproject.toml
6
+ remold/__init__.py
7
+ remold.egg-info/PKG-INFO
8
+ remold.egg-info/SOURCES.txt
9
+ remold.egg-info/dependency_links.txt
10
+ remold.egg-info/requires.txt
11
+ remold.egg-info/top_level.txt
12
+ tests/test_remold.py
@@ -0,0 +1,7 @@
1
+ libcst
2
+ ast-grep-py
3
+
4
+ [dev]
5
+ fastship
6
+ build
7
+ twine
@@ -0,0 +1 @@
1
+ remold
remold-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,134 @@
1
+ import pytest
2
+ from remold import cst, m, astmap, cstmap, code, whereis
3
+
4
+ tf = m.SimpleStatementLine(body=[m.Expr(m.Call(
5
+ func=m.Name('test_fail'),
6
+ args=[m.Arg(m.Lambda(body=m.SaveMatchedNode(m.DoNotCare(), 'body'))),
7
+ m.Arg(keyword=m.Name('contains'), value=m.SaveMatchedNode(m.DoNotCare(), 'msg'))]))])
8
+
9
+ def _fix(node, caps): return f"with expect_fail(Exception, {code(caps['msg'])}): {code(caps['body'])}"
10
+
11
+
12
+ def test_astmap():
13
+ fix = astmap(("test_fail(lambda: $BODY, contains=$MSG)", "with expect_fail(Exception, $MSG): $BODY"),
14
+ ("test_fail(lambda: $BODY)", "with expect_fail(Exception): $BODY"))
15
+ src = "x = 1\ntest_fail(lambda: f(x), contains='boom') # why\ntest_fail(lambda: g())\n"
16
+ assert fix(src) == "x = 1\nwith expect_fail(Exception, 'boom'): f(x) # why\nwith expect_fail(Exception): g()\n"
17
+
18
+ # non-matching forms pass through, later rules see earlier rules' output
19
+ assert fix("test_fail(divide, args=(1,0))\n") == "test_fail(divide, args=(1,0))\n"
20
+ two = astmap(("a()", "b()"), ("b()", "c()"))
21
+ assert two("a()\n") == "c()\n"
22
+
23
+ # a callable replacement gets the raw ast-grep match
24
+ up = astmap(("print($X)", lambda mch: f"log({mch['X'].text().upper()})"))
25
+ assert up("print(msg)\n") == "log(MSG)\n"
26
+
27
+ # unknown metavariables in the template fail loudly
28
+ with pytest.raises(KeyError): astmap(("print($X)", "log($Y)"))("print(msg)\n")
29
+
30
+
31
+ def test_cstmap():
32
+ src = "x = 1\ntest_fail(lambda: f(x), contains='boom') # why\ny = 2\n"
33
+ assert cstmap(tf, _fix)(src) == "x = 1\nwith expect_fail(Exception, 'boom'): f(x) # why\ny = 2\n"
34
+
35
+ # leading comments and blank lines survive too
36
+ src = "# setup\n\ntest_fail(lambda: g(), contains='no')\n"
37
+ assert cstmap(tf, _fix)(src) == "# setup\n\nwith expect_fail(Exception, 'no'): g()\n"
38
+
39
+ # works at any indentation depth
40
+ src = "def t():\n test_fail(lambda: f(1), contains='boom') # why\n"
41
+ assert cstmap(tf, _fix)(src) == "def t():\n with expect_fail(Exception, 'boom'): f(1) # why\n"
42
+
43
+ # expression context: replacement string parsed as an expression
44
+ up = cstmap(m.Name('a'), lambda n,c: 'a2')
45
+ assert up("b = a + a # keep\n") == "b = a2 + a2 # keep\n"
46
+
47
+ # returning None leaves the node alone; non-matching text untouched
48
+ assert cstmap(tf, lambda n,c: None)("test_fail(lambda: f(), contains='x')\n") == "test_fail(lambda: f(), contains='x')\n"
49
+ assert cstmap(tf, _fix)("test_fail(divide, args=(1,0))\n") == "test_fail(divide, args=(1,0))\n"
50
+
51
+ # returning a node is full-surgery mode
52
+ ren = cstmap(m.Name('old'), lambda n,c: n.with_changes(value='new'))
53
+ assert ren("old = old + 1\n") == "new = new + 1\n"
54
+
55
+
56
+ def test_trivia():
57
+ src = "test_fail(lambda: f(), contains='x') # ho\n"
58
+ # trivia='given': the returned string is the whole truth, so the comment moves where fn puts it
59
+ def fix(node, caps):
60
+ c = node.trailing_whitespace.comment
61
+ new = f"with expect_fail(Exception, {code(caps['msg'])}): {code(caps['body'])}"
62
+ return f"{code(c)}\n{new}" if c else new
63
+ assert cstmap(tf, fix, trivia='given')(src) == "# ho\nwith expect_fail(Exception, 'x'): f()\n"
64
+
65
+ # the moved comment indents contextually when the statement is nested
66
+ src = "def t():\n test_fail(lambda: f(), contains='x') # ho\n"
67
+ assert cstmap(tf, fix, trivia='given')(src) == "def t():\n # ho\n with expect_fail(Exception, 'x'): f()\n"
68
+
69
+ # multi-statement strings expand in place
70
+ dup = cstmap(m.SimpleStatementLine(body=[m.Expr(m.Call(func=m.Name('once')))]), lambda n,c: "first()\nsecond()")
71
+ assert dup("a = 1\nonce()\n") == "a = 1\nfirst()\nsecond()\n"
72
+
73
+ # empty string removes the statement
74
+ rm = cstmap(m.SimpleStatementLine(body=[m.Expr(m.Call(func=m.Name('gone')))]), lambda n,c: '')
75
+ assert rm("gone()\nkeep()\n") == "keep()\n"
76
+
77
+ # unparseable replacement fails loudly
78
+ bad = cstmap(tf, lambda n,c: 'def broken(')
79
+ with pytest.raises(cst.ParserSyntaxError): bad("test_fail(lambda: f(), contains='x')\n")
80
+
81
+
82
+ def test_relayout():
83
+ # the README signature example: code unchanged, comments and line structure are the payload
84
+ def fix(fd, _):
85
+ ps = [code(p).strip() for p in fd.params.params]
86
+ c = fd.body.header.comment
87
+ if c: ps[-1] = f"{ps[-1]} {code(c)}"
88
+ return f"def {fd.name.value}(\n " + "\n ".join(ps) + "\n):" + code(fd.body.with_changes(header=cst.TrailingWhitespace()))
89
+
90
+ src = "def f(foo, # hey\n bam, # gg\n bar): # ho\n pass\n"
91
+ assert cstmap(m.FunctionDef(), fix, trivia='given')(src) == (
92
+ "def f(\n foo, # hey\n bam, # gg\n bar # ho\n):\n pass\n")
93
+
94
+ # continuation-line whitespace is contextual in LibCST, so nested defs re-indent correctly
95
+ src = "class A:\n def f(foo, # hey\n bam,\n bar): # ho\n pass\n"
96
+ assert cstmap(m.FunctionDef(), fix, trivia='given')(src) == (
97
+ "class A:\n def f(\n foo, # hey\n bam,\n bar # ho\n ):\n pass\n")
98
+
99
+
100
+ def test_move_across_depths():
101
+ # extract a method to a top-level fastcore-style @patch function: match the *enclosing* ClassDef
102
+ # (matching the method would replace it in place), return the new arrangement as one string
103
+ def fix(cd, _):
104
+ fs = [s for s in cd.body.body if m.matches(s, m.FunctionDef(name=m.Name('f')))]
105
+ if not fs: return None
106
+ fd = fs[0]
107
+ rest = cd.with_changes(body=cd.body.with_changes(body=[s for s in cd.body.body if s is not fd]))
108
+ p1 = code(fd.params.params[0]).strip().rstrip(',')
109
+ ps = ', '.join([f'{p1}:{cd.name.value}'] + [code(p).strip().rstrip(',') for p in fd.params.params[1:]])
110
+ return f"{code(rest)}\n@patch\ndef {fd.name.value}({ps}):{code(fd.body)}"
111
+
112
+ src = ("class A:\n def __init__(self): self.x = 1\n\n"
113
+ " def f(self, n): # add `n` to `x`\n y = self.x+n\n return y\n")
114
+ assert cstmap(m.ClassDef(), fix, trivia='given')(src) == (
115
+ "class A:\n def __init__(self): self.x = 1\n\n"
116
+ "@patch\ndef f(self:A, n): # add `n` to `x`\n y = self.x+n\n return y\n")
117
+
118
+
119
+ def test_whereis():
120
+ src = "def f(foo, # hey\n bam, # gg\n bar): # ho\n pass\n"
121
+ w = whereis(src, 'foo', '# ho', '# hey')
122
+ assert w['foo'] == ['.body[0].params.params[0].name']
123
+ assert w['# ho'][0] == '.body[0].body.header.comment'
124
+ assert w['# hey'][0] == '.body[0].params.params[0].comma.whitespace_after.first_line.comment'
125
+ # contains=True finds fragments inside larger nodes
126
+ w = whereis(src, 'hey', contains=True)
127
+ assert '.body[0].params.params[0].comma.whitespace_after.first_line.comment' in w['hey']
128
+
129
+
130
+ def test_code():
131
+ node = cst.parse_expression('f(x, y)')
132
+ assert code(node) == 'f(x, y)'
133
+ p = cst.parse_module("def f(foo, # hey\n bar): pass\n").body[0].params.params[0]
134
+ assert code(p) == 'foo, # hey\n '