greggd 1.0.11

Lightweight Linux, macOS, and Windows metrics daemon that exposes a read-only JSON API for the gregg client.
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
//! CLI argument parsing and subcommand dispatch for `greggd`.
//!
//! Uses `clap` derive macros for structured argument parsing. Each
//! subcommand has a stable help message and returns a meaningful exit code.

use std::fmt;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, TcpStream};
use std::path::PathBuf;
use std::process::{Command as ProcessCommand, Stdio};
use std::time::Duration;

use clap::{Parser, Subcommand};

use crate::config::{Config, ConfigError};
#[cfg(target_os = "windows")]
use crate::service::ServiceError;

/// Lightweight metrics daemon for the gregg monitoring system.
#[derive(Parser)]
#[command(
    name = "greggd",
    version,
    about = "Lightweight Linux, macOS, and Windows metrics daemon",
    long_about = "greggd runs on designated systems and exposes a read-only JSON API \
                  for the gregg terminal client. It samples CPU, memory, swap, and \
                  load metrics on a configurable interval and serves cached immutable \
                  snapshots over HTTP/1."
)]
pub struct Cli {
    /// Path to the configuration file.
    #[arg(
        long,
        short = 'c',
        global = true,
        help = "Path to the TOML configuration file",
        value_name = "PATH"
    )]
    pub config: Option<PathBuf>,

    #[command(subcommand)]
    pub command: Command,
}

/// Available subcommands.
#[derive(Subcommand)]
pub enum Command {
    /// Run the daemon in the foreground.
    Run,
    /// Stop a running greggd instance via the local Unix control socket
    /// (Linux/macOS) or via the Windows Service Control Manager (Windows).
    Stop,
    /// Start the greggd Windows service.
    #[cfg(target_os = "windows")]
    Start,
    /// Restart the greggd Windows service.
    #[cfg(target_os = "windows")]
    Restart,
    /// Ensure greggd is running. Probes the configured local TCP port and,
    /// if nothing is listening, spawns `greggd run` as a detached child.
    /// Intended for cron, Task Scheduler, and other operator-managed
    /// supervisors that have no built-in readiness monitoring.
    Croncheck,
    /// Print the configured bind address without probing or mutating state.
    Configprint,
    /// Update the bind address (applies on the next daemon start).
    Host {
        /// The new IPv4 or IPv6 address to bind to.
        address: IpAddr,
    },
    /// Update the TCP port (applies on the next daemon start).
    Port {
        /// The new port number (1-65535).
        port: u16,
    },
    /// Print the binary version.
    Version,
    /// Internal: Windows SCM service entry point. Not for interactive use.
    #[cfg(target_os = "windows")]
    #[command(hide = true)]
    Service,
}

/// Exit codes returned by greggd commands.
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExitCode {
    Success = 0,
    /// Configuration error (invalid, missing, or unwritable).
    ConfigError = 1,
    /// Service management command failed.
    ServiceError = 2,
    /// The daemon could not start (port conflict, etc.).
    RuntimeError = 3,
    /// Permission denied for the requested operation.
    PermissionDenied = 4,
}

impl From<&ConfigError> for ExitCode {
    fn from(e: &ConfigError) -> Self {
        match e {
            ConfigError::Io { source, .. }
                if source.kind() == std::io::ErrorKind::PermissionDenied =>
            {
                Self::PermissionDenied
            }
            ConfigError::AtomicWrite { source, .. } => match source {
                crate::config::AtomicWriteError::Io(io)
                    if io.kind() == std::io::ErrorKind::PermissionDenied =>
                {
                    Self::PermissionDenied
                }
                _ => Self::ConfigError,
            },
            _ => Self::ConfigError,
        }
    }
}

#[cfg(target_os = "windows")]
impl From<&ServiceError> for ExitCode {
    fn from(e: &ServiceError) -> Self {
        match e {
            ServiceError::CommandFailed { .. }
            | ServiceError::ExecFailed { .. }
            | ServiceError::NotAvailable { .. }
            | ServiceError::StateQueryFailed { .. }
            | ServiceError::Timeout { .. } => Self::ServiceError,
            ServiceError::AccessDenied => Self::PermissionDenied,
        }
    }
}

