import re import typing as t CONTENT = """ #!/usr/local/bin/node import ElectronLogo from "@assets/electron.svg"; // My first group import { Fragment, type ReactNode } from "react"; import Versions from "./Versions.tsx"; import ElectronLogo2 from "@assets/electron.svg"; /* * My second group */ import { Fragment2, type ReactNode2 } from "react"; import Versions2 from "./Versions.tsx"; const myvar = true; """.lstrip() # triple-quotes produce extra newline at line 0 def extract_shebang_line(content: t.List[str]) -> t.Tuple[str, t.List[str]]: if content[0].startswith("#!"): return content[0], content[1:] return '', content def separate_imports(content: t.List[str]) -> t.Tuple[t.List[str], t.List[str]]: imports = [] pattern = re.compile(r'^(import|//|/\*| \*| \*/)') for i, line in enumerate(content): if pattern.match(line) or line == '': imports.append(line) continue return imports, content[i:] def break_into_groups(content: t.List[str]) -> t.List[t.List[str]]: groups = [] current_group = [] for line in content: if line != '': current_group.append(line) continue elif not current_group: # exclude empty groups continue groups.append(current_group) current_group = [] return groups def bubble_up_group_comments(content: t.List[str]) -> None: pattern = re.compile(r'^(//|/\*| \*| \*/)') comments, imports = [], [] for line in content: if pattern.match(line): comments.append(line) continue imports.append(line) sort_imports_by_distance(imports) content.clear() content.extend(comments) content.extend(imports) def sort_imports_by_distance(content: t.List[str]) -> None: # Implement the Biome import sort by distance algorithm here pass def main(): shebang, other = extract_shebang_line(CONTENT.split('\n')) imports, other = separate_imports(other) groups = break_into_groups(imports) content = [] if shebang: content.append(shebang) for group in groups: bubble_up_group_comments(group) content.extend(group) content.append('') content.extend(other) for line in content: print(line) if __name__ == '__main__': main()