Repository navigation
refactor(render): split RenderOptions into common + per-renderer specific structs - #147
Conversation
…ific structs
Mirrors the fetcher pattern (`FetchContext.options: Option<toml::Value>` → typed
per-fetcher struct) on the renderer side. `RenderOptions` keeps the cross-cutting
fields used by ≥2 renderers across families (`align`, `style`, `color`, `label`,
`padding`, `bullet`, `max_items`, `tone`, `value_format`, `duration_ms`, `axes`)
and collects everything else into a flatten'd `raw: toml::Table`. Each renderer
now declares its own `Options { #[serde(deny_unknown_fields)] }` and reads it via
`opts.parse_specific::<Options>()`, so renderer-specific knobs live next to the
code that consumes them instead of bloating the central bag.
Adds `with_extra` / `without_extra` builder helpers for tests and animation
wrappers that need to forward a modified options bag, plus thin `extra_str` /
`extra_string_array` accessors used by xtask preview helpers that don't pull in
serde directly.
Migrates every existing renderer (text_ascii / chart_* / gauge_* / grid_* /
list_timeline / status_badge / media_image / animated_*) and the preview /
snapshot helpers in `install` and `xtask`.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
📝 WalkthroughWalkthrough
Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #147 +/- ##
==========================================
+ Coverage 79.29% 79.32% +0.02%
==========================================
Files 98 98
Lines 18478 18552 +74
==========================================
+ Hits 14652 14716 +64
- Misses 3826 3836 +10
🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (6)
src/render/grid_table.rs (1)
84-90: Minor: parameter-type asymmetry betweenrender_rowsandrender_inline.
render_rowsnow takes&Optionswhilerender_inlinestill takes&RenderOptions(only to read the commonalign). It works, but it makes the dispatch inrender(lines 84-89) read inconsistently. Either pass bothoptsand&specificto both helpers, or just pass&RenderOptionseverywhere and let each helper callparse_specificitself when it needs renderer-specific keys. Not blocking.♻️ Optional unification
if let Body::Entries(d) = body { let specific: Options = opts.parse_specific(); match specific.layout.as_deref() { - Some("inline") => render_inline(frame, area, d, opts, theme), - _ => render_rows(frame, area, d, &specific, theme), + Some("inline") => render_inline(frame, area, d, opts, theme), + _ => render_rows(frame, area, d, &specific, theme), } }(Or equivalently, pass
opts.align.as_deref()throughOptionsand drop the&RenderOptionsarg fromrender_inline.)Also applies to: 109-115
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/render/grid_table.rs` around lines 84 - 90, The dispatch in render uses mixed parameter types—render_rows(&Options) vs render_inline(&RenderOptions)—which is inconsistent; update the helper signatures so both accept the same type: either change render_inline to take &Options (the parsed specific) or change render_rows to take &RenderOptions and let each helper call parse_specific() as needed; adjust all call sites (including the other occurrences around lines 109-115) and update parameter names in render_inline, render_rows, and any internal uses of align or specific fields (Options, RenderOptions, parse_specific, render_inline, render_rows, render) to match the unified signature.src/render/chart_bar.rs (1)
14-28: LGTM — the per-renderer split is clean.
max_bars,horizontal, andbar_widthmove into the localOptions, andstackedis correctly carved out as a forward-compat reservation (with#[allow(dead_code)]plus an inline rationale). One small note: existing tests covermax_barsviacapped_bars(...)directly but never exercise the option going throughparse_specific()end-to-end. If you want a tiny safety net for the new wiring, a test that driveshorizontal = trueormax_bars = 2through aRenderSpec::Fullwould catch a future regression where the keys silently fall back toDefault.Also applies to: 100-109
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/render/chart_bar.rs` around lines 14 - 28, Tests don't exercise the new per-renderer Options being parsed from a RenderSpec end-to-end; add a small unit/integration test that constructs a RenderSpec::Full containing the options keys (e.g., "horizontal": true and "max_bars": 2 or "bar_width": N) and calls parse_specific() to ensure the produced Options struct (and downstream behavior) reflects those values rather than defaults. Locate the parsing path that produces Options (the Options struct in chart_bar.rs and the parse_specific() call site) and assert that Options.horizontal, Options.max_bars, and Options.bar_width are set as expected when parsed through RenderSpec::Full so future regressions are caught.src/render/media_image.rs (1)
102-118: Optional: parseOptionsonce and thread it through.
compute_targetandrender_imageboth callopts.parse_specific()for the same(fit, max_width, max_height)triple per draw. Mirroring thetext_asciichange (parse once inrender, pass&Optionsto helpers) would avoid the double decode and keep the two read sites in sync ifOptionsgrows.♻️ Sketch
-fn render_image_payload( - frame: &mut Frame, - area: Rect, - data: &ImageData, - opts: &RenderOptions, - theme: &Theme, -) { - let target = compute_target(area, opts); - match render_image(frame, target, &data.path, opts) { +fn render_image_payload( + frame: &mut Frame, + area: Rect, + data: &ImageData, + opts: &RenderOptions, + theme: &Theme, +) { + let specific: Options = opts.parse_specific(); + let target = compute_target(area, opts, &specific); + match render_image(frame, target, &data.path, &specific) {Also applies to: 130-138
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/render/media_image.rs` around lines 102 - 118, compute_target and render_image both call opts.parse_specific(), causing duplicate parsing; parse the specific Options once in the caller (e.g., in render before calling compute_target and render_image), store it in a local variable (Options) and pass a reference (&Options) into compute_target and render_image instead of calling parse_specific() inside them; update function signatures to accept the &Options reference where needed (compute_target(..., opts: &RenderOptions, specific: &Options) or compute_target(..., specific: &Options)) and remove the internal parse_specific() calls in render_image and the other helper (also adjust the second site mentioned around the 130-138 region), ensuring all uses reference the single parsed Options instance.src/install/preview.rs (1)
264-284: Use the newextra_str/extra_string_arrayaccessors instead of ad-hocWrapperstructs.
xtask/src/dashboard_snapshot.rsdoes the exact same lookup againstopts.extra_str("inner")andopts.extra_string_array("font_sequence")— the helpers were added in this PR for precisely this peek-one-key use case. Aligning here removes the duplicatedWrapperboilerplate and also avoids theparse_specific+deny_unknown_fieldscascade (an unknown key inrawwould currently make theseWrappers parse-fail and silently dropinner/font_sequence).♻️ Proposed simplification
-/// Pull the wrapper renderer's `inner` field out of the raw extras blob, falling back to -/// `text_plain` so previews always have a concrete renderer to delegate to. -fn inner_renderer_name(opts: &RenderOptions) -> String { - #[derive(serde::Deserialize, Default)] - struct Wrapper { - #[serde(default)] - inner: Option<String>, - } - let parsed: Wrapper = opts.parse_specific(); - parsed.inner.unwrap_or_else(|| "text_plain".into()) -} - -fn font_sequence(opts: &RenderOptions) -> Option<Vec<String>> { - #[derive(serde::Deserialize, Default)] - struct Wrapper { - #[serde(default)] - font_sequence: Option<Vec<String>>, - } - let parsed: Wrapper = opts.parse_specific(); - parsed.font_sequence -} +/// Pull the wrapper renderer's `inner` field out of the raw extras blob, falling back to +/// `text_plain` so previews always have a concrete renderer to delegate to. +fn inner_renderer_name(opts: &RenderOptions) -> String { + opts.extra_str("inner") + .map(String::from) + .unwrap_or_else(|| "text_plain".into()) +} + +fn font_sequence(opts: &RenderOptions) -> Option<Vec<String>> { + opts.extra_string_array("font_sequence") +}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/install/preview.rs` around lines 264 - 284, Replace the ad-hoc serde Wrapper parsing in inner_renderer_name and font_sequence with the new RenderOptions accessors: call opts.extra_str("inner") and use its Some value or default to "text_plain" for inner_renderer_name, and call opts.extra_string_array("font_sequence") to return the Option<Vec<String>> for font_sequence; this removes the Wrapper structs and avoids parse_specific/deny_unknown_fields behavior while preserving the same return semantics.src/render/animated_wave.rs (1)
183-192: Fragile:inner_optionsstrips keys that belong to other wrappers.
effectisanimated_postfx,boot_linesisanimated_boot,font_sequenceisanimated_figlet_morph. Each animated wrapper now has to know about every other wrapper's keys so the inner renderer'sparse_specific(which usesdeny_unknown_fields) doesn't reject them and silently drop its own config. Every new wrapper key will require an edit here and in every sibling wrapper.Two cleaner options worth considering:
- Centralize: a single
WRAPPER_KEYS: &[&str]constant (orRenderOptions::without_wrapper_extras()helper) that every wrapper can call.- Or: relax the inner renderers'
Optionsto not usedeny_unknown_fields, since unknown keys can legitimately come from outer wrappers.Either avoids the "every wrapper must enumerate every other wrapper's keys" coupling.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/render/animated_wave.rs` around lines 183 - 192, The current inner_options function in animated_wave.rs enumerates other wrappers' keys (effect, boot_lines, font_sequence) which is fragile; instead add a centralized list or helper and use that here: create a single WRAPPER_KEYS constant (or implement RenderOptions::without_wrapper_extras(&self)) that contains all wrapper-specific keys, and change inner_options to clone opts and call the new helper (e.g., opts.clone().without_extras(&WRAPPER_KEYS) or opts.clone().without_wrapper_extras()) so wrappers no longer need to know each other's keys and new wrapper keys only require updating the single central list/helper.src/render/mod.rs (1)
173-184: Considerpub(crate)or a typed builder instead ofpubforraw.The doc-comment instructs callers to go through
with_extra/without_extra, butpub raw: toml::Tablelets any downstream insert/remove arbitrary entries and bypass that contract. The justification ("pubso functional-record-update compiles in tests and thextaskcrate") is real, but it could also be served by:
pub(crate)plus a re-export shim ifxtaskactually needs it (the newextra_str/extra_string_arrayalready cover the snapshot's read needs), or- Keeping it
pubbut adding#[doc(hidden)]so it doesn't appear in the public API surface.Not blocking — flagging in case the long-term plan is to keep these helpers as the only mutation path.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/render/mod.rs` around lines 173 - 184, The field RenderOptions::raw is public but callers should use with_extra/without_extra; change its visibility to pub(crate) to prevent downstream mutation (update any xtask consumers by adding a crate-level re-export/shim if needed), or if you must keep it public for tests/xtask, annotate it with #[doc(hidden)] and keep the existing extra_str/extra_string_array helpers for snapshot reads; ensure code references to raw in tests or xtask are adjusted to use the shim or remain accessible via the intended visibility.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/render/animated_postfx.rs`:
- Around line 386-393: The test is vacuous because parse_specific::<Options>()
returns Default when unknown fields exist; instead assert against the raw blob
to ensure stripping happened: after calling the helper (e.g.
without_extra/inner_options) check inner.raw (the raw JSON/string map) does not
contain the keys "inner" and "effect" (and/or their serialized forms) and still
contains the renderer-specific key "pixel_size" so parsed_text.pixel_size
remains "quadrant"; keep the existing parse_specific checks for parsed_text but
replace or add assertions that directly inspect inner.raw to confirm "inner" and
"effect" were removed.
In `@src/render/animated_scanlines.rs`:
- Around line 183-192: The helper logic that strips wrapper-specific extra keys
is duplicated across inner_options in multiple files; create a single helper on
RenderOptions (e.g. pub(crate) fn strip_wrapper_extras(self) -> Self) that
iterates a single const slice (e.g. WRAPPER_EXTRA_KEYS =
&["inner","effect","boot_lines","font_sequence"]) and calls without_extra for
each key, then replace each inner_options implementation to call
RenderOptions::strip_wrapper_extras(); update wrappers that call
parse_specific() to use the centralized helper so the list of keys lives in one
place.
- Around line 211-223: The test inner_options_strips_wrapper_fields only sets
the "inner" extra, so it doesn't verify that "effect", "boot_lines", and
"font_sequence" are stripped; update the test to pre-populate all four extras
(e.g., call
RenderOptions::default().with_extra("inner","text_ascii").with_extra("effect","...").with_extra("boot_lines","...").with_extra("font_sequence","..."))
and then assert that inner_options(&opts).parse_specific() has
parsed.inner.is_none() and that the Options returned by inner_options has
duration_ms None and style preserved and, crucially, that effect, boot_lines,
and font_sequence are also removed; alternatively replace the body with a call
to the shared helper strip_wrapper_extras that pre-populates and asserts removal
for all four keys so the test fails if the strip list drifts.
In `@src/render/gauge_circle.rs`:
- Around line 9-20: The current parse_specific flow hides serde errors by using
unwrap_or_default in parse_specific (called from src/render/mod.rs) so
#[serde(deny_unknown_fields)] on types like Options in gauge_circle.rs and
grid_calendar.rs is effectively ignored; update parse_specific to return
Result<T, serde_yaml::Error> (or a suitable Error) instead of unwrapping to
default, and change callers (renderers that call parse_specific) to handle Err
by returning/producing an in-band error string for the renderer; alternatively,
if you prefer to accept silent defaults, remove #[serde(deny_unknown_fields)]
and the misleading comments in gauge_circle.rs and grid_calendar.rs—pick one
approach and make consistent changes to parse_specific and all call sites (and
adjust function signatures) accordingly.
In `@src/render/mod.rs`:
- Around line 192-199: The parse_specific function currently swallows
deserialization errors via .unwrap_or_default(), which causes wrapper renderer
Options (e.g., animated_postfx::Options and other wrapper renderers using
deny_unknown_fields) to silently drop inner fields; replace the
.unwrap_or_default() call in parse_specific with explicit error handling: match
the toml::Value::Table(self.raw.clone()).try_into() result, and on Err(e) log a
clear warning including the error message and the offending self.raw (so
typos/unknown keys are visible) and then return T::default(); on Ok(v) return v.
This makes deserialization failures observable while preserving the existing
fallback behavior.
---
Nitpick comments:
In `@src/install/preview.rs`:
- Around line 264-284: Replace the ad-hoc serde Wrapper parsing in
inner_renderer_name and font_sequence with the new RenderOptions accessors: call
opts.extra_str("inner") and use its Some value or default to "text_plain" for
inner_renderer_name, and call opts.extra_string_array("font_sequence") to return
the Option<Vec<String>> for font_sequence; this removes the Wrapper structs and
avoids parse_specific/deny_unknown_fields behavior while preserving the same
return semantics.
In `@src/render/animated_wave.rs`:
- Around line 183-192: The current inner_options function in animated_wave.rs
enumerates other wrappers' keys (effect, boot_lines, font_sequence) which is
fragile; instead add a centralized list or helper and use that here: create a
single WRAPPER_KEYS constant (or implement
RenderOptions::without_wrapper_extras(&self)) that contains all wrapper-specific
keys, and change inner_options to clone opts and call the new helper (e.g.,
opts.clone().without_extras(&WRAPPER_KEYS) or
opts.clone().without_wrapper_extras()) so wrappers no longer need to know each
other's keys and new wrapper keys only require updating the single central
list/helper.
In `@src/render/chart_bar.rs`:
- Around line 14-28: Tests don't exercise the new per-renderer Options being
parsed from a RenderSpec end-to-end; add a small unit/integration test that
constructs a RenderSpec::Full containing the options keys (e.g., "horizontal":
true and "max_bars": 2 or "bar_width": N) and calls parse_specific() to ensure
the produced Options struct (and downstream behavior) reflects those values
rather than defaults. Locate the parsing path that produces Options (the Options
struct in chart_bar.rs and the parse_specific() call site) and assert that
Options.horizontal, Options.max_bars, and Options.bar_width are set as expected
when parsed through RenderSpec::Full so future regressions are caught.
In `@src/render/grid_table.rs`:
- Around line 84-90: The dispatch in render uses mixed parameter
types—render_rows(&Options) vs render_inline(&RenderOptions)—which is
inconsistent; update the helper signatures so both accept the same type: either
change render_inline to take &Options (the parsed specific) or change
render_rows to take &RenderOptions and let each helper call parse_specific() as
needed; adjust all call sites (including the other occurrences around lines
109-115) and update parameter names in render_inline, render_rows, and any
internal uses of align or specific fields (Options, RenderOptions,
parse_specific, render_inline, render_rows, render) to match the unified
signature.
In `@src/render/media_image.rs`:
- Around line 102-118: compute_target and render_image both call
opts.parse_specific(), causing duplicate parsing; parse the specific Options
once in the caller (e.g., in render before calling compute_target and
render_image), store it in a local variable (Options) and pass a reference
(&Options) into compute_target and render_image instead of calling
parse_specific() inside them; update function signatures to accept the &Options
reference where needed (compute_target(..., opts: &RenderOptions, specific:
&Options) or compute_target(..., specific: &Options)) and remove the internal
parse_specific() calls in render_image and the other helper (also adjust the
second site mentioned around the 130-138 region), ensuring all uses reference
the single parsed Options instance.
In `@src/render/mod.rs`:
- Around line 173-184: The field RenderOptions::raw is public but callers should
use with_extra/without_extra; change its visibility to pub(crate) to prevent
downstream mutation (update any xtask consumers by adding a crate-level
re-export/shim if needed), or if you must keep it public for tests/xtask,
annotate it with #[doc(hidden)] and keep the existing
extra_str/extra_string_array helpers for snapshot reads; ensure code references
to raw in tests or xtask are adjusted to use the shim or remain accessible via
the intended visibility.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 066bbeb1-0896-424f-9e64-ae010220bbef
📒 Files selected for processing (22)
src/install/preview.rssrc/render/animated_boot.rssrc/render/animated_figlet_morph.rssrc/render/animated_postfx.rssrc/render/animated_scanlines.rssrc/render/animated_splitflap.rssrc/render/animated_wave.rssrc/render/chart_bar.rssrc/render/chart_histogram.rssrc/render/chart_pie.rssrc/render/chart_scatter.rssrc/render/gauge_circle.rssrc/render/gauge_segment.rssrc/render/grid_calendar.rssrc/render/grid_heatmap.rssrc/render/grid_table.rssrc/render/list_timeline.rssrc/render/media_image.rssrc/render/mod.rssrc/render/status_badge.rssrc/render/text_ascii.rsxtask/src/dashboard_snapshot.rs
| // postfx-specific keys are stripped from the forwarded raw blob… | ||
| let parsed_inner: Options = inner.parse_specific(); | ||
| assert!(parsed_inner.inner.is_none()); | ||
| assert!(parsed_inner.effect.is_none()); | ||
| // …but the inner renderer still sees its own keys (e.g. text_ascii's pixel_size). | ||
| let parsed_text: crate::render::text_ascii::Options = inner.parse_specific(); | ||
| assert_eq!(parsed_text.pixel_size.as_deref(), Some("quadrant")); | ||
| assert!(inner.duration_ms.is_none()); |
There was a problem hiding this comment.
This test passes vacuously — it doesn't actually verify the inner/effect stripping.
After inner_options, inner.raw still contains pixel_size (a key unknown to animated_postfx::Options). Because Options uses deny_unknown_fields, parse_specific::<Options>() returns Default regardless of whether inner / effect were stripped — so parsed_inner.inner.is_none() and parsed_inner.effect.is_none() would hold even if without_extra was a no-op.
Verify the stripping directly against raw so the test fails if the helper regresses:
🧪 Proposed assertion
let inner = inner_options(&opts);
assert_eq!(inner.style.as_deref(), Some("figlet"));
assert_eq!(inner.align.as_deref(), Some("center"));
- // postfx-specific keys are stripped from the forwarded raw blob…
- let parsed_inner: Options = inner.parse_specific();
- assert!(parsed_inner.inner.is_none());
- assert!(parsed_inner.effect.is_none());
+ // postfx-specific keys are stripped from the forwarded raw blob…
+ assert!(inner.extra_str("inner").is_none());
+ assert!(inner.extra_str("effect").is_none());
// …but the inner renderer still sees its own keys (e.g. text_ascii's pixel_size).
let parsed_text: crate::render::text_ascii::Options = inner.parse_specific();
assert_eq!(parsed_text.pixel_size.as_deref(), Some("quadrant"));
assert!(inner.duration_ms.is_none());🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/render/animated_postfx.rs` around lines 386 - 393, The test is vacuous
because parse_specific::<Options>() returns Default when unknown fields exist;
instead assert against the raw blob to ensure stripping happened: after calling
the helper (e.g. without_extra/inner_options) check inner.raw (the raw
JSON/string map) does not contain the keys "inner" and "effect" (and/or their
serialized forms) and still contains the renderer-specific key "pixel_size" so
parsed_text.pixel_size remains "quadrant"; keep the existing parse_specific
checks for parsed_text but replace or add assertions that directly inspect
inner.raw to confirm "inner" and "effect" were removed.
| fn inner_options(opts: &RenderOptions) -> RenderOptions { | ||
| RenderOptions { | ||
| inner: None, | ||
| effect: None, | ||
| duration_ms: None, | ||
| boot_lines: None, | ||
| font_sequence: None, | ||
| ..opts.clone() | ||
| } | ||
| .without_extra("inner") | ||
| .without_extra("effect") | ||
| .without_extra("boot_lines") | ||
| .without_extra("font_sequence") | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
Centralize the wrapper-extras strip — root cause for several files.
The inner_options body is duplicated verbatim across animated_scanlines.rs, animated_splitflap.rs (lines 194-203), animated_boot.rs (lines 212-221), and per the PR description also in animated_postfx.rs / animated_wave.rs. The list of stripped keys ("inner", "effect", "boot_lines", "font_sequence") has to stay in lockstep with every wrapper's Options schema — and because each inner renderer uses #[serde(deny_unknown_fields)], a missed key here causes the inner parse_specific() to silently fall back to defaults (no surfaced error). That's the exact failure mode this set of strips is supposed to prevent, and it currently has five copies to keep in sync.
Extract a single helper — e.g. RenderOptions::strip_wrapper_extras(self) -> Self on the type, or a super::wrapper::inner_options(opts) free function — and have every wrapper delegate. The list of wrapper keys then lives in one place and gains a single point of test coverage.
♻️ Sketch (apply once, then call from all five wrappers)
// In src/render/mod.rs (or src/render/wrapper.rs):
pub(crate) const WRAPPER_EXTRA_KEYS: &[&str] =
&["inner", "effect", "boot_lines", "font_sequence"];
impl RenderOptions {
pub(crate) fn strip_wrapper_extras(mut self) -> Self {
for k in WRAPPER_EXTRA_KEYS {
self = self.without_extra(k);
}
self
}
} fn inner_options(opts: &RenderOptions) -> RenderOptions {
RenderOptions {
duration_ms: None,
..opts.clone()
}
- .without_extra("inner")
- .without_extra("effect")
- .without_extra("boot_lines")
- .without_extra("font_sequence")
+ .strip_wrapper_extras()
}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/render/animated_scanlines.rs` around lines 183 - 192, The helper logic
that strips wrapper-specific extra keys is duplicated across inner_options in
multiple files; create a single helper on RenderOptions (e.g. pub(crate) fn
strip_wrapper_extras(self) -> Self) that iterates a single const slice (e.g.
WRAPPER_EXTRA_KEYS = &["inner","effect","boot_lines","font_sequence"]) and calls
without_extra for each key, then replace each inner_options implementation to
call RenderOptions::strip_wrapper_extras(); update wrappers that call
parse_specific() to use the centralized helper so the list of keys lives in one
place.
| fn inner_options_strips_wrapper_fields() { | ||
| let opts = RenderOptions { | ||
| inner: Some("text_ascii".into()), | ||
| duration_ms: Some(1500), | ||
| style: Some("figlet".into()), | ||
| ..RenderOptions::default() | ||
| }; | ||
| } | ||
| .with_extra("inner", "text_ascii"); | ||
| let inner = inner_options(&opts); | ||
| assert!(inner.inner.is_none()); | ||
| let parsed: Options = inner.parse_specific(); | ||
| assert!(parsed.inner.is_none()); | ||
| assert!(inner.duration_ms.is_none()); | ||
| assert_eq!(inner.style.as_deref(), Some("figlet")); | ||
| } |
There was a problem hiding this comment.
Test only covers stripping of inner — the other three keys are vacuously asserted.
The opts under test only has inner set via with_extra, so the test never demonstrates that effect, boot_lines, or font_sequence are actually removed. If the strip list ever drifts (e.g., someone removes .without_extra("effect")), this test still passes.
If you adopt the shared strip_wrapper_extras helper from the previous comment, this becomes a single test against the helper that pre-populates all four keys via with_extra and asserts each is gone. Otherwise, extend this test in place to inject all four.
♻️ Inline-fix variant
let opts = RenderOptions {
duration_ms: Some(1500),
style: Some("figlet".into()),
..RenderOptions::default()
}
- .with_extra("inner", "text_ascii");
+ .with_extra("inner", "text_ascii")
+ .with_extra("effect", "fade_in")
+ .with_extra("boot_lines", vec!["a".to_string()])
+ .with_extra("font_sequence", vec!["small".to_string()]);
let inner = inner_options(&opts);
- let parsed: Options = inner.parse_specific();
- assert!(parsed.inner.is_none());
+ let parsed: Options = inner.parse_specific();
+ assert!(parsed.inner.is_none());
+ assert!(inner.extra_str("effect").is_none());
+ assert!(inner.extra_string_array("boot_lines").is_none());
+ assert!(inner.extra_string_array("font_sequence").is_none());
assert!(inner.duration_ms.is_none());
assert_eq!(inner.style.as_deref(), Some("figlet"));🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/render/animated_scanlines.rs` around lines 211 - 223, The test
inner_options_strips_wrapper_fields only sets the "inner" extra, so it doesn't
verify that "effect", "boot_lines", and "font_sequence" are stripped; update the
test to pre-populate all four extras (e.g., call
RenderOptions::default().with_extra("inner","text_ascii").with_extra("effect","...").with_extra("boot_lines","...").with_extra("font_sequence","..."))
and then assert that inner_options(&opts).parse_specific() has
parsed.inner.is_none() and that the Options returned by inner_options has
duration_ms None and style preserved and, crucially, that effect, boot_lines,
and font_sequence are also removed; alternatively replace the body with a call
to the shared helper strip_wrapper_extras that pre-populates and asserts removal
for all four keys so the test fails if the strip list drifts.
| /// Reserved forward-compat fields. ratatui's current Gauge widget is a single full-height | ||
| /// bar so neither field has a visible effect yet; declared here for `deny_unknown_fields` | ||
| /// parity with the documented schema. | ||
| #[derive(Debug, Clone, Default, serde::Deserialize)] | ||
| #[serde(deny_unknown_fields)] | ||
| #[allow(dead_code)] | ||
| struct Options { | ||
| #[serde(default)] | ||
| pub ring_thickness: Option<u16>, | ||
| #[serde(default)] | ||
| pub label_position: Option<String>, | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Inspect parse_specific's signature and body to confirm error handling.
fd -e rs | xargs rg -nP -C5 'fn\s+parse_specific\b'
echo '---'
# And the with_extra builder (used in list_timeline tests)
fd -e rs | xargs rg -nP -C3 'fn\s+with_extra\b|fn\s+without_extra\b'
echo '---'
# Sanity check: any existing test that exercises an unknown key against parse_specific?
rg -nP 'parse_specific|deny_unknown_fields' --type=rs -C2Repository: unhappychoice/splashboard
Length of output: 2000
🏁 Script executed:
# Get complete parse_specific implementation and surrounding context
sed -n '185,205p' src/render/mod.rsRepository: unhappychoice/splashboard
Length of output: 1164
🏁 Script executed:
# Search for tests that exercise parse_specific with invalid keys
rg 'parse_specific' src/ -A 3 -B 1 --type rustRepository: unhappychoice/splashboard
Length of output: 14334
🏁 Script executed:
# Check if deny_unknown_fields is actually tested anywhere
rg 'deny_unknown_fields|unknown.*key|bogus' src/ --type rust -C 2Repository: unhappychoice/splashboard
Length of output: 19620
🏁 Script executed:
# Check gauge_circle.rs and grid_calendar.rs to see how Options is used
echo "=== gauge_circle.rs ===" && sed -n '1,100p' src/render/gauge_circle.rs | head -60
echo "=== grid_calendar.rs ===" && sed -n '1,50p' src/render/grid_calendar.rs 2>/dev/null || echo "File not found or too large"Repository: unhappychoice/splashboard
Length of output: 3681
parse_specific() silently swallows deny_unknown_fields errors—claims about surfacing unknown keys are false.
The implementation at src/render/mod.rs:192-199 calls .unwrap_or_default() on the deserialization result, which means errors from deny_unknown_fields are caught and silently converted to T::default(). The comments in gauge_circle.rs and grid_calendar.rs claiming "unknown keys still fail per deny_unknown_fields" are misleading—the serde attribute triggers, but the error is hidden.
Invalid renderer-specific configs are never surfaced to users; they silently become defaults instead. This violates the learning requirement that unknown values must render an in-band error string.
Either:
- Change
parse_specific()to returnResult<T, Error>and have renderers emit error strings on parse failure, or - Accept that unknown keys are silently ignored and remove the
deny_unknown_fieldsderive (which has no effect) and misleading comments.
Confirm which direction this PR intends.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/render/gauge_circle.rs` around lines 9 - 20, The current parse_specific
flow hides serde errors by using unwrap_or_default in parse_specific (called
from src/render/mod.rs) so #[serde(deny_unknown_fields)] on types like Options
in gauge_circle.rs and grid_calendar.rs is effectively ignored; update
parse_specific to return Result<T, serde_yaml::Error> (or a suitable Error)
instead of unwrapping to default, and change callers (renderers that call
parse_specific) to handle Err by returning/producing an in-band error string for
the renderer; alternatively, if you prefer to accept silent defaults, remove
#[serde(deny_unknown_fields)] and the misleading comments in gauge_circle.rs and
grid_calendar.rs—pick one approach and make consistent changes to parse_specific
and all call sites (and adjust function signatures) accordingly.
| pub fn parse_specific<T: serde::de::DeserializeOwned + Default>(&self) -> T { | ||
| if self.raw.is_empty() { | ||
| return T::default(); | ||
| } | ||
| toml::Value::Table(self.raw.clone()) | ||
| .try_into() | ||
| .unwrap_or_default() | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Confirm wrapper renderers ship Options with deny_unknown_fields, so the cascade above is reachable.
rg -nP -B1 -A3 'deny_unknown_fields' --type=rust -g 'src/render/animated_*.rs'
# And spot any tests that mix inner-renderer keys on a wrapper's top level today.
rg -nP -B2 -A6 'animated_postfx|animated_wave|animated_boot|animated_figlet_morph' --type=rust -g 'tests/**' -g 'templates/**'Repository: unhappychoice/splashboard
Length of output: 2223
🏁 Script executed:
#!/bin/bash
# Examine parse_specific implementation and surrounding context
sed -n '180,210p' src/render/mod.rs
# Check where parse_specific is called and how raw is populated
rg -n 'parse_specific' --type=rust src/render/
# Look for test cases exercising wrapper renderers with configs
rg -n 'animated_postfx|animated_wave|animated_boot|animated_figlet_morph' --type=rust -A5 -B2Repository: unhappychoice/splashboard
Length of output: 26194
unwrap_or_default() + deny_unknown_fields on wrapper renderer Options silently drops all renderer specifics on an unknown key.
Concrete example: a config like render = { type = "animated_postfx", inner = "text_ascii", effect = "dissolve", pixel_size = "quadrant" } leaves raw = { inner, effect, pixel_size }. animated_postfx::Options uses deny_unknown_fields and doesn't declare pixel_size, so try_into() returns Err, and unwrap_or_default() collapses the struct to inner: None, effect: None. The render path then silently falls back to default_renderer_for(shape) — the user's inner and effect are lost without any diagnostic.
The same trap fires for typos. All wrapper renderers (animated_postfx, animated_wave, animated_boot, animated_boot, animated_scanlines, animated_splitflap, animated_figlet_morph) use deny_unknown_fields, making this reachable whenever a user mixes an unknown key (whether a typo or a key intended for a different renderer) into the top-level options table.
Mitigations to consider:
- Don't use
deny_unknown_fieldson wrapperOptions; they inherently coexist with inner-renderer keys. Leaf renderers can keep it. - Or have wrappers grab their single keys via
extra_str/extra_string_arrayinstead of Options structs. - At minimum, log the deserialize error before
unwrap_or_default()so silent drops are observable:
Proposed observability fix
pub fn parse_specific<T: serde::de::DeserializeOwned + Default>(&self) -> T {
if self.raw.is_empty() {
return T::default();
}
- toml::Value::Table(self.raw.clone())
- .try_into()
- .unwrap_or_default()
+ match toml::Value::Table(self.raw.clone()).try_into() {
+ Ok(v) => v,
+ Err(e) => {
+ tracing::warn!(
+ target: "splashboard::render",
+ error = %e,
+ "renderer-specific options failed to parse; falling back to defaults"
+ );
+ T::default()
+ }
+ }
}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/render/mod.rs` around lines 192 - 199, The parse_specific function
currently swallows deserialization errors via .unwrap_or_default(), which causes
wrapper renderer Options (e.g., animated_postfx::Options and other wrapper
renderers using deny_unknown_fields) to silently drop inner fields; replace the
.unwrap_or_default() call in parse_specific with explicit error handling: match
the toml::Value::Table(self.raw.clone()).try_into() result, and on Err(e) log a
clear warning including the error message and the offending self.raw (so
typos/unknown keys are visible) and then return T::default(); on Ok(v) return v.
This makes deserialization failures observable while preserving the existing
fallback behavior.
Summary
RenderOptionskeeps only the 12 fields used by ≥2 renderers across families (align,style,color,label,padding,bullet,max_items,tone,value_format,duration_ms,axes); the previous 40+ flat-bag fields collapse into a flatten'draw: toml::Table. Each renderer now owns a privateOptions { #[serde(deny_unknown_fields)] }and reads it viaopts.parse_specific::<Options>(), mirroring the fetcher side (FetchContext.options→ per-fetcher struct).with_extra/without_extrabuilder methods for animation wrappers (animated_postfx/animated_boot/animated_scanlines/animated_splitflap/animated_wave) and tests that previously poked private fields via FRU.extra_str/extra_string_arraygive thextaskcrate a serde-free way to peek at single keys without growing a new dependency.text_ascii,chart_bar/histogram/pie/scatter,gauge_circle/segment,grid_calendar/heatmap/table,list_timeline,status_badge,media_image, allanimated_*) plus the preview / snapshot helpers insrc/install/preview.rsandxtask/src/dashboard_snapshot.rs. No behavioural change — typo detection on per-renderer keys now happens via eachOptions::deny_unknown_fieldsinstead of one struct-wide attribute.Test plan
cargo fmt --all -- --checkcargo clippy --all-targets --workspace -- -D warningscargo test --workspace(615 + 12 + 2 passing)cargo run --bin splashboard— sanity-check that an existing dashboard still renders unchanged🤖 Generated with Claude Code
Summary by CodeRabbit