/// Resolve the config path: explicit `--config` or platform default.
pub fn resolve_config_path(explicit: Option<&PathBuf>) -> PathBuf {
    explicit.cloned().unwrap_or_else(Config::default_path)
}

/// Load or create the configuration.
///
/// If the config file exists, load and validate it. If it does not exist
/// and no explicit path was given, use defaults. If an explicit path was
/// given but the file is missing, return an error.
pub fn load_config(path: &std::path::Path, explicit: bool) -> Result<Config, ConfigError> {
    if path.exists() {
        Config::load(path)
    } else if explicit {
        Err(ConfigError::Io {
            path: path.to_path_buf(),
            source: std::io::Error::new(
                std::io::ErrorKind::NotFound,
                format!("configuration file not found: {}", path.display()),
            ),
        })
    } else {
        // No explicit path and file doesn't exist — use defaults.
        Ok(Config::default())
    }
}

/// Error returned when config validation fails during mutation.
///
/// This is separate from `ConfigError` because it carries the violations
/// for structured reporting and requires a distinct exit code.
#[derive(Debug)]
pub struct ConfigValidationError(pub Vec<crate::config::ConfigViolation>);

impl fmt::Display for ConfigValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "configuration validation failed:")?;
        for v in &self.0 {
            write!(f, "\n  - {v}")?;
        }
        Ok(())
    }
}

impl std::error::Error for ConfigValidationError {}

/// Update a single field in the config and atomically persist it.
///
/// This is the shared logic for `host` and `port` subcommands.
pub fn mutate_config(
    path: &std::path::Path,
    explicit: bool,
    mutate: impl FnOnce(&mut Config),
) -> Result<(), Box<dyn std::error::Error>> {
    let mut config = load_config(path, explicit)?;
    mutate(&mut config);

    let violations = config.validate();
    if !violations.is_empty() {
        return Err(Box::new(ConfigValidationError(violations)));
    }

    config.write_atomic(path)?;

    Ok(())
}

/// Return the compile-time version rendered for the daemon binary.
#[must_use]
pub fn version_string() -> String {
    format!("greggd {}", env!("CARGO_PKG_VERSION"))
}

/// Map wildcard bind addresses to local loopback addresses for probing.
#[must_use]
pub fn probe_address(address: IpAddr) -> IpAddr {
    match address {
        IpAddr::V4(value) if value.is_unspecified() => IpAddr::V4(Ipv4Addr::LOCALHOST),
        IpAddr::V6(value) if value.is_unspecified() => IpAddr::V6(Ipv6Addr::LOCALHOST),
        value => value,
    }
}

/// Derive the local probe target from daemon configuration.
#[must_use]
pub fn croncheck_target(config: &Config) -> SocketAddr {
    SocketAddr::new(probe_address(config.host), config.port)
}

/// Return the configured bind address in canonical socket-address form.
#[must_use]
pub fn config_address(config: &Config) -> SocketAddr {
    SocketAddr::new(config.host, config.port)
}

/// Return the bind address for `configprint`, resolving wildcards to
/// the host's primary local IP so the output is a usable address a
/// remote client can dial.
///
/// A specific host is returned unchanged. A `0.0.0.0` wildcard is
/// resolved to the local IPv4 address and an `::` wildcard to the
/// local IPv6 address (with an IPv4 fallback). If the local interface
/// cannot be resolved, the wildcard is preserved verbatim so the
/// output is still a valid socket address.
#[must_use]
pub fn display_address(config: &Config) -> SocketAddr {
    display_address_from(
        config,
        crate::net::local_ipv4_address,
        crate::net::local_ipv6_address,
    )
}

/// Same as [`display_address`] but with explicit local-address probes
/// for testability. The probes are plain `fn() -> Option<IpAddr>`
/// callbacks so callers can inject deterministic addresses without
/// touching the kernel's routing table.
#[must_use]
#[allow(clippy::module_name_repetitions)]
pub fn display_address_from(
    config: &Config,
    local_ipv4: fn() -> Option<IpAddr>,
    local_ipv6: fn() -> Option<IpAddr>,
) -> SocketAddr {
    let host = match config.host {
        IpAddr::V4(value) if value.is_unspecified() => local_ipv4().unwrap_or(config.host),
        IpAddr::V6(value) if value.is_unspecified() => {
            local_ipv6().or_else(local_ipv4).unwrap_or(config.host)
        }
        other => other,
    };
    SocketAddr::new(host, config.port)
}

