docs

您正在閱讀 v0.1.2 的文件。Nabi 0.1.2 已停止支援。 最新版本:v0.1.3 →

本頁尚未翻譯,以下為英文原文。

#Command-line tool

本頁內容

mgrep, a small grep-like tool, parses its command-line arguments by hand into a struct and handles --help and bad arguments with throws.

#Code

Run without arguments, it tries a few built-in sample invocations in turn.

$ mgrep --help
usage: mgrep [-i] [-n] [-c] [-m NUM] PATTERN [FILE]...
  -i, --ignore-case   match case-insensitively
  -n, --line-number   prefix each line with its number
  -c, --count         print only the number of matching lines
  -m, --max NUM       stop after NUM matches
  -h, --help          show this help
$ mgrep -n are
1:Roses are red,
2:violets are blue.
4:and so are you.
$ mgrep -i -c NABI
1
$ mgrep -m 1 are
Roses are red,
$ mgrep -x are
mgrep: unknown option '-x'
(try --help)
$ mgrep --max
mgrep: option '--max' needs a value
(try --help)

#Walkthrough

  • env::args() is a List<str> with the program name at [0], so skip(1).to_list() keeps the rest (env::args).
  • The options live in an Options struct with field defaults. Fields that have a default can be left out, as in Options { pattern: "" } (Structs, enums and traits, 2.3.3 field defaults).
  • String literal patterns joined with |, as in match a { "-i" | "--ignore-case" => ... }, accept the short and long form at once. Assignment is a statement, not an expression, so those arm bodies are wrapped in a { ...; } block (Control flow).
  • Bad arguments are thrown as the ArgError enum. run declares throws (ArgError | IoError), and main uses one catch per type to choose the exit code (2 or 1) (Errors, 3.14.4 catch).
  • The number after -m is read with parse::<usize>(); on failure, catch _ { throw ...; } turns it into a friendlier error. opts.max is usize | none, so the comparison supplies a default with ?? usize::MAX.

#Running it

To search real files, build an executable and pass arguments.

bash
nabic build mgrep.nabi -o mgrep
./mgrep -n -i nabi notes.txt todo.txt
./mgrep --count error app.log

Found a mistake? Edit this page on GitHub. Last updated