32. Command-line arguments — Homework solutions

The .go solution files are in exercises/32/homework/solutions/. Run each one from go-work, with arguments after the file name.

Problem 1 — Repeat

Problem. A flag for the count, words for the text, and two checks with exit code 2.

How to think about it. Define the flag, then flag.Parse(), then check. The checks go before any work, as guards. Both are usage problems, the user ran the tool the wrong way, so both exit with 2. The words are in flag.Args(), and strings.Join turns them back into one line.

Worked solution.

func main() {
    n := flag.Int("n", 2, "how many times to print the line")
    flag.Parse()

    if flag.NArg() == 0 {
        fmt.Fprintln(os.Stderr, "usage: repeat [-n N] WORD...")
        os.Exit(2)
    }
    if *n < 1 {
        fmt.Fprintf(os.Stderr, "repeat: -n must be 1 or more, not %d\n", *n)
        os.Exit(2)
    }

    line := strings.Join(flag.Args(), " ")
    for range *n {
        fmt.Println(line)
    }
}

Some runs:

go run exercises/32/homework/solutions/01-repeat.go -n 3 hello world
hello world
hello world
hello world

go run exercises/32/homework/solutions/01-repeat.go hi
hi
hi

go run exercises/32/homework/solutions/01-repeat.go -n 0 hi
repeat: -n must be 1 or more, not 0
exit status 2

Common mistakes.

  • Using n instead of *n. n is a pointer, so for range n stops with cannot range over n (variable of type *int).
  • Reading os.Args[1:] for the words. That still holds -n and 3, so they get printed too. After flag.Parse(), use flag.Args().
  • Checking *n before flag.Parse(). It is still the default, 2, whatever the user typed.

Problem 2 — Sum

Problem. Convert each argument to a number and add them up, stopping at the first one that is not a number.

How to think about it. There are no flags, so plain os.Args[1:] is enough. The loop is a running total, as in Chapter 20, with an strconv.Atoi check inside it. A bad number is not a usage mistake but bad input, so it exits with 1. %q puts quotes around the argument, so that an empty one, or one with spaces, is still visible in the message.

Worked solution.

func main() {
    if len(os.Args) < 2 {
        fmt.Fprintln(os.Stderr, "usage: sum NUMBER...")
        os.Exit(2)
    }

    total := 0
    for _, arg := range os.Args[1:] {
        number, err := strconv.Atoi(arg)
        if err != nil {
            fmt.Fprintf(os.Stderr, "sum: %q is not a whole number\n", arg)
            os.Exit(1)
        }
        total += number
    }
    fmt.Println(total)
}

Some runs:

go run exercises/32/homework/solutions/02-sum.go 3 4 5
12

go run exercises/32/homework/solutions/02-sum.go 3 abc 5
sum: "abc" is not a whole number
exit status 1

Negative numbers work too: -4 10 prints 6. Because this program does not use the flag package, nothing tries to read -4 as a flag.

Common mistakes.

  • Starting at os.Args[0]. That is the program's own path, and it is never a number.
  • Printing the error with fmt.Println. It looks the same on screen, but it goes to standard output, mixed in with the results.

Problem 3 — An upper-case filter

Problem. Read standard input to the end, and print each line changed.

How to think about it. This is the scanner loop from Chapter 31, with os.Stdin in place of an opened file. There is nothing to open, so there is nothing to close. The -n flag only changes how each line is printed, so it is one if inside the loop.

Worked solution.

func main() {
    numbers := flag.Bool("n", false, "number the lines")
    flag.Parse()

    scanner := bufio.NewScanner(os.Stdin)
    number := 0
    for scanner.Scan() {
        number++
        line := strings.ToUpper(scanner.Text())
        if *numbers {
            fmt.Printf("%3d  %s\n", number, line)
        } else {
            fmt.Println(line)
        }
    }

    err := scanner.Err()
    if err != nil {
        fmt.Fprintln(os.Stderr, "upper:", err)
        os.Exit(1)
    }
}

Output:

Get-Content exercises/31/poem.txt | go run exercises/32/homework/solutions/03-upper.go -n
  1  THE KETTLE SINGS BEFORE THE SUN,
  2  THE CAT IS WAITING BY THE DOOR.
  3  A PROGRAM STARTS WHEN IT IS RUN,
  4  AND STOPS WHEN THERE IS NOTHING MORE.
  5
  6  SAVE YOUR WORK BEFORE YOU GO:
  7  A FILE REMEMBERS WHAT YOU KNOW.

