Skip to content

Commit ae923bb

Browse files
committed
Make print_ast() break arguments over multiple lines
Replicates graphql/graphql-js@b9cf5f3
1 parent 2f25886 commit ae923bb

File tree

2 files changed

+52
-13
lines changed

2 files changed

+52
-13
lines changed

src/graphql/language/printer.py

+9-10
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
__all__ = ["print_ast"]
1010

1111

12+
MAX_LINE_LENGTH = 80
13+
1214
Strings = Collection[str]
1315

1416

@@ -100,16 +102,13 @@ def leave_selection_set(node: PrintedNode, *_args: Any) -> str:
100102

101103
@staticmethod
102104
def leave_field(node: PrintedNode, *_args: Any) -> str:
103-
return join(
104-
(
105-
wrap("", node.alias, ": ")
106-
+ node.name
107-
+ wrap("(", join(node.arguments, ", "), ")"),
108-
join(node.directives, " "),
109-
node.selection_set,
110-
),
111-
" ",
112-
)
105+
prefix = wrap("", node.alias, ": ") + node.name
106+
args_line = prefix + wrap("(", join(node.arguments, ", "), ")")
107+
108+
if len(args_line) > MAX_LINE_LENGTH:
109+
args_line = prefix + wrap("(\n", indent(join(node.arguments, "\n")), "\n)")
110+
111+
return join((args_line, join(node.directives, " "), node.selection_set), " ")
113112

114113
@staticmethod
115114
def leave_argument(node: PrintedNode, *_args: Any) -> str:

tests/language/test_printer.py

+43-3
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,42 @@ def prints_query_with_variable_directives():
7878
"""
7979
)
8080

81+
def keeps_arguments_on_one_line_if_line_has_80_chars_or_less():
82+
printed = print_ast(parse("{trip(wheelchair:false arriveBy:false){dateTime}}"))
83+
84+
assert printed == dedent(
85+
"""
86+
{
87+
trip(wheelchair: false, arriveBy: false) {
88+
dateTime
89+
}
90+
}
91+
"""
92+
)
93+
94+
def puts_arguments_on_multiple_lines_if_line_has_more_than_80_chars():
95+
printed = print_ast(
96+
parse(
97+
"{trip(wheelchair:false arriveBy:false includePlannedCancellations:true"
98+
" transitDistanceReluctance:2000){dateTime}}"
99+
)
100+
)
101+
102+
assert printed == dedent(
103+
"""
104+
{
105+
trip(
106+
wheelchair: false
107+
arriveBy: false
108+
includePlannedCancellations: true
109+
transitDistanceReluctance: 2000
110+
) {
111+
dateTime
112+
}
113+
}
114+
"""
115+
)
116+
81117
def experimental_prints_fragment_with_variable_directives():
82118
query_ast_with_variable_directive = parse(
83119
"fragment Foo($foo: TestType @test) on TestType @testDirective { id }",
@@ -149,9 +185,13 @@ def prints_kitchen_sink(kitchen_sink_query): # noqa: F811
149185
}
150186
151187
fragment frag on Friend @onFragmentDefinition {
152-
foo(size: $size, bar: $b, obj: {key: "value", block: """
153-
block string uses \"""
154-
"""})
188+
foo(
189+
size: $size
190+
bar: $b
191+
obj: {key: "value", block: """
192+
block string uses \"""
193+
"""}
194+
)
155195
}
156196
157197
{

0 commit comments

Comments
 (0)