Repository navigation
feat(fetcher): add fetchers + shape extensions for 0.x presets - #88
Conversation
- clock: cover the custom strftime path via top-level `format` with a test. - system: add `Text` shape + `kind` option (terminal / os / os_version / hostname / shell / arch); terminal detection via well-known env vars. - weather: new cached Safe fetcher backed by Open-Meteo at a fixed host (`api.open-meteo.com`). Options: latitude / longitude / units. Emits Entries (primary) or Text. - github_avatar: new cached Safe fetcher. Downloads github.com/<user>.png into `$SPLASHBOARD_HOME/cache/avatars/<user>-<size>.png` and emits `Body::Image`. No auth — public endpoint, hardcoded host. Refs #81. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
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 50 minutes and 58 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 selected for processing (3)
📝 WalkthroughWalkthroughThis PR introduces three new fetchers (GitHub avatar, Open-Meteo weather, and clock format testing) and extends the system fetcher to support text-based output with customizable field selection. New fetchers are registered in the framework registry. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related issues
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 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 #88 +/- ##
==========================================
- Coverage 76.88% 76.05% -0.83%
==========================================
Files 74 76 +2
Lines 11354 11892 +538
==========================================
+ Hits 8729 9045 +316
- Misses 2625 2847 +222
🚀 New features to boost your workflow:
|
Open-Meteo's default `wind_speed_unit` is `km/h`, not `m/s` — the metric branch needs to pass `wind_speed_unit=ms` explicitly. Without this the "m/s" label disagreed with the numeric value returned. Verified against the live API via an ignored smoke test. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/fetcher/github/mod.rs (1)
1-5:⚠️ Potential issue | 🟡 MinorUpdate the GitHub module safety docs for the avatar fetcher.
The new avatar fetcher targets
github.com, notapi.github.com, so the module-level statement is now inaccurate.📝 Proposed wording
-//! GitHub fetchers. All classify as `Safety::Safe` because every request targets -//! `api.github.com` — the host is never config-driven, so the auth token can't be redirected +//! GitHub fetchers. All classify as `Safety::Safe` because every request targets +//! a fixed GitHub-owned host (`api.github.com` for API fetchers, `github.com` for avatars) — +//! the host is never config-driven, so the auth token can't be redirectedAlso applies to: 15-15, 49-49
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/fetcher/github/mod.rs` around lines 1 - 5, Update the module-level safety documentation in src/fetcher/github/mod.rs to reflect that while most GitHub fetchers target api.github.com, the avatar fetcher targets github.com; revise the blanket statement that every request targets api.github.com and clarify which functions/resources (specifically mention the avatar fetcher) use github.com so the Safety::Safe rationale remains accurate for functions like the avatar fetcher and the other API fetchers referenced in this module.
🤖 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/mod.rs`:
- Around line 186-204: The test custom_format_renders_date_template currently
passes "%Y · %A" which misses exercising the preset-style ordering; update the
call to ctx_with_format in that test to use a full preset-style format like "%e
%B %Y · %A" (or another preset-style string) so ClockFetcher.compute is
exercised with day-month-year ordering and will detect regressions in the preset
format handling.
In `@src/fetcher/github/avatar.rs`:
- Around line 121-122: Validate the incoming GitHub username before using it to
build cache filenames: ensure the `user` value (used when constructing `path`
with `out_dir.join(format!("{user}-{size}.png"))`) matches GitHub login rules
(only ASCII letters, digits and hyphens, max 39 chars, and not starting or
ending with a hyphen); if validation fails return an appropriate
`FetchError::Failed` instead of writing the file. Apply the same validation and
early-return logic wherever `user` is used to construct paths or URLs in this
module (including the other occurrence around lines 130–139) so `out_dir.join`
never receives an absolute or path-containing string and the cache filename is
always safe.
In `@src/fetcher/weather.rs`:
- Around line 141-148: The build_url function currently only sets
wind_speed_unit for Imperial but not for metric, causing Open-Meteo to return
km/h while wind_label() displays m/s; update build_url (function name:
build_url) to append "&wind_speed_unit=ms" when units is not Units::Imperial
(i.e., for metric) so the API returns m/s; adjust the conditional that checks
matches!(units, Units::Imperial) to append the imperial query params only in
that branch and append "&wind_speed_unit=ms" in the else/metric branch (or
explicitly add when matches!(units, Units::Metric)) so the returned wind units
match wind_label().
---
Outside diff comments:
In `@src/fetcher/github/mod.rs`:
- Around line 1-5: Update the module-level safety documentation in
src/fetcher/github/mod.rs to reflect that while most GitHub fetchers target
api.github.com, the avatar fetcher targets github.com; revise the blanket
statement that every request targets api.github.com and clarify which
functions/resources (specifically mention the avatar fetcher) use github.com so
the Safety::Safe rationale remains accurate for functions like the avatar
fetcher and the other API fetchers referenced in this module.
🪄 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: 64ebc59c-ef99-4ad2-a023-a22e7c19b9c5
📒 Files selected for processing (6)
src/fetcher/clock/mod.rssrc/fetcher/github/avatar.rssrc/fetcher/github/mod.rssrc/fetcher/mod.rssrc/fetcher/system.rssrc/fetcher/weather.rs
| #[test] | ||
| fn custom_format_renders_date_template() { | ||
| let p = ClockFetcher.compute(&ctx_with_format("%Y · %A")); | ||
| match p.body { | ||
| Body::Text(d) => { | ||
| assert!( | ||
| d.value.contains(" · "), | ||
| "expected middot separator from template, got {:?}", | ||
| d.value | ||
| ); | ||
| assert!( | ||
| d.value.chars().next().is_some_and(|c| c.is_ascii_digit()), | ||
| "expected year digits at start, got {:?}", | ||
| d.value | ||
| ); | ||
| } | ||
| _ => panic!("expected text"), | ||
| } | ||
| } |
There was a problem hiding this comment.
Exercise the actual preset-style date format.
This test uses %Y · %A, so %e %B %Y · %A can still regress unnoticed even though that is the format called out for the 0.x preset coverage.
🧪 Proposed test adjustment
#[test]
fn custom_format_renders_date_template() {
- let p = ClockFetcher.compute(&ctx_with_format("%Y · %A"));
+ let p = ClockFetcher.compute(&ctx_with_format("%e %B %Y · %A"));
match p.body {
Body::Text(d) => {
assert!(
d.value.contains(" · "),
"expected middot separator from template, got {:?}",
d.value
);
assert!(
- d.value.chars().next().is_some_and(|c| c.is_ascii_digit()),
- "expected year digits at start, got {:?}",
+ d.value.chars().any(|c| c.is_ascii_digit()),
+ "expected date digits from template, got {:?}",
d.value
);
}
_ => panic!("expected text"),
}
}📝 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.
| #[test] | |
| fn custom_format_renders_date_template() { | |
| let p = ClockFetcher.compute(&ctx_with_format("%Y · %A")); | |
| match p.body { | |
| Body::Text(d) => { | |
| assert!( | |
| d.value.contains(" · "), | |
| "expected middot separator from template, got {:?}", | |
| d.value | |
| ); | |
| assert!( | |
| d.value.chars().next().is_some_and(|c| c.is_ascii_digit()), | |
| "expected year digits at start, got {:?}", | |
| d.value | |
| ); | |
| } | |
| _ => panic!("expected text"), | |
| } | |
| } | |
| #[test] | |
| fn custom_format_renders_date_template() { | |
| let p = ClockFetcher.compute(&ctx_with_format("%e %B %Y · %A")); | |
| match p.body { | |
| Body::Text(d) => { | |
| assert!( | |
| d.value.contains(" · "), | |
| "expected middot separator from template, got {:?}", | |
| d.value | |
| ); | |
| assert!( | |
| d.value.chars().any(|c| c.is_ascii_digit()), | |
| "expected date digits from template, got {:?}", | |
| d.value | |
| ); | |
| } | |
| _ => panic!("expected text"), | |
| } | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/fetcher/clock/mod.rs` around lines 186 - 204, The test
custom_format_renders_date_template currently passes "%Y · %A" which misses
exercising the preset-style ordering; update the call to ctx_with_format in that
test to use a full preset-style format like "%e %B %Y · %A" (or another
preset-style string) so ClockFetcher.compute is exercised with day-month-year
ordering and will detect regressions in the preset format handling.
| let path = out_dir.join(format!("{user}-{size}.png")); | ||
| std::fs::write(&path, &bytes).map_err(|e| FetchError::Failed(format!("write avatar: {e}")))?; |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
rg -n -C3 'fn resolve_user|out_dir\.join|format!\("\{user\}-\{size\}\.png"\)' src/fetcher/github/avatar.rsRepository: unhappychoice/splashboard
Length of output: 1560
🏁 Script executed:
cat -n src/fetcher/github/avatar.rsRepository: unhappychoice/splashboard
Length of output: 9477
🏁 Script executed:
python3 << 'EOF'
import subprocess
import os
# Create a test Rust program to verify Path::join behavior
test_code = '''
use std::path::PathBuf;
fn main() {
let base = PathBuf::from("/tmp/base");
// Test 1: Relative path
let result1 = base.join("subdir/file.txt");
println!("Relative: base.join('subdir/file.txt') = {}", result1.display());
// Test 2: Absolute path
let result2 = base.join("/etc/passwd");
println!("Absolute: base.join('/etc/passwd') = {}", result2.display());
// Test 3: Path with /
let result3 = base.join("user-with/slash-200.png");
println!("With /: base.join('user-with/slash-200.png') = {}", result3.display());
}
'''
with open('/tmp/test_path.rs', 'w') as f:
f.write(test_code)
# Try to compile and run it (if rustc available)
result = subprocess.run(['rustc', '/tmp/test_path.rs', '-o', '/tmp/test_path'],
capture_output=True, text=True, timeout=10)
if result.returncode == 0:
result = subprocess.run(['/tmp/test_path'], capture_output=True, text=True, timeout=5)
print(result.stdout)
else:
print("rustc not available, but Path::join behavior is well-documented:")
print("- join() with relative path appends it")
print("- join() with absolute path REPLACES the entire path")
print("- join() with path containing '/' treats it as path separator")
EOFRepository: unhappychoice/splashboard
Length of output: 623
🌐 Web query:
Rust PathBuf join absolute path behavior documentation
💡 Result:
In Rust's standard library, PathBuf::join(&self, path: P) -> PathBuf creates a new PathBuf by adjoining the given path to self. The key behavior when joining an absolute path is that it replaces the current path contents. From the official documentation (stable Rust docs): "If path is absolute, it replaces the current path. On Windows: - if path has a root but no prefix (e.g., \windows), it replaces everything except for the prefix (if any) of self. - if path has a prefix but no root, self is ignored and path is returned. - if self has a verbatim prefix (e.g. \?\C:\windows) and path is not empty, the new path is normalized: all references to . and .. are removed." Examples: use std::path::{Path, PathBuf}; assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd")); // relative: appends assert_eq!(Path::new("/etc").join("/bin/sh"), PathBuf::from("/bin/sh")); // absolute: replaces This matches PathBuf::push(&mut self, path: P), which mutates in place with identical semantics (join internally uses push logic). A path is absolute if Path::is_absolute returns true: on Unix, starts with /; on Windows, has both prefix (e.g. C:) and root (). This design allows absolute paths to override (like cd /bin/sh from /etc), while relative paths append (like cd bin/sh). It's consistent across platforms with Windows nuances for prefixes. Source code confirms: in library/std/src/path.rs, push clears self.inner if path.is_absolute || path.prefix.is_some (Unix prefix always None). As of 2026-04-23, no changes; behavior stable since Rust 1.0.
Citations:
- 1: https://doc.rust-lang.org/beta/std/path/struct.PathBuf.html
- 2: https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html
- 3: https://github.com/rust-lang/rust/blob/master/library/std/src/path.rs
- 4: https://stackoverflow.com/questions/53430401/why-does-joining-paths-completely-replace-the-original-path-in-rust/53430667
Add username validation to prevent path traversal in avatar cache filename.
The user parameter accepts any non-empty string, including absolute paths (e.g., /etc/passwd) or paths with separators. Rust's PathBuf::join() with absolute paths replaces the entire base path, allowing writes outside the cache directory. Validate against GitHub's login constraints (alphanumeric + hyphens, max 39 chars, no leading/trailing hyphens) before constructing the URL or cache filename.
🛡️ Proposed fix
fn resolve_user(explicit: Option<&str>) -> Result<String, String> {
- if let Some(u) = explicit.filter(|s| !s.is_empty()) {
- return Ok(u.into());
- }
- if let Ok(u) = std::env::var("GITHUB_USER")
- && !u.is_empty()
- {
- return Ok(u);
- }
- Err("set `user = \"<login>\"` or the GITHUB_USER env var".into())
+ let user = explicit
+ .filter(|s| !s.is_empty())
+ .map(str::to_owned)
+ .or_else(|| std::env::var("GITHUB_USER").ok().filter(|s| !s.is_empty()))
+ .ok_or_else(|| "set `user = \"<login>\"` or the GITHUB_USER env var".to_string())?;
+
+ if is_safe_github_login(&user) {
+ Ok(user)
+ } else {
+ Err("github login must contain only ASCII letters, digits, or hyphens".into())
+ }
}
+
+fn is_safe_github_login(user: &str) -> bool {
+ !user.is_empty()
+ && user.len() <= 39
+ && !user.starts_with('-')
+ && !user.ends_with('-')
+ && user
+ .bytes()
+ .all(|b| b.is_ascii_alphanumeric() || b == b'-')
+}Also applies to: 130–139
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/fetcher/github/avatar.rs` around lines 121 - 122, Validate the incoming
GitHub username before using it to build cache filenames: ensure the `user`
value (used when constructing `path` with
`out_dir.join(format!("{user}-{size}.png"))`) matches GitHub login rules (only
ASCII letters, digits and hyphens, max 39 chars, and not starting or ending with
a hyphen); if validation fails return an appropriate `FetchError::Failed`
instead of writing the file. Apply the same validation and early-return logic
wherever `user` is used to construct paths or URLs in this module (including the
other occurrence around lines 130–139) so `out_dir.join` never receives an
absolute or path-containing string and the cache filename is always safe.
GitHub serves whichever image format the user uploaded even when the URL ends in `.png` — unhappychoice's avatar actually came back as JPEG. `image::ImageReader::open` decodes by extension hint, so saving JPEG bytes under a `.png` name caused render failures. Detect the real format from the magic bytes and save with the matching suffix. Also adds ignored smoke tests for system (prints Text shape output for every `kind`) and github_avatar (verifies downloaded magic bytes). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Summary
Fills in the fetcher gaps needed by the 0.x dashboard presets (#77).
clock— confirm the existing strftime path (top-levelformatfield) with a test. No new code; covers"%e %B %Y · %A"style templates thathome_dailyneeds.system— extend withTextshape +kindoption (terminal/os/os_version/hostname/shell/arch). Terminal detection via well-known env vars (WT_SESSION,TERM_PROGRAM,KITTY_WINDOW_ID,ALACRITTY_WINDOW_ID,WEZTERM_PANE,GHOSTTY_RESOURCES_DIR, …) with a generic fallback.weather(new) — Open-Meteo forecast at a fixed host (api.open-meteo.com).Safety::Safebecause the user supplies coordinates, not a URL. Options:latitude/longitude/units("metric" | "imperial"). EmitsEntries(primary) orText.github_avatar(new) — downloadsgithub.com/<user>.png?size=Ninto\$SPLASHBOARD_HOME/cache/avatars/<user>-<size>.pngand emitsBody::Image. Fixed host, no auth (public endpoint), so noGH_TOKENleaks along the redirect chain.userfalls back to\$GITHUB_USER.Closes checklist items on #81.
Test plan
cargo test— 415 passed (+22 new)cargo clippy --all-targets -- -D warnings— cleancargo fmt --all -- --check— cleancargo xtaskregenerates the reference matrix (weather + github_avatar pages appear)🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Tests