-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
405 lines (331 loc) · 10.8 KB
/
Copy pathProgram.cs
File metadata and controls
405 lines (331 loc) · 10.8 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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
using System.Text.Json;
using System.Text.Json.Serialization;
var app = new TaskPilotApp(new JsonTaskStore(TaskStorePaths.DefaultPath));
return app.Run(args);
internal sealed class TaskPilotApp
{
private readonly ITaskStore _store;
public TaskPilotApp(ITaskStore store)
{
_store = store;
}
public int Run(string[] args)
{
if (args.Length == 0 || IsHelp(args[0]))
{
PrintHelp();
return 0;
}
try
{
return args[0].ToLowerInvariant() switch
{
"add" => Add(args[1..]),
"list" => List(args[1..]),
"done" => MarkDone(args[1..]),
"remove" or "rm" => Remove(args[1..]),
"stats" => Stats(),
_ => Fail($"Unknown command '{args[0]}'. Run 'taskpilot help' for usage.")
};
}
catch (TaskPilotException ex)
{
return Fail(ex.Message);
}
catch (JsonException ex)
{
return Fail($"Task data is corrupt: {ex.Message}");
}
}
private int Add(string[] args)
{
var options = CommandOptions.Parse(args);
var title = options.PositionalText;
if (string.IsNullOrWhiteSpace(title))
{
throw new TaskPilotException("Add needs a task title. Example: taskpilot add \"Pay invoice\" --due 2026-07-15");
}
var tasks = _store.Load();
DateOnly? dueDate = options.Has("due") ? ParseDate(options.RequireValue("due")) : null;
var priority = options.Get("priority") ?? options.Get("p") ?? "medium";
if ((options.Has("priority") && options.Get("priority") is null) || (options.Has("p") && options.Get("p") is null))
{
throw new TaskPilotException("Priority needs a value: low, medium, or high.");
}
if (!Enum.TryParse<TaskPriority>(priority, ignoreCase: true, out var parsedPriority))
{
throw new TaskPilotException("Priority must be low, medium, or high.");
}
var task = new WorkTask
{
Id = NextId(tasks),
Title = title,
Priority = parsedPriority,
DueDate = dueDate,
CreatedAt = DateTimeOffset.Now
};
tasks.Add(task);
_store.Save(tasks);
Console.WriteLine($"Added #{task.Id}: {task.Title}");
return 0;
}
private int List(string[] args)
{
var options = CommandOptions.Parse(args);
var tasks = _store.Load();
var filtered = tasks.AsEnumerable();
if (!options.Has("all"))
{
filtered = filtered.Where(task => !task.IsDone);
}
if (options.Has("today"))
{
filtered = filtered.Where(task => task.DueDate == DateOnly.FromDateTime(DateTime.Today));
}
if (options.Has("overdue"))
{
var today = DateOnly.FromDateTime(DateTime.Today);
filtered = filtered.Where(task => task.DueDate is not null && task.DueDate < today && !task.IsDone);
}
var rows = filtered
.OrderBy(task => task.IsDone)
.ThenBy(task => task.DueDate is null)
.ThenBy(task => task.DueDate)
.ThenByDescending(task => task.Priority)
.ThenBy(task => task.Id)
.ToList();
if (rows.Count == 0)
{
Console.WriteLine("No tasks found.");
return 0;
}
Console.WriteLine("ID Status Priority Due Title");
Console.WriteLine("-- ------ -------- ---------- -----");
foreach (var task in rows)
{
var status = task.IsDone ? "done" : "open";
var due = task.DueDate?.ToString("yyyy-MM-dd") ?? "-";
Console.WriteLine($"{task.Id,-2} {status,-6} {task.Priority,-8} {due,-10} {task.Title}");
}
return 0;
}
private int MarkDone(string[] args)
{
var id = ParseRequiredId(args, "done");
var tasks = _store.Load();
var task = FindTask(tasks, id);
if (task.IsDone)
{
Console.WriteLine($"#{task.Id} was already done.");
return 0;
}
task.CompletedAt = DateTimeOffset.Now;
_store.Save(tasks);
Console.WriteLine($"Completed #{task.Id}: {task.Title}");
return 0;
}
private int Remove(string[] args)
{
var id = ParseRequiredId(args, "remove");
var tasks = _store.Load();
var task = FindTask(tasks, id);
tasks.Remove(task);
_store.Save(tasks);
Console.WriteLine($"Removed #{task.Id}: {task.Title}");
return 0;
}
private int Stats()
{
var tasks = _store.Load();
var today = DateOnly.FromDateTime(DateTime.Today);
var open = tasks.Count(task => !task.IsDone);
var done = tasks.Count(task => task.IsDone);
var overdue = tasks.Count(task => !task.IsDone && task.DueDate is not null && task.DueDate < today);
var dueToday = tasks.Count(task => !task.IsDone && task.DueDate == today);
Console.WriteLine($"Open: {open}");
Console.WriteLine($"Done: {done}");
Console.WriteLine($"Due today: {dueToday}");
Console.WriteLine($"Overdue: {overdue}");
Console.WriteLine($"Data file: {TaskStorePaths.DefaultPath}");
return 0;
}
private static int Fail(string message)
{
Console.Error.WriteLine($"Error: {message}");
return 1;
}
private static bool IsHelp(string value)
{
return value is "help" or "-h" or "--help";
}
private static DateOnly ParseDate(string value)
{
if (DateOnly.TryParse(value, out var date))
{
return date;
}
throw new TaskPilotException("Due date must be a valid date such as 2026-07-15.");
}
private static int ParseRequiredId(string[] args, string command)
{
if (args.Length == 0 || !int.TryParse(args[0], out var id) || id <= 0)
{
throw new TaskPilotException($"{command} needs a positive task id.");
}
return id;
}
private static WorkTask FindTask(List<WorkTask> tasks, int id)
{
return tasks.FirstOrDefault(task => task.Id == id)
?? throw new TaskPilotException($"Task #{id} was not found.");
}
private static int NextId(IReadOnlyCollection<WorkTask> tasks)
{
return tasks.Count == 0 ? 1 : tasks.Max(task => task.Id) + 1;
}
private static void PrintHelp()
{
Console.WriteLine("""
TaskPilot - small file-backed task tracker
Usage:
taskpilot add "Ship report" --due 2026-07-15 --priority high
taskpilot list [--all] [--today] [--overdue]
taskpilot done <id>
taskpilot remove <id>
taskpilot stats
Priorities: low, medium, high
""");
}
}
internal interface ITaskStore
{
List<WorkTask> Load();
void Save(List<WorkTask> tasks);
}
internal sealed class JsonTaskStore : ITaskStore
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true,
Converters = { new JsonStringEnumConverter() }
};
private readonly string _path;
public JsonTaskStore(string path)
{
_path = path;
}
public List<WorkTask> Load()
{
if (!File.Exists(_path))
{
return [];
}
var json = File.ReadAllText(_path);
return JsonSerializer.Deserialize<List<WorkTask>>(json, JsonOptions) ?? [];
}
public void Save(List<WorkTask> tasks)
{
var directory = Path.GetDirectoryName(_path);
if (!string.IsNullOrWhiteSpace(directory))
{
Directory.CreateDirectory(directory);
}
File.WriteAllText(_path, JsonSerializer.Serialize(tasks, JsonOptions));
}
}
internal static class TaskStorePaths
{
public static string DefaultPath
{
get
{
var overridePath = Environment.GetEnvironmentVariable("TASKPILOT_DATA_FILE");
if (!string.IsNullOrWhiteSpace(overridePath))
{
return overridePath;
}
var dataDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
if (string.IsNullOrWhiteSpace(dataDirectory))
{
dataDirectory = Environment.CurrentDirectory;
}
return Path.Combine(dataDirectory, "TaskPilot", "tasks.json");
}
}
}
internal sealed class CommandOptions
{
private readonly Dictionary<string, string?> _options;
private CommandOptions(Dictionary<string, string?> options, string positionalText)
{
_options = options;
PositionalText = positionalText;
}
public string PositionalText { get; }
public static CommandOptions Parse(string[] args)
{
var options = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
var positional = new List<string>();
for (var i = 0; i < args.Length; i++)
{
var value = args[i];
if (!value.StartsWith("-", StringComparison.Ordinal))
{
positional.Add(value);
continue;
}
var key = value.StartsWith("--", StringComparison.Ordinal)
? value[2..]
: value[1..];
if (string.IsNullOrWhiteSpace(key))
{
throw new TaskPilotException("Option names cannot be empty.");
}
if (i + 1 < args.Length && !args[i + 1].StartsWith("--", StringComparison.Ordinal))
{
options[key] = args[++i];
}
else
{
options[key] = null;
}
}
return new CommandOptions(options, string.Join(" ", positional));
}
public bool Has(string name)
{
return _options.ContainsKey(name);
}
public string? Get(string name)
{
return _options.GetValueOrDefault(name);
}
public string RequireValue(string name)
{
return _options.GetValueOrDefault(name)
?? throw new TaskPilotException($"--{name} needs a value.");
}
}
internal sealed class WorkTask
{
public int Id { get; set; }
public required string Title { get; set; }
public TaskPriority Priority { get; set; } = TaskPriority.Medium;
public DateOnly? DueDate { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset? CompletedAt { get; set; }
public bool IsDone => CompletedAt is not null;
}
internal enum TaskPriority
{
Low = 0,
Medium = 1,
High = 2
}
internal sealed class TaskPilotException : Exception
{
public TaskPilotException(string message)
: base(message)
{
}
}