Skip to content

Commit 87fee42

Browse files
author
Ahmed Mustafa
committed
Added python 3 script to sort entries in README.md
1 parent 40ac968 commit 87fee42

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

sort.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
"""
2+
The approach taken is explained below. I decided to do it simply.
3+
Initially I was considering parsing the data into some sort of
4+
structure and then generating an appropriate README. I am still
5+
considering doing it - but for now this should work. The only issue
6+
I see is that it only sorts the entries at the lowest level, and that
7+
the order of the top-level contents do not match the order of the actual
8+
entries.
9+
10+
This could be extended by having nested blocks, sorting them recursively
11+
and flattening the end structure into a list of lines. Revision 2 maybe ^.^.
12+
"""
13+
14+
def main():
15+
#First, we load the current README into memory as an array of lines
16+
with open('README.md', 'r') as read_me_file:
17+
read_me = read_me_file.readlines()
18+
19+
#Then we cluster the lines together as blocks
20+
#Each block represents a collection of lines that should be sorted
21+
#This was done by assuming only links ([...](...)) are meant to be sorted
22+
#Clustering is done by indentation
23+
blocks = []
24+
last_indent = None
25+
for line in read_me:
26+
s_line = line.lstrip()
27+
indent = len(line) - len(s_line)
28+
29+
if any([s_line.startswith(s) for s in ['* [', '- [']]):
30+
if indent == last_indent:
31+
blocks[-1].append(line)
32+
else:
33+
blocks.append([line])
34+
last_indent = indent
35+
else:
36+
blocks.append([line])
37+
last_indent = None
38+
39+
with open('README.md', 'w+') as sorted_file:
40+
#Then all of the blocks are sorted individually
41+
blocks = [''.join(sorted(block, key=lambda s: s.lower())) for block in blocks]
42+
#And the result is written back to README.md
43+
sorted_file.write(''.join(blocks))
44+
45+
46+
if __name__ == "__main__":
47+
main()

0 commit comments

Comments
 (0)