/// Bounded TCP-connect check used by `croncheck`.
///
/// Returns `true` if a listener accepts the connection within the
/// timeout, `false` otherwise. A refusal, timeout, or unreachable host
/// all mean the daemon is not accepting traffic on this address.
fn is_listening(target: SocketAddr) -> bool {
    const TIMEOUT: Duration = Duration::from_millis(750);
    TcpStream::connect_timeout(&target, TIMEOUT).is_ok()
}

/// Build the [`Command`] used by `croncheck` to spawn `greggd run` as a
/// detached watchdog child. Stdio is closed; the daemon's own logging is
/// independent of croncheck's. On Unix the child is placed in a new
/// process group so signals sent to croncheck's group (for example
/// SIGHUP from a closing terminal) do not reach the daemon.
///
/// Exposed crate-internally so tests can inspect `program()` and `get_args()`
/// without actually forking. The caller is responsible for `.spawn()`.
fn build_daemon_command(
    config_path: &std::path::Path,
    explicit: bool,
) -> std::io::Result<ProcessCommand> {
    let exe = std::env::current_exe()?;
    let mut cmd = ProcessCommand::new(exe);
    cmd.arg("run");
    if explicit {
        cmd.arg("--config").arg(config_path);
    }
    cmd.stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());

    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        cmd.process_group(0);
    }

    Ok(cmd)
}

/// Dispatch a subcommand using the path's current existence as a compatibility
/// fallback. The binary entry point uses [`dispatch_with_config_intent`] so a
/// missing explicit path remains distinguishable from a missing default path.
///
/// # Errors
///
/// Returns an error if the command fails.
pub fn dispatch(
    command: &Command,
    config_path: &std::path::Path,
) -> Result<(), Box<dyn std::error::Error>> {
    dispatch_with_config_intent(command, config_path, config_path.exists())
}

/// Dispatch a command while preserving whether the config path was explicit.
pub fn dispatch_with_config_intent(
    command: &Command,
    config_path: &std::path::Path,
    explicit: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    match command {
        Command::Run => {
            // Delegate to the async run entry point.
            // This is handled in main.rs.
            unreachable!("Command::Run is handled in main.rs")
        }
        Command::Stop => {
            // Unix uses the local control socket and is dispatched at the
            // binary boundary (see main.rs) so it can return errors as the
            // runtime/library boundary without a global tracing init.
            #[cfg(unix)]
            {
                unreachable!("Command::Stop is handled at the binary boundary on Unix")
            }
            #[cfg(not(unix))]
            {
                unreachable!("Command::Stop is handled at the binary boundary on Windows")
            }
        }
        Command::Croncheck => {
            let config = load_config(config_path, explicit)?;
            let target = croncheck_target(&config);
            if is_listening(target) {
                // Daemon is already accepting traffic on the configured
                // bind. Nothing to do.
                return Ok(());
            }
            // Nothing is listening: spawn `greggd run` as a detached
            // watchdog child. The kernel's bind semantics prevent a
            // second concurrent start once the first child binds its
            // listener; any spawn that loses the race surfaces as a
            // nonzero exit and the next cron tick will retry.
            build_daemon_command(config_path, explicit)?.spawn()?;
            Ok(())
        }
        Command::Configprint => {
            let config = load_config(config_path, explicit)?;
            println!("{}", display_address(&config));
            Ok(())
        }
        Command::Host { address } => mutate_config(config_path, explicit, |config| {
            config.host = *address;
        }),
        Command::Port { port } => mutate_config(config_path, explicit, |config| {
            config.port = *port;
        }),
        Command::Version => {
            println!("{}", version_string());
            Ok(())
        }
        #[cfg(target_os = "windows")]
        Command::Start | Command::Restart => {
            unreachable!("Windows service commands are dispatched at the binary boundary")
        }
        #[cfg(target_os = "windows")]
        Command::Service => {
            unreachable!("Command::Service is handled in main.rs")
        }
    }
}

#[cfg(all(test, not(target_os = "windows")))]
mod native_tests {
    use super::*;
    use clap::Parser;
    use std::net::TcpListener;

