-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsort.py
More file actions
83 lines (66 loc) · 2.08 KB
/
sort.py
File metadata and controls
83 lines (66 loc) · 2.08 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import re
import fileinput
import os
import sys
require_start_pattern = re.compile("\s*\(:require.*")
require_end_pattern = re.compile(".*\)")
namespace_pattern = re.compile("\[.*]")
clj_filename_pattern = ".clj"
def get_ns_and_sort(filename):
ns = []
with open(filename, "r") as file:
line = file.readline()
while line:
if require_start_pattern.match(line):
while namespace_pattern.search(line):
ns.append(namespace_pattern.search(line).group(0))
if require_end_pattern.match(line):
break
else:
line = file.readline()
ns.sort()
replace(filename, ns)
return
line = file.readline()
def replace(filename, ns):
print(filename, ": rewriting [", len(ns), "] namespaces")
with fileinput.FileInput(filename, inplace=True) as file:
line = file.readline()
while line:
if require_start_pattern.match(line):
ns_count = 0
while namespace_pattern.search(line) \
and ns_count < len(ns):
replace_line = re.sub("\[.*]", ns[ns_count], line)
print(replace_line, end="")
ns_count = ns_count + 1
line = file.readline()
print(line, end="")
line = file.readline()
def handle(dirname):
for root, _, filenames in os.walk(dirname):
for filename in filenames:
if clj_filename_pattern in filename:
get_ns_and_sort(os.path.join(root, filename))
def usage():
print("""
Sort .clj namespaces
example:
python sort.py /path/to/clojure
""")
def error(e):
print("""
Error:
""", e)
def main(argv):
if len(argv) < 2:
usage()
exit(-1)
dirname = argv[1]
if not os.path.isdir(dirname):
error("Invalid dir")
exit(-2)
print("Target: ", dirname)
handle(dirname)
if __name__ == '__main__':
main(sys.argv)