|
12 | 12 |
|
13 | 13 |
|
14 | 14 | def format_script(path, script_node, source_lines, check): |
| 15 | + """ |
| 16 | + Returns formatted source and the original location of the node |
| 17 | + """ |
15 | 18 | start, end = script_node.location[0], script_node.end[0] - 1 |
16 | 19 |
|
17 | 20 | source = "".join(source_lines[start:end]) |
@@ -66,29 +69,48 @@ def format_file(path, check=False, write=True): |
66 | 69 | lines = fh.readlines() |
67 | 70 |
|
68 | 71 | script_node = parser.root.child_with_tag("script") |
69 | | - template_node = parser.root.child_with_tag("template") |
| 72 | + template_nodes = [ |
| 73 | + node |
| 74 | + for node in parser.root.children |
| 75 | + if not hasattr(node, "tag") or node.tag != "script" |
| 76 | + ] |
70 | 77 |
|
71 | 78 | script_content, script_location = format_script(path, script_node, lines, check) |
72 | | - template_content, template_location = format_template( |
73 | | - template_node, lines, parser=parser |
74 | | - ) |
75 | | - |
76 | | - changed = ( |
77 | | - lines[script_location[0] : script_location[1]] != script_content |
78 | | - or lines[template_location[0] : template_location[1]] != template_content |
| 79 | + formatted_template_nodes = [ |
| 80 | + format_template(node, lines, parser=parser) for node in template_nodes |
| 81 | + ] |
| 82 | + |
| 83 | + changed_script = lines[script_location[0] : script_location[1]] != script_content |
| 84 | + changed_template = any( |
| 85 | + [ |
| 86 | + lines[template_location[0] : template_location[1]] != template_content |
| 87 | + for template_content, template_location in formatted_template_nodes |
| 88 | + ] |
79 | 89 | ) |
| 90 | + needs_newline_at_end_of_file = not lines[-1].endswith("\n") |
| 91 | + changed = changed_script or changed_template or needs_newline_at_end_of_file |
80 | 92 | if check: |
81 | 93 | if changed: |
82 | 94 | logger.warning(f"Would change: {path}") |
83 | 95 | return 1 |
84 | 96 | return 0 |
85 | 97 |
|
86 | | - if script_location[0] > template_location[0]: |
87 | | - lines[script_location[0] : script_location[1]] = script_content |
88 | | - lines[template_location[0] : template_location[1]] = template_content |
89 | | - else: |
90 | | - lines[script_location[0] : script_location[1]] = script_content |
91 | | - lines[template_location[0] : template_location[1]] = template_content |
| 98 | + formatted_parts = reversed( |
| 99 | + sorted( |
| 100 | + [ |
| 101 | + (script_content, script_location), |
| 102 | + *formatted_template_nodes, |
| 103 | + ], |
| 104 | + key=lambda x: x[1][0], |
| 105 | + ) |
| 106 | + ) |
| 107 | + |
| 108 | + for formatted_content, (start, end) in formatted_parts: |
| 109 | + lines[start:end] = formatted_content |
| 110 | + |
| 111 | + if needs_newline_at_end_of_file: |
| 112 | + lines.append("\n") |
| 113 | + |
92 | 114 | if not write: |
93 | 115 | return lines |
94 | 116 |
|
|
0 commit comments