    #[test]
    fn parser_accepts_run_stop_croncheck_mutations_and_version_but_not_windows_lifecycle() {
        for args in ["run", "stop", "croncheck", "configprint", "version"] {
            let argv = if args == "host" {
                vec!["greggd", "host", "127.0.0.1"]
            } else if args == "port" {
                vec!["greggd", "port", "11310"]
            } else {
                vec!["greggd", args]
            };
            assert!(Cli::try_parse_from(argv).is_ok(), "failed to parse {args}");
        }
        assert!(Cli::try_parse_from(["greggd", "host", "127.0.0.1"]).is_ok());
        assert!(Cli::try_parse_from(["greggd", "port", "11310"]).is_ok());
        // `croncheck` no longer takes a `--target` flag: it operates on
        // the configured local bind only.
        assert!(
            Cli::try_parse_from(["greggd", "croncheck", "--target", "192.168.182.143:11310"])
                .is_err()
        );
        for command in ["start", "restart"] {
            assert!(Cli::try_parse_from(["greggd", command]).is_err());
        }
    }

    #[test]
    fn wildcard_probe_addresses_use_loopback() {
        assert_eq!(
            probe_address("0.0.0.0".parse::<IpAddr>().unwrap()),
            "127.0.0.1".parse::<IpAddr>().unwrap()
        );
        assert_eq!(
            probe_address("::".parse::<IpAddr>().unwrap()),
            "::1".parse::<IpAddr>().unwrap()
        );
        assert_eq!(
            probe_address("192.0.2.1".parse::<IpAddr>().unwrap()),
            "192.0.2.1".parse::<IpAddr>().unwrap()
        );
    }

    #[test]
    fn config_address_preserves_wildcards_and_formats_ipv6() {
        let mut config = Config::default();
        assert_eq!(config_address(&config).to_string(), "0.0.0.0:11310");
        config.host = "fd00::10".parse().unwrap();
        config.port = 11320;
        assert_eq!(config_address(&config).to_string(), "[fd00::10]:11320");
    }

    #[test]
    fn display_address_preserves_specific_hosts() {
        let config = Config {
            host: "192.168.182.143".parse().unwrap(),
            port: 11310,
            ..Config::default()
        };
        assert_eq!(
            display_address_from(&config, || None, || None).to_string(),
            "192.168.182.143:11310"
        );
        let config = Config {
            host: "fd00::10".parse().unwrap(),
            port: 11320,
            ..Config::default()
        };
        assert_eq!(
            display_address_from(&config, || None, || None).to_string(),
            "[fd00::10]:11320"
        );
    }

    #[test]
    fn display_address_resolves_ipv4_wildcard_to_local_ipv4() {
        let config = Config {
            host: "0.0.0.0".parse().unwrap(),
            ..Config::default()
        };
        let resolved = display_address_from(
            &config,
            || Some("192.168.182.143".parse().unwrap()),
            || None,
        );
        assert_eq!(resolved.to_string(), "192.168.182.143:11310");
    }

    #[test]
    fn display_address_resolves_ipv6_wildcard_to_local_ipv6() {
        let config = Config {
            host: "::".parse().unwrap(),
            ..Config::default()
        };
        let resolved = display_address_from(&config, || None, || Some("fd00::10".parse().unwrap()));
        assert_eq!(resolved.to_string(), "[fd00::10]:11310");
    }

    #[test]
    fn display_address_falls_back_from_ipv6_to_ipv4_wildcard() {
        let config = Config {
            host: "::".parse().unwrap(),
            ..Config::default()
        };
        let resolved = display_address_from(
            &config,
            || Some("192.168.182.143".parse().unwrap()),
            || None,
        );
        assert_eq!(resolved.to_string(), "192.168.182.143:11310");
    }

    #[test]
    fn display_address_preserves_wildcard_when_no_local_address() {
        let config = Config {
            host: "0.0.0.0".parse().unwrap(),
            ..Config::default()
        };
        let resolved = display_address_from(&config, || None, || None);
        assert_eq!(resolved.to_string(), "0.0.0.0:11310");

        let config = Config {
            host: "::".parse().unwrap(),
            ..Config::default()
        };
        let resolved = display_address_from(&config, || None, || None);
        assert_eq!(resolved.to_string(), "[::]:11310");
    }

