-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsort_files.py
executable file
·42 lines (32 loc) · 1.2 KB
/
sort_files.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#!/usr/bin/env python3
import sys
from pathlib import Path
import re
prefix_re = re.compile(r"^(-?\d+(?:\.\d+)?)-")
def get_prefix_float(s: str) -> float:
searched = prefix_re.search(s)
assert searched is not None, f"no prefix found in {s}"
return float(searched.group(1))
def path_sort_key(p: Path) -> tuple:
name_first_float = get_prefix_float(p.name)
# sort by: initial integer, then number of parts, then initial float, then by the path itself
# this is so that files like 01.1-hello.txt come before test/dir/01-world.txt
return (int(name_first_float), len(p.parts), name_first_float, str(p))
def sort_files(input_files: list[Path]) -> list[Path]:
return sorted(input_files, key=path_sort_key)
if __name__ == "__main__":
sorted_files = [str(p) for p in sort_files([Path(p) for p in sys.argv[1:]])]
seen = []
duplicates = []
for f in sorted_files:
path = Path(f)
if path.name in seen:
duplicates.append(path.name)
seen.append(path.name)
if duplicates:
for name in duplicates:
try:
sorted_files.remove(name)
except ValueError:
pass
print(" ".join(sorted_files))