Capstone A: the command line

The report of the capstone is a program that reads a log. A program a person runs needs a front end: a command that says what to do, a message when the command is wrong, and a status that a script can read. This lesson puts the report behind two subcommands and records what every call returns.

A command line

The program takes its first argument as the name of a subcommand and its second as a file, and it writes its own small log when no file is named, so every run below is reproducible. The whole program is one listing:

var path = Path.Combine(Path.GetTempPath(), "aredel-cli.log"); File.WriteAllLines(path, new[] { "2024-03-10T09:30:00Z INFO request id=1 ms=12", "2024-03-10T09:30:01Z WARN request id=2 ms=240", "2024-03-10T09:30:02Z ERROR request id=3 ms=90", "2024-03-10T09:30:03Z INFO request id=4 ms=30", }); var command = args.Length > 0 ? args[0] : ""; var file = args.Length > 1 ? args[1] : path; Console.WriteLine($"command [{command}] file [{file}]"); if (command is "") { return Usage(); } if (!File.Exists(file)) { Console.Error.WriteLine($"no such file: {file}"); return 3; } switch (command) { case "report": Report(file); return 0; case "count": Console.WriteLine($"{File.ReadLines(file).Count()} lines"); return 0; default: Console.Error.WriteLine($"unknown command: {command}"); return Usage(); } static void Report(string file) { var groups = File.ReadLines(file) .Select(line => line.Split(' ', StringSplitOptions.RemoveEmptyEntries)) .Where(parts => parts.Length >= 2) .GroupBy(parts => parts[1]) .OrderBy(group => group.Key); foreach (var group in groups) { Console.WriteLine($"{group.Key,-6}{group.Count(),3}"); } } static int Usage() { Console.Error.WriteLine("usage: app report|count [file]"); return 2; }

The first line of the output echoes the two values, which is what a command-line tool does while it is being built: it says what it understood before it acts on it. dotnet run has options of its own, so its own arguments and the arguments of the program are separated by --:

dotnet run
echo "status: $?"

command [] file [/tmp/aredel-cli.log]
usage: app report|count [file]
status: 2

Nothing follows the command, so the program prints the usage message on standard error and returns 2. The status: line is the shell command echo "status: $?" and not something the program printed: the number is what the operating system received.

The switch

The dispatch is one switch statement over the command, and each arm returns its own status. Before the switch, one check asks whether the file exists, because every subcommand needs it:

dotnet run -- report
echo "status: $?"

command [report] file [/tmp/aredel-cli.log]
ERROR   1
INFO    2
WARN    1
status: 0

The table is the report of lesson 115 in a smaller shape: the level, padded to six characters, and the count, right-aligned in three. The status is zero, which is what a shell reads as success.

A command that is not in the switch and a file that is not there take two different paths, and the statuses differ so a script can tell them apart:

dotnet run -- bogus
echo "status: $?"

command [bogus] file [/tmp/aredel-cli.log]
unknown command: bogus
usage: app report|count [file]
status: 2

dotnet run -- count /nope.log
echo "status: $?"

command [count] file [/nope.log]
no such file: /nope.log
status: 3

The exit status

The program uses four statuses, and each one has one meaning:

StatusMeaning
0the command did its work
1a syntax error in an expression, which lesson 124 adds
2the command line itself is wrong: no command, or an unknown one
3the file is not there

A top-level program returns a status with return, and the compiler turns the whole file into an int entry point when any path returns a value. The other way is Environment.ExitCode = 2; followed by a plain exit, which lesson 062 measured; a return is clearer because the status stands where the path ends.

Messages about a failure go to Console.Error, so a pipeline that reads the normal output does not receive the usage text. Both streams were merged into one block above with 2>&1, which is why the usage line appears between the two lines of the program.

The next lesson turns the same report into JSON, and the one after that turns the parser into a table of tests with a status of its own.

Exercises

  1. Add a levels subcommand that prints one level per line, sorted.
  2. Return 4 for a file that exists but cannot be read, and catch the exception to do it.
  3. Accept the file as --file <path> instead of the second word, and print the usage when the option is repeated.
  4. Print the usage message on standard output when --help is the command and return zero, so app --help | less works.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does dotnet run -- report pass to the program?

    Answer

    The single argument report

    Everything after -- goes to the program, and the separator itself does not.

  2. Why does the usage message go to Console.Error?

    Answer

    So the normal output of a pipeline stays clean

    A failure message is not part of the report.

  3. What does this program print? Console.Error.WriteLine("bad"); return 2;

    Answer

    bad

    The line goes to standard error, and the return becomes status 2.

  4. Which status does the program return for an unknown command?

    Answer

    2

    The unknown command path returns the usage status, which the measured run shows.

  5. What does this program print? var words = new[] { "report", "log.txt" }; Console.WriteLine(words[1]);

    Answer

    log.txt

    Index one is the second element.

  6. What is the status of a program that ends without a return value?

    Answer

    0

    Zero is success, and a program that runs to its end has succeeded.

  7. What does this program print? switch ("count") { case "report": Console.WriteLine("r"); break; case "count": Console.WriteLine("c"); break; default: Console.WriteLine("d"); break; }

    Answer

    c

    The value matches the second case.

  8. Why check File.Exists before the switch?

    Answer

    Every subcommand reads the file, so the check belongs before the dispatch

    One check gives one status for a missing file instead of one per command.

  9. What does this program print? File.WriteAllText(Path.Combine(Path.GetTempPath(), "t.txt"), "a\nb\n"); Console.WriteLine(File.ReadLines(Path.Combine(Path.GetTempPath(), "t.txt")).Count());

    Answer

    2

    Two lines end with the file, so the count is two.

  10. Where does the number in the status line of the output come from?

    Answer

    The shell, from echo "status: $?", after the program exits

    The program never prints the word status; the command in the block does.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev