Skip to content

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.

Here’s a real session with the finished program:

Terminal window
./todo add Buy milk
./todo add Call grandma
./todo add Write the Zig project page
./todo done 2
./todo remove 1
./todo list

You’ll see:

added task 1: Buy milk
added task 2: Call grandma
added task 3: Write the Zig project page
done: Call grandma
removed: Buy milk
1. [x] Call grandma
2. [ ] Write the Zig project page

And when something’s wrong, it says so in plain words instead of crashing:

$ ./todo done 5
there's no task with that number (you have 2)
$ ./todo remove two
'two' isn't a task number
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

What you’ll practise:

Make a folder with one source file, todo.zig:

Terminal window
mkdir todo
cd todo

Before 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:

  1. parseCommand: turn the command-line arguments into a Command value.
  2. load: read the file into a list of tasks.
  3. run: carry out the command on the list.
  4. 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.

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 plants
  • fromLine returns ?Task: a task, or null when the line isn’t in our format. Returning null instead 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 that line starts with "[ ] " and gives you the rest, or null if it doesn’t. if (...) |text| unwraps it.
  • The task’s text is 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.
  • writeLine takes any *std.Io.Writer. Here it’s stdout; in Step 5 it’ll be the file. if (task.done) "x" else " " is an if expression that picks which string to print.

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"
list
done 2
error.BadNumber
error.MissingText
error.UnknownCommand
error.MissingCommand

What’s happening:

  • ParseError lists every way parsing can fail, with names that say what the user did wrong. OutOfMemory is there because std.mem.join allocates. 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’t switch on strings, so a chain of ifs is the normal way to match command names.
  • For add, the task text is every remaining argument joined with spaces: todo add Buy milk arrives as "Buy" and "milk", and std.mem.join makes "Buy milk". People don’t have to put quotes around their tasks.
  • parseNumber rejects 0. Task numbers start at 1 for people, and n - 1 for a 0 would 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 same switch the real program uses in Step 4.

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 switch covers all four commands. If you add a fifth to Command later and forget it here, the program won’t compile (more on that in “Common mistakes”).
  • done and remove check the number first and return error.NoSuchTask if it’s too big. That error isn’t in any set we wrote: run returns !bool, so Zig infers its error set from what the body can return (NoSuchTask plus 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.
  • orderedRemove removes an item and moves the rest up, so the list keeps its order. (swapRemove is 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 without try: the first branch gets the value, the else gets the error.

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 tasks
the file:
[x] Buy milk
[ ] Call grandma
loaded 2 tasks, first: Buy milk
  • load treats error.FileNotFound as an empty list. The very first time you run todo 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 readFileAlloc into the arena. Each task’s text is 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 by fromLine.
  • save uses createFile, which replaces the old file, a buffered writer, and the all-important flush before the file closes (Zig File I/O explains why).

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:

Terminal window
zig build-exe todo.zig
./todo list
./todo add Buy milk
./todo add Call grandma
./todo list
cat todo.txt

You’ll see:

nothing to do!
added task 1: Buy milk
added 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:

  • usage is a multiline string literal: each line starts with \\. It’s printed whenever the command line doesn’t make sense, and main returns 2, the usual exit code for “used wrong”.
  • The catch |err| after parseCommand has a switch with one prong per error in ParseError, and the compiler checks that none is missing. MissingCommand prints nothing extra, since the usage text says it all.
  • error.BadNumber uses args[2] and error.UnknownCommand uses args[1]. That’s safe because those errors only happen when those arguments exist.
  • run’s errors get the same treatment, with else => return err for anything unexpected (like a failed write to stdout).
  • save only runs when run returned true, so todo list never rewrites the file.

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.

  • undo <n> to mark a task as not done again. It’s one more union field and one more switch prong, and the compiler will remind you where.
  • clear removes every finished task. Walk the list backwards with orderedRemove, or build a new list of the tasks you keep.
  • Safer saving. If the computer crashes halfway through save, todo.txt could be left half-written. std.Io.Dir.cwd().createFileAtomic(io, path, .{ .replace = true }) writes to a temporary file and replace(io) swaps it in only when it’s complete.
  • Keep the file in your home folder, so todo works from any directory. Read HOME (or USERPROFILE on Windows) with Zig Environment Variables and build the path.
  • Save as JSON instead of the [x] format, with std.json from Zig JSON. Then you can add fields like a due date without inventing a new format.
  • Test parseCommand and run. They don’t touch files, so they’re easy to cover with test blocks and std.Io.Writer.fixed. See Zig Testing.
  • Split a CLI into parse → load → run → save. Keep parse and run free of files so you can run them with made-up input.
  • A tagged union like Command holds one of several commands, each with its own data. A switch on it must handle every field, so adding a command shows you everything to update.
  • A written-out error set (ParseError) lets main switch on errors and give a clear message for each. Inferred sets (!bool) are fine for internal functions.
  • error.FileNotFound on 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: 0 for success, 1 for a failure, 2 for 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

1. Why is Command a tagged union instead of a struct with a name string and optional fields?
2. What does load do the first time you run the program, when todo.txt doesn't exist?
3. You add clear, to Command but don't change run. What happens?
4. Why can the program allocate from init.arena without ever calling free?