Skip to content

Commit 8901920

Browse files
committed
Handle other nested cases (dicts and lists) for yapf fixup.
1 parent 7d4a5ba commit 8901920

File tree

4 files changed

+65
-3
lines changed

4 files changed

+65
-3
lines changed

formate/__init__.py

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -227,9 +227,23 @@ def yapf_hook(source: str, formate_global_config: Optional[Mapping] = None, **kw
227227
reformatted_code: str = FormatTree(tree, style_config=str(config_file))
228228

229229
# Yapf can collapse nested calls onto one line but does nothing about the commas.
230-
bad_nested_call = "), )"
231-
while bad_nested_call in reformatted_code:
232-
reformatted_code = reformatted_code.replace(bad_nested_call, "))")
230+
# TODO: more performant, with re.sub?
231+
for bad_pattern, good_pattern in [
232+
("), )", "))"),
233+
("), }", ")}"),
234+
("), ]", ")]"),
235+
236+
("], )", "])"),
237+
("], }", "]}"),
238+
("], ]", "]]"),
239+
240+
("}, )", "})"),
241+
("}, }", "}}"),
242+
("}, ]", "}]"),
243+
]:
244+
245+
while bad_pattern in reformatted_code:
246+
reformatted_code = reformatted_code.replace(bad_pattern, good_pattern)
233247

234248
return reformatted_code
235249

tests/test_yapf_nested_fixups.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# 3rd party
2+
from coincidence.regressions import AdvancedFileRegressionFixture
3+
from domdf_python_tools.paths import PathPlus
4+
5+
# this package
6+
from formate import yapf_hook
7+
8+
9+
def test_nested_call(advanced_file_regression: AdvancedFileRegressionFixture):
10+
src = """
11+
a = cls(**dict(map(
12+
lambda f: (f[0].name, curried.get_in(f[1], d, f[0].default)),
13+
from_fields,
14+
), ), )
15+
"""
16+
17+
advanced_file_regression.check(yapf_hook(src))
18+
19+
20+
def test_nested_array(advanced_file_regression: AdvancedFileRegressionFixture):
21+
src = """
22+
def foo():
23+
example = {
24+
"table": {"nested_table": [
25+
{"array_options": [1, 2, 3]},
26+
{"another_array": [1, 2]},
27+
{'c': 3},
28+
], },
29+
}
30+
"""
31+
32+
advanced_file_regression.check(
33+
yapf_hook(src, yapf_style=PathPlus(__file__).parent.parent.joinpath(".style.yapf").as_posix()),
34+
)
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
def foo():
2+
example = {
3+
"table": {"nested_table": [
4+
{"array_options": [1, 2, 3]},
5+
{"another_array": [1, 2]},
6+
{'c': 3},
7+
]},
8+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
a = cls(
2+
**dict(
3+
map(
4+
lambda f: (f[0].name, curried.get_in(f[1], d, f[0].default)),
5+
from_fields,
6+
)))

0 commit comments

Comments
 (0)