diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f143e4e8d..03c88a652 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -226,6 +226,25 @@ jobs: env: RUST_BACKTRACE: 1 + # Doctests. `--lib` above does NOT run them, and no other job did either: + # before this step, `grep -rn -- '--doc' .github/workflows/` returned + # nothing, so every `///` example in the workspace was unverified. The + # `Documentation` job runs `cargo doc`, which builds the pages and does + # not compile the examples in them. + # + # This matters because the examples are the first code a new contributor + # copies. Measured on the tree that added this step: 21 passed, 0 failed. + # + # It is a thin gate today and the number says why: 193 of the workspace's + # examples are fenced ```rust,ignore``` and are skipped, so this compiles + # 21 of 214. Converting the ignores that only need to type-check to + # ```no_run``` is the follow-up that gives this step its teeth; the step + # has to exist first or there is nothing to convert them into. + - name: Doctests + run: cargo test --workspace --exclude horus_py --doc + env: + RUST_BACKTRACE: 1 + # The resolver's crates.io/PyPI tests carry #[ignore] so a contributor # without network access gets a green suite and a failure means the # resolver is wrong rather than the network. CI does have access, so it @@ -360,6 +379,19 @@ jobs: # also the right call — docs should describe the crate as it ships, # i.e. with its default features on. cargo doc --workspace --no-deps --exclude horus_manager + # Again with horus_core's internals visible. + # + # Ten of its eleven modules are `#[doc(hidden)]` by default, and + # rustdoc does not resolve links inside a hidden module — so the run + # above holds `-D warnings` over roughly a quarter of the crate and + # silently skips the rest. Four broken links had accumulated behind + # that gap, including a `[`HorusError::OutOfRange`]` naming a variant + # the error refactor deleted, and two pointing at private items. + # + # `internal-docs` is docs-only: it gates nothing but the + # `#[doc(hidden)]` attributes, so this compiles no extra code. The + # published documentation is still what the first command renders. + cargo doc -p horus_core --no-deps --features internal-docs env: RUSTDOCFLAGS: ${{ (github.ref == 'refs/heads/main' || github.base_ref == 'main') && '-D warnings' || '' }} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 96eb74cb0..2c24f44ad 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -757,13 +757,16 @@ repository; `:850` notes that neither substitutes for the other. and line 794 sits inside the `cli-integration` job (`:309`) which is in the aggregator's needs list (`:1374`). - The exception is `readme_contract.rs`'s `the_readme_quick_start_compiles`, - which is `#[ignore]`d with the reason "run in the docs-contract job" - (`readme_contract.rs:146`). Nothing runs it: no workflow mentions - `readme_contract`, `docs-contract.yml`'s cargo invocations name only the - `docs_*` targets, and `integration-tests.yml:794` passes no - `--include-ignored`. If you change the README's Quick Start, compile it - yourself: + `readme_contract.rs`'s `the_readme_quick_start_compiles` is `#[ignore]`d + with the reason "run in the docs-contract job" (`readme_contract.rs:146`), + and that job does now run it — `docs-contract.yml` invokes + `cargo test -p horus_manager --test readme_contract -- --include-ignored`. + + This paragraph previously said the opposite ("Nothing runs it: no workflow + mentions `readme_contract`") and told you to compile the Quick Start by hand. + That was true when it was written and stopped being true when the invocation + was added; the prose was not updated with it. You can still run it locally, + but CI will catch a broken Quick Start without you: ```bash cargo test -p horus_manager --test readme_contract -- --include-ignored diff --git a/docs/TESTING.md b/docs/TESTING.md index 39a87728a..87ebcb142 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -544,8 +544,8 @@ coverage, and gates nothing. | `cli_runtime_integration` (18 ignored), `launch_and_workflow` (5), `real_project_ipc` (3) | `horus_core/tests/` | need a debug build of `-p horus --examples` plus `horus_manager` that no job produces (`integration-tests.yml:160-166`) | | `transient_subscribers_permanently_flip_a_topic_to_a_lossy_backend` | `participant_count_leak.rs:62` | `#[ignore]`d with the reason "documents an open defect" | | `naive_protocol_tears_proving_the_model_can_detect_it` | `loom_pod_broadcast.rs:225` | deliberately excluded (`integration-tests.yml:186`); it is supposed to fail, so running it in CI would be wrong — but nothing checks that it *still* fails | -| `docs_parity` | `horus_manager/tests/docs_parity.rs` | all three of its tests are `#[ignore]`d with the reason "needs a horus-docs checkout; wired into the docs-contract workflow" (`:193,:259,:336`). `grep -rn docs_parity .github/` returns nothing. The suite that exists to catch *undocumented* new surface never runs | -| `readme_contract`'s `#[ignore]`d test | `readme_contract.rs:146` | reason: "slow: builds a scratch crate; run in the docs-contract job". That job does not name the target. The other 10 tests in the file do run, via `integration-tests.yml:794` | +| `docs_parity` | `horus_manager/tests/docs_parity.rs` | all three tests are `#[ignore]`d with the reason "needs a horus-docs checkout; wired into the docs-contract workflow" (`:193,:259,:336`) — and it **is** wired: `docs-contract.yml` runs `cargo test -p horus_manager --test docs_parity -- --ignored --nocapture`. This row previously read "`grep -rn docs_parity .github/` returns nothing … never runs", which was true when written and was falsified by the commit that added the invocation | +| `readme_contract`'s `#[ignore]`d test | `readme_contract.rs:146` | reason: "slow: builds a scratch crate; run in the docs-contract job". That job **does** name the target now (`docs-contract.yml`, `--include-ignored`); this row previously said it did not. The other 10 tests in the file also run, via `integration-tests.yml:794` | | `cpp_toolchain_contract`'s `#[ignore]`d test | `cpp_toolchain_contract.rs:464` | reason: "slow: cross-compiles horus_cpp; run with `--ignored`". Nothing does. The other 19 run | | `.config/nextest.toml` | repo root config | a fully worked per-test timeout guard (60 s × 3 hard kill at `:50`, `test-threads = 1` at `:66`, `retries = 0` at `:70`, `leak-timeout = "500ms"` at `:77`, a `ci` profile with JUnit output at `:83-101` and a `soak` profile at `:103-110`) that no workflow uses — `grep -rn nextest .github/` returns nothing, and no markdown mentions it | | `horus_manager/tests/web_e2e/` | Puppeteer suite, `package.json:5-7` | referenced only by `.github/dependabot.yml:105`, whose own comment records that no CI workflow runs the suite and that puppeteer is `hasInstallScript: true`, so the dependency graph is exercised exclusively on workstations | @@ -554,12 +554,18 @@ coverage, and gates nothing. | `tests/docker/run_all.sh` | repo `tests/docker/` | `docker-distro-tests.yml:43-61` builds the five Dockerfiles and runs the image `CMD` and `test_user_workflow.sh` directly; `run_all.sh` is unreferenced. `acceptance_linux_macos.sh` and `acceptance_windows.ps1` beside it *are* used, by `cross-platform-parity.yml` and `distribution.yml` | | `horus_core`'s doctests | 13 blocks tagged ```` ```rust ```` and one ```` ```no_run ```` in `horus_core/src` | see below | -Three of these are worse than merely unrun, and the distinction matters when you -are deciding what to fix first: `docs_parity`, `readme_contract` and -`cpp_toolchain_contract` carry `#[ignore]` *reason strings asserting they are -wired*. A reader of the source has no way to discover otherwise short of -grepping the workflows. If you add an `#[ignore]` with a reason naming a -workflow, add the invocation in the same commit. +`cpp_toolchain_contract` carries an `#[ignore]` *reason string asserting it is +wired* while nothing runs it, and a reader of the source has no way to discover +that short of grepping the workflows. If you add an `#[ignore]` whose reason +names a workflow, add the invocation in the same commit. + +`docs_parity` and `readme_contract` used to be listed here for the same fault +and have since been wired up — which exposed the mirror-image hazard this table +now demonstrates twice over. **A table asserting that something is unrun is +itself untested prose, and it rots in the direction that wastes a newcomer's +time**: it sends them to hand-run a suite CI already covers, and it teaches them +to distrust the workflows. Re-derive the rows against +`grep -rn '' .github/` before relying on any of them. **On `nextest.toml`.** Its stated premise has partly expired: it says at `:8` that "None of the jobs in `.github/workflows/ci.yml` set `timeout-minutes`", and diff --git a/horus_core/Cargo.toml b/horus_core/Cargo.toml index ecbe54d54..1124cd66b 100644 --- a/horus_core/Cargo.toml +++ b/horus_core/Cargo.toml @@ -75,6 +75,9 @@ horus-tf = { git = "https://github.com/softmata/horus-tf.git", rev = "d525dfcf58 workspace = true [features] +# Render the crate-internal modules in rustdoc. Docs-only: it gates nothing +# but `#[doc(hidden)]`, so it changes no code and no dependency. +internal-docs = [] default = ["macros", "telemetry", "blackbox"] macros = ["horus_macros"] diff --git a/horus_core/README.md b/horus_core/README.md index 1d4274932..48010af79 100644 --- a/horus_core/README.md +++ b/horus_core/README.md @@ -111,9 +111,17 @@ caught it (`rt_allocator.rs:21-26`, `rt_alloc_guard_installed.rs:35-38`). ## How to read the internals `--document-private-items` is **not** enough on its own. It disables rustdoc's -private-stripping pass, not its hidden-stripping pass, so the eleven hidden -modules stay stripped. You need nightly and `--document-hidden-items`, which is -unstable and refuses to run without `-Z unstable-options`: +private-stripping pass, not its hidden-stripping pass, so the hidden modules +stay stripped. Use the `internal-docs` feature, which lifts the +`#[doc(hidden)]` attributes and works on stable: + +```sh +cargo doc -p horus_core --no-deps --document-private-items \ + --features internal-docs --open +``` + +The nightly form below still works and needs no feature, but it requires a +nightly toolchain and an unstable flag, which is why the feature exists: ```sh RUSTDOCFLAGS="-Z unstable-options --document-hidden-items" \ diff --git a/horus_core/src/core/log_buffer.rs b/horus_core/src/core/log_buffer.rs index 509ec71b0..914b7b75f 100644 --- a/horus_core/src/core/log_buffer.rs +++ b/horus_core/src/core/log_buffer.rs @@ -614,9 +614,11 @@ pub fn publish_log(entry: LogEntry) { /// /// Returns a join handle. Drop or join to stop the drain thread. pub fn start_log_file_drain() -> Option> { - let enabled = std::env::var("HORUS_LOG_FILE") - .map(|v| v == "true" || v == "1") - .unwrap_or(false); + // `env_flag`, not a local truth table. This site accepted only "true" and + // "1", so `HORUS_LOG_FILE=yes` turned logging off while `HORUS_SIM_MODE=yes` + // turned simulation on — the same framework disagreeing with itself about + // one word. See `horus_sys::env` for the vocabulary. + let enabled = horus_sys::env::env_flag("HORUS_LOG_FILE").unwrap_or(false); if !enabled { return None; } diff --git a/horus_core/src/drivers/mod.rs b/horus_core/src/drivers/mod.rs index 1605b4be0..1422b929c 100644 --- a/horus_core/src/drivers/mod.rs +++ b/horus_core/src/drivers/mod.rs @@ -96,9 +96,13 @@ pub fn load_from>(path: P) -> HorusResult> = if sim_mode { std::env::var("HORUS_SIM_TARGETS") diff --git a/horus_core/src/error.rs b/horus_core/src/error.rs index 4c3ad45bf..4f9079d05 100644 --- a/horus_core/src/error.rs +++ b/horus_core/src/error.rs @@ -850,7 +850,7 @@ macro_rules! horus_internal { /// Convenience type alias for Results using HorusError. /// -/// **Prefer the short aliases [`Result`] and [`Error`] in all new code.** +/// **Prefer the short aliases [`Result`] and [`Error`](type@Error) in all new code.** /// `HorusResult` and `HorusError` are the canonical names but verbose — /// the aliases exist specifically so you can write `Result<()>` and `Error` /// without the `Horus` prefix everywhere. diff --git a/horus_core/src/lib.rs b/horus_core/src/lib.rs index 3b4034e41..efbb4554f 100644 --- a/horus_core/src/lib.rs +++ b/horus_core/src/lib.rs @@ -15,25 +15,45 @@ //! **Note:** This is an internal crate. Users should depend on `horus` and //! import from `horus::prelude::*`. -// Public modules — accessible cross-crate but hidden from user docs. -// Users should go through `horus::prelude`, not import from `horus_core` directly. -#[doc(hidden)] +// Public modules — accessible cross-crate, hidden from user docs by default. +// Users should go through `horus::prelude`, not import from `horus_core` +// directly, and the crate note above says so. +// +// The hiding is `cfg_attr`'d rather than unconditional so a MAINTAINER can lift +// it on stable: +// +// cargo doc -p horus_core --no-deps --document-private-items \ +// --features internal-docs --open +// +// Before this was a feature, the only way to read the internals was the nightly +// incantation in horus_core/README.md — `-Z unstable-options +// --document-hidden-items` — because `--document-private-items` disables +// rustdoc's private-stripping pass and not its hidden-stripping pass. That put +// the API browser for a 112k-line crate behind an unstable flag, so on stable +// `cargo doc --open` showed one module (`terminal`), zero structs and an empty +// search index. +// +// CI documents WITH the feature (ci.yml, Documentation job) precisely so +// `-D warnings` sees these modules: while they were unconditionally hidden, +// rustdoc never resolved their links and four broken ones had accumulated, +// including a `HorusError::OutOfRange` the error refactor had deleted. +#[cfg_attr(not(feature = "internal-docs"), doc(hidden))] pub mod actions; -#[doc(hidden)] +#[cfg_attr(not(feature = "internal-docs"), doc(hidden))] pub mod communication; -#[doc(hidden)] +#[cfg_attr(not(feature = "internal-docs"), doc(hidden))] pub mod core; -#[doc(hidden)] +#[cfg_attr(not(feature = "internal-docs"), doc(hidden))] pub mod drivers; -#[doc(hidden)] +#[cfg_attr(not(feature = "internal-docs"), doc(hidden))] pub mod error; -#[doc(hidden)] +#[cfg_attr(not(feature = "internal-docs"), doc(hidden))] pub mod memory; -#[doc(hidden)] +#[cfg_attr(not(feature = "internal-docs"), doc(hidden))] pub mod params; -#[doc(hidden)] +#[cfg_attr(not(feature = "internal-docs"), doc(hidden))] pub mod scheduling; -#[doc(hidden)] +#[cfg_attr(not(feature = "internal-docs"), doc(hidden))] pub mod services; /// Non-panicking console output. /// @@ -42,7 +62,7 @@ pub mod services; /// operator pipes `horus run` into `head`. Anything printing from a node, a /// background thread, or a safety path should use these instead. pub mod terminal; -#[doc(hidden)] +#[cfg_attr(not(feature = "internal-docs"), doc(hidden))] pub mod types; pub(crate) mod utils; diff --git a/horus_core/src/memory/depth_image.rs b/horus_core/src/memory/depth_image.rs index 8d81ec7d2..a5d8081c0 100644 --- a/horus_core/src/memory/depth_image.rs +++ b/horus_core/src/memory/depth_image.rs @@ -134,10 +134,15 @@ impl DepthImage { /// /// # Errors /// - /// - [`HorusError::OutOfRange`] — for U16 images, if the converted + /// - [`HorusError::InvalidInput`] — for U16 images, if the converted /// millimeter value does not fit in `u16` (e.g., value > 65.535m at /// default scale 1.0). Callers must handle this instead of silently /// storing the saturated `u16::MAX`. + /// + /// The link used to name `HorusError::OutOfRange`, which the error refactor + /// folded into `InvalidInput(ValidationError::…)` (see error.rs:399). The + /// broken link survived because this module was `#[doc(hidden)]`, so + /// rustdoc never resolved it. pub fn set_depth(&mut self, x: u32, y: u32, value: f32) -> HorusResult<&mut Self> { if x >= self.width() || y >= self.height() { return Ok(self); diff --git a/horus_core/src/memory/tensor_handle.rs b/horus_core/src/memory/tensor_handle.rs index 023c1cc2b..dbf833320 100644 --- a/horus_core/src/memory/tensor_handle.rs +++ b/horus_core/src/memory/tensor_handle.rs @@ -101,7 +101,7 @@ impl TensorHandle { /// and dtype. /// /// This is the ergonomic constructor for creating a tensor to fill in and - /// publish: the data lives in the [`global_pool`](crate::communication::topic::pool_registry::global_pool) + /// publish: the data lives in the process-wide tensor pool (`global_pool`) /// and the device is inferred from that pool's backend (CPU by default). For /// an explicit pool or device, use [`alloc`](Self::alloc). /// diff --git a/horus_core/src/params.rs b/horus_core/src/params.rs index 1a519ccce..ce6f8e6ad 100644 --- a/horus_core/src/params.rs +++ b/horus_core/src/params.rs @@ -51,11 +51,21 @@ impl ParamMetadata { } } +/// Callback type for parameter change notification. +/// Called with (key, old_value, new_value). Return Err to reject the change. +pub type ParamChangeCallback = + Arc, &Value) -> Result<(), String> + Send + Sync>; + /// Runtime parameter store for dynamic configuration. /// /// Provides a typed key-value store with validation, persistence, and /// concurrent access support. /// +/// The whole of this block — description and doctest — used to sit on +/// `ParamChangeCallback` below, a type alias, because a new item was inserted +/// between the comment and the struct it belonged to. `RuntimeParams` itself +/// rendered undocumented while a callback alias carried its example. +/// /// # Example /// /// ```rust @@ -69,11 +79,6 @@ impl ParamMetadata { /// let speed: f64 = params.get("max_speed").unwrap(); /// assert_eq!(speed, 1.5); /// ``` -/// Callback type for parameter change notification. -/// Called with (key, old_value, new_value). Return Err to reject the change. -pub type ParamChangeCallback = - Arc, &Value) -> Result<(), String> + Send + Sync>; - pub struct RuntimeParams { /// Parameter storage - BTreeMap maintains sorted order params: Arc>>, diff --git a/horus_core/src/scheduling/scheduler/mod.rs b/horus_core/src/scheduling/scheduler/mod.rs index 568decbdb..c40203c41 100644 --- a/horus_core/src/scheduling/scheduler/mod.rs +++ b/horus_core/src/scheduling/scheduler/mod.rs @@ -323,7 +323,6 @@ pub(crate) struct RecordingState { /// lifetime and dropped during shutdown — use `Drop` to clean up resources. pub type LifecycleStartFn = Box Option> + Send>; -/// Central orchestrator: holds nodes, drives the tick loop. /// What the presence refresh needs about a node the main thread does not own. #[derive(Debug, Clone)] pub(super) struct PresenceEntry { @@ -336,6 +335,17 @@ pub(super) struct PresenceEntry { pub main_thread: bool, } +/// Central orchestrator: holds nodes, drives the tick loop. +/// +/// This is the type a HORUS program is built around: nodes are registered on +/// it, it partitions them by scheduling class across the RT, compute, event and +/// async-I/O executors, and it owns the loop that ticks them and enforces their +/// deadlines. +/// +/// The doc line above used to sit one item higher, stranded on top of +/// `PresenceEntry`'s own comment — so the framework's primary public type +/// rendered with no description at all, and a private struct was documented as +/// the orchestrator. pub struct Scheduler { pub(super) nodes: Vec, pub(super) running: Arc, @@ -688,13 +698,14 @@ impl Scheduler { }; // Network discovery is enabled by default (like ROS2). - // Opt out via HORUS_NET_ENABLED=false (or =0) env var, or `.network(false)`. + // Opt out via HORUS_NET_ENABLED=false (or 0/no/off), or `.network(false)`. // The actual horus_net startup is handled by a lifecycle hook registered // by the integration layer (e.g., the `horus` umbrella crate). - if std::env::var("HORUS_NET_ENABLED") - .map(|v| v == "0" || v.eq_ignore_ascii_case("false")) - .unwrap_or(false) - { + // + // An opt-out reads the same vocabulary as an opt-in: this site accepted + // `0` and `false` but not `no` or `off`, so two of the four words that + // mean "off" everywhere else in HORUS left networking running. + if horus_sys::env::env_flag("HORUS_NET_ENABLED") == Some(false) { s.network_enabled = false; } @@ -1996,7 +2007,7 @@ impl Scheduler { /// Set OS-level scheduling priority using SCHED_FIFO (Linux RT-PREEMPT required). /// - /// Delegates to [`super::rt::set_realtime_priority`]. + /// Delegates to `super::rt::set_realtime_priority` (crate-private). /// /// # Arguments /// * `priority` - Priority level (1-99, higher = more important) diff --git a/horus_sys/src/env/mod.rs b/horus_sys/src/env/mod.rs new file mode 100644 index 000000000..48b1dd26b --- /dev/null +++ b/horus_sys/src/env/mod.rs @@ -0,0 +1,153 @@ +//! One vocabulary for boolean environment variables. +//! +//! # Why this exists +//! +//! HORUS reads 60-odd `HORUS_*` variables, and before this module every site +//! decided for itself what counted as "on". The forms in production were: +//! +//! ```text +//! v == "true" || v == "1" HORUS_LOG_FILE +//! !(v.is_empty() || v == "0" || eq_ic(v, "false")) HORUS_SIM_MODE +//! v == "0" || eq_ic(v, "false") HORUS_NET_ENABLED (opt-out) +//! env::var(..).is_ok() presence-only +//! v == "1" HORUS_WIN_REALTIME_CLASS +//! ``` +//! +//! The consequence was not academic. `HORUS_LOG_FILE=yes` was **false** while +//! `HORUS_SIM_MODE=no` was **true** — the second one silently swapping every +//! driver for an inert `SimStubNode`, actuators never commanded and sensors +//! never read. Two variables in the same framework disagreed about the word +//! "no", and nothing in the codebase said which was right. +//! +//! # The vocabulary +//! +//! `1`, `true`, `yes`, `on` are true. `0`, `false`, `no`, `off` and the empty +//! string are false. Matching is ASCII case-insensitive, so `True` and `ON` +//! work. Surrounding whitespace is trimmed, because a value that arrived from a +//! YAML launch file or a shell here-doc often carries some. +//! +//! # Why an unrecognised value is `None`, not `false` +//! +//! `env_flag` returns `Option`: `None` means "unset or not a boolean I +//! recognise", which leaves the caller's default in force. `HORUS_SIM_MODE=maybe` +//! therefore keeps simulation off rather than turning it on — the old +//! `!(v == "0")` shape treated every typo as an opt-in, which is the wrong +//! direction for a flag that disconnects the robot from its hardware. +//! +//! It also matches what the reference page already promises for +//! `HORUS_SHM_PREFAULT`: "an unrecognised value keeps the default rather than +//! meaning off". + +/// Read a boolean environment variable using the project-wide vocabulary. +/// +/// Returns `None` when the variable is unset, or set to something that is not +/// a recognised truth value — in both cases the caller's default should stand. +/// +/// ``` +/// # use horus_sys::env::parse_flag; +/// assert_eq!(parse_flag("yes"), Some(true)); +/// assert_eq!(parse_flag("off"), Some(false)); +/// assert_eq!(parse_flag(""), Some(false)); +/// // Not a truth value: the caller's default stands. +/// assert_eq!(parse_flag("maybe"), None); +/// ``` +/// +/// The example exercises [`parse_flag`] rather than `env_flag` on purpose: an +/// assertion about a variable being *unset* is only true until someone's shell +/// or CI image happens to set it, and a doctest that depends on the ambient +/// environment is a flake waiting for a machine that disagrees. +pub fn env_flag(name: &str) -> Option { + parse_flag(std::env::var(name).ok()?.as_str()) +} + +/// The parsing half, separated from the environment so it can be tested +/// without mutating process-global state — `set_var` is not safe against a +/// concurrent `getenv` on another thread, and the test binaries here run +/// in parallel. +pub fn parse_flag(raw: &str) -> Option { + let v = raw.trim(); + if v.is_empty() { + return Some(false); + } + if v.eq_ignore_ascii_case("1") + || v.eq_ignore_ascii_case("true") + || v.eq_ignore_ascii_case("yes") + || v.eq_ignore_ascii_case("on") + { + return Some(true); + } + if v.eq_ignore_ascii_case("0") + || v.eq_ignore_ascii_case("false") + || v.eq_ignore_ascii_case("no") + || v.eq_ignore_ascii_case("off") + { + return Some(false); + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_whole_vocabulary_is_accepted_in_any_case() { + for t in ["1", "true", "TRUE", "True", "yes", "YES", "on", "On"] { + assert_eq!(parse_flag(t), Some(true), "{t:?} must be true"); + } + for f in ["0", "false", "FALSE", "no", "NO", "off", "Off", ""] { + assert_eq!(parse_flag(f), Some(false), "{f:?} must be false"); + } + } + + /// The two divergences that motivated this module, pinned as tests. + #[test] + fn the_words_that_used_to_disagree_now_agree() { + // `HORUS_LOG_FILE=yes` was false because that site matched only + // "true"/"1". + assert_eq!(parse_flag("yes"), Some(true)); + // `HORUS_SIM_MODE=no` was TRUE, because that site treated anything + // that was not "0"/"false"/empty as an opt-in — so a deploy script + // saying "no" got inert SimStubNodes and no diagnostic. + assert_eq!(parse_flag("no"), Some(false)); + } + + #[test] + fn an_unrecognised_value_leaves_the_default_in_force() { + for junk in ["maybe", "2", "yep", "sim", "-1"] { + assert_eq!( + parse_flag(junk), + None, + "{junk:?} must not be read as a truth value in either direction" + ); + } + } + + #[test] + fn whitespace_from_a_launch_file_or_here_doc_is_trimmed() { + assert_eq!(parse_flag(" true "), Some(true)); + assert_eq!(parse_flag("\toff\n"), Some(false)); + } + + /// `env_flag` is the thin half — it reads the variable and hands the value + /// to `parse_flag`. Asserting it on a name this process itself controls + /// keeps the check honest without depending on what the ambient + /// environment happens to hold. + #[test] + fn env_flag_delegates_to_parse_flag() { + // A name unique to this process, so a developer's shell or a CI image + // cannot decide the outcome. + let name = format!("HORUS_ENV_FLAG_SELFTEST_{}", std::process::id()); + assert_eq!(env_flag(&name), None, "an unset variable must not decide"); + + // SAFETY: the name embeds this process's pid and is used by nothing + // else, so no other thread can be reading it concurrently. + unsafe { std::env::set_var(&name, "YES") }; + assert_eq!(env_flag(&name), Some(true)); + unsafe { std::env::set_var(&name, "off") }; + assert_eq!(env_flag(&name), Some(false)); + unsafe { std::env::set_var(&name, "banana") }; + assert_eq!(env_flag(&name), None); + unsafe { std::env::remove_var(&name) }; + } +} diff --git a/horus_sys/src/lib.rs b/horus_sys/src/lib.rs index ced8779dd..bef5b96d3 100644 --- a/horus_sys/src/lib.rs +++ b/horus_sys/src/lib.rs @@ -18,6 +18,7 @@ //! | [`device`] | Serial port and video device enumeration | //! | [`platform`] | OS/distro detection, directories, shell, package manager | //! | [`sync`] | Environment synchronization (toolchains, system deps) | +//! | [`mod@env`] | One vocabulary for boolean `HORUS_*` environment variables | //! //! ## Platform Support //! @@ -28,6 +29,7 @@ pub mod device; pub mod discover; +pub mod env; pub mod fs; pub mod platform; pub mod process;