Sorts the imports in a single import statement. Args: import_statement (`str`): The import statement in which to sort the imports. Returns: `str`: The same as the input, but with objects properly sorted.
(import_statement: str)
| 175 | |
| 176 | |
| 177 | def sort_objects_in_import(import_statement: str) -> str: |
| 178 | """ |
| 179 | Sorts the imports in a single import statement. |
| 180 | |
| 181 | Args: |
| 182 | import_statement (`str`): The import statement in which to sort the imports. |
| 183 | |
| 184 | Returns: |
| 185 | `str`: The same as the input, but with objects properly sorted. |
| 186 | """ |
| 187 | |
| 188 | # This inner function sort imports between [ ]. |
| 189 | def _replace(match): |
| 190 | imports = match.groups()[0] |
| 191 | # If there is one import only, nothing to do. |
| 192 | if "," not in imports: |
| 193 | return f"[{imports}]" |
| 194 | keys = [part.strip().replace('"', "") for part in imports.split(",")] |
| 195 | # We will have a final empty element if the line finished with a comma. |
| 196 | if len(keys[-1]) == 0: |
| 197 | keys = keys[:-1] |
| 198 | return "[" + ", ".join([f'"{k}"' for k in sort_objects(keys)]) + "]" |
| 199 | |
| 200 | lines = import_statement.split("\n") |
| 201 | if len(lines) > 3: |
| 202 | # Here we have to sort internal imports that are on several lines (one per name): |
| 203 | # key: [ |
| 204 | # "object1", |
| 205 | # "object2", |
| 206 | # ... |
| 207 | # ] |
| 208 | |
| 209 | # We may have to ignore one or two lines on each side. |
| 210 | idx = 2 if lines[1].strip() == "[" else 1 |
| 211 | keys_to_sort = [(i, _re_strip_line.search(line).groups()[0]) for i, line in enumerate(lines[idx:-idx])] |
| 212 | sorted_indices = sort_objects(keys_to_sort, key=lambda x: x[1]) |
| 213 | sorted_lines = [lines[x[0] + idx] for x in sorted_indices] |
| 214 | return "\n".join(lines[:idx] + sorted_lines + lines[-idx:]) |
| 215 | elif len(lines) == 3: |
| 216 | # Here we have to sort internal imports that are on one separate line: |
| 217 | # key: [ |
| 218 | # "object1", "object2", ... |
| 219 | # ] |
| 220 | if _re_bracket_content.search(lines[1]) is not None: |
| 221 | lines[1] = _re_bracket_content.sub(_replace, lines[1]) |
| 222 | else: |
| 223 | keys = [part.strip().replace('"', "") for part in lines[1].split(",")] |
| 224 | # We will have a final empty element if the line finished with a comma. |
| 225 | if len(keys[-1]) == 0: |
| 226 | keys = keys[:-1] |
| 227 | lines[1] = get_indent(lines[1]) + ", ".join([f'"{k}"' for k in sort_objects(keys)]) |
| 228 | return "\n".join(lines) |
| 229 | else: |
| 230 | # Finally we have to deal with imports fitting on one line |
| 231 | import_statement = _re_bracket_content.sub(_replace, import_statement) |
| 232 | return import_statement |
| 233 | |
| 234 |
no test coverage detected