    #[test]
    fn display_address_prefers_configured_loopback_over_resolved_address() {
        // 127.0.0.1 is loopback but not unspecified, so it must pass
        // through unchanged; resolution only applies to wildcards.
        let config = Config {
            host: "127.0.0.1".parse().unwrap(),
            ..Config::default()
        };
        let resolved = display_address_from(
            &config,
            || Some("192.168.182.143".parse().unwrap()),
            || None,
        );
        assert_eq!(resolved.to_string(), "127.0.0.1:11310");
    }

    #[test]
    fn configprint_uses_default_for_missing_implicit_config() {
        let path =
            std::env::temp_dir().join(format!("greggd-configprint-{}.toml", std::process::id()));
        let _ = std::fs::remove_file(&path);
        dispatch_with_config_intent(&Command::Configprint, &path, false).unwrap();
        assert!(!path.exists());
    }

    #[test]
    fn configprint_rejects_missing_explicit_config() {
        let path = std::env::temp_dir().join(format!(
            "greggd-configprint-missing-{}.toml",
            std::process::id(),
        ));
        let _ = std::fs::remove_file(&path);
        assert!(dispatch_with_config_intent(&Command::Configprint, &path, true).is_err());
    }

    #[test]
    fn version_string_uses_package_version() {
        assert_eq!(
            version_string(),
            format!("greggd {}", env!("CARGO_PKG_VERSION"))
        );
    }

    #[test]
    fn config_mutation_is_persisted_without_service_dispatch() {
        let dir = std::env::temp_dir().join("greggd_native_mutation_test");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");
        mutate_config(&path, false, |config| config.port = 11320).unwrap();
        assert_eq!(Config::load(&path).unwrap().port, 11320);
        let _ = std::fs::remove_dir_all(dir);
    }

    fn bind_loopback() -> SocketAddr {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let target = listener.local_addr().unwrap();
        // Hold the listener for the duration of the test by leaking it;
        // both `is_listening` paths own nothing and tests close over the
        // target only.
        std::mem::forget(listener);
        target
    }

    fn unbound_loopback() -> SocketAddr {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        listener.local_addr().unwrap()
    }

    #[test]
    fn is_listening_accepts_a_bound_port() {
        let target = bind_loopback();
        assert!(is_listening(target));
    }

    #[test]
    fn is_listening_rejects_a_closed_port() {
        let target = unbound_loopback();
        assert!(!is_listening(target));
    }

    #[test]
    fn croncheck_dispatch_exits_when_listener_up_without_spawning() {
        // With a listener up on the configured port, `croncheck` must
        // return Ok and never invoke the spawn path. The only observable
        // side effect would be a backgrounded child, which we cannot
        // inspect here; the assertion is the Ok result.
        let target = bind_loopback();
        let dir = std::env::temp_dir().join("greggd_croncheck_listener_up_test");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("greggd.toml");
        std::fs::write(
            &path,
            format!(
                "name = \"loopback-croncheck-test\"\n\
                 host = \"127.0.0.1\"\n\
                 port = {}\n\
                 sample_interval_ms = 1000\n\
                 stale_after_ms = 10000\n",
                target.port()
            ),
        )
        .unwrap();
        dispatch_with_config_intent(&Command::Croncheck, &path, true).unwrap();
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn build_daemon_command_includes_run_and_explicit_config() {
        let dir = std::env::temp_dir().join("greggd_build_daemon_explicit_test");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");
        let cmd = build_daemon_command(&path, true).unwrap();
        assert_eq!(
            cmd.get_program(),
            std::env::current_exe().unwrap().as_os_str()
        );
        let args: Vec<std::ffi::OsString> =
            cmd.get_args().map(std::ffi::OsStr::to_os_string).collect();
        assert_eq!(
            args,
            vec![
                std::ffi::OsString::from("run"),
                std::ffi::OsString::from("--config"),
                path.as_os_str().to_os_string(),
            ]
        );
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn build_daemon_command_omits_config_when_implicit() {
        let cmd = build_daemon_command(std::path::Path::new("/nonexistent.toml"), false).unwrap();
        assert_eq!(
            cmd.get_program(),
            std::env::current_exe().unwrap().as_os_str()
        );
        let args: Vec<std::ffi::OsString> =
            cmd.get_args().map(std::ffi::OsStr::to_os_string).collect();
        assert_eq!(args, vec![std::ffi::OsString::from("run")]);
    }
}