todo.py 2.6 KB

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