Show only the most recent lines in logview
C++ · C++ · beginner · modification
Support engineers mostly care about the end of a log, so `logview` gets a `--last N` option. The selection is a small header-only function, `logview::last_lines` in `src/logview/tail.hpp`, that returns `std::string_view`s into the lines already read, oldest first. `src/logview/main.cpp` learns the new argument shape, parses N with `std::from_chars` (anything that is not a whole number from 1 to 100000 gets the usage line and exit status 2) and now prints through `last_lines` in both modes, passing the full line count when the option is absent. `tests/tail_test.cpp` adds unit tests for `last_lines` on a short sample log.
C++20, standard library only, built with CMake (unchanged: it builds `src/logview/*.cpp` into the `logview` binary and every `tests/*_test.cpp` together with `tests/check_main.cpp` into the test runner) by Apple clang 17 locally and GCC 13 in CI, with `-Wall -Wextra -Wconversion -Werror`. Single-threaded command-line tool used by the support team on log files from customer bundles (at most a few hundred MB; reading the whole file into memory is accepted). Existing and unchanged: `logview::read_lines(const char* path)` in `src/logview/io.hpp` returns `std::optional<std::vector<std::string>>`, one element per line without the trailing newline, or `std::nullopt` when the file cannot be opened. `tests/check.hpp` is the repo's tiny test helper: `TEST(name) { ... }` registers a test, `CHECK(expr)` and `CHECK_EQ(a, b)` record a failure with file and line, and the `main` in `tests/check_main.cpp` runs every registered test and exits non-zero if any check failed.
Requirements
- `logview FILE` (existing) prints every line of a log file to standard output, one per line, in file order. Add an option, `logview --last N FILE`, that prints only the last N lines of the file, still in file order (oldest of them first). When the file has N lines or fewer, every line is printed, the same output as without the option; an empty file prints nothing.
- N is a decimal integer from 1 to 100000 inclusive, digits only (no sign, no spaces, no trailing characters). Any other value, a missing value or any other argument shape prints the usage line to standard error and exits with status 2. A file that cannot be opened prints `logview: cannot read FILE` to standard error and exits with status 1, as today. Every successful run exits with status 0.
- The selection lives in a reusable function, `logview::last_lines(lines, n)`, which returns views of the selected lines (borrowed from `lines`, oldest first) and follows the same rule: the last `n` lines, or all of them when there are `n` or fewer. It also accepts `n` = 0 (no lines); `main` calls it without the option with `n` equal to the line count.
- Ship unit tests for `last_lines` using the repo's `tests/check.hpp` helper.
Files touched
- src/logview/main.cpp
- src/logview/tail.hpp
- tests/tail_test.cpp