Project: To-Do List CLI
In this project you’ll build a small to-do list that lives in your terminal. You type add Buy milk, and it remembers. Close the terminal, come back tomorrow, type list, and your tasks are still there.
It’s a good second project because it looks like a real tool. It uses structs with methods, printing your own types, lists, match, custom errors, command-line arguments and file I/O. We’ll build and test each piece on its own, and then put it all together.
What you’ll build
Section titled “What you’ll build”Here’s a real session with the finished tool:
$ mojo run todo.mojo add Buy milkAdded task 1.$ mojo run todo.mojo add Call grandmaAdded task 2.$ mojo run todo.mojo done 1Marked task 1 as done.$ mojo run todo.mojo list[x] 1: Buy milk[ ] 2: Call grandma$ mojo run todo.mojo done twoerror: 'two' isn't a task number$ mojo run todo.mojo remove 1Removed task 1: Buy milkThe tasks live in a file called todo.txt, one task per line, in the form id|done|text:
2|0|Call grandmadone is 1 for finished and 0 for not finished. A plain text format like this is easy to read, easy to fix by hand, and easy to parse.
Step 1: The Task struct
Section titled “Step 1: The Task struct”Every task has a number (so you can refer to it), a done flag and some text. That’s a struct. We give it three methods: one to turn a task into a line for the file, one to read a task back from a line, and write_to so print(task) shows it nicely.
@fieldwise_initstruct Task(Copyable, Writable): var id: Int var done: Bool var text: String
def to_line(self) -> String: return String(t"{self.id}|{1 if self.done else 0}|{self.text}")
@staticmethod def from_line(line: StringSlice) raises -> Task: var parts = line.split("|", maxsplit=2) if len(parts) != 3: raise Error(t"bad line: {line}") return Task(Int(parts[0]), parts[1] == "1", String(parts[2]))
def write_to(self, mut writer: Some[Writer]): writer.write("[x] " if self.done else "[ ] ", self.id, ": ", self.text)
def main() raises: var task = Task(1, False, "Buy milk | eggs") print(task)
var line = task.to_line() print(line)
var back = Task.from_line(line) print(back.id, back.done, back.text)
try: _ = Task.from_line("oops") except e: print("Error:", e)Output:
[ ] 1: Buy milk | eggs1|0|Buy milk | eggs1 False Buy milk | eggsError: bad line: oopsLet’s go through it:
to_linebuilds the line with a t-string.1 if self.done else 0is a conditional expression, the same as in Python.from_lineis a static method: it has noself, and you call it on the type,Task.from_line(...). Itraisesbecause a broken line (or a bad number in it) is an error the caller should hear about.split("|", maxsplit=2)splits at most twice. That’s what keeps a|inside the text safe:Buy milk | eggssurvives the round trip in one piece.write_tois whatprintcalls for aWritabletype. The Mojo Printing Your Types lesson explains it.
Step 2: Working with the list of tasks
Section titled “Step 2: Working with the list of tasks”All the tasks live in a List[Task]. We need three small helpers: pick the next free number, find a task by its number, and change or remove it.
@fieldwise_initstruct Task(Copyable, Writable): var id: Int var done: Bool var text: String
def write_to(self, mut writer: Some[Writer]): writer.write("[x] " if self.done else "[ ] ", self.id, ": ", self.text)
def next_id(tasks: List[Task]) -> Int: var biggest = 0 for task in tasks: biggest = max(biggest, task.id) return biggest + 1
def find(tasks: List[Task], id: Int) -> Int: for i in range(len(tasks)): if tasks[i].id == id: return i return -1
def main(): var tasks: List[Task] = [] tasks.append(Task(next_id(tasks), False, "Buy milk")) tasks.append(Task(next_id(tasks), False, "Call grandma")) tasks.append(Task(next_id(tasks), False, "Water the plants"))
var i = find(tasks, 2) tasks[i].done = True
var removed = tasks.pop(find(tasks, 1)) print("Removed:", removed.text)
tasks.append(Task(next_id(tasks), False, "Read a book")) for task in tasks: print(task) print("Task 9 is at index", find(tasks, 9))Output:
Removed: Buy milk[x] 2: Call grandma[ ] 3: Water the plants[ ] 4: Read a bookTask 9 is at index -1A few details worth a closer look:
next_iduses the biggest number plus one, notlen(tasks) + 1. After removing task 1, there are 2 tasks left, andlen + 1would hand out the number 3 a second time. The biggest-plus-one rule never repeats a number that’s still in use.findreturns the index, or-1when there’s no such task. Mojo has no negative indexing, so-1can’t be mistaken for a real position.tasks[i].done = Truechanges the task inside the list. That works becausetasks[i]refers to the item in place. A loop variable doesn’t: see Common mistakes below.tasks.pop(i)removes the item at indexiand gives it back, so we can print what was removed.
Step 3: Turning arguments into commands
Section titled “Step 3: Turning arguments into commands”The program gets its command as a list of words, like ["add", "Buy", "milk"] or ["done", "2"]. A match on the first word picks what to do. Every problem (unknown command, missing text, bad number) becomes a raised Error with a helpful message.
For now the “command line” is a hard-coded list, and the tasks stay in memory, so we can test every command in one run:
@fieldwise_initstruct Task(Copyable, Writable): var id: Int var done: Bool var text: String
def write_to(self, mut writer: Some[Writer]): writer.write("[x] " if self.done else "[ ] ", self.id, ": ", self.text)
def next_id(tasks: List[Task]) -> Int: var biggest = 0 for task in tasks: biggest = max(biggest, task.id) return biggest + 1
def find(tasks: List[Task], id: Int) -> Int: for i in range(len(tasks)): if tasks[i].id == id: return i return -1
def run(args: List[String], mut tasks: List[Task]) raises: var command = args[0] match command: case "add": if len(args) < 2: raise Error("add needs some text, like: add Buy milk") var id = next_id(tasks) tasks.append(Task(id, False, " ".join(args[1:]))) print(t"Added task {id}.") case "list": if len(tasks) == 0: print("Nothing to do!") for task in tasks: print(task) case "done" | "remove": if len(args) != 2: raise Error(t"{command} needs a task number, like: {command} 2") var id: Int try: id = Int(args[1]) except: raise Error(t"'{args[1]}' isn't a task number") var i = find(tasks, id) if i == -1: raise Error(t"there's no task {id}") if command == "done": tasks[i].done = True print(t"Marked task {id} as done.") else: var removed = tasks.pop(i) print(t"Removed task {id}: {removed.text}") case _: raise Error(t"unknown command '{command}'")
def main(): var tasks: List[Task] = [] var commands: List[String] = [ "list", "add Buy milk", "add Call grandma", "done 1", "done two", "remove 7", "fly", "list", ] for line in commands: print(t"> {line}") var args: List[String] = [] for word in line.split(): args.append(String(word)) try: run(args, tasks) except e: print(t"error: {e}")Output:
> listNothing to do!> add Buy milkAdded task 1.> add Call grandmaAdded task 2.> done 1Marked task 1 as done.> done twoerror: 'two' isn't a task number> remove 7error: there's no task 7> flyerror: unknown command 'fly'> list[x] 1: Buy milk[ ] 2: Call grandmaThe new pieces:
mut tasks: List[Task]letsrunchange the caller’s list. Withoutmut, arguments are read-only. See Mojo Argument Conventions.case "done" | "remove":matches either word, because both need the same checks. Inside, a plainifdecides which one we’re doing." ".join(args[1:])glues the remaining words back together, soadd Buy milkstoresBuy milk.raise Error(...)insideexcept: whenInt(args[1])fails, we replace its technical message with a friendlier one.- In
main, onetry/exceptaroundrunhandles every problem in one place. That keepsrunsimple: it raises and moves on.
Step 4: Saving and loading the file
Section titled “Step 4: Saving and loading the file”To remember tasks between runs, we write them to todo.txt after every change and read them back at the start. If the file doesn’t exist yet, that just means there are no tasks.
from std.os.path import exists
@fieldwise_initstruct Task(Copyable, Writable): var id: Int var done: Bool var text: String
def to_line(self) -> String: return String(t"{self.id}|{1 if self.done else 0}|{self.text}")
@staticmethod def from_line(line: StringSlice) raises -> Task: var parts = line.split("|", maxsplit=2) if len(parts) != 3: raise Error(t"bad line: {line}") return Task(Int(parts[0]), parts[1] == "1", String(parts[2]))
def write_to(self, mut writer: Some[Writer]): writer.write("[x] " if self.done else "[ ] ", self.id, ": ", self.text)
def load(path: String) raises -> List[Task]: var tasks: List[Task] = [] if not exists(path): return tasks^ var text = open(path, "r").read() for line in text.splitlines(): if line.byte_length() > 0: tasks.append(Task.from_line(line)) return tasks^
def save(tasks: List[Task], path: String) raises: with open(path, "w") as f: for task in tasks: f.write(task.to_line(), "\n")
def main() raises: print("Before saving:", len(load("demo-todo.txt")), "tasks")
var tasks: List[Task] = [Task(1, True, "Buy milk"), Task(2, False, "Call grandma")] save(tasks, "demo-todo.txt")
print("File contents:") print(open("demo-todo.txt", "r").read(), end="")
print("Loaded back:") for task in load("demo-todo.txt"): print(task)Output:
Before saving: 0 tasksFile contents:1|1|Buy milk2|0|Call grandmaLoaded back:[x] 1: Buy milk[ ] 2: Call grandma(Run it twice and the first line says 2 tasks, because the file is still there from the first run. Delete demo-todo.txt to start over.)
exists(path)fromstd.os.pathchecks for the file before we try to open it.open(path, "w")creates the file, or empties it if it exists, andwithcloses it for us at the end of the block. Theopen()reference lists the other modes, such as"a"to add to the end of a file.f.write(...)takes several values, likeprint.splitlines()cuts the text into lines, and we skip empty ones, for example a blank line you added by hand.- Both functions raise: a file you can’t write, or a line that isn’t
id|done|text, is a real problem and the user should see it.
Step 5: The complete program
Section titled “Step 5: The complete program”Now we read the real command-line arguments with argv(), load the tasks, run the command and save. Save this as todo.mojo:
from std.os.path import existsfrom std.sys import argv, exit, stderr
comptime FILE = "todo.txt"
@fieldwise_initstruct Task(Copyable, Writable): var id: Int var done: Bool var text: String
def to_line(self) -> String: return String(t"{self.id}|{1 if self.done else 0}|{self.text}")
@staticmethod def from_line(line: StringSlice) raises -> Task: var parts = line.split("|", maxsplit=2) if len(parts) != 3: raise Error(t"bad line: {line}") return Task(Int(parts[0]), parts[1] == "1", String(parts[2]))
def write_to(self, mut writer: Some[Writer]): writer.write("[x] " if self.done else "[ ] ", self.id, ": ", self.text)
def next_id(tasks: List[Task]) -> Int: var biggest = 0 for task in tasks: biggest = max(biggest, task.id) return biggest + 1
def find(tasks: List[Task], id: Int) -> Int: for i in range(len(tasks)): if tasks[i].id == id: return i return -1
def load(path: String) raises -> List[Task]: var tasks: List[Task] = [] if not exists(path): return tasks^ var text = open(path, "r").read() for line in text.splitlines(): if line.byte_length() > 0: tasks.append(Task.from_line(line)) return tasks^
def save(tasks: List[Task], path: String) raises: with open(path, "w") as f: for task in tasks: f.write(task.to_line(), "\n")
def run(args: List[String]) raises: var tasks = load(FILE) var command = args[0] match command: case "add": if len(args) < 2: raise Error("add needs some text, like: add Buy milk") var id = next_id(tasks) tasks.append(Task(id, False, " ".join(args[1:]))) save(tasks, FILE) print(t"Added task {id}.") case "list": if len(tasks) == 0: print("Nothing to do!") for task in tasks: print(task) case "done" | "remove": if len(args) != 2: raise Error(t"{command} needs a task number, like: {command} 2") var id: Int try: id = Int(args[1]) except: raise Error(t"'{args[1]}' isn't a task number") var i = find(tasks, id) if i == -1: raise Error(t"there's no task {id}") if command == "done": tasks[i].done = True print(t"Marked task {id} as done.") else: var removed = tasks.pop(i) print(t"Removed task {id}: {removed.text}") save(tasks, FILE) case _: raise Error(t"unknown command '{command}'")
def main(): var args: List[String] = [] for arg in argv()[1:]: args.append(String(arg)) if len(args) == 0: print("usage: todo add <text> | list | done <id> | remove <id>") return try: run(args) except e: print(t"error: {e}", file=stderr) exit(1)Run it with a command after the file name. Everything after todo.mojo goes to your program:
mojo run todo.mojo add Buy milkmojo run todo.mojo listYou’ll get the session from the top of this page. Run it with no command and it prints the usage line.
Compared with Step 3, two things changed:
argv()[1:]skips the program name and copies each argument into aString, sorungets the same kind of list it got in our test.- Errors go to
stderrand the program ends withexit(1), so a shell script can tell that something went wrong.runalso saves the file afteradd,doneandremove, but not afterlist, which changes nothing.
Common mistakes
Section titled “Common mistakes”Changing a task through the loop variable. A plain loop variable is read-only, so this doesn’t compile:
@fieldwise_initstruct Task(Copyable): var id: Int var done: Bool
def main(): var tasks: List[Task] = [Task(1, False), Task(2, False)] for task in tasks: if task.id == 2: task.done = True print(tasks[1].done)todo.mojo:10:17: error: expression must be mutable in assignment task.done = True ~~~~^~~~~mojo: error: failed to parse the provided Mojo source moduleWrite for ref task in tasks: to get a reference you can change, or use an index as in tasks[i].done = True. The Mojo For lesson covers both.
Comparing a line with "". splitlines() gives you StringSpan views, and in Mojo 1.2 comparing one with a string literal doesn’t compile:
def main(): var text = "1|0|Buy milk\n\n2|1|Call grandma\n" for line in text.splitlines(): if line != "": print(line)todo.mojo:4:20: error: cannot implicitly convert 'String' value to 'StringSpan[origin_of(text["bytes"])]' if line != "": ^~mojo: error: failed to parse the provided Mojo source moduleCheck line.byte_length() > 0, as in load, or turn the line into a String first.
Reusing numbers. Using len(tasks) + 1 as the next id gives two tasks the same number after a remove. Use the biggest id plus one.
Ideas to extend it
Section titled “Ideas to extend it”clear: remove every finished task in one go. (Practice 1.)- Show a summary after
list, like1 of 3 done. edit <id> <text>to change a task’s text.undo <id>to mark a task as not done again.- Priorities: add a fourth field,
highorlow, and list high ones first withsort. - A different file: read the file name from an environment variable like
TODO_FILE, withtodo.txtas the default.
Practice
Section titled “Practice”This exercise works on an in-memory list, like Step 2, so you can compare your output with ours.
1. Clear finished tasks
Section titled “1. Clear finished tasks”Write def clear_done(mut tasks: List[Task]) -> Int that removes every finished task and returns how many it removed.
Hint: build a new list with only the unfinished tasks, then replace the old one: tasks = keep^.
Show solution
@fieldwise_initstruct Task(Copyable, Writable): var id: Int var done: Bool var text: String
def write_to(self, mut writer: Some[Writer]): writer.write("[x] " if self.done else "[ ] ", self.id, ": ", self.text)
def clear_done(mut tasks: List[Task]) -> Int: var keep: List[Task] = [] for task in tasks: if not task.done: keep.append(task.copy()) var removed = len(tasks) - len(keep) tasks = keep^ return removed
def main(): var tasks: List[Task] = [ Task(1, True, "Buy milk"), Task(2, False, "Call grandma"), Task(3, True, "Water the plants"), ] print("Removed", clear_done(tasks), "tasks") for task in tasks: print(task)Output:
Removed 2 tasks[ ] 2: Call grandmaRemoving items from a list while you loop over it is a classic bug in any language, because the positions shift under you. Building a new list avoids it. task.copy() is needed because a Task holds a String and isn’t copied implicitly.
- A struct with methods keeps a task’s data and its file format together:
to_line()and a@staticmethodfrom_line()that raises on bad input. split("|", maxsplit=2)splits a line into a fixed number of parts and keeps the rest of the text in one piece.matchon the command word withcase "done" | "remove":andcase _:reads like a menu.- Raise an
Errorwith a clear message wherever something’s wrong, and catch it once inmain. - Save with
open(path, "w")insidewith, load withread()andsplitlines(), and checkexists(path)first. - Change list items with
tasks[i]orfor ref, never through a plain loop variable.
Next up: Project: Mandelbrot Set, where you draw a famous fractal in the terminal and make it faster with SIMD.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Structs: Mojo manual: fields, methods, static methods and
@fieldwise_init. - open: Mojo std library: file modes and the
FileHandleyou get back. - argv: Mojo std library: the command-line arguments as a list.
- exists: Mojo std library: checking whether a path exists.
- Errors and exceptions: Mojo manual: raising and catching errors.