Common mistakes.

  • Putting -n before the file name, as in go run -n exercises/32/homework/solutions/03-upper.go. Then it is a flag for go itself, not for your program. For go run, -n happens to mean "show what you would do, but run nothing", so you see a strange path and no poem. Flags for your program go after the file name.
  • Running it with no pipe and thinking it is stuck. It is waiting for the keyboard. Type some lines, then Ctrl + Z and Enter.

Challenge — A search tool

Problem. A real tool: one flag, a required word, optional files, standard input, and three exit codes.

How to think about it. Split it into small jobs, as in Chapter 05:

  1. Does one line match? That depends on -i, so it gets its own function, matches.
  2. Search one open file, print its matches, and say how many there were. Like count in the chapter, it takes an *os.File, so it works for files and standard input. A prefix parameter carries the file name, or nothing for standard input.
  3. Open, search and close one file by name: searchFile, the same shape as countFile.
  4. main checks the arguments, picks standard input or files, and works out the exit code from two facts: did anything fail, and did anything match.

The flag is a package-level variable here, so that matches can read it without passing it through every function.

Worked solution. The helpers:

var ignoreCase = flag.Bool("i", false, "ignore upper and lower case")

// matches reports whether line contains word.
func matches(line string, word string) bool {
    if *ignoreCase {
        return strings.Contains(strings.ToLower(line), strings.ToLower(word))
    }
    return strings.Contains(line, word)
}

// search prints the matching lines of f, each starting with prefix, and
// returns how many lines matched.
func search(f *os.File, word string, prefix string) (int, error) {
    found := 0
    number := 0
    scanner := bufio.NewScanner(f)
    for scanner.Scan() {
        number++
        line := scanner.Text()
        if matches(line, word) {
            fmt.Printf("%s%d: %s\n", prefix, number, line)
            found++
        }
    }
    return found, scanner.Err()
}

func searchFile(name string, word string) (int, error) {
    f, err := os.Open(name)
    if err != nil {
        return 0, err
    }
    defer f.Close()

    return search(f, word, name+":")
}

And main:

func main() {
    flag.Usage = usage
    flag.Parse()

    if flag.NArg() == 0 {
        usage()
        os.Exit(2)
    }
    word := flag.Arg(0)
    files := flag.Args()[1:]

    if len(files) == 0 {
        found, err := search(os.Stdin, word, "")
        if err != nil {
            fmt.Fprintln(os.Stderr, "search:", err)
            os.Exit(2)
        }
        if found == 0 {
            os.Exit(1)
        }
        return
    }

    total := 0
    failed := false
    for _, name := range files {
        found, err := searchFile(name, word)
        if err != nil {
            fmt.Fprintln(os.Stderr, "search:", err)
            failed = true
            continue
        }
        total += found
    }

    if failed {
        os.Exit(2)
    }
    if total == 0 {
        os.Exit(1)
    }
}

Built and run:

go build -o search.exe exercises/32/homework/solutions/04-search.go

.\search.exe -i SAVE exercises\31\poem.txt
exercises\31\poem.txt:6: Save your work before you go:

.\search.exe SAVE exercises\31\poem.txt
$LASTEXITCODE
1

.\search.exe is nothing.txt exercises\31\poem.txt
search: open nothing.txt: The system cannot find the file specified.
exercises\31\poem.txt:2: the cat is waiting by the door.
exercises\31\poem.txt:3: A program starts when it is run,
exercises\31\poem.txt:4: and stops when there is nothing more.

Get-Content exercises\31\poem.txt | .\search.exe run
3: A program starts when it is run,

The third run still searches the poem after the missing file, and its exit code is 2. The second prints nothing at all. A search with no match is not an error, so there is no message: the exit code alone says "nothing found", for a script to check.

Common mistakes.

  • Using flag.Args()[1:] before checking flag.NArg(). With no arguments, the slice is empty, and [1:] stops with panic: runtime error: slice bounds out of range [1:0].
  • Exiting at the first missing file. The other files are still worth searching. Note the failure, carry on, and decide the exit code at the end.
  • Lowering only the line for -i, and not the word. -i SAVE then never matches, because the lowered line contains save, not SAVE.

Done?

Your programs can now take orders from the command line and fit into pipes. They also have a lot of if err != nil in them. The next chapter looks at errors properly: how to add details to them, how to check what kind of error you have, and where to handle them.