Zig Project: To-Do List CLI
In this project you’ll build a to-do list that lives in your terminal. You type todo add Buy milk, todo list, todo done 1, and it remembers your tasks between runs by saving them to a plain text file.
It’s the kind of small tool developers really write for themselves, and it’s a great way to see several Zig ideas working together: a tagged union for the commands, custom error sets for things that can go wrong, an ArrayList for the tasks, and files to keep them. Each step below is a complete program you can run, and the last one is the finished app.
What you’ll build
Section titled “What you’ll build”Here’s a real session with the finished program:
./todo add Buy milk./todo add Call grandma./todo add Write the Zig project page./todo done 2./todo remove 1./todo listYou’ll see:
added task 1: Buy milkadded task 2: Call grandmaadded task 3: Write the Zig project pagedone: Call grandmaremoved: Buy milk 1. [x] Call grandma 2. [ ] Write the Zig project pageAnd when something’s wrong, it says so in plain words instead of crashing:
$ ./todo done 5there's no task with that number (you have 2)$ ./todo remove two'two' isn't a task numberusage: todo add <text> add a task todo list show all tasks todo done <n> mark task n as done todo remove <n> delete task nWhat you’ll practise:
- A struct for a task, with methods to read and write it as a line of text (Zig Struct Methods).
- A tagged union for the commands, and a
switchthat must handle every one (Zig Tagged Unions). - An error set for bad input, turned into helpful messages (Zig Custom Error Sets).
- An arena allocator for a short-lived program (Zig Arena Allocator).
- Loading and saving a file, where “no file yet” is normal and not an error (Zig File I/O).
Step 1: Set up and plan
Section titled “Step 1: Set up and plan”Make a folder with one source file, todo.zig:
mkdir todocd todoBefore writing code, it helps to decide two things.
How are tasks saved? One task per line, in a format you could also read and edit by hand:
[x] Call grandma[ ] Write the Zig project page[x] means done, [ ] means not yet, and the rest of the line is the text. A plain text file is easy to check with cat, easy to fix in an editor, and easy to parse.
How is the program split up? Into small functions that each do one job:
parseCommand: turn the command-line arguments into aCommandvalue.load: read the file into a list of tasks.run: carry out the command on the list.save: write the list back to the file, if it changed.
Only main, load and save touch the outside world. parseCommand and run work on plain values, which is what lets every step below run with made-up input. Everything here was checked with Zig 0.17.1.
Step 2: A task and its line in the file
Section titled “Step 2: A task and its line in the file”A task is two things: whether it’s done, and its text. The struct gets two small methods, one to read a line and one to write it:
const std = @import("std");
pub fn main(init: std.process.Init) !void { var buffer: [256]u8 = undefined; var stdout_writer = std.Io.File.stdout().writer(init.io, &buffer); const out = &stdout_writer.interface;
const lines = [_][]const u8{ "[ ] Buy milk", "[x] Call grandma", "Buy milk", "[ ] " }; for (lines) |line| { if (Task.fromLine(line)) |task| { try out.print("done={} text=\"{s}\"\n", .{ task.done, task.text }); } else { try out.print("not a task line: \"{s}\"\n", .{line}); } }
// And back again, as a line of text. try Task.writeLine(.{ .done = true, .text = "Water the plants" }, out); try out.flush();}
const Task = struct { done: bool, text: []const u8,
/// Reads one line of the file: "[ ] text" or "[x] text". fn fromLine(line: []const u8) ?Task { if (std.mem.cutPrefix(u8, line, "[ ] ")) |text| return .{ .done = false, .text = text }; if (std.mem.cutPrefix(u8, line, "[x] ")) |text| return .{ .done = true, .text = text }; return null; }
fn writeLine(task: Task, w: *std.Io.Writer) !void { try w.print("[{s}] {s}\n", .{ if (task.done) "x" else " ", task.text }); }};Output:
done=false text="Buy milk"done=true text="Call grandma"not a task line: "Buy milk"done=false text=""[x] Water the plantsfromLinereturns?Task: a task, ornullwhen the line isn’t in our format. Returningnullinstead of an error is a choice: a stray line in the file will be skipped, not stop the whole program.std.mem.cutPrefix(u8, line, "[ ] ")checks thatlinestarts with"[ ] "and gives you the rest, ornullif it doesn’t.if (...) |text|unwraps it.- The task’s
textis a slice of the line, not a copy. That’s fine as long as the line’s memory stays alive, which we’ll make sure of in Step 5. writeLinetakes any*std.Io.Writer. Here it’s stdout; in Step 5 it’ll be the file.if (task.done) "x" else " "is anifexpression that picks which string to print.
Step 3: Commands as a tagged union
Section titled “Step 3: Commands as a tagged union”The program has four commands, and each carries different data: add needs text, done and remove need a number, list needs nothing. That’s exactly what a tagged union is for: a Command value is one of the four at a time, with that command’s data, and Zig remembers which. You’ll find it below main in this program. list has no type after it, which means it carries no data (its type is void). Building values looks like .{ .add = "Buy milk" }, .{ .done = 2 } and plain .list. The tagged union section of the language reference has more examples, including switch captures.
The parser gets the arguments after the program name and returns a Command, or an error from our own error set saying what was wrong:
const std = @import("std");
pub fn main(init: std.process.Init) void { const arena = init.arena.allocator(); const tries = [_][]const [:0]const u8{ &.{ "add", "Buy", "milk" }, &.{"list"}, &.{ "done", "2" }, &.{ "remove", "x" }, &.{"add"}, &.{"fly"}, &.{}, }; for (tries) |args| { if (parseCommand(arena, args)) |command| { switch (command) { .add => |text| std.debug.print("add \"{s}\"\n", .{text}), .list => std.debug.print("list\n", .{}), .done => |n| std.debug.print("done {d}\n", .{n}), .remove => |n| std.debug.print("remove {d}\n", .{n}), } } else |err| { std.debug.print("error.{t}\n", .{err}); } }}
const Command = union(enum) { add: []const u8, list, done: usize, remove: usize,};
const ParseError = error{ MissingCommand, UnknownCommand, MissingText, MissingNumber, BadNumber, OutOfMemory };
/// Turns the arguments after the program name into a Command.fn parseCommand(arena: std.mem.Allocator, args: []const [:0]const u8) ParseError!Command { if (args.len == 0) return error.MissingCommand; const name = args[0]; const rest = args[1..];
if (std.mem.eql(u8, name, "list")) return .list; if (std.mem.eql(u8, name, "add")) { if (rest.len == 0) return error.MissingText; return .{ .add = try std.mem.join(arena, " ", rest) }; } if (std.mem.eql(u8, name, "done")) return .{ .done = try parseNumber(rest) }; if (std.mem.eql(u8, name, "remove")) return .{ .remove = try parseNumber(rest) }; return error.UnknownCommand;}
fn parseNumber(rest: []const [:0]const u8) ParseError!usize { if (rest.len == 0) return error.MissingNumber; const n = std.fmt.parseInt(usize, rest[0], 10) catch return error.BadNumber; if (n == 0) return error.BadNumber; return n;}Output:
add "Buy milk"listdone 2error.BadNumbererror.MissingTexterror.UnknownCommanderror.MissingCommandWhat’s happening:
ParseErrorlists every way parsing can fail, with names that say what the user did wrong.OutOfMemoryis there becausestd.mem.joinallocates. Writing the set out in full, instead of letting Zig infer it with!Command, documents every way parsing can fail right in the function’s signature.std.mem.eql(u8, name, "list")compares the text. Zig can’tswitchon strings, so a chain ofifs is the normal way to match command names.- For
add, the task text is every remaining argument joined with spaces:todo add Buy milkarrives as"Buy"and"milk", andstd.mem.joinmakes"Buy milk". People don’t have to put quotes around their tasks. parseNumberrejects0. Task numbers start at 1 for people, andn - 1for a0would underflow later. Catching it here keeps the rest of the code simple.- In
main,switch (command)with|text|and|n|captures each command’s data. That’s the sameswitchthe real program uses in Step 4.
Step 4: Carry out a command
Section titled “Step 4: Carry out a command”run takes the list of tasks and a command, does the work, and prints a short message. It returns true when the list changed, so main knows whether to save:
const std = @import("std");
pub fn main(init: std.process.Init) !void { const arena = init.arena.allocator();
var tasks: std.ArrayList(Task) = .empty; try tasks.append(arena, .{ .done = false, .text = "Buy milk" });
var buffer: [1024]u8 = undefined; var stdout_writer = std.Io.File.stdout().writer(init.io, &buffer); const out = &stdout_writer.interface;
const commands = [_]Command{ .{ .add = "Call grandma" }, .{ .done = 1 }, .list, .{ .remove = 1 }, .list, }; for (commands) |command| { const changed = try run(arena, &tasks, command, out); try out.print(" (changed: {})\n", .{changed}); }
if (run(arena, &tasks, .{ .done = 7 }, out)) |_| {} else |err| { try out.print("done 7 -> error.{t}\n", .{err}); } try out.flush();}
const Task = struct { done: bool, text: []const u8,};
const Command = union(enum) { add: []const u8, list, done: usize, remove: usize,};
/// Carries out a command. Returns true if the list changed and needs saving.fn run(arena: std.mem.Allocator, tasks: *std.ArrayList(Task), command: Command, out: *std.Io.Writer) !bool { switch (command) { .add => |text| { try tasks.append(arena, .{ .done = false, .text = text }); try out.print("added task {d}: {s}\n", .{ tasks.items.len, text }); return true; }, .list => { if (tasks.items.len == 0) try out.writeAll("nothing to do!\n"); for (tasks.items, 1..) |task, n| { try out.print("{d:>2}. [{s}] {s}\n", .{ n, if (task.done) "x" else " ", task.text }); } return false; }, .done => |n| { if (n > tasks.items.len) return error.NoSuchTask; tasks.items[n - 1].done = true; try out.print("done: {s}\n", .{tasks.items[n - 1].text}); return true; }, .remove => |n| { if (n > tasks.items.len) return error.NoSuchTask; const removed = tasks.orderedRemove(n - 1); try out.print("removed: {s}\n", .{removed.text}); return true; }, }}Output:
added task 2: Call grandma (changed: true)done: Buy milk (changed: true) 1. [x] Buy milk 2. [ ] Call grandma (changed: false)removed: Buy milk (changed: true) 1. [ ] Call grandma (changed: false)done 7 -> error.NoSuchTask- The
switchcovers all four commands. If you add a fifth toCommandlater and forget it here, the program won’t compile (more on that in “Common mistakes”). doneandremovecheck the number first and returnerror.NoSuchTaskif it’s too big. That error isn’t in any set we wrote:runreturns!bool, so Zig infers its error set from what the body can return (NoSuchTaskplus the writer’s errors). Inferred sets are handy for internal functions like this one.- People count from 1 and slices from 0, so the code uses
n - 1. Converting in exactly one place keeps off-by-one bugs away. orderedRemoveremoves an item and moves the rest up, so the list keeps its order. (swapRemoveis faster but moves the last task into the gap, which would shuffle a to-do list.)if (run(...)) |_| {} else |err| { ... }is how you look at an error withouttry: the first branch gets the value, theelsegets the error.
Step 5: Load and save the file
Section titled “Step 5: Load and save the file”Last piece: the file. load reads it into a list, and save writes the list back:
const std = @import("std");
pub fn main(init: std.process.Init) !void { const io = init.io; const arena = init.arena.allocator(); const cwd = std.Io.Dir.cwd();
// No file yet: an empty list, not an error. const empty = try load(io, arena, "todo-test.txt"); std.debug.print("before saving: {d} tasks\n", .{empty.items.len});
const tasks = [_]Task{ .{ .done = true, .text = "Buy milk" }, .{ .done = false, .text = "Call grandma" }, }; try save(io, "todo-test.txt", &tasks); defer cwd.deleteFile(io, "todo-test.txt") catch {};
const data = try cwd.readFileAlloc(io, "todo-test.txt", arena, .limited(4096)); std.debug.print("the file:\n{s}", .{data});
const loaded = try load(io, arena, "todo-test.txt"); std.debug.print("loaded {d} tasks, first: {s}\n", .{ loaded.items.len, loaded.items[0].text });}
const Task = struct { done: bool, text: []const u8,
/// Reads one line of the file: "[ ] text" or "[x] text". fn fromLine(line: []const u8) ?Task { if (std.mem.cutPrefix(u8, line, "[ ] ")) |text| return .{ .done = false, .text = text }; if (std.mem.cutPrefix(u8, line, "[x] ")) |text| return .{ .done = true, .text = text }; return null; }
fn writeLine(task: Task, w: *std.Io.Writer) !void { try w.print("[{s}] {s}\n", .{ if (task.done) "x" else " ", task.text }); }};
/// Reads the task file. A missing file just means an empty list.fn load(io: std.Io, arena: std.mem.Allocator, path: []const u8) !std.ArrayList(Task) { var tasks: std.ArrayList(Task) = .empty; const data = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(1024 * 1024)) catch |err| switch (err) { error.FileNotFound => return tasks, else => return err, }; var lines = std.mem.splitScalar(u8, data, '\n'); while (lines.next()) |raw| { const line = std.mem.trimEnd(u8, raw, "\r"); if (Task.fromLine(line)) |task| try tasks.append(arena, task); } return tasks;}
/// Writes every task to the file, replacing what was there.fn save(io: std.Io, path: []const u8, tasks: []const Task) !void { const file = try std.Io.Dir.cwd().createFile(io, path, .{}); defer file.close(io);
var buffer: [4096]u8 = undefined; var file_writer = file.writer(io, &buffer); for (tasks) |task| try task.writeLine(&file_writer.interface); try file_writer.interface.flush();}Output:
before saving: 0 tasksthe file:[x] Buy milk[ ] Call grandmaloaded 2 tasks, first: Buy milkloadtreatserror.FileNotFoundas an empty list. The very first time you runtodo list, there’s no file yet, and that’s normal. Every other error (no permission, the path is a folder) is passed up.- The file is read in one go with
readFileAllocinto the arena. Each task’stextis a slice into that data, and the arena keeps it alive until the program ends, which is why the slices from Step 2 are safe. splitScalar(u8, data, '\n')gives one line at a time.trimEnd(..., "\r")drops a Windows line ending in case someone edited the file in Notepad. Lines that aren’t tasks, including the empty one after the last\n, are skipped byfromLine.saveusescreateFile, which replaces the old file, a buffered writer, and the all-importantflushbefore the file closes (Zig File I/O explains why).
Step 6: The complete program
Section titled “Step 6: The complete program”main ties it all together: parse the arguments, load the file, run the command, save if needed. It turns each error into a message and an exit code. Here’s the full todo.zig:
const std = @import("std");
const file_name = "todo.txt";
const usage = \\usage: \\ todo add <text> add a task \\ todo list show all tasks \\ todo done <n> mark task n as done \\ todo remove <n> delete task n \\;
pub fn main(init: std.process.Init) !u8 { const io = init.io; const arena = init.arena.allocator();
const args = try init.minimal.args.toSlice(arena); const command = parseCommand(arena, args[1..]) catch |err| { switch (err) { error.MissingCommand => {}, error.UnknownCommand => std.debug.print("unknown command '{s}'\n", .{args[1]}), error.MissingText => std.debug.print("what should the task say?\n", .{}), error.MissingNumber => std.debug.print("which task? give its number\n", .{}), error.BadNumber => std.debug.print("'{s}' isn't a task number\n", .{args[2]}), error.OutOfMemory => return err, } std.debug.print(usage, .{}); return 2; };
var tasks = try load(io, arena, file_name);
var out_buffer: [4096]u8 = undefined; var stdout_writer = std.Io.File.stdout().writer(io, &out_buffer); const out = &stdout_writer.interface;
const changed = run(arena, &tasks, command, out) catch |err| switch (err) { error.NoSuchTask => { std.debug.print("there's no task with that number (you have {d})\n", .{tasks.items.len}); return 1; }, else => return err, }; try out.flush();
if (changed) try save(io, file_name, tasks.items); return 0;}
const Task = struct { done: bool, text: []const u8,
/// Reads one line of the file: "[ ] text" or "[x] text". fn fromLine(line: []const u8) ?Task { if (std.mem.cutPrefix(u8, line, "[ ] ")) |text| return .{ .done = false, .text = text }; if (std.mem.cutPrefix(u8, line, "[x] ")) |text| return .{ .done = true, .text = text }; return null; }
fn writeLine(task: Task, w: *std.Io.Writer) !void { try w.print("[{s}] {s}\n", .{ if (task.done) "x" else " ", task.text }); }};
const Command = union(enum) { add: []const u8, list, done: usize, remove: usize,};
const ParseError = error{ MissingCommand, UnknownCommand, MissingText, MissingNumber, BadNumber, OutOfMemory };
/// Turns the arguments after the program name into a Command.fn parseCommand(arena: std.mem.Allocator, args: []const [:0]const u8) ParseError!Command { if (args.len == 0) return error.MissingCommand; const name = args[0]; const rest = args[1..];
if (std.mem.eql(u8, name, "list")) return .list; if (std.mem.eql(u8, name, "add")) { if (rest.len == 0) return error.MissingText; return .{ .add = try std.mem.join(arena, " ", rest) }; } if (std.mem.eql(u8, name, "done")) return .{ .done = try parseNumber(rest) }; if (std.mem.eql(u8, name, "remove")) return .{ .remove = try parseNumber(rest) }; return error.UnknownCommand;}
fn parseNumber(rest: []const [:0]const u8) ParseError!usize { if (rest.len == 0) return error.MissingNumber; const n = std.fmt.parseInt(usize, rest[0], 10) catch return error.BadNumber; if (n == 0) return error.BadNumber; return n;}
/// Carries out a command. Returns true if the list changed and needs saving.fn run(arena: std.mem.Allocator, tasks: *std.ArrayList(Task), command: Command, out: *std.Io.Writer) !bool { switch (command) { .add => |text| { try tasks.append(arena, .{ .done = false, .text = text }); try out.print("added task {d}: {s}\n", .{ tasks.items.len, text }); return true; }, .list => { if (tasks.items.len == 0) try out.writeAll("nothing to do!\n"); for (tasks.items, 1..) |task, n| { try out.print("{d:>2}. [{s}] {s}\n", .{ n, if (task.done) "x" else " ", task.text }); } return false; }, .done => |n| { if (n > tasks.items.len) return error.NoSuchTask; tasks.items[n - 1].done = true; try out.print("done: {s}\n", .{tasks.items[n - 1].text}); return true; }, .remove => |n| { if (n > tasks.items.len) return error.NoSuchTask; const removed = tasks.orderedRemove(n - 1); try out.print("removed: {s}\n", .{removed.text}); return true; }, }}
/// Reads the task file. A missing file just means an empty list.fn load(io: std.Io, arena: std.mem.Allocator, path: []const u8) !std.ArrayList(Task) { var tasks: std.ArrayList(Task) = .empty; const data = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(1024 * 1024)) catch |err| switch (err) { error.FileNotFound => return tasks, else => return err, }; var lines = std.mem.splitScalar(u8, data, '\n'); while (lines.next()) |raw| { const line = std.mem.trimEnd(u8, raw, "\r"); if (Task.fromLine(line)) |task| try tasks.append(arena, task); } return tasks;}
/// Writes every task to the file, replacing what was there.fn save(io: std.Io, path: []const u8, tasks: []const Task) !void { const file = try std.Io.Dir.cwd().createFile(io, path, .{}); defer file.close(io);
var buffer: [4096]u8 = undefined; var file_writer = file.writer(io, &buffer); for (tasks) |task| try task.writeLine(&file_writer.interface); try file_writer.interface.flush();}Build it and try it:
zig build-exe todo.zig./todo list./todo add Buy milk./todo add Call grandma./todo listcat todo.txtYou’ll see:
nothing to do!added task 1: Buy milkadded task 2: Call grandma 1. [ ] Buy milk 2. [ ] Call grandma[ ] Buy milk[ ] Call grandma(On Windows the program is todo.exe, and you’d use type todo.txt instead of cat.) You can also use zig run todo.zig -- add Buy milk while you’re working on it; everything after -- goes to the program.
A few details in main:
usageis a multiline string literal: each line starts with\\. It’s printed whenever the command line doesn’t make sense, andmainreturns2, the usual exit code for “used wrong”.- The
catch |err|afterparseCommandhas aswitchwith one prong per error inParseError, and the compiler checks that none is missing.MissingCommandprints nothing extra, since the usage text says it all. error.BadNumberusesargs[2]anderror.UnknownCommandusesargs[1]. That’s safe because those errors only happen when those arguments exist.run’s errors get the same treatment, withelse => return errfor anything unexpected (like a failed write to stdout).saveonly runs whenrunreturnedtrue, sotodo listnever rewrites the file.
Common mistakes
Section titled “Common mistakes”Adding a command but not handling it. Say you add clear, to Command to remove all finished tasks, and build before writing the code for it. Zig stops you:
todo.zig:102:5: error: switch must handle all possibilities switch (command) { ^~~~~~todo.zig:72:5: note: unhandled enumeration value: 'clear' clear, ^~~~~This is the tagged union paying off: the compiler finds every switch that needs updating. Resist the urge to add else => {} to make the error go away. That turns the helpful check off for good.
Treating a missing file as an error. If load just used try on readFileAlloc, the very first todo add would fail with error.FileNotFound, because the file is created by the first save. Decide which errors are really “normal situations” and handle those right where they happen.
Mixing up numbers for people and indexes for code. The list shows 1. for the first task, but it’s items[0]. Do the - 1 in one place, right after checking the range, and the rest of the code never has to think about it.
Forgetting flush in save. The file gets created but stays empty or loses its last tasks. Nothing warns you, so it’s worth remembering: a buffered writer writes nothing until you flush it.
Ideas to extend it
Section titled “Ideas to extend it”undo <n>to mark a task as not done again. It’s one more union field and one moreswitchprong, and the compiler will remind you where.clearremoves every finished task. Walk the list backwards withorderedRemove, or build a new list of the tasks you keep.- Safer saving. If the computer crashes halfway through
save,todo.txtcould be left half-written.std.Io.Dir.cwd().createFileAtomic(io, path, .{ .replace = true })writes to a temporary file andreplace(io)swaps it in only when it’s complete. - Keep the file in your home folder, so
todoworks from any directory. ReadHOME(orUSERPROFILEon Windows) with Zig Environment Variables and build the path. - Save as JSON instead of the
[x]format, withstd.jsonfrom Zig JSON. Then you can add fields like a due date without inventing a new format. - Test
parseCommandandrun. They don’t touch files, so they’re easy to cover withtestblocks andstd.Io.Writer.fixed. See Zig Testing.
- Split a CLI into parse → load → run → save. Keep
parseandrunfree of files so you can run them with made-up input. - A tagged union like
Commandholds one of several commands, each with its own data. Aswitchon it must handle every field, so adding a command shows you everything to update. - A written-out error set (
ParseError) letsmainswitchon errors and give a clear message for each. Inferred sets (!bool) are fine for internal functions. error.FileNotFoundon the first run is normal: return an empty list instead of failing.- For a short-lived tool, the arena (
init.arena) is the simplest way to manage memory: allocate freely, everything is freed at exit. - Return exit codes from
main:0for success,1for a failure,2for wrong usage.
Next up: Zig Project: HTTP Server, a small web server built on the standard library that you can talk to with curl.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Tagged unions in the 0.17.1 reference:
union(enum), capturing the payload in aswitch, andvoidfields likelist. - Error sets in the 0.17.1 reference: writing your own sets, merging them, and inferred error sets.
- Multiline string literals in the 0.17.1 reference: the
\\lines used for the usage text. std.Io.Dirsource (0.17.1):readFileAlloc,createFileandcreateFileAtomicfor the safer-saving idea.