from enum import Enum from typing import List TODO_FILE_NAME = "TODO.md" TODO_LINE_START_COMPLETED = "- [x] " TODO_LINE_START_UNCOMPLETED = "- [ ] " class PrevItemState(Enum): COMPLETED = 0 UNCOMPLETED = 1 UNDETERMINED = 2 def main(): with open(TODO_FILE_NAME) as todo_file: todo_lines = todo_file.readlines() completed: List[str] = [] uncompleted: List[str] = [] prev_item_state = PrevItemState.UNDETERMINED for [index, line] in enumerate(todo_lines): if len(line) == 0: continue if line.startswith(TODO_LINE_START_COMPLETED): completed.append(line) prev_item_state = PrevItemState.COMPLETED elif line.startswith(TODO_LINE_START_UNCOMPLETED): uncompleted.append(line) prev_item_state = PrevItemState.UNCOMPLETED elif line[0].isspace(): if prev_item_state == PrevItemState.COMPLETED: completed.append(line) elif prev_item_state == PrevItemState.UNCOMPLETED: uncompleted.append(line) elif prev_item_state == PrevItemState.UNDETERMINED: print( f"Error: todo line {index + 1} starts with whitespace but there is " "no previous item" ) exit(1) else: print(f"Error: todo line {index + 1} does not have correct syntax") exit(1) with open(TODO_FILE_NAME, "w") as todo_file: todo_file.writelines(uncompleted) todo_file.writelines(completed) if __name__ == "__main__": main()