Skip to content

feat(fetcher): add fetchers + shape extensions for 0.x presets - #88

Merged
unhappychoice merged 3 commits into
mainfrom
feat/fetchers-for-0x-presets
Apr 23, 2026
Merged

unhappychoice merged 3 commits into
mainfrom
feat/fetchers-for-0x-presets

Conversation

@unhappychoice

@unhappychoice unhappychoice commented Apr 23, 2026 •

Copy link
Copy Markdown
Owner

Summary

Fills in the fetcher gaps needed by the 0.x dashboard presets (#77).

  • clock — confirm the existing strftime path (top-level format field) with a test. No new code; covers "%e %B %Y · %A" style templates that home_daily needs.
  • system — extend with Text shape + kind option (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::Safe because the user supplies coordinates, not a URL. Options: latitude / longitude / units ("metric" | "imperial"). Emits Entries (primary) or Text.
  • github_avatar (new) — downloads github.com/<user>.png?size=N into \$SPLASHBOARD_HOME/cache/avatars/<user>-<size>.png and emits Body::Image. Fixed host, no auth (public endpoint), so no GH_TOKEN leaks along the redirect chain. user falls back to \$GITHUB_USER.

Closes checklist items on #81.

Test plan

  • cargo test — 415 passed (+22 new)
  • cargo clippy --all-targets -- -D warnings — clean
  • cargo fmt --all -- --check — clean
  • cargo xtask regenerates the reference matrix (weather + github_avatar pages appear)

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added GitHub avatar fetcher for downloading and caching user profile avatars.
    • Added weather fetcher for current conditions via Open-Meteo, supporting metric/imperial units.
    • Extended system fetcher to display individual system details (OS, hostname, architecture, shell, terminal).
  • Tests

    • Added comprehensive tests for new fetchers and extended system information functionality.

- 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]>
@coderabbitai

coderabbitai Bot commented Apr 23, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@unhappychoice has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 50 minutes and 58 seconds before requesting another review.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6b0b6ff8-c1e6-4e28-b4a5-98069b61a552

📥 Commits

Reviewing files that changed from the base of the PR and between 2048bcb and c98720c.

📒 Files selected for processing (3)
  • src/fetcher/github/avatar.rs
  • src/fetcher/system.rs
  • src/fetcher/weather.rs
📝 Walkthrough

Walkthrough

This 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

Cohort / File(s) Summary
Clock Fetcher Testing
src/fetcher/clock/mod.rs
Added FetchContext test helper with custom format and Shape::Text, plus unit test validating ClockFetcher.compute respects strftime-like template formatting.
GitHub Avatar Fetcher
src/fetcher/github/avatar.rs
New fetcher downloading GitHub user avatar PNG from github.com/<user>.png?size=<size>, caching to avatars/<user>-<size>.png, with configurable user and size options; includes option parsing, precedence/fallback logic, and error handling.
GitHub Module Integration
src/fetcher/github/mod.rs
Registers new avatar submodule and GithubAvatar fetcher in the GitHub fetcher factory.
System Fetcher Extension
src/fetcher/system.rs
Extended SystemFetcher to support Shape::Text output with new kind option schema; adds typed option parsing, terminal/OS/shell/arch detection, and single-value text rendering alongside existing Entries/TextBlock shapes.
Weather Fetcher
src/fetcher/weather.rs
New fetcher for Open-Meteo current weather forecasts; parses required latitude/longitude and optional units options, requests API endpoint, deserializes JSON, renders as entry rows or formatted text with WMO weather code mappings; includes cached reqwest::Client with 10s timeout.
Fetcher Registry
src/fetcher/mod.rs
Adds weather module and registers WeatherFetcher in default Registry alongside existing fetchers.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Possibly related PRs

Poem

🐰 Three new fetchers hop into the field,
GitHub avatars and weather revealed,
System stats now speak in text so clear,
The registry grows with each new cheer! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 35.90% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(fetcher): add fetchers + shape extensions for 0.x presets' clearly describes the main changes: adding new fetchers (weather, github_avatar) and shape extensions (Text for system, template support for clock) to support 0.x dashboard presets.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/fetchers-for-0x-presets

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov

codecov Bot commented Apr 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 59.18367% with 220 lines in your changes missing coverage. Please review.
✅ Project coverage is 76.05%. Comparing base (82c6566) to head (c98720c).
⚠️ Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
src/fetcher/weather.rs 57.84% 94 Missing ⚠️
src/fetcher/github/avatar.rs 55.23% 77 Missing ⚠️
src/fetcher/system.rs 60.97% 48 Missing ⚠️
src/fetcher/clock/mod.rs 94.73% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            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     
Files with missing lines Coverage Δ
src/fetcher/github/mod.rs 100.00% <100.00%> (ø)
src/fetcher/mod.rs 76.00% <100.00%> (+0.09%) ⬆️
src/fetcher/clock/mod.rs 87.24% <94.73%> (+1.09%) ⬆️
src/fetcher/system.rs 74.78% <60.97%> (-3.86%) ⬇️
src/fetcher/github/avatar.rs 55.23% <55.23%> (ø)
src/fetcher/weather.rs 57.84% <57.84%> (ø)

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 | 🟡 Minor

Update the GitHub module safety docs for the avatar fetcher.

The new avatar fetcher targets github.com, not api.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 redirected

Also 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

📥 Commits

Reviewing files that changed from the base of the PR and between 82c6566 and 2048bcb.

📒 Files selected for processing (6)
  • src/fetcher/clock/mod.rs
  • src/fetcher/github/avatar.rs
  • src/fetcher/github/mod.rs
  • src/fetcher/mod.rs
  • src/fetcher/system.rs
  • src/fetcher/weather.rs

Comment thread src/fetcher/clock/mod.rs
Comment on lines +186 to +204
#[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"),
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

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.

Suggested change
#[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.

Comment thread src/fetcher/github/avatar.rs Outdated
Comment on lines +121 to +122
let path = out_dir.join(format!("{user}-{size}.png"));
std::fs::write(&path, &bytes).map_err(|e| FetchError::Failed(format!("write avatar: {e}")))?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -n -C3 'fn resolve_user|out_dir\.join|format!\("\{user\}-\{size\}\.png"\)' src/fetcher/github/avatar.rs

Repository: unhappychoice/splashboard

Length of output: 1560


🏁 Script executed:

cat -n src/fetcher/github/avatar.rs

Repository: 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")
EOF

Repository: 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:


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.

Comment thread src/fetcher/weather.rs Resolved
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant