nitr-cli 0.0.0-beta.7

The Nitr command-line server binary.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
// SPDX-License-Identifier: MIT OR Apache-2.0
// This file is part of Nitr.
// See https://nitrweb.com/ for more information
// Copyright (C) 2024-present Jose Quintana <joseluisq.net>

//! The `nitr` binary: serve, develop, check, test, migrate, build, and
//! scaffold Nitr applications.

#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used))]

use std::path::{Path, PathBuf};

use anyhow::{Context as _, bail};
use clap::{Parser, Subcommand};

use nitr::{Config, Server};
use nitr_cli::apidef;
mod bundle;
mod cmd;
mod diag;
mod scaffold;

const DEFAULT_CONFIG_FILE: &str = "nitr.toml";

/// The Nitr server: drop a binary and a few Lua files onto a machine and
/// you have a complete small HTTP application.
#[derive(Parser)]
#[command(
    name = "nitr",
    disable_version_flag = true,
    after_help = "Signals:\n  SIGHUP           Zero-downtime reload: rebuilds the Lua runtime pool and re-reads TLS certificates"
)]
struct Cli {
    /// Print the version and exit.
    #[arg(short = 'v', long = "version", global = true)]
    version: bool,
    /// Path to the TOML config file (default: ./nitr.toml).
    #[arg(short = 'c', long = "config", global = true, value_name = "PATH")]
    config: Option<PathBuf>,
    /// Enable development mode (hot reload).
    #[arg(long, global = true)]
    dev: bool,
    #[command(subcommand)]
    command: Option<Command>,
}

#[derive(Subcommand)]
enum Command {
    /// Start the server (the default when no command is given).
    Run {
        /// Apply pending migrations first, then serve: one command for a
        /// container's entrypoint.
        #[arg(long)]
        migrate: bool,
    },
    /// Start the server in development mode (hot reload).
    Dev {
        /// Apply pending migrations first, then serve.
        #[arg(long)]
        migrate: bool,
    },
    /// Load the configuration and scripts, then exit.
    Check {
        /// Print the effective configuration after file, environment, and
        /// flag layering — the answer to "which value actually won?".
        #[arg(long)]
        print_config: bool,
    },
    /// Run the Lua tests against an in-process server.
    Test {
        /// Run only tests whose name (or file name) contains this string.
        #[arg(long, value_name = "SUBSTRING")]
        filter: Option<String>,
        /// Stop at the first failing test (the verdict still prints).
        #[arg(long)]
        bail: bool,
        /// Print every test with its file:line and skip/todo markers,
        /// without running any.
        #[arg(long)]
        list: bool,
        /// Run again whenever a Lua source, a template, or a test file
        /// changes, until Ctrl-C.
        #[arg(long)]
        watch: bool,
        /// Report format: pretty lines, one JSON document, or JUnit XML.
        #[arg(long, value_enum, default_value = "pretty")]
        reporter: cmd::test::Reporter,
        /// Write the JSON/JUnit report to this file (the pretty lines still
        /// go to standard output).
        #[arg(short, long, value_name = "FILE")]
        output: Option<PathBuf>,
        /// Stream log lines as they happen instead of capturing them per
        /// test and printing them under a failure.
        #[arg(long)]
        nocapture: bool,
    },
    /// Generate the OpenAPI document from the application's routes.
    Openapi {
        /// Write the document to this file instead of standard output.
        #[arg(short, long, value_name = "PATH")]
        output: Option<PathBuf>,
        /// Compare the generated document with the file at --output (or
        /// `[openapi] output`, or openapi.json) and exit 1 when it differs.
        #[arg(long)]
        check: bool,
        /// Write a self-contained Swagger UI site into this directory.
        #[arg(long, value_name = "DIR")]
        ui: Option<PathBuf>,
    },
    /// Apply pending SQL migrations from migrations/.
    Migrate {
        /// Report what has run and what is pending, applying nothing.
        #[arg(long)]
        status: bool,
    },
    /// Scaffold a new Nitr application.
    Init {
        /// Directory to scaffold into (default: the current directory).
        dir: Option<PathBuf>,
        /// Only the bare minimum: nitr.toml, app.lua, a static page, one
        /// test — instead of the full documented layout.
        #[arg(long)]
        minimal: bool,
    },
    /// Package the application and this binary into one runnable file.
    Build {
        /// Path of the artifact to write.
        #[arg(short, long, value_name = "PATH")]
        output: PathBuf,
    },
    /// Ask a running server (found via its `pidfile`) to reload.
    Reload,
    /// Print an argon2id hash for a password, read from a prompt or stdin.
    HashPassword,
}

/// The configuration, plus the warnings met while loading it: the
/// subscriber does not exist yet (its format comes from this very
/// configuration), so they are logged once it does.
fn load_config(cli: &Cli) -> anyhow::Result<(Config, Vec<String>)> {
    // A bundled executable carries its own application; the config file
    // and every path in it come from the extracted archive.
    // Where a relative `env_file` (and the implicit `.env`) resolves: next
    // to the config file. A bundle's config lives in a temp extraction
    // dir, but its env file is external state like the database, so it
    // resolves against the working directory instead.
    let mut env_base = PathBuf::from(".");
    let bundled = bundle::load()?;
    let is_bundle = bundled.is_some();
    if is_bundle && cli.config.is_some() {
        anyhow::bail!(
            "this executable carries a bundle with its own configuration; --config is not \
             accepted (values that must differ per deployment come from the environment)"
        );
    }
    let mut warnings = Vec::new();
    let mut cfg = match bundled {
        Some((cfg, bundle_warnings)) => {
            warnings = bundle_warnings;
            cfg
        }
        None => match &cli.config {
            Some(path) => {
                if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
                    env_base = parent.to_path_buf();
                }
                Config::from_file(path)?
            }
            None => {
                let default = Path::new(DEFAULT_CONFIG_FILE);
                if default.is_file() {
                    Config::from_file(default)?
                } else {
                    Config::default()
                }
            }
        },
    };
    // The env file loads first so `apply_env` sees its values — while the
    // real process environment still wins (the file never overwrites it).
    cfg.load_env_file(&env_base)?;
    cfg.apply_env()?;
    if cli.dev || matches!(cli.command, Some(Command::Dev { .. })) {
        cfg.dev_mode = true;
    }
    if is_bundle {
        warnings.extend(bundle::seal(&mut cfg));
    }
    Ok((cfg, warnings))
}

/// Installs the tracing subscriber per the `[log]` configuration.
/// `RUST_LOG` wins over the configured level; without either the default
/// is `info` (`debug` in dev mode).
/// Whether a command's standard output is a document rather than a log:
/// `nitr openapi` prints the JSON there, and so does `nitr test` with a
/// JSON or JUnit reporter and no `--output`, so their log lines go to
/// stderr.
fn logs_to_stderr(command: &Option<Command>) -> bool {
    match command {
        Some(Command::Openapi { .. }) => true,
        Some(Command::Test {
            reporter, output, ..
        }) => *reporter != cmd::test::Reporter::Pretty && output.is_none(),
        _ => false,
    }
}

/// How `nitr test` wants its logs: captured per test (the default,
/// `[testing] capture`), and streamed to the console only with
/// `--nocapture`.
#[derive(Clone, Copy)]
struct TestLogs {
    capture: bool,
    console: bool,
}

/// The `nitr test` log setup for a command, when it is one.
fn test_logs(command: &Option<Command>, cfg: &Config) -> Option<TestLogs> {
    match command {
        Some(Command::Test { nocapture, .. }) if cfg.testing.capture => Some(TestLogs {
            capture: true,
            console: *nocapture,
        }),
        _ => None,
    }
}

fn init_logging(
    cfg: Option<&Config>,
    dev: bool,
    to_stderr: bool,
    test: Option<TestLogs>,
) -> anyhow::Result<()> {
    let fallback = || -> anyhow::Result<tracing_subscriber::EnvFilter> {
        let configured = cfg.and_then(|c| c.log.level.clone());
        let level = configured.unwrap_or_else(|| {
            if dev || cfg.is_some_and(|c| c.dev_mode) {
                "debug".into()
            } else {
                "info".into()
            }
        });
        // `EnvFilter` reads a bare word it does not know as a target name
        // at TRACE, so a misspelt level would silently log almost nothing.
        let is_level =
            |word: &str| word.eq_ignore_ascii_case("off") || word.parse::<tracing::Level>().is_ok();
        let directive_ok = |directive: &str| directive.contains('=') || is_level(directive.trim());
        if !level.split(',').all(directive_ok) {
            anyhow::bail!(
                "[log] level = {level:?} is not a level (error, warn, info, debug, trace, \
                 off) or a `target=level` list"
            );
        }
        tracing_subscriber::EnvFilter::try_new(&level)
            .map_err(|err| anyhow::anyhow!("[log] level = {level:?} is not a valid filter: {err}"))
    };
    let filter = match tracing_subscriber::EnvFilter::try_from_default_env() {
        Ok(filter) => filter,
        Err(_) => fallback()?,
    };
    let json = matches!(cfg.map(|c| c.log.format), Some(nitr::LogFormat::Json));
    // One color decision drives everything: the log format (JSON must
    // never carry ANSI), the stream the subscriber writes to (stdout),
    // and the user's `NO_COLOR` preference. The same bool goes to
    // tracing's own ANSI support (level and field coloring), to the
    // diagnostic-painting event formatter (source snippets, tracebacks
    // — see `diag::PaintedFormat` for why painting must happen at the
    // formatter layer), and to the test runner's markers, so they can
    // never disagree — a terminal gets all of it, a pipe or shipper
    // gets byte-clean plain text.
    use std::io::IsTerminal as _;
    let stream_is_terminal = if to_stderr {
        std::io::stderr().is_terminal()
    } else {
        std::io::stdout().is_terminal()
    };
    let colors =
        !json && stream_is_terminal && std::env::var_os("NO_COLOR").is_none_or(|v| v.is_empty());
    nitr::diag::set_console_colors(colors);
    if let Some(test) = test {
        init_test_logging(filter, test, json, colors, to_stderr);
        return Ok(());
    }
    // Span close events are what make the span timings visible: the
    // `request` span's close line is an access-log entry (id, method,
    // path, status), and at debug level the inner spans (`pool_checkout`,
    // `lua_handler`, `db_query`, `fetch`) decompose where the time went.
    let builder = tracing_subscriber::fmt()
        .with_env_filter(filter)
        .with_span_events(tracing_subscriber::fmt::format::FmtSpan::CLOSE);
    if to_stderr {
        finish_logging(builder.with_writer(std::io::stderr), json, colors);
    } else {
        finish_logging(builder, json, colors);
    }
    Ok(())
}

/// The last step of the subscriber setup, over whichever stream was
/// chosen.
fn finish_logging<W>(
    builder: tracing_subscriber::fmt::SubscriberBuilder<
        tracing_subscriber::fmt::format::DefaultFields,
        tracing_subscriber::fmt::format::Format,
        tracing_subscriber::EnvFilter,
        W,
    >,
    json: bool,
    colors: bool,
) where
    W: for<'w> tracing_subscriber::fmt::MakeWriter<'w> + Send + Sync + 'static,
{
    if json {
        builder.json().init();
    } else if colors {
        builder
            .event_format(diag::PaintedFormat(
                tracing_subscriber::fmt::format().with_ansi(true),
            ))
            .init();
    } else {
        builder.with_ansi(false).init();
    }
}

/// The `nitr test` subscriber: the console layer (the same formats as
/// every other command, filtered as configured, present only under
/// `--nocapture`) beside the capture layer that records each test's
/// entries.
///
/// The capture layer accepts the `lua` target at `debug` whatever the
/// console level: `nitr.log` gates on `tracing::enabled!`, so without
/// this a `log.debug` in a handler would be invisible to `t.logs()`
/// unless the console were at debug too.
fn init_test_logging(
    console_filter: tracing_subscriber::EnvFilter,
    test: TestLogs,
    json: bool,
    colors: bool,
    to_stderr: bool,
) {
    use tracing_subscriber::Layer as _;
    use tracing_subscriber::layer::SubscriberExt as _;
    use tracing_subscriber::util::SubscriberInitExt as _;

    let capture_filter = tracing_subscriber::EnvFilter::new(console_filter.to_string())
        .add_directive(
            "lua=debug"
                .parse()
                .unwrap_or_else(|_| tracing::Level::DEBUG.into()),
        );
    let console = test.console.then(|| {
        let base = tracing_subscriber::fmt::layer()
            .with_span_events(tracing_subscriber::fmt::format::FmtSpan::CLOSE);
        let layer: Box<dyn tracing_subscriber::Layer<tracing_subscriber::Registry> + Send + Sync> =
            match (json, colors, to_stderr) {
                (true, _, false) => base.json().boxed(),
                (true, _, true) => base.json().with_writer(std::io::stderr).boxed(),
                (false, true, false) => base
                    .event_format(diag::PaintedFormat(
                        tracing_subscriber::fmt::format().with_ansi(true),
                    ))
                    .boxed(),
                (false, true, true) => base
                    .event_format(diag::PaintedFormat(
                        tracing_subscriber::fmt::format().with_ansi(true),
                    ))
                    .with_writer(std::io::stderr)
                    .boxed(),
                (false, false, false) => base.with_ansi(false).boxed(),
                (false, false, true) => base.with_ansi(false).with_writer(std::io::stderr).boxed(),
            };
        layer.with_filter(console_filter)
    });
    let capture = test
        .capture
        .then(|| cmd::test::capture::CaptureLayer.with_filter(capture_filter));
    tracing_subscriber::registry()
        .with(console)
        .with(capture)
        .init();
}

/// Writes the pidfile on creation, removes it on drop — including the
/// error path, so a crashed server does not leave a stale pid behind for
/// `nitr reload` to signal.
struct Pidfile(PathBuf);

impl Pidfile {
    /// Claims the pidfile. Never written through an existing path: a
    /// plain `fs::write` followed a pre-planted symlink and silently
    /// replaced a live instance's file (whose `Drop` then deleted ours).
    /// An existing file is honored when its pid is alive and refused as
    /// a second instance; a stale one (a crash, an OOM kill) is replaced.
    fn write(path: &Path) -> anyhow::Result<Self> {
        use std::io::Write as _;
        let create = || {
            std::fs::OpenOptions::new()
                .write(true)
                .create_new(true)
                .open(path)
        };
        let mut file = match create() {
            Ok(file) => file,
            Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {
                if let Some(pid) = read_pid(path)
                    && pid != std::process::id()
                    && process_alive(pid)
                {
                    bail!(
                        "the pidfile {} names a running process ({pid}); is another \
                         instance already up? Stop it, or point `pidfile` elsewhere",
                        path.display()
                    );
                }
                std::fs::remove_file(path).with_context(|| {
                    format!("cannot replace the stale pidfile {}", path.display())
                })?;
                create().with_context(|| format!("cannot create the pidfile {}", path.display()))?
            }
            Err(err) => {
                return Err(err)
                    .with_context(|| format!("cannot create the pidfile {}", path.display()));
            }
        };
        writeln!(file, "{}", std::process::id())
            .with_context(|| format!("cannot write the pidfile {}", path.display()))?;
        Ok(Self(path.to_path_buf()))
    }
}

/// The pid a pidfile names, when it holds one.
fn read_pid(path: &Path) -> Option<u32> {
    std::fs::read_to_string(path).ok()?.trim().parse().ok()
}

/// Whether a process with this pid exists.
///
/// `/proc/<pid>` where there is a procfs (Linux: no external binary, and
/// another user's live process still counts as alive), else `kill -0`.
/// A `kill` that cannot be spawned reports "alive" — a false "dead" here
/// deletes a live instance's pidfile, which is the failure this check
/// exists to prevent, so the doubt goes the safe way.
#[cfg(unix)]
fn process_alive(pid: u32) -> bool {
    if Path::new("/proc/self").exists() {
        return Path::new(&format!("/proc/{pid}")).exists();
    }
    match std::process::Command::new("kill")
        .args(["-0", &pid.to_string()])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
    {
        Ok(status) => status.success(),
        Err(_) => true,
    }
}

/// Whether `pid` runs nitr, judged from procfs when there is one; without
/// procfs there is nothing to judge from and the answer is yes.
///
/// "Runs nitr" means: the same executable as this one, a `nitr build`
/// artifact (this executable with an archive appended, under whatever
/// name the operator chose — recognised by its trailer), or, when the
/// executable link cannot be read, a process named like ours.
#[cfg(unix)]
fn is_nitr_process(pid: u32) -> bool {
    if !Path::new("/proc/self").exists() {
        return true;
    }
    if let Ok(exe) = std::fs::read_link(format!("/proc/{pid}/exe")) {
        // The kernel appends " (deleted)" to a replaced binary; the path
        // before it is still what to compare.
        let exe = PathBuf::from(
            exe.to_string_lossy()
                .trim_end_matches(" (deleted)")
                .to_string(),
        );
        if std::env::current_exe().is_ok_and(|own| own == exe) {
            return true;
        }
        if let Ok(Some(_)) = bundle::read_appended(&exe) {
            return true;
        }
    }
    let own_comm = std::fs::read_to_string("/proc/self/comm")
        .map(|s| s.trim().to_string())
        .unwrap_or_default();
    match std::fs::read_to_string(format!("/proc/{pid}/comm")) {
        Ok(comm) => comm.trim().contains("nitr") || comm.trim() == own_comm,
        // No comm to read (another user's process): nothing says it is
        // not ours.
        Err(_) => true,
    }
}

#[cfg(not(unix))]
fn process_alive(_pid: u32) -> bool {
    false
}

impl Drop for Pidfile {
    fn drop(&mut self) {
        std::fs::remove_file(&self.0).ok();
    }
}

/// Sends SIGHUP to the process named by the configured `pidfile`.
fn reload(cfg: &Config) -> anyhow::Result<()> {
    let path = cfg.pidfile.as_ref().context(
        "no `pidfile` is configured: set `pidfile` in nitr.toml so `nitr reload` \
         can find the running server",
    )?;
    let raw = std::fs::read_to_string(path).with_context(|| {
        format!(
            "cannot read the pidfile {} (is the server running?)",
            path.display()
        )
    })?;
    let pid: u32 = raw
        .trim()
        .parse()
        .with_context(|| format!("the pidfile {} does not contain a pid", path.display()))?;
    // `kill -HUP 0` signals the caller's whole process group and pid 1 is
    // init: neither is ever a server this file could name.
    if pid < 2 || pid == std::process::id() {
        bail!(
            "the pidfile {} names pid {pid}, which cannot be a running server",
            path.display()
        );
    }

    #[cfg(unix)]
    {
        // The pid may have been reused since the file was written (a
        // crash leaves the file behind). Where the kernel says what runs
        // under it, insist that it is a nitr server before signalling.
        if !is_nitr_process(pid) {
            bail!(
                "pid {pid} from the pidfile {} does not look like a nitr server. If the \
                 server is a `nitr build` artifact, run `reload` from that artifact; if \
                 it is not running any more, remove the stale pidfile",
                path.display()
            );
        }
        let status = std::process::Command::new("kill")
            .args(["-HUP", &pid.to_string()])
            .status()
            .context("cannot run `kill`")?;
        if !status.success() {
            bail!("kill -HUP {pid} failed: is the server still running?");
        }
        println!("sent SIGHUP to pid {pid}: the server is rebuilding its runtime pool");
        Ok(())
    }
    #[cfg(not(unix))]
    {
        let _ = pid;
        bail!("`nitr reload` needs Unix signals, which this platform does not have");
    }
}

#[tokio::main]
async fn main() {
    if let Err(err) = run_main().await {
        // Print the report ourselves instead of returning the error:
        // diagnostics get color on a terminal (plain text otherwise, same
        // bytes anyhow would have printed).
        diag::report(&err);
        std::process::exit(1);
    }
}

async fn run_main() -> anyhow::Result<()> {
    let cli = Cli::parse();
    if cli.version {
        println!("nitr {}", env!("CARGO_PKG_VERSION"));
        return Ok(());
    }

    // `init` runs before any configuration exists; everything else loads
    // the configuration first so `[log]` can shape the subscriber.
    if let Some(Command::Init { dir, minimal }) = &cli.command {
        init_logging(None, cli.dev, logs_to_stderr(&cli.command), None)?;
        return scaffold::init(dir.as_deref().unwrap_or(Path::new(".")), *minimal);
    }
    // `hash-password` needs no application at all: it is the one command
    // an operator runs *before* there is a working nitr.toml, and a
    // broken one must not stand between them and a credential.
    if let Some(Command::HashPassword) = &cli.command {
        init_logging(None, cli.dev, logs_to_stderr(&cli.command), None)?;
        return cmd::hash_password::hash_password().await;
    }

    let cfg = match load_config(&cli) {
        Ok((cfg, warnings)) => {
            init_logging(
                Some(&cfg),
                cli.dev,
                logs_to_stderr(&cli.command),
                test_logs(&cli.command, &cfg),
            )?;
            for warning in warnings {
                tracing::warn!("{warning}");
            }
            cfg
        }
        Err(err) => {
            init_logging(None, cli.dev, logs_to_stderr(&cli.command), None)?;
            return Err(err);
        }
    };

    match cli.command.unwrap_or(Command::Run { migrate: false }) {
        // Invariant: both commands returned early above — `Init` before
        // the config load (it *creates* the config), `HashPassword` right
        // after it (it must work without one) — so neither can reach this
        // match. The arm exists only to keep the match exhaustive.
        #[allow(clippy::unreachable)]
        Command::Init { .. } | Command::HashPassword => unreachable!("handled above"),
        Command::Run { migrate } | Command::Dev { migrate } => {
            if migrate {
                cmd::migrate::migrate(&cfg, false)?;
            }
            let pidfile_path = cfg.pidfile.clone();
            let server = Server::builder().config(cfg).build().await?;
            // Written only once the build succeeded: a pid that never
            // served is not one `nitr reload` should be signalling.
            let pidfile = pidfile_path.as_deref().map(Pidfile::write).transpose()?;
            let result = server.serve().await;
            drop(pidfile);
            result?;
        }
        Command::Check { print_config } => {
            if print_config {
                print!("{}", cfg.effective_toml()?);
                return Ok(());
            }
            cmd::check::check(cfg).await?;
        }
        Command::Test {
            filter,
            bail,
            list,
            watch,
            reporter,
            output,
            nocapture,
        } => {
            let args = cmd::test::TestArgs {
                filter,
                bail,
                list,
                watch,
                reporter,
                output,
                nocapture,
            };
            if args.watch {
                cmd::test::watch(cfg, &args).await?;
                // Ctrl-C may land mid-run, and a run is Lua that can go
                // seconds without yielding: returning would drop the
                // runtime, which waits for that run to reach a yield.
                // The session is over, so the process ends here.
                std::process::exit(0);
            }
            // Exit 1 on any failure, or on a `t.only` left in place.
            if cmd::test::run(cfg, &args).await?.failed() {
                std::process::exit(1);
            }
        }
        Command::Migrate { status } => cmd::migrate::migrate(&cfg, status)?,
        Command::Openapi { output, check, ui } => {
            let args = cmd::openapi::OpenapiArgs { output, check, ui };
            if cmd::openapi::run(cfg, args).await? == cmd::openapi::Outcome::Drift {
                std::process::exit(1);
            }
        }
        Command::Build { output } => {
            let cfg_path = cli
                .config
                .as_deref()
                .unwrap_or(Path::new(DEFAULT_CONFIG_FILE));
            if !cfg_path.is_file() {
                bail!(
                    "`nitr build` needs a configuration file ({} not found): the \
                     bundle records it as the application manifest",
                    cfg_path.display()
                );
            }
            bundle::build(cfg_path, &cfg, &output)?;
        }
        Command::Reload => reload(&cfg)?,
    }
    Ok(())
}