Part 7 mini-project: To-do Tool

Chapter 31 promised a to-do list tool that you run as .\todo.exe add "buy milk", with tests that check it works. This is it. It uses every chapter of Part 7: a file read line by line and written back (Chapter 31), subcommands and flags (Chapter 32), sentinel and wrapped errors (Chapter 33), tests with go test and t.TempDir (Chapter 34), and dates (Chapter 35).

What to build

A program todo with four subcommands:

Command What it does
add "TEXT" Adds a task at the end of the list.
list Shows the tasks that are not done yet. list -all shows every task.
done N Marks task N as done.
remove N Takes task N out of the list. The tasks after it move up by one number.

The rules:

  • Tasks are numbered from 1, in the order they were added.
  • Spaces around a task's text are trimmed. A task with no text is an error, and so is a text with a tab or a line break in it.
  • Each task remembers the day it was added, and list shows how long ago that was: today, yesterday, or 3 days ago.
  • The tasks are kept in todo.txt, in the folder the program runs from. The flag -file NAME picks another file. A missing file is an empty list, not an error.
  • Every problem prints one line on standard error, starting with todo:. A mistake in how the tool was run, such as an unknown command, ends with exit code 2, as in Chapter 32. Any other problem ends with exit code 1.

The finished tool, built and run in its folder on one day:

go build -o todo.exe

.\todo.exe add "buy milk"
Added task 1: buy milk

.\todo.exe add "call Arif"
Added task 2: call Arif

.\todo.exe add "water the plants"
Added task 3: water the plants

.\todo.exe done 1
Done: buy milk

.\todo.exe list
  2. [ ] call Arif (today)
  3. [ ] water the plants (today)

.\todo.exe list -all
  1. [x] buy milk (today)
  2. [ ] call Arif (today)
  3. [ ] water the plants (today)

.\todo.exe remove 1
Removed: buy milk

.\todo.exe list
  1. [ ] call Arif (today)
  2. [ ] water the plants (today)

Run list again tomorrow, and both tasks say (yesterday). When every task is done, or there are none, list prints Nothing to do.

And the mistakes:

.\todo.exe done 7
todo: task 7: no such task

$LASTEXITCODE
1

.\todo.exe done 1
Done: call Arif

.\todo.exe done 1
todo: task 1 is already done

.\todo.exe done two
todo: "two" is not a task number

.\todo.exe add buy bread
todo: add needs the task text in quotes, as in: todo add "buy milk"

.\todo.exe fly
todo: unknown command "fly" (try add, list, done or remove)

$LASTEXITCODE
2

done 7 is a problem with the tasks, so it ends with 1. fly is a mistake in how the tool was run, so it ends with 2.

add buy bread without quotes reaches the program as two arguments, buy and bread, as Chapter 32 showed. The tool refuses it rather than guess.

With no command at all, it prints its help, and then the problem:

.\todo.exe
Usage: todo [-file NAME] COMMAND

Commands:
  add "TEXT"     add a task
  list [-all]    show the tasks not done yet (-all: every task)
  done N         mark task N as done
  remove N       remove task N

Flags:
  -file string
        the file that holds the tasks (default "todo.txt")
todo: no command given

The -file flag comes before the command, because flag.Parse stops at the first argument that is not a flag:

.\todo.exe -file work.txt add "send the report"
Added task 1: send the report

The file

todo.txt is a plain text file with one task per line. A line has three parts, separated by tabs: the state (todo or done), the day the task was added, and the text. After the session above, it holds two lines like these, with today's date:

done    2025-08-17  call Arif
todo    2025-08-17  water the plants

A tab cannot appear in a task's text, which is why add refuses one: it would break the line into too many parts. Open the file in VS Code and you can read and even edit it. If you break a line, the tool says where:

todo: todo.txt line 2: the state "maybe" is not todo or done

File layout

The project is a module with one package of your own, as in Part 6. Both versions are under projects/06-todo-cli/:

starter/
    go.mod
    main.go
    tasks/
        tasks.go
        tasks_test.go
finished/
    go.mod
    main.go
    tasks/
        tasks.go
        tasks_test.go

To work on the starter, go into its folder. go run . runs the tool, and go test ./... runs the tests of every package in the module:

cd projects/06-todo-cli/starter
go run . list
go test ./...

To run the finished version, and build it into a .exe:

cd projects/06-todo-cli/finished
go test ./...
go build -o todo.exe
.\todo.exe list

With no file name, go build builds the package in the current folder. todo.exe and todo.txt appear next to main.go. Delete todo.txt to start with an empty list.

To go back up to go-work afterwards:

cd ../../..

The finished tests pass:

?       todoapp [no test files]
ok      todoapp/tasks   0.012s

The first line says that package main has no tests, which is fine: the rules live in tasks. The time on the second line will be different for you.

The starter runs as it is. go run . list prints Nothing to do., and go run . add "buy milk" stops with todo: TODO: Add is not written yet. main.go is finished, and the TODOs are all in tasks/tasks.go. So is the test file: in the starter, most of its tests fail, and each failure points at a function that is not written yet. Your job is to make go test ./... say ok.

What to build it from

main.go knows about the command line: arguments, flags, and printing. The package tasks knows about the list and the file, and nothing about the command line. That split is what makes the list testable: a test calls Add and Done directly, with no arguments to parse and nothing printed.

main itself only calls run and reports its error, so there is one place where the program prints a problem and exits, as Chapter 33 suggests. A usage mistake is a usageError, a small error type as in Chapter 33, and errors.As finds it to choose exit code 2:

type usageError struct {
    problem string
}

func (e usageError) Error() string {
    return e.problem
}

func main() {
    err := run()
    if err == nil {
        return
    }

    fmt.Fprintln(os.Stderr, "todo:", err)
    var wrongUsage usageError
    if errors.As(err, &wrongUsage) {
        os.Exit(2)
    }
    os.Exit(1)
}

run parses the flags, loads the list, and picks the subcommand, as in Chapter 32:

func run() error {
    file := flag.String("file", "todo.txt", "the file that holds the tasks")
    flag.Usage = func() {
        fmt.Fprintln(os.Stderr, usage)
        flag.PrintDefaults()
    }
    flag.Parse()

    args := flag.Args()
    if len(args) == 0 {
        flag.Usage()
        return usageError{"no command given"}
    }
    command := args[0]
    rest := args[1:]

    list, err := tasks.Load(*file)
    if err != nil {
        return err
    }

    switch command {
    case "add":
        return add(list, *file, rest)
    case "list":
        return show(list, rest)
    case "done":
        return done(list, *file, rest)
    case "remove":
        return remove(list, *file, rest)
    default:
        return usageError{fmt.Sprintf("unknown command %q (try add, list, done or remove)", command)}
    }
}

Each command function checks its arguments, changes the list, saves it, and prints one line. add passes time.Now() to list.Add, and show passes it to tasks.Age. The package never asks for the time itself, so a test can hand it any day it likes.

The package tasks has, already written in the starter:

  • Task, with the fields Text, Done and Created.
  • List, with one unexported field, tasks, a slice of Task.
  • ErrEmptyText and ErrNoTask, two sentinel errors.
  • (l *List) Tasks(), which returns a copy of the tasks.
  • calendarDay(t), from Chapter 35, which keeps only the date of t.
  • (l *List) Save(filename) and formatLine(task), which write the file.

The TODOs:

  • (l *List) Add(text, now) returns the new task's number and an error.
  • (l *List) Done(n) and (l *List) Remove(n) return the task and an error.
  • (l *List) check(n) returns an error that wraps ErrNoTask when n is not a task number.
  • Age(created, now) returns "today", "yesterday" or "3 days ago".
  • Load(filename) reads a file into a *List.
  • parseLine(line) is the opposite of formatLine.

tasks_test.go is the same in both versions. It checks, among other things, that Add trims the text and numbers from 1, that a bad number gives an error that errors.Is matches with ErrNoTask, that Age counts calendar days and not 24-hour periods, that each bad line is refused by parseLine, and that a list saved in t.TempDir() loads back the same. Read it before you start: it is the most exact description of what each function must do.

Hints

  • Start with check, because Done and Remove use it. Wrap the sentinel with %w, as in Chapter 33: fmt.Errorf("task %d: %w", n, ErrNoTask). The message then reads task 7: no such task, and errors.Is(err, ErrNoTask) is still true.
  • Task numbers start at 1, and slice indexes at 0. Task n is l.tasks[n-1].
  • Done changes the task in the slice, so write l.tasks[n-1].Done = true. A copy from range would be changed instead, and the list would stay as it was.
  • Remove keeps the task before it deletes it, with slices.Delete from Chapter 24. Assign the result back to l.tasks.
  • strings.ContainsAny(text, "\t\n\r") is true if text holds any one of those characters. Check it after strings.TrimSpace, which removes them from the ends.
  • Age is the due-date label from the Chapter 35 challenge, turned around: count the days from calendarDay(created) to calendarDay(now). A task added at 23:00 is yesterday at 01:00 the next morning, though only two hours have passed.
  • Load is printNumbered from Chapter 31 with a list in place of the printing. Count every line, empty ones too, so that the number in an error matches the line the user sees in VS Code. Check for os.ErrNotExist as loadName in Chapter 31 did.
  • In parseLine, strings.Split(line, "\t") gives the parts, and time.Parse with dateLayout reads the date, as in Chapter 35. Give each problem its own message. The user sees it after the file name and line number.
  • Run one test at a time while you work, with go test -run TestAdd ./..., and add -v to see each test's name.

A bigger challenge (optional)

  • Undo. Add undone N, which sets a done task back to not done.
  • Clear. Add clear, which removes every done task at once, and prints how many.
  • Edit. Add edit N "TEXT", which changes a task's text with the same checks as Add.
  • Due dates. Add a flag -due 2025-08-20 to add, store the date as a fourth part on the line, and show the label from the Chapter 35 challenge in list. Old files with three parts should still load. Write the tests first.
  • A safer save. Save replaces the whole file. If the computer stops halfway, the list is lost. Write to todo.txt.tmp first, and rename it over todo.txt with os.Rename only once the write has worked.

None of these are required to finish the project.

Done?

When go test ./... says ok, and your todo.exe keeps your tasks from one run to the next, Part 7 is complete. You can copy todo.exe anywhere and use it for real. Move on to Chapter 36 — Goroutines, the start of Part 8.