|
12 | 12 | This could be extended by having nested blocks, sorting them recursively |
13 | 13 | and flattening the end structure into a list of lines. Revision 2 maybe ^.^. |
14 | 14 | """ |
15 | | - |
16 | | - |
17 | | -def main(): |
| 15 | +def sort_blocks(): |
18 | 16 | # First, we load the current README into memory |
19 | 17 | with open('README.md', 'r') as read_me_file: |
20 | 18 | read_me = read_me_file.read() |
@@ -42,6 +40,40 @@ def main(): |
42 | 40 | with open('README.md', 'w+') as sorted_file: |
43 | 41 | sorted_file.write(final_README) |
44 | 42 |
|
| 43 | +def main(): |
| 44 | + # First, we load the current README into memory as an array of lines |
| 45 | + with open('README.md', 'r') as read_me_file: |
| 46 | + read_me = read_me_file.readlines() |
| 47 | + |
| 48 | + # Then we cluster the lines together as blocks |
| 49 | + # Each block represents a collection of lines that should be sorted |
| 50 | + # This was done by assuming only links ([...](...)) are meant to be sorted |
| 51 | + # Clustering is done by indentation |
| 52 | + blocks = [] |
| 53 | + last_indent = None |
| 54 | + for line in read_me: |
| 55 | + s_line = line.lstrip() |
| 56 | + indent = len(line) - len(s_line) |
| 57 | + |
| 58 | + if any([s_line.startswith(s) for s in ['* [', '- [']]): |
| 59 | + if indent == last_indent: |
| 60 | + blocks[-1].append(line) |
| 61 | + else: |
| 62 | + blocks.append([line]) |
| 63 | + last_indent = indent |
| 64 | + else: |
| 65 | + blocks.append([line]) |
| 66 | + last_indent = None |
| 67 | + |
| 68 | + with open('README.md', 'w+') as sorted_file: |
| 69 | + # Then all of the blocks are sorted individually |
| 70 | + blocks = [''.join(sorted(block, key=lambda s: s.lower())) for block in blocks] |
| 71 | + # And the result is written back to README.md |
| 72 | + sorted_file.write(''.join(blocks)) |
| 73 | + |
| 74 | + # Then we call the sorting method |
| 75 | + sort_blocks() |
| 76 | + |
45 | 77 |
|
46 | 78 | if __name__ == "__main__": |
47 | 79 | main() |
0 commit comments