Capstone 2: the commands
The command layer is the code between the storage and main: one method per operation, a Store and an io.Writer, and no knowledge of flags or of the process. Everything the command command does is testable with a fake store and a buffer, and everything main does is parsing and exit codes.
The command layer
Add takes a title and a due date, asks the store for an id, validates through New, stores and returns the task. List prints through the writer and also returns the tasks, so a caller can use them without a second read. Toggle and Remove are the other two. Every storage error is wrapped with the operation name, which is what the user sees.
type Commands struct {
Store Store
Out io.Writer
}
// Add creates a task with the next id and stores it.
func (c *Commands) Add(title string, due time.Time) (Task, error) {
id, err := c.Store.NextID()
if err != nil {
return Task{}, Wrap("next id", err)
}
task, err := New(id, title, due)
if err != nil {
return Task{}, err
}
if err := c.Store.Put(task); err != nil {
return Task{}, Wrap("add", err)
}
return task, nil
}
// List prints every task and returns them.
func (c *Commands) List() ([]Task, error) {
tasks, err := c.Store.All()
if err != nil {
return nil, Wrap("list", err)
}
for _, task := range tasks {
fmt.Fprintln(c.Out, task)
}
fmt.Fprintf(c.Out, "%d task(s)\n", len(tasks))
return tasks, nil
}
// Toggle flips a task and stores it.
func (c *Commands) Toggle(id int) (Task, error) {
task, err := c.Store.Get(id)
if err != nil {
return Task{}, Wrap("toggle", err)
}
task.Toggle()
if err := c.Store.Put(task); err != nil {
return Task{}, Wrap("toggle", err)
}
return task, nil
}
// Remove deletes a task.
func (c *Commands) Remove(id int) error {
if err := c.Store.Delete(id); err != nil {
return Wrap("remove", err)
}
return nil
}
The layer prints in List because the table is part of the command's output and the method is the one place that formats it. A program with two commands that print differently would extract a formatter; this one has one list and one format.
The dispatch
main reads the first argument as a subcommand, builds the store from TASKS_FILE or the default tasks.json, and switches. Each subcommand has its own flag.NewFlagSet, so add -due is parsed by the add set and list -json by the list one; the flags of one never leak into the other.
package main
import (
"flag"
"fmt"
"os"
"time"
"example.com/tasks/tasks"
)
var version = "dev"
func main() {
if len(os.Args) < 2 {
usage()
os.Exit(2)
}
file := os.Getenv("TASKS_FILE")
if file == "" {
file = "tasks.json"
}
store := tasks.NewFileStore(file)
cmd := &tasks.Commands{Store: store, Out: os.Stdout}
var err error
switch os.Args[1] {
case "add":
fs := flag.NewFlagSet("add", flag.ExitOnError)
due := fs.String("due", "", "due date as 2006-01-02")
fs.Parse(os.Args[2:])
if fs.NArg() == 0 {
err = tasks.ErrEmptyTitle
break
}
var dueDate time.Time
if *due != "" {
dueDate, err = time.Parse("2006-01-02", *due)
if err != nil {
break
}
}
var task tasks.Task
task, err = cmd.Add(fs.Arg(0), dueDate)
if err == nil {
fmt.Println("added:", task.ID)
}
case "list":
fs := flag.NewFlagSet("list", flag.ExitOnError)
asJSON := fs.Bool("json", false, "print one JSON object per task")
fs.Parse(os.Args[2:])
if *asJSON {
_, err = cmd.ListJSON()
} else {
_, err = cmd.List()
}
case "done":
id, ok := parseID(os.Args[2:])
if !ok {
os.Exit(2)
}
var task tasks.Task
task, err = cmd.Toggle(id)
if err == nil {
fmt.Println(task)
}
case "remove":
id, ok := parseID(os.Args[2:])
if !ok {
os.Exit(2)
}
err = cmd.Remove(id)
case "version":
fmt.Println("tasks", version)
return
default:
usage()
os.Exit(2)
}
if err != nil {
fmt.Fprintln(os.Stderr, "tasks:", err)
os.Exit(tasks.ExitCode(err))
}
}
func parseID(args []string) (int, bool) {
if len(args) != 1 {
fmt.Fprintln(os.Stderr, "tasks: one id expected")
return 0, false
}
var id int
if _, err := fmt.Sscanf(args[0], "%d", &id); err != nil {
fmt.Fprintln(os.Stderr, "tasks: id must be a number")
return 0, false
}
return id, true
}
func usage() {
fmt.Fprintln(os.Stderr, "usage: tasks add|list|done|remove|version [flags]")
}
The flags come before the positional arguments, because the flag package stops at the first word that is not a flag: add -due 2026-11-20 "buy milk" works and add "buy milk" -due ... stores the date as part of the title. The command prints its usage to standard error and exits 2 for neither a subcommand nor an id, and lesson 124 maps the errors to the other statuses.
A real run
The sequence below uses a file in /tmp so the run is reproducible and does not touch the working directory. It adds two tasks, lists them, toggles the first and removes the second.
TASKS_FILE=/tmp/tasks-demo.json ./bin/tasks add -due 2026-11-20 "buy milk"
TASKS_FILE=/tmp/tasks-demo.json ./bin/tasks add "write lesson"
TASKS_FILE=/tmp/tasks-demo.json ./bin/tasks list
added: 1
added: 2
[ ] 1 buy milk (due 2026-11-20)
[ ] 2 write lesson
2 task(s)
TASKS_FILE=/tmp/tasks-demo.json ./bin/tasks done 1
TASKS_FILE=/tmp/tasks-demo.json ./bin/tasks remove 2
TASKS_FILE=/tmp/tasks-demo.json ./bin/tasks list
[x] 1 buy milk (due 2026-11-20)
[x] 1 buy milk (due 2026-11-20)
[ ] 2 write lesson
2 task(s)
[x] 1 buy milk (due 2026-11-20)
1 task(s)
Each command printed its own line and the final list has one task. The middle two lines are the done command printing the toggled task and the list after the remove; the output blocks follow the commands in order, which is why the same task appears twice.
Ids and flags
An id is parsed with fmt.Sscanf into an int and a word that is not a number stops the command with status 2 before the store is touched. The due date is parsed with the layout from lesson 86, so a typo is an error and not a zero date. Both checks live in main because both are about the words the user typed, not about the tasks.
A command that explains itself
The usage line names the five subcommands, and each command that takes an id prints why an id is missing. A command that prints nothing on a wrong input is the one users file bugs about. The rule for the layer is the same as for the HTTP handlers: the error is a value, the message is for the user, and the status is for the shell.
The next lesson takes the errors and the statuses apart.
Exercises
- Add a clear subcommand that deletes every task after a confirmation flag. Which layer does it belong to, and what does the fake store need?
- Move -due after the title and run the command. What is stored, and how does the usage line warn a user?
- Add an -all flag to list that includes done tasks only. Which flag set changes, and what does the command layer gain?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does the command layer depend on?
Answer
The Store interface and an io.Writer
A fake and a buffer test it.
-
Why does List return the tasks as well as print them?
Answer
A caller can use them without a second read
ListJSON uses the same read.
-
Why a flag set per subcommand?
Answer
Flags of one command do not leak into another
add -due belongs to add.
-
Where must a flag come on the command line?
Answer
Before the first positional argument
flag stops at the first non-flag word.
-
What does the command do with a non-numeric id?
Answer
Prints a message and exits 2 before the store
The parse is in main.
-
Which layout parses the due date?
Answer
2006-01-02
It is the date form of the reference layout.
-
What does Toggle print?
Answer
The toggled task
The command prints the result.
-
What wraps a storage error?
Answer
The operation name, with %w
The user sees toggle: task not found.
-
Why use TASKS_FILE in the run?
Answer
The run is reproducible and does not touch the working directory
The environment sets the path.
-
What is the next lesson about?
Answer
The errors and the exit codes
The statuses are mapped there.
The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev