-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask_manager.py
More file actions
250 lines (190 loc) · 6.94 KB
/
task_manager.py
File metadata and controls
250 lines (190 loc) · 6.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import json
import os
import datetime
import sys
TASKS_FILE = "tasks.json"
def load_tasks():
#check if the file exists
if not os.path.exists(TASKS_FILE):
return []
try:
with open(TASKS_FILE, 'r') as f:
tasks = json.load(f)
return tasks
except (json.JSONDecodeError, IOError):
return []
def save_tasks(tasks):
with open(TASKS_FILE, 'w') as f:
json.dump(tasks, f, indent = 4)
#--------Task Functions---------
def get_next_id(tasks):
if not tasks:
return 1
return max(task['id'] for task in tasks) + 1
def add_task(description):
tasks = load_tasks()
now = datetime.datetime.now().isoformat()
new_task = {
"id": get_next_id(tasks),
"description": description,
"status": "todo",
"createdAt": now,
"updatedAt": now
}
tasks.append(new_task)
save_tasks(tasks)
print(f"Success: Added new task (ID: {new_task['id']})")
print(f" Description: {description}")
def print_task(task):
try:
created_at = datetime.datetime.fromisoformat(task['createdAt']).strftime('%Y-%m-%d %H:%M')
updated_at = datetime.datetime.fromisoformat(task['updatedAt']).strftime('%Y-%m-%d %H:%M')
except ValueError:
created_at = task['createdAt']
updated_at = task['updatedAt']
print(f"\n ID: {task['id']}")
print(f" Description: {task['description']}")
print(f" Status: {task['status']}")
print(f" Created: {created_at}")
print(f" Updated: {updated_at}")
print("-" * 20)
def list_tasks(status_filter = None):
tasks = load_tasks()
if not tasks:
print("There are no tasks. Let's add one!")
return
valid_statuses = ["todo", "in-progress", "done", "not-done"]
if status_filter:
if status_filter not in valid_statuses:
print(f"Invalid Status Filter : {status_filter}")
print(f"Valid Filters are : 'todo' 'in-progress' 'done' 'not-done'")
return
filtered_tasks = []
if status_filter == "not-done":
filtered_tasks = [task for task in tasks if task['status'] in ("todo", "in-progress")]
else:
filtered_tasks = [task for task in tasks if task['status'] == status_filter]
tasks_to_display = filtered_tasks
else:
tasks_to_display = tasks
if not tasks_to_display:
if status_filter:
print(f" No tasks found with status: '{status_filter}'")
return
print(f"--- Showing {len(tasks_to_display)} Task(s) ---")
for task in tasks_to_display:
print_task(task)
def update_task_status(task_id_str, new_status):
valid_statuses = ["todo", "in-progress", "done"]
if new_status not in valid_statuses:
print(f"Error: Invalid Status - '{new_status}'")
print(f"Status must be 'todo', 'in-progress' or 'done'.")
return
try:
task_id = int(task_id_str)
except ValueError:
print(f"Error: Invalid Task ID '{task_id_str}'. ID must be a number.")
return
tasks = load_tasks()
task_found = False
for task in tasks:
if task['id'] == task_id:
task['status'] = new_status
task['updatedAt'] = datetime.datetime.now().isoformat()
task_found = True
break
if task_found:
save_tasks(tasks)
print(f"Updated status for task {task_id} to '{new_status}'")
else:
print(f"Error: Task with ID {task_id} not found.")
def delete_task(task_id_str):
try:
task_id = int(task_id_str)
except ValueError:
print(f"Error: Invalid task ID '{task_id_str}'. ID must be a number.")
return
tasks = load_tasks()
tasks_kept = [task for task in tasks if task['id'] != task_id]
if len(tasks) == len(tasks_kept):
print(f"Error: Task with ID {task_id} not found.")
else:
save_tasks(tasks_kept)
print(f"Task Deleted! {task_id}.")
def update_task_description(task_id_str, new_description):
if not new_description:
print("Error: New Description cannot be empty.")
return
try:
task_id = int(task_id_str)
except ValueError:
print(f"Error: Invalid task ID '{task_id_str}'. ID must be a number.")
return
tasks = load_tasks()
task_found = False
for task in tasks:
if task['id'] == task_id:
task['description'] = new_description
task['updatedAt'] = datetime.datetime.now().isoformat()
task_found = True
break
if task_found:
save_tasks(tasks)
print(f"Success: Updated task description for {task_id}.")
print(f"New description: {new_description}")
else:
print(f"Task with ID '{task_id}' not found.")
#--------MAIN APP LOGIC---------
def print_usage():
print("Usage - python task_manager.py <command> [arguements]")
print("\nCommands")
print(" add <description> - Add a new task")
print(" list [status] - List all tasks or filter by status (todo, in-progress, done, not-done)")
print(" status <id> <status> - Update a task's status('todo', 'in-progress', 'done')")
print(" delete <id> - Delete a task by its ID")
print(" update <id> <desc> - Update a task's description")
def main():
if len(sys.argv) < 2:
print_usage()
return
command = sys.argv[1]
if command == "add":
if len(sys.argv) < 3:
print("Error: Missing Task Description.")
print("Usage: python task_manager.py add <description>")
return
description = " ".join(sys.argv[2:])
add_task(description)
elif command == "list":
status_filter = None
if len(sys.argv) > 2:
status_filter = sys.argv[2]
list_tasks(status_filter)
elif command == "status":
if len(sys.argv) < 4:
print("Error: Missing arguments for 'status' command.")
print("Usage: python_task_manager.py status <id> <status>")
return
task_id_str = sys.argv[2]
new_status = sys.argv[3]
update_task_status(task_id_str, new_status)
elif command == "delete":
if len(sys.argv) < 3:
print("Error: Missing task ID.")
print("Usage: python task_manager.py delete <id>")
return
task_id_str = sys.argv[2]
delete_task(task_id_str)
elif command == "update":
if len(sys.argv) < 4:
print("Error: Missing arguments for 'update' command.")
print("Usage: python_task_manager.py update <id> <new description>")
return
task_id_str = sys.argv[2]
new_description = " ".join(sys.argv[3:])
update_task_description(task_id_str, new_description)
else:
print(f"Error: Unknown Command {command}")
print_usage()
if __name__ == "__main__":
main()