1+ import click
2+
3+ @click .group ()
4+ @click .pass_context
5+ def todo (ctx ):
6+ '''Simple CLI Todo App'''
7+ ctx .ensure_object (dict )
8+ #Open todo.txt – first line contains latest ID, rest contain tasks and IDs
9+ with open ('./todo.txt' ) as f :
10+ content = f .readlines ()
11+ #Transfer data from todo.txt to the context
12+ ctx .obj ['LATEST' ] = int (content [:1 ][0 ])
13+ ctx .obj ['TASKS' ] = {en .split ('```' )[0 ]:en .split ('```' )[1 ][:- 1 ] for en in content [1 :]}
14+
15+ @todo .command ()
16+ @click .pass_context
17+ def tasks (ctx ):
18+ '''Display tasks'''
19+ if ctx .obj ['TASKS' ]:
20+ click .echo ('YOUR TASKS\n **********' )
21+ #Iterate through all the tasks stored in the context
22+ for i , task in ctx .obj ['TASKS' ].items ():
23+ click .echo ('• ' + task + ' (ID: ' + i + ')' )
24+ click .echo ('' )
25+ else :
26+ click .echo ('No tasks yet! Use ADD to add one.\n ' )
27+
28+ @todo .command ()
29+ @click .pass_context
30+ @click .option ('-add' , '--add_task' , prompt = 'Enter task to add' )
31+ def add (ctx , add_task ):
32+ '''Add a task'''
33+ if add_task :
34+ #Add task to list in context
35+ ctx .obj ['TASKS' ][ctx .obj ['LATEST' ]] = add_task
36+ click .echo ('Added task "' + add_task + '" with ID ' + str (ctx .obj ['LATEST' ]))
37+ #Open todo.txt and write current index and tasks with IDs (separated by " ``` ")
38+ curr_ind = [str (ctx .obj ['LATEST' ] + 1 )]
39+ tasks = [str (i ) + '```' + t for (i , t ) in ctx .obj ['TASKS' ].items ()]
40+ with open ('./todo.txt' , 'w' ) as f :
41+ f .writelines (['%s\n ' % en for en in curr_ind + tasks ])
42+
43+ @todo .command ()
44+ @click .pass_context
45+ @click .option ('-fin' , '--fin_task_id' , prompt = 'Enter ID of task to finish' , type = int )
46+ def done (ctx , fin_task_id ):
47+ '''Delete a task by ID'''
48+ #Find task with associated ID
49+ if str (fin_task_id ) in ctx .obj ['TASKS' ].keys ():
50+ task = ctx .obj ['TASKS' ][str (fin_task_id )]
51+ #Delete task from task list in context
52+ del ctx .obj ['TASKS' ][str (fin_task_id )]
53+ click .echo ('Finished and removed task "' + task + '" with id ' + str (fin_task_id ))
54+ #Open todo.txt and write current index and tasks with IDs (separated by " ``` ")
55+ if ctx .obj ['TASKS' ]:
56+ curr_ind = [str (ctx .obj ['LATEST' ] + 1 )]
57+ tasks = [str (i ) + '```' + t for (i , t ) in ctx .obj ['TASKS' ].items ()]
58+ with open ('./todo.txt' , 'w' ) as f :
59+ f .writelines (['%s\n ' % en for en in curr_ind + tasks ])
60+ else :
61+ #Resets ID tracker to 0 if list is empty
62+ with open ('./todo.txt' , 'w' ) as f :
63+ f .writelines ([str (0 ) + '\n ' ])
64+ else :
65+ click .echo ('Error: no task with id ' + str (fin_task_id ))
66+
67+ if __name__ == '__main__' :
68+ todo ()
0 commit comments