Skip to content

Trace a Command Through the Files

The Course
•
18 min study

main.go connects the program to stdin and stdout. app.go scans lines, dispatches commands and writes reports. queue.go owns the map and its rules.

The Tasks method collects copies of records into a fresh slice. slices.SortFunc orders them with cmp.Compare, which puts the smaller ID first. Returning copies lets callers edit the report slice without editing the queue.

New syntax in this project

The project uses a few things that didn't need a lesson of their own. Read these before tracing.

  • switch verb in execute picks the command, as in the Day 5 command lesson. Only the first matching case runs, and default reports an unknown verb.
  • Named results. execute is declared as func execute(...) (commandErr, writeErr error). The two results have names, which documents which error is which: a rejected command, or a failure to write output. Every return in it still lists both values explicitly, for example return err, nil for a rejected command.
  • os.Stderr is standard error, the third standard stream from the beginner course. It is a writer like os.Stdout, but meant for problems, so a person can send the report to a file and still see errors on screen. main writes run's error there with fmt.Fprintln(os.Stderr, err).
  • os.Exit(1) ends the program immediately with exit status 1. By convention 0 means success and anything else means failure, which scripts and other tools can check. main uses it only after printing the error, because nothing after os.Exit runs, not even deferred code.
Trace a task Go
package main import ( "fmt" "os" ) func main() { if err := run(os.Stdin, os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } package main import ( "cmp" "errors" "fmt" "slices" "strings" ) type TaskID int32 type Task struct { ID TaskID Title string Done bool } type Queue struct { tasks map[TaskID]Task } var ( errID = errors.New("ID must be a positive 32-bit integer") errTitle = errors.New("title is required") errDuplicate = errors.New("ID already exists") errMissing = errors.New("task not found") errDone = errors.New("task is already done") ) func (q *Queue) Add(id TaskID, title string) error { if id <= 0 { return errID } title = strings.TrimSpace(title) if title == "" { return errTitle } if _, exists := q.tasks[id]; exists { return fmt.Errorf("task %d: %w", id, errDuplicate) } if q.tasks == nil { q.tasks = make(map[TaskID]Task) } q.tasks[id] = Task{ID: id, Title: title} return nil } func (q *Queue) Finish(id TaskID) error { task, exists := q.tasks[id] if !exists { return fmt.Errorf("task %d: %w", id, errMissing) } if task.Done { return fmt.Errorf("task %d: %w", id, errDone) } task.Done = true q.tasks[id] = task return nil } func (q *Queue) Tasks() []Task { tasks := make([]Task, 0, len(q.tasks)) for _, task := range q.tasks { tasks = append(tasks, task) } slices.SortFunc(tasks, func(a, b Task) int { return cmp.Compare(a.ID, b.ID) }) return tasks } package main import ( "bufio" "errors" "fmt" "io" "strconv" "strings" ) func parseID(text string) (TaskID, error) { n, err := strconv.ParseInt(text, 10, 32) if err != nil || n <= 0 { return 0, errID } return TaskID(n), nil } // execute distinguishes a command rejection from an output failure. func execute(q *Queue, w io.Writer, line string) (commandErr, writeErr error) { verb, rest, _ := strings.Cut(line, " ") rest = strings.TrimSpace(rest) switch verb { case "add": rawID, title, ok := strings.Cut(rest, " ") if !ok { return errors.New("use add ID title"), nil } id, err := parseID(rawID) if err != nil { return err, nil } if err := q.Add(id, title); err != nil { return err, nil } _, err = fmt.Fprintf(w, "Added %d\n", id) return nil, err case "done": id, err := parseID(rest) if err != nil { return err, nil } if err := q.Finish(id); err != nil { return err, nil } _, err = fmt.Fprintf(w, "Done %d\n", id) return nil, err case "list": if rest != "" { return errors.New("list takes no arguments"), nil } return nil, report(w, q.Tasks()) default: return fmt.Errorf("unknown command %q", verb), nil } } func report(w io.Writer, tasks []Task) error { if _, err := fmt.Fprintln(w, "Task queue"); err != nil { return err } for _, task := range tasks { status := "open" if task.Done { status = "done" } if _, err := fmt.Fprintf(w, "%d [%s] %s\n", task.ID, status, task.Title); err != nil { return err } } _, err := fmt.Fprintln(w, "Tasks:", len(tasks)) return err } func run(r io.Reader, w io.Writer) error { var queue Queue scanner := bufio.NewScanner(r) lineNumber := 0 for scanner.Scan() { lineNumber++ line := strings.TrimSpace(scanner.Text()) if line == "" { continue } commandErr, writeErr := execute(&queue, w, line) if writeErr != nil { return fmt.Errorf("write line %d: %w", lineNumber, writeErr) } if commandErr != nil { if _, err := fmt.Fprintf(w, "Line %d: %s\n", lineNumber, commandErr); err != nil { return fmt.Errorf("write line %d: %w", lineNumber, err) } } } if err := scanner.Err(); err != nil { return fmt.Errorf("read input: %w", err) } return nil } add 9 Draft notes add 2 Read chapter two add 2 Replacement done 2 done 7 list
Exercise

Trace a rejected transition

Follow done 7 from input to report. Where is the missing ID detected? Why does a command failure continue the loop, but a read or write failure ends the program?

Hint 1: the idea

Separate an invalid request from a failure of the input or output destination.

Hint 2: a first step

Find the lookup in Finish and follow the two error results returned by execute.

Worked solution

Finish finds no task for 7 and returns an error wrapping errMissing. execute returns that as a command error. run writes a line-numbered message and keeps scanning. A read or write failure means it cannot reliably continue reading commands or reporting their outcomes, so run returns the error. A successful state change may already have happened before writing its confirmation.

Was this article helpful?

Your response is saved on this device.