Skip to content

Instantly share code, notes, and snippets.

@maxdevjs
Forked from ForgottenProgramme/todo.py
Created September 26, 2021 08:42
Show Gist options
  • Save maxdevjs/b0187679daec192999d3a890de0415de to your computer and use it in GitHub Desktop.
Save maxdevjs/b0187679daec192999d3a890de0415de to your computer and use it in GitHub Desktop.
Todo Manager CLI tool (Python) Mahe Iram Khan
#!/usr/bin/env python
import sys
from datetime import datetime
HELP_MESSAGE = """/
Usage :-
$ ./todo add "todo item" # Add a new todo
$ ./todo ls # Show remaining todos
$ ./todo del NUMBER # Delete a todo
$ ./todo done NUMBER # Complete a todo
$ ./todo help # Show usage
$ ./todo report # Statistics"""
TODO_FILE = "todo.txt"
DONE_FILE = "done.txt"
now = datetime.now()
def add(task):
# Add task to todo.txt file
if(task == ""):
print("Error: Missing todo string. Nothing added!")
return
with open(TODO_FILE, 'a') as fd:
fd.write(task)
fd.write("\n")
print(f'Added todo: "{task}"')
def ls(_):
NO_PENDING_TASKS_MESSAGE = "There are no pending todos!"
try:
with open(TODO_FILE) as fd:
todo_list = fd.readlines() #reads the todo.txt file and saves the tasks in a list
list_size = len(todo_list)
if(list_size==0):
print(NO_PENDING_TASKS_MESSAGE)
for index, todo_list in enumerate(reversed(todo_list)):
print(f"[{list_size - index}] {todo_list.strip()}")
except FileNotFoundError:
print(NO_PENDING_TASKS_MESSAGE)
def delete(task):
task = int(task)
with open(TODO_FILE) as fd:
todo_list = fd.readlines()
if len(todo_list) < task:
print(f"Error: todo #{task} does not exist.")
return
task = task-1
with open(TODO_FILE, 'w') as fd:
for pos, todo_list in enumerate(todo_list):
if pos != task:
fd.write(todo_list)
print(f"Deleted todo #{task+1}")
def done(task):
with open(TODO_FILE) as fd:
todo_list = fd.readlines()
task = int(task)
if len(todo_list) < task:
print(f"Error: todo #{task} does not exist.")
return
task = task-1
with open(DONE_FILE, 'a') as fd:
fd.write("x ")
fd.write(now.strftime("%Y/%m/%d "))
fd.write(todo_list[task])
fd.write("\n")
with open(TODO_FILE, 'w') as fd:
for pos, todo_list in enumerate(todo_list):
if pos != task:
fd.write(todo_list)
print(f"Marked todo #{task+1} as done")
def report(_):
with open(TODO_FILE, 'r') as fd:
todo_list = fd.readlines()
todo_size = len(todo_list)
with open (DONE_FILE, 'r') as fd:
done_list = fd.readlines()
done_size = len(done_list)
print(f"{now.strftime('%Y/%m/%d')} Pending: {todo_size} Completed: {done_size}")
def help(_):
print(HELP_MESSAGE)
def controller(command, task):
operator = {
"help": help,
"add" : add,
"ls" : ls,
"del": delete,
"done":done,
"report" : report,
}. get(command, help)
return operator(task)
def main():
if len(sys.argv)<2:
sys.exit(HELP_MESSAGE)
_,command,*task = sys.argv
task = " ".join(task)
controller(command, task)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment