CLI — Commands and Tests
What you will learn
By the end of this checkpoint, you will be able to:
- keep
mainseparate from testable command logic; - parse subcommands without global state;
- inject output streams and application services;
- map domain failures to useful command diagnostics;
- test the program without launching another process.
Keep main tiny
func main() {
if err := run(context.Background(), os.Args[1:], os.Stdout, os.Stderr); err != nil {
fmt.Fprintln(os.Stderr, "tasker:", err)
os.Exit(1)
}
}
For more precise exit codes, return an integer from a mainCode function and call os.Exit exactly once. Do not call it from code that owns deferred cleanup.
Build dependencies in run
func run(ctx context.Context, args []string, stdout, stderr io.Writer) error {
config, err := parseRootOptions(args)
if err != nil {
return err
}
store := task.NewFileStore(config.DataPath)
service, err := task.NewService(store, time.Now)
if err != nil {
return err
}
return execute(ctx, config.CommandArgs, stdout, stderr, service)
}
For tests, call execute with a fake service or call run with a temporary data path.
Parse subcommands explicitly
func execute(ctx context.Context, args []string, stdout, stderr io.Writer, service *task.Service) error {
if len(args) == 0 {
return errors.New("missing command; use tasker help")
}
switch args[0] {
case "add":
return runAdd(ctx, args[1:], stdout, stderr, service)
case "list":
return runList(ctx, args[1:], stdout, stderr, service)
case "complete":
return runComplete(ctx, args[1:], stdout, stderr, service)
case "remove":
return runRemove(ctx, args[1:], stdout, stderr, service)
case "help":
writeUsage(stdout)
return nil
default:
return fmt.Errorf("unknown command %q; use tasker help", args[0])
}
}
Each subcommand can own a flag.FlagSet with ContinueOnError and its output directed to stderr.
Parse IDs safely
func parseID(value string) (task.ID, error) {
parsed, err := strconv.Atoi(value)
if err != nil || parsed <= 0 {
return 0, fmt.Errorf("task ID must be a positive integer: %q", value)
}
return task.ID(parsed), nil
}
Validate argument count before indexing the slice.
Format output as a contract
func writeTasks(output io.Writer, tasks []task.Task) error {
writer := tabwriter.NewWriter(output, 0, 4, 2, ' ', 0)
defer writer.Flush()
if _, err := fmt.Fprintln(writer, "ID\tSTATUS\tTITLE"); err != nil {
return err
}
for _, item := range tasks {
status := "open"
if item.Completed {
status = "done"
}
if _, err := fmt.Fprintf(writer, "%d\t%s\t%s\n", item.ID, status, item.Title); err != nil {
return err
}
}
return nil
}
Output is part of a CLI contract. Human-readable tables can evolve, but scripts need a documented stable format such as optional JSON output.
Test without starting a process
func TestExecuteAdd(t *testing.T) {
store := &memoryStore{}
service, err := task.NewService(store, func() time.Time {
return time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC)
})
if err != nil {
t.Fatal(err)
}
var stdout bytes.Buffer
var stderr bytes.Buffer
err = execute(context.Background(), []string{"add", "Learn maps"}, &stdout, &stderr, service)
if err != nil {
t.Fatalf("execute() error = %v", err)
}
if len(store.tasks) != 1 || store.tasks[0].Title != "Learn maps" {
t.Fatalf("stored tasks = %#v", store.tasks)
}
}
Add integration tests with t.TempDir() for JSON persistence and corrupt-file handling.
Completion checklist
- Run formatting and tests in a real Go environment.
- Exercise every command manually when an environment is available.
- Confirm repeated completion succeeds.
- Confirm removal preserves other IDs.
- Confirm corrupt JSON is not overwritten.
- Confirm write failures are returned.
- Add help text and examples to the project README.
- Do not add concurrency: one CLI invocation doing local file work does not benefit yet.
Practice
Add tasker list --format=json without changing the service. Add tests proving the JSON schema and human table both remain correct.
type OutputFormat string
const (
FormatTable OutputFormat = "table"
FormatJSON OutputFormat = "json"
)
func writeTaskList(output io.Writer, tasks []task.Task, format OutputFormat) error {
switch format {
case FormatTable:
return writeTasks(output, tasks)
case FormatJSON:
encoder := json.NewEncoder(output)
encoder.SetIndent("", " ")
return encoder.Encode(tasks)
default:
return fmt.Errorf("unsupported output format %q", format)
}
}
Parse --format in the list subcommand and convert it to the defined type. Golden files can test a complex table, while decoding JSON into a typed value avoids brittle whitespace comparisons.
Summary
- Keep process exit in
mainand command behaviour in testable functions. - Pass arguments and output streams explicitly.
- Give each subcommand its own parser and validation.
- Treat output formats as user-facing contracts.
- Finish with domain, command, and real-file tests at their natural boundaries.
Ready to wrap up?
Mark this complete when you can explain the main idea and finish the practice task.