viva_camctl/lib.rs
1//! `viva-camctl` — the GenICam diagnostic CLI, as a library.
2//!
3//! The command-line surface lives in a private `cli` module, driven by [`run`], so there
4//! is exactly one implementation of it. The `viva-camctl` binary calls [`run`],
5//! and so does the `viva-camctl` console script that `pip install viva-genicam`
6//! installs — the Python users we most often ask for a `viva-camctl report` are
7//! the ones least able to build it from source, and a second entry point would
8//! be a second thing to keep in step.
9
10mod cli;
11mod cmd_action;
12mod cmd_bench;
13mod cmd_chunks;
14mod cmd_config;
15mod cmd_events;
16mod cmd_execute;
17mod cmd_get;
18mod cmd_inspect;
19mod cmd_list;
20mod cmd_registers;
21mod cmd_report;
22mod cmd_set;
23mod cmd_set_ip;
24mod cmd_stream;
25mod cmd_usb;
26mod cmd_xml;
27mod common;
28#[cfg(test)]
29mod field_engineer;
30
31use std::ffi::OsString;
32
33use common::with_camera;
34
35use clap::Parser;
36
37/// Exit code for a command that ran but failed, matching `ExitCode::FAILURE`.
38const FAILURE: u8 = 1;
39
40/// Parse `args`, run the selected command to completion, and return the exit
41/// code the process should use.
42///
43/// `args` is a complete argv, program name included. Diagnostics go to stderr in
44/// `anyhow`'s `Debug` layout, so an error's source chain survives, without
45/// repeating a cause the error's own message already prints. The code is clap's own for a usage error
46/// or for `--help`, and 1 for a command that ran and failed.
47///
48/// A plain `u8` rather than [`ExitCode`](std::process::ExitCode) because
49/// `ExitCode` cannot be inspected, and the Python entry point has to hand the
50/// number back to the interpreter rather than exit the process itself.
51///
52/// Builds its own multi-thread tokio runtime rather than requiring one, so it
53/// works from a plain `fn main` and from a Python interpreter that has none.
54pub fn run<I, T>(args: I) -> u8
55where
56 I: IntoIterator<Item = T>,
57 T: Into<OsString> + Clone,
58{
59 let cli = match cli::Cli::try_parse_from(args) {
60 Ok(cli) => cli,
61 Err(err) => {
62 // Covers `--help` and `--version` too, which clap reports as errors
63 // carrying an exit code of 0.
64 let _ = err.print();
65 return u8::try_from(err.exit_code()).unwrap_or(FAILURE);
66 }
67 };
68
69 let runtime = match tokio::runtime::Builder::new_multi_thread()
70 .enable_all()
71 .build()
72 {
73 Ok(runtime) => runtime,
74 Err(err) => {
75 eprintln!("Error: could not start the async runtime: {err}");
76 return FAILURE;
77 }
78 };
79
80 match runtime.block_on(cli::dispatch(cli)) {
81 Ok(()) => 0,
82 Err(err) => {
83 eprintln!("Error: {}", common::error_report(&err));
84 FAILURE
85 }
86 }
87}