Repository navigation
feat(fetcher): split clock into clock_* sibling fetchers - #51
Conversation
|
Warning Rate limit exceeded
Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 19 minutes and 41 seconds. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (14)
📝 WalkthroughWalkthroughThe PR restructures the clock fetcher from a monolithic module into a modular architecture supporting multiple rendering modes (countdown, timezone display, sunrise/sunset, state badges, ratio gauges, and derived calendar values). A new Changes
Sequence DiagramsequenceDiagram
participant Widget as Widget Config
participant Runtime as Runtime
participant Fetcher as ClockFetcher
participant Options as Options Parser
participant Renderer as Mode Renderer<br/>(countdown/derived/ratio/etc)
participant Output as Body Output
Widget->>Runtime: fetch with options
Runtime->>Fetcher: compute(FetchContext{options})
Fetcher->>Options: parse(ctx.options)
alt Valid Options
Options->>Fetcher: Options{mode, timezone, ...}
Fetcher->>Fetcher: validate_shape(mode, shape)
alt Shape Valid
Fetcher->>Renderer: dispatch to mode-specific renderer
Renderer->>Renderer: compute current time (timezone-aware)
Renderer->>Output: generate Body::Lines/Entries/Ratio/Badge/Calendar
else Shape Invalid
Fetcher->>Output: fallback placeholder body
end
else Parse Error
Fetcher->>Output: fallback placeholder body with error hint
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 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 |
There was a problem hiding this comment.
Actionable comments posted: 5
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/fetcher/mod.rs (1)
122-128:⚠️ Potential issue | 🟡 Minor
default_cache_keyignoresctx.options— latent cache-coherency hazard once a cached fetcher starts using options.Clock is a
RealtimeFetcherso it's safe today, butFetchContext.optionsis exposed to all fetchers includingCached(_). The moment a cached fetcher keys its output offoptions(e.g. a futureread_storefilter, or a network fetcher with URL-via-options), two widgets differing only in[widget.options]will share a cache file and stomp each other's payloads.Either mix a stable serialization of
optionsinto the default key now, or leave a guard so cached fetchers that use options must overridecache_key. Worth a short note either way.🔧 Possible fix
pub fn default_cache_key(name: &str, ctx: &FetchContext) -> String { use sha2::{Digest, Sha256}; - let raw = format!("{}|{}", name, ctx.format.as_deref().unwrap_or("")); + let opts = ctx + .options + .as_ref() + .map(|v| v.to_string()) + .unwrap_or_default(); + let raw = format!("{}|{}|{}", name, ctx.format.as_deref().unwrap_or(""), opts); let digest = Sha256::digest(raw.as_bytes()); let hex: String = digest.iter().take(8).map(|b| format!("{b:02x}")).collect(); format!("{name}-{hex}") }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/fetcher/mod.rs` around lines 122 - 128, The default_cache_key implementation for default_cache_key(name: &str, ctx: &FetchContext) currently ignores ctx.options; update it to incorporate a stable serialization of ctx.options into the cache key (or reject use of the default when options is non-empty). Specifically, when building the raw string, include a deterministic representation of ctx.options (e.g., canonical JSON with sorted keys or a sorted key-value join) so that two FetchContext instances that differ only by options produce different keys; alternatively, add a guard in default_cache_key to panic or return a distinct marker when ctx.options is non-empty and document that fetchers using options must implement their own cache_key. Ensure you modify only default_cache_key and reference ctx.options and ctx.format in the new key composition.
♻️ Duplicate comments (1)
src/config.rs (1)
48-52:⚠️ Potential issue | 🟡 MinorSame doc/behavior mismatch as
FetchContext.options."Unknown keys are ignored so upgrading the fetcher never invalidates old configs" overstates the guarantee — clock's options use
deny_unknown_fields, so typos there fail parsing. Align with whatever wording you land on forsrc/fetcher/mod.rsLines 56–58.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/config.rs` around lines 48 - 52, Update the doc comment for the options field to remove the absolute guarantee that "unknown keys are ignored so upgrading the fetcher never invalidates old configs" and instead mirror the wording used for FetchContext.options in fetcher/mod.rs (lines ~56–58); specifically, explain that options are provided as a TOML sub-table (`[widget.options]`) and while the top-level behavior treats unknown keys as ignored for toml::Value, specific fetcher option structs may use deny_unknown_fields and thus can still reject unknown keys—adjust the comment on the `options` field (pub options: Option<toml::Value>) to reflect this nuance.
🧹 Nitpick comments (1)
src/fetcher/clock/ratio.rs (1)
48-57: Dead fallback inmonth_fraction:from_ymd_opt(year, month, 1)can't fail for a month fromnow.month().
chrono::Datelike::month()is always in1..=12, and day 1 is always valid for every month, so theunwrap_or_else(|| from_ymd_opt(year, 1, 1)…)branch is unreachable. Same idea could simplifynext_month_start's trailingunwrap_or_else(Lines 88). A plain.expect("month 1..=12 with day 1 is always valid")(or.unwrap(), consistent withquarter_fraction/year_fraction) documents the invariant without the phantom recovery path.♻️ Suggested simplification
- let month_start = NaiveDate::from_ymd_opt(now.year(), now.month(), 1).unwrap_or_else(|| { - NaiveDate::from_ymd_opt(now.year(), 1, 1).expect("year start always valid") - }); + let month_start = NaiveDate::from_ymd_opt(now.year(), now.month(), 1) + .expect("month 1..=12 with day 1 is always valid");🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/fetcher/clock/ratio.rs` around lines 48 - 57, The fallback in month_fraction is unreachable because DateTime::month() returns 1..=12 and day 1 is always valid; replace the unwrap_or_else(...) used on NaiveDate::from_ymd_opt(now.year(), now.month(), 1) with a direct expect (or unwrap) documenting the invariant (e.g., expect("month 1..=12 with day 1 is always valid")), and apply the same simplification to the similar unwrap_or_else in next_month_start so code matches the style used in quarter_fraction/year_fraction.
🤖 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/fetcher/clock/derived.rs`:
- Around line 139-146: The code initializes current to the hardcoded "小寒",
causing Jan 1–5 to incorrectly show 小寒; change the logic in the jp_season (or
the function containing let (m, d) = (now.month(), now.day())) so that instead
of defaulting to "小寒" you set current to the last entry in TERMS (the previous
year's final term) or explicitly check if (m,d) is before the first TERMS
boundary and then assign current = TERMS.last().name; then proceed with the
existing loop over TERMS to overwrite when appropriate. Ensure you reference
TERMS and the local current variable when making the change.
In `@src/fetcher/clock/options.rs`:
- Around line 56-60: Add the serde attribute to reject unknown fields for the
nested struct: annotate the TargetEntry struct (the one with #[derive(Debug,
Clone, Deserialize)]) with #[serde(deny_unknown_fields)] so that deserialization
of TargetEntry rejects any unexpected keys (e.g., extra "typo" fields) instead
of silently ignoring them.
In `@src/fetcher/clock/sunrise.rs`:
- Around line 35-43: The compute function incorrectly applies a single
FixedOffset from opts.timezone_now() to both solar events, which breaks DST
transitions; update compute to convert each UTC event (the up and down values
from solar_events) using the configured timezone (e.g., parse or use the
chrono_tz::Tz from Options) to get zone-aware local DateTimes per event, and
only fall back to using the FixedOffset via to_local when no Tz is available;
adjust calls around solar_events, to_local, and timezone_now/Options so each
event is converted through the timezone-aware path independently.
In `@src/fetcher/clock/timezones.rs`:
- Around line 36-48: The zoned_times() function should capture Utc::now() once
and reuse that instant for every timezone instead of calling Utc::now() inside
resolve() per-iteration; change resolve(name: &str) ->
Option<DateTime<FixedOffset>> to accept the instant (e.g., resolve(name: &str,
instant: DateTime<Utc>)) and have zoned_times() call let now = Utc::now(); then
map each timezone to (name.clone(), resolve(name, now)); ensure resolve projects
the provided instant into the zone with with_timezone(&tz).fixed_offset(), and
update any tests to pass the captured instant accordingly to keep the realtime
path infallible and fast.
In `@src/fetcher/mod.rs`:
- Around line 56-58: The field `pub options: Option<toml::Value>` in
src/fetcher/mod.rs currently has a doc comment claiming "unknown keys are
ignored", but concrete consumers like the clock `Options` in
src/fetcher/clock/options.rs use `#[serde(deny_unknown_fields)]` so unknown keys
are rejected; update the doc for `options` to remove the incorrect "ignored"
claim and instead state that each fetcher decides strict vs lenient
deserialization (or explicitly note that some fetchers may deny unknown fields),
and make the same corresponding wording change in the similar note in
src/config.rs so docs match actual behavior and callers like the clock `Options`
using `deny_unknown_fields` are accurately described.
---
Outside diff comments:
In `@src/fetcher/mod.rs`:
- Around line 122-128: The default_cache_key implementation for
default_cache_key(name: &str, ctx: &FetchContext) currently ignores ctx.options;
update it to incorporate a stable serialization of ctx.options into the cache
key (or reject use of the default when options is non-empty). Specifically, when
building the raw string, include a deterministic representation of ctx.options
(e.g., canonical JSON with sorted keys or a sorted key-value join) so that two
FetchContext instances that differ only by options produce different keys;
alternatively, add a guard in default_cache_key to panic or return a distinct
marker when ctx.options is non-empty and document that fetchers using options
must implement their own cache_key. Ensure you modify only default_cache_key and
reference ctx.options and ctx.format in the new key composition.
---
Duplicate comments:
In `@src/config.rs`:
- Around line 48-52: Update the doc comment for the options field to remove the
absolute guarantee that "unknown keys are ignored so upgrading the fetcher never
invalidates old configs" and instead mirror the wording used for
FetchContext.options in fetcher/mod.rs (lines ~56–58); specifically, explain
that options are provided as a TOML sub-table (`[widget.options]`) and while the
top-level behavior treats unknown keys as ignored for toml::Value, specific
fetcher option structs may use deny_unknown_fields and thus can still reject
unknown keys—adjust the comment on the `options` field (pub options:
Option<toml::Value>) to reflect this nuance.
---
Nitpick comments:
In `@src/fetcher/clock/ratio.rs`:
- Around line 48-57: The fallback in month_fraction is unreachable because
DateTime::month() returns 1..=12 and day 1 is always valid; replace the
unwrap_or_else(...) used on NaiveDate::from_ymd_opt(now.year(), now.month(), 1)
with a direct expect (or unwrap) documenting the invariant (e.g., expect("month
1..=12 with day 1 is always valid")), and apply the same simplification to the
similar unwrap_or_else in next_month_start so code matches the style used in
quarter_fraction/year_fraction.
🪄 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: c7ac2c49-f58f-4c58-a6d6-78ab57a5e280
⛔ Files ignored due to path filters (1)
Cargo.lockis excluded by!**/*.lock
📒 Files selected for processing (15)
.splashboard/config.tomlCargo.tomlsrc/config.rssrc/fetcher/clock.rssrc/fetcher/clock/countdown.rssrc/fetcher/clock/derived.rssrc/fetcher/clock/format.rssrc/fetcher/clock/mod.rssrc/fetcher/clock/options.rssrc/fetcher/clock/ratio.rssrc/fetcher/clock/state.rssrc/fetcher/clock/sunrise.rssrc/fetcher/clock/timezones.rssrc/fetcher/mod.rssrc/runtime.rs
💤 Files with no reviewable changes (1)
- src/fetcher/clock.rs
| let (m, d) = (now.month(), now.day()); | ||
| let mut current = "小寒"; | ||
| for &(tm, td, name) in TERMS { | ||
| if (m, d) >= (tm, td) { | ||
| current = name; | ||
| } | ||
| } | ||
| current.into() |
There was a problem hiding this comment.
jp_season returns 小寒 for Jan 1–5, but those dates belong to the previous year's 冬至.
The current = "小寒" default only applies when no term boundary has been crossed yet this year, which for early January means the widget shows 小寒 a few days before its actual start (Jan 6). The correct seed for Jan 1–5 is 冬至 (carried over from the previous year's Dec 22 boundary).
The module comment already acknowledges ±1-day drift, so this is minor — flagging because it's a multi-day deviation at a predictable window, not the ±1-day drift advertised.
🔧 Suggested fix
- let (m, d) = (now.month(), now.day());
- let mut current = "小寒";
- for &(tm, td, name) in TERMS {
- if (m, d) >= (tm, td) {
- current = name;
- }
- }
- current.into()
+ let (m, d) = (now.month(), now.day());
+ // Seed with 冬至 so Jan 1–5 (before 小寒 on Jan 6) reports the previous year's last term.
+ let mut current = "冬至";
+ for &(tm, td, name) in TERMS {
+ if (m, d) >= (tm, td) {
+ current = name;
+ }
+ }
+ current.into()📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| let (m, d) = (now.month(), now.day()); | |
| let mut current = "小寒"; | |
| for &(tm, td, name) in TERMS { | |
| if (m, d) >= (tm, td) { | |
| current = name; | |
| } | |
| } | |
| current.into() | |
| let (m, d) = (now.month(), now.day()); | |
| // Seed with 冬至 so Jan 1–5 (before 小寒 on Jan 6) reports the previous year's last term. | |
| let mut current = "冬至"; | |
| for &(tm, td, name) in TERMS { | |
| if (m, d) >= (tm, td) { | |
| current = name; | |
| } | |
| } | |
| current.into() |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/fetcher/clock/derived.rs` around lines 139 - 146, The code initializes
current to the hardcoded "小寒", causing Jan 1–5 to incorrectly show 小寒; change
the logic in the jp_season (or the function containing let (m, d) =
(now.month(), now.day())) so that instead of defaulting to "小寒" you set current
to the last entry in TERMS (the previous year's final term) or explicitly check
if (m,d) is before the first TERMS boundary and then assign current =
TERMS.last().name; then proceed with the existing loop over TERMS to overwrite
when appropriate. Ensure you reference TERMS and the local current variable when
making the change.
| #[derive(Debug, Clone, Deserialize)] | ||
| pub struct TargetEntry { | ||
| pub label: String, | ||
| pub target: String, | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify nested target-entry validation is declared.
# Expected after the fix: TargetEntry has #[serde(deny_unknown_fields)] immediately above it.
rg -n -C3 'deny_unknown_fields|struct TargetEntry' --type=rustRepository: unhappychoice/splashboard
Length of output: 1412
Add #[serde(deny_unknown_fields)] to TargetEntry.
Options rejects unknown top-level keys, but nested TargetEntry accepts extra fields. This inconsistency allows silent config errors like targets = [{ label = "x", target = "2099-01-01", typo = true }] where typo is silently ignored instead of rejected.
Proposed fix
#[derive(Debug, Clone, Deserialize)]
+#[serde(deny_unknown_fields)]
pub struct TargetEntry {
pub label: String,
pub target: String,
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| #[derive(Debug, Clone, Deserialize)] | |
| pub struct TargetEntry { | |
| pub label: String, | |
| pub target: String, | |
| } | |
| #[derive(Debug, Clone, Deserialize)] | |
| #[serde(deny_unknown_fields)] | |
| pub struct TargetEntry { | |
| pub label: String, | |
| pub target: String, | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/fetcher/clock/options.rs` around lines 56 - 60, Add the serde attribute
to reject unknown fields for the nested struct: annotate the TargetEntry struct
(the one with #[derive(Debug, Clone, Deserialize)]) with
#[serde(deny_unknown_fields)] so that deserialization of TargetEntry rejects any
unexpected keys (e.g., extra "typo" fields) instead of silently ignoring them.
| fn compute(opts: &Options) -> Result<(DateTime<FixedOffset>, DateTime<FixedOffset>), String> { | ||
| let lat = opts.lat.ok_or("lat required")?; | ||
| let lon = opts.lon.ok_or("lon required")?; | ||
| let now = opts.timezone_now(); | ||
| let date = now.date_naive(); | ||
| let offset = *now.offset(); | ||
| let (up, down) = | ||
| solar_events(date, lat, lon).ok_or("no sunrise/sunset at this latitude today")?; | ||
| Ok((to_local(date, up, offset), to_local(date, down, offset))) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify the fixed-offset path used by sunrise/sunset conversion.
# Expected: sunrise.rs calls Options::timezone_now() and passes a FixedOffset into to_local().
rg -n -C3 'timezone_now|to_local|FixedOffset' --type=rustRepository: unhappychoice/splashboard
Length of output: 24396
Use timezone-aware conversion per event to handle DST transitions correctly.
The code extracts a single FixedOffset from opts.timezone_now() and applies it to both sunrise and sunset UTC times. On DST transition days, sunrise and sunset can correspond to different local offsets, producing one-hour errors. Instead, when a timezone is configured, convert each UTC event directly through chrono_tz::Tz to preserve DST rules. Fall back to FixedOffset only when no valid zone is available.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/fetcher/clock/sunrise.rs` around lines 35 - 43, The compute function
incorrectly applies a single FixedOffset from opts.timezone_now() to both solar
events, which breaks DST transitions; update compute to convert each UTC event
(the up and down values from solar_events) using the configured timezone (e.g.,
parse or use the chrono_tz::Tz from Options) to get zone-aware local DateTimes
per event, and only fall back to using the FixedOffset via to_local when no Tz
is available; adjust calls around solar_events, to_local, and
timezone_now/Options so each event is converted through the timezone-aware path
independently.
| fn zoned_times(opts: &Options) -> Vec<(String, Option<DateTime<FixedOffset>>)> { | ||
| opts.timezones | ||
| .as_deref() | ||
| .unwrap_or(&[]) | ||
| .iter() | ||
| .map(|name| (name.clone(), resolve(name))) | ||
| .collect() | ||
| } | ||
|
|
||
| fn resolve(name: &str) -> Option<DateTime<FixedOffset>> { | ||
| let tz: chrono_tz::Tz = name.parse().ok()?; | ||
| Some(Utc::now().with_timezone(&tz).fixed_offset()) | ||
| } |
There was a problem hiding this comment.
Capture Utc::now() once for the whole world-clock strip.
Calling Utc::now() once per timezone can render rows from different instants when a tick crosses a second/minute boundary, and it adds avoidable work on the realtime path. Capture one timestamp in zoned_times() and project that same instant into every zone. Based on learnings, Realtime fetchers must have < 1ms execution time and be infallible with no I/O operations.
Proposed fix
fn zoned_times(opts: &Options) -> Vec<(String, Option<DateTime<FixedOffset>>)> {
+ let now = Utc::now();
opts.timezones
.as_deref()
.unwrap_or(&[])
.iter()
- .map(|name| (name.clone(), resolve(name)))
+ .map(|name| (name.clone(), resolve(&now, name)))
.collect()
}
-fn resolve(name: &str) -> Option<DateTime<FixedOffset>> {
+fn resolve(now: &DateTime<Utc>, name: &str) -> Option<DateTime<FixedOffset>> {
let tz: chrono_tz::Tz = name.parse().ok()?;
- Some(Utc::now().with_timezone(&tz).fixed_offset())
+ Some(now.with_timezone(&tz).fixed_offset())
}Update the tests to pass a captured Utc::now() into resolve().
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| fn zoned_times(opts: &Options) -> Vec<(String, Option<DateTime<FixedOffset>>)> { | |
| opts.timezones | |
| .as_deref() | |
| .unwrap_or(&[]) | |
| .iter() | |
| .map(|name| (name.clone(), resolve(name))) | |
| .collect() | |
| } | |
| fn resolve(name: &str) -> Option<DateTime<FixedOffset>> { | |
| let tz: chrono_tz::Tz = name.parse().ok()?; | |
| Some(Utc::now().with_timezone(&tz).fixed_offset()) | |
| } | |
| fn zoned_times(opts: &Options) -> Vec<(String, Option<DateTime<FixedOffset>>)> { | |
| let now = Utc::now(); | |
| opts.timezones | |
| .as_deref() | |
| .unwrap_or(&[]) | |
| .iter() | |
| .map(|name| (name.clone(), resolve(&now, name))) | |
| .collect() | |
| } | |
| fn resolve(now: &DateTime<Utc>, name: &str) -> Option<DateTime<FixedOffset>> { | |
| let tz: chrono_tz::Tz = name.parse().ok()?; | |
| Some(now.with_timezone(&tz).fixed_offset()) | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/fetcher/clock/timezones.rs` around lines 36 - 48, The zoned_times()
function should capture Utc::now() once and reuse that instant for every
timezone instead of calling Utc::now() inside resolve() per-iteration; change
resolve(name: &str) -> Option<DateTime<FixedOffset>> to accept the instant
(e.g., resolve(name: &str, instant: DateTime<Utc>)) and have zoned_times() call
let now = Utc::now(); then map each timezone to (name.clone(), resolve(name,
now)); ensure resolve projects the provided instant into the zone with
with_timezone(&tz).fixed_offset(), and update any tests to pass the captured
instant accordingly to keep the realtime path infallible and fast.
| /// Fetcher-specific options passed through from `[widget.options]`. Each fetcher | ||
| /// deserializes its own typed view; unknown keys are ignored. | ||
| pub options: Option<toml::Value>, |
There was a problem hiding this comment.
Doc contradicts actual behavior — options with unknown keys is rejected, not ignored.
The comment says "unknown keys are ignored", but the only current consumer (clock's Options in src/fetcher/clock/options.rs) is annotated with #[serde(deny_unknown_fields)], so a typo in [widget.options] surfaces as a parse error and renders a shape-mismatch / error placeholder. Either drop the "ignored" claim here (and in src/config.rs Lines 48–52 which carries the same misleading note) or state that each fetcher chooses strict-vs-lenient on its own.
📝 Suggested doc tweak
- /// Fetcher-specific options passed through from `[widget.options]`. Each fetcher
- /// deserializes its own typed view; unknown keys are ignored.
+ /// Fetcher-specific options passed through from `[widget.options]`. Each fetcher
+ /// deserializes its own typed view and decides how strict to be about unknown keys
+ /// (the clock fetcher, for example, uses `deny_unknown_fields`).
pub options: Option<toml::Value>,📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| /// Fetcher-specific options passed through from `[widget.options]`. Each fetcher | |
| /// deserializes its own typed view; unknown keys are ignored. | |
| pub options: Option<toml::Value>, | |
| /// Fetcher-specific options passed through from `[widget.options]`. Each fetcher | |
| /// deserializes its own typed view and decides how strict to be about unknown keys | |
| /// (the clock fetcher, for example, uses `deny_unknown_fields`). | |
| pub options: Option<toml::Value>, |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/fetcher/mod.rs` around lines 56 - 58, The field `pub options:
Option<toml::Value>` in src/fetcher/mod.rs currently has a doc comment claiming
"unknown keys are ignored", but concrete consumers like the clock `Options` in
src/fetcher/clock/options.rs use `#[serde(deny_unknown_fields)]` so unknown keys
are rejected; update the doc for `options` to remove the incorrect "ignored"
claim and instead state that each fetcher decides strict vs lenient
deserialization (or explicitly note that some fetchers may deny unknown fields),
and make the same corresponding wording change in the similar note in
src/config.rs so docs match actual behavior and callers like the clock `Options`
using `deny_unknown_fields` are accurately described.
b478643 to
1e491b6
Compare
Adds a generic `options: Option<toml::Value>` on WidgetConfig and FetchContext so fetchers can read typed `[widget.options]` sub-tables. Splits temporal features into sibling fetchers under a `clock_*` prefix instead of one fat fetcher with mode dispatch: - `clock` — base (Lines / Entries / Calendar), `timezone` / `events` - `clock_timezones` — world-clock strip - `clock_countdown` — target / targets - `clock_ratio` — day / year / month / week / quarter / hour fraction - `clock_state` — business_hours / weekend / night badge - `clock_sunrise` — NOAA approximation from lat/lon - `clock_derived` — moon_phase / zodiac / iso_week / 六曜 / ... (Lines) Each has a narrow `Options` struct with `deny_unknown_fields` so invalid keys surface as placeholders instead of silent wrong renders. Shared primitives (tz resolution, safe strftime, julian day) live in `clock/common.rs`. Refs #41. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
1e491b6 to
bcd5523
Compare
Summary
options: Option<toml::Value>onWidgetConfig/FetchContextso each fetcher deserializes its own typed[widget.options]sub-table. Reusable by future fetchers — no per-option typed fields sprawling onWidgetConfig.clock_*prefix rather than one fat fetcher with mode dispatch. Same read primitives are shared viaclock/common.rs; each fetcher has a narrowOptionsstruct and a smallshapes()list. Every options struct usesdeny_unknown_fieldsso typos surface as placeholders instead of silent wrong renders.clocktimezone,eventsclock_timezonestimezones = [...]clock_countdowntargetortargets = [...],target_labelclock_ratioperiod = \"day\"|\"year\"|\"month\"|\"week\"|\"quarter\"|\"hour\"clock_statekind = \"business_hours\"|\"weekend\"|\"night\"clock_sunriselat,lon,timezoneclock_derivedkind = \"moon_phase\"|\"zodiac\"|\"chinese_zodiac\"|\"season\"|\"jp_season\"|\"rokuyou\"|\"iso_week\"|\"day_of_year\"|\"julian_day\"|\"unix_epoch\"|\"time_of_day\"chrono-tz(IANA DB)..splashboard/config.toml(world clock, year progress gauge, business-hours badge, moon phase, Tokyo sunrise/sunset, New Year countdown).Design note
An earlier iteration consolidated all of this into one
clockfetcher with aModeenum dispatching on options. The implementation revealed that mode-dispatch + broadOptions+ per-mode shape validation was heavier than splitting, and docs catalog (#52) will benefit from one fetcher = one coherent page. Matches the establishedsystem/cpu_load/memorysplit pattern.Refs #41.
Test plan
cargo test— 258 passed, 0 failed (covers options parsing,deny_unknown_fieldsrejection, per-fetcher shape / option matrices, fraction correctness at period boundaries, sunrise plausibility for Tokyo).cargo clippy --all-targets -- -D warningsclean.cargo fmt --all --checkclean.cargo runin the repo renders the dogfood config with all new widgets.🤖 Generated with Claude Code