Repository navigation
feat: "splashboard cache" management CLI — list, clear, path (#40) - #216
Conversation
…choice#40) Adds a top-level `cache` subcommand for inspecting and managing the disk cache at $HOME/.splashboard/cache/. Closes unhappychoice#40. Subcommands: - `splashboard cache path` — print the resolved cache directory. - `splashboard cache list [--json]` — one row per .json entry plus any orphan .lock files, sorted oldest first. Columns: KEY, KIND, AGE(s), TTL(s), STATE (fresh/stale), SIZE(B), OUTCOME (ok/err/timeout). JSON mode emits one object per line for scripting. - `splashboard cache clear [--yes] [--json]` — remove every .json + .lock file in the cache dir. Confirms unless --yes; never touches files with other extensions. - `splashboard cache clear <widget_id> [--json]` — remove a single widget's entry plus its lock. Per issue Option 1: computes the cache key from the current config (`resolve_dashboard_source`) — works as long as the widget is still configured; reports a clear error if not. The widget-id path replicates the sanitize step from cache::Cache::path_for (module-private). A test (`clear_one_matches_cache_filename_layout`) pins the contract: the on-disk filename main.rs computes for a key must equal what cache.rs writes. If cache::sanitize ever diverges from main::sanitize_cache_key, that test fires. Locale/timezone are explicitly None on the synthesized FetchContext — default_cache_key doesn't read them, and any fetcher that overrides cache_key to consume them produces keys we can't reproduce here anyway. 7 unit tests cover: sanitize alnum passthrough + path-char replacement, the cache::path_for contract, missing-dir handling for both list and clear, list reading entry + lock + skipping unrelated extensions, and clear_all preserving non-cache files in the same directory. All 35 splashboard binary tests pass. Cache format unchanged. No widget_id stored alongside the entry — kept the schema as-is per issue Open Questions.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughAdds a ChangesCache Management CLI
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Tip 💬 Introducing Slack Agent: The best way for teams to turn conversations into code.Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.
Built for teams:
One agent for your entire SDLC. Right inside Slack. 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: 1
🧹 Nitpick comments (2)
src/main.rs (2)
628-722: ⚖️ Poor tradeoffFunction length significantly exceeds guideline.
This ~95-line function exceeds the coding guideline target of ~10–15 lines per function. Consider splitting into smaller helpers: (1) resolve widget and fetcher, (2) compute cache key, (3) remove files, (4) format output. As per coding guidelines, keep functions small with single responsibility, aiming for ~10–15 lines per function.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/main.rs` around lines 628 - 722, The clear_one function is too large—split it into small helpers: add resolve_widget_and_fetcher(source: &...)->Result<(Widget, Fetcher), io::Error> to encapsulate loading config, finding widget (used where clear_one currently calls load_full_config and Registry::get_cached), add compute_cache_key(widget: &Widget, fetcher: &dyn Fetcher)->String to build the FetchContext and call fetcher.cache_key + sanitize_cache_key, add remove_cache_files(dir: &Path, key: &str)->Result<(Vec<String>,Vec<String>), io::Error> to handle removing the .json and .lock files and return (removed, missing), and add format_clear_output(widget_id: &str, key: &str, removed: Vec<String>, missing: Vec<String>, json: bool) to handle printing JSON or human-readable output; then refactor clear_one to call these helpers in sequence (resolve_widget_and_fetcher -> compute_cache_key -> remove_cache_files -> format_clear_output) keeping clear_one as a thin coordinator.
479-550: 💤 Low valueFunction length exceeds guideline but is acceptable here.
This ~70-line function exceeds the coding guideline of ~10–15 lines per function, but the logic is cohesive (reading cache directory, extracting metadata for .json and .lock files) and readable. Splitting it further might hurt clarity. As per coding guidelines, aim to keep functions small with single responsibility.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/main.rs` around lines 479 - 550, The function collect_cache_rows is longer than the project's guideline—refactor it into smaller helpers without changing behavior: keep collect_cache_rows as the top-level loop (preserving the NotFound-as-empty-dir and error propagation) but extract the per-file logic into one or two functions such as process_cache_path(path: &Path, now: SystemTime) -> Option<CacheListRow> and parse_json_cache_entry(path: &Path) -> Option<(u64 /*ttl*/, &'static str /*freshness*/, &'static str /*outcome*/)>, so the match on ext ("json"/"lock"/_) and the serde_json/CacheEntry/cache::CacheEntryKind handling live in parse_json_cache_entry/process_cache_path while collect_cache_rows only handles iteration and pushing returned CacheListRow objects; ensure CacheListRow, CacheEntry, and cache::CacheEntryKind semantics (age_seconds, size_bytes, ttl_seconds, freshness, outcome) are preserved exactly.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/main.rs`:
- Around line 667-670: The cache key currently uses fetcher.default_shape()
(shape: Some(fetcher.default_shape())) which can differ from a widget's runtime
shape override (and may also differ by locale/timezone), so update the clear
path that handles a failed clear_one to mention this limitation: in the Clear
subcommand's failure branch (where clear_one fails to find an entry) augment the
error message to state that the key was computed using default_shape() and that
a runtime shape override or locale/timezone differences could cause a mismatch;
alternatively add a short note to the Clear subcommand help text explaining that
cache keys include shape/locale/timezone and that overrides can prevent a match.
Ensure you reference default_shape() and the Clear subcommand help text when
making the change.
---
Nitpick comments:
In `@src/main.rs`:
- Around line 628-722: The clear_one function is too large—split it into small
helpers: add resolve_widget_and_fetcher(source: &...)->Result<(Widget, Fetcher),
io::Error> to encapsulate loading config, finding widget (used where clear_one
currently calls load_full_config and Registry::get_cached), add
compute_cache_key(widget: &Widget, fetcher: &dyn Fetcher)->String to build the
FetchContext and call fetcher.cache_key + sanitize_cache_key, add
remove_cache_files(dir: &Path, key: &str)->Result<(Vec<String>,Vec<String>),
io::Error> to handle removing the .json and .lock files and return (removed,
missing), and add format_clear_output(widget_id: &str, key: &str, removed:
Vec<String>, missing: Vec<String>, json: bool) to handle printing JSON or
human-readable output; then refactor clear_one to call these helpers in sequence
(resolve_widget_and_fetcher -> compute_cache_key -> remove_cache_files ->
format_clear_output) keeping clear_one as a thin coordinator.
- Around line 479-550: The function collect_cache_rows is longer than the
project's guideline—refactor it into smaller helpers without changing behavior:
keep collect_cache_rows as the top-level loop (preserving the
NotFound-as-empty-dir and error propagation) but extract the per-file logic into
one or two functions such as process_cache_path(path: &Path, now: SystemTime) ->
Option<CacheListRow> and parse_json_cache_entry(path: &Path) -> Option<(u64
/*ttl*/, &'static str /*freshness*/, &'static str /*outcome*/)>, so the match on
ext ("json"/"lock"/_) and the serde_json/CacheEntry/cache::CacheEntryKind
handling live in parse_json_cache_entry/process_cache_path while
collect_cache_rows only handles iteration and pushing returned CacheListRow
objects; ensure CacheListRow, CacheEntry, and cache::CacheEntryKind semantics
(age_seconds, size_bytes, ttl_seconds, freshness, outcome) are preserved
exactly.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
Addresses CodeRabbit feedback on unhappychoice#216: the cache key clear_one computes uses fetcher.default_shape() with locale/timezone = None. Runtime overrides (per-widget shape, [general].locale, [general].timezone) would write the on-disk entry under a different key — clear would silently not match, leaving the user confused whether the cache was empty or just key-mismatched. Two small changes: 1. The 'had no cache entry' error message now spells out the limitation and points the user at `splashboard cache list` + manual delete as the fallback. 2. The Clear subcommand help text gains a 'Note:' paragraph saying the same thing — visible via `splashboard cache clear --help`. Skipped the two function-length nitpicks from the same review: CodeRabbit itself marked them 'Poor tradeoff' / 'Low value', and the helpers would be six-line abstractions over a two-call sequence used once. Happy to split them if you'd prefer; the actionable one above is the one that affects users.
|
Thanks for the review — pushed 1eac161 addressing the actionable item: Line 670 shape-override caveat ✅ — the Two function-length nitpicks — skipped intentionally:
Both are cosmetic; final call yours. |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #216 +/- ##
==========================================
- Coverage 95.97% 95.59% -0.38%
==========================================
Files 154 156 +2
Lines 45421 46971 +1550
==========================================
+ Hits 43593 44903 +1310
- Misses 1828 2068 +240
🚀 New features to boost your workflow:
|
Two clippy errors from CI (cargo clippy --all-targets -- -D warnings): - clippy::unnecessary_sort_by at line 451 — switched sort_by with manual reverse closure to sort_by_key(|r| std::cmp::Reverse(r.age_seconds)). - clippy::print_literal at line 468 — inlined the trailing OUTCOME literal directly into the format string instead of passing it as a positional arg. Plus 11 new tests targeting CodeRabbit / codecov coverage gaps in the cache CLI: - clear_all_handles_empty_dir: yes=false path against empty dir (no prompt because nothing to remove), both json + human modes - clear_all_ignores_non_cache_extensions: .tmp / .bak / .md must survive a clear; only .json + .lock removed - truncate_short_passes_through + truncate_exact_length_passes_through: no-op cases - truncate_long_gets_ellipsis_suffix: confirms ellipsis + 10-grapheme output - truncate_handles_one_char_cap: edge case (max=1) — saturating_sub semantics - collect_cache_rows_skips_unknown_extensions: .tmp / .bak ignored, only .json + .lock surfaced - collect_cache_rows_marks_unreadable_entries: garbage JSON still appears with freshness='unreadable' so users can see + delete it - collect_cache_rows_skips_subdirectories: subdirs ignored - run_cache_list_json_mode_succeeds_on_populated_dir + empty_dir: both branches in both formats Total tests in bin: 35 → 46 (+11). cargo clippy --all-targets -- -D warnings: clean. cargo test --bin splashboard: 46 passed, 0 failed.
|
Pushed 3b45780: Clippy fixes (CI was hitting
Coverage boost: 35 → 46 tests (+11) targeting the codecov gaps:
Re-running CI now. |
unhappychoice
left a comment
There was a problem hiding this comment.
Thanks for the thorough write-up and tests — the contract pin in clear_one_matches_cache_filename_layout is exactly the right defense for the duplicated sanitize logic. A few things worth addressing before merge.
Correctness
truncate can panic on multi-byte keys
format!("{}…", &s[..max.saturating_sub(1)]) slices by byte offset. If a cache key ever contains a multi-byte UTF-8 codepoint (a fetcher overriding cache_key, or stray entries from outside the registry), and the cut lands inside that codepoint, this panics. Cache keys today are alnum + dash, so it's latent — but cheap to make robust:
fn truncate(s: &str, max: usize) -> String {
if s.chars().count() <= max { return s.to_string(); }
let take = max.saturating_sub(1);
let prefix: String = s.chars().take(take).collect();
format!("{prefix}…")
}cache::sanitize vs main::sanitize_cache_key — prefer reuse over duplication
The round-trip test pins the relationship for one input (clock-3f2a1c8b), but if cache::sanitize ever tightens (say, to also reject leading .), main won't follow and clear_one will silently miss entries. Since they must stay byte-for-byte equivalent, expose the existing one:
// in src/cache.rs
pub(crate) fn sanitize(s: &str) -> String { ... }and call cache::sanitize from main.rs. The contract test becomes a one-liner (assert_eq!(cache::path_for(...), expected)) and the drift risk disappears entirely. The PR description already cites avoiding "widening the public API" — pub(crate) doesn't widen it.
Sort order doc says "descending"; please say "oldest first"
The List subcommand doc comment reads "Sorted by age descending" — technically correct but reads as "newest first" to half of readers. The code comment in run_cache_list already uses "Oldest first by default"; mirror that in the user-facing doc string since --help shows it verbatim.
Behavior / UX
clear_one can't reach the home dashboard from a project dir
resolve_dashboard_source() picks project-local if you're in a repo, so running splashboard cache clear clock from inside a repo can never clear the home dashboard's clock entry. The fallback in the comment ("falls back to the home dashboard so the command works outside any project-local context") doesn't kick in when there's a local config. Two options:
- accept it as a known limit and mention in
--help("looks up the widget in whatever dashboard would render here"), - add
--source home|project|<path>(matches the existing trust-gating vocabulary).
I'd lean toward the first for this PR and file a follow-up if anyone asks.
clear_one silently ignores --yes
--yes is documented as "Skip the confirmation prompt for clear (no widget id)" but clap will accept it on the widget_id variant too with no effect. Either:
- move
--yesto a flag that only exists on the no-id arm (different subcommand struct), or - keep the current shape and note in
--helpthat it has no effect when a widget id is given.
Concurrency: clearing while the daemon is fetching
Open question 3 calls this out. On Linux, unlink()-ing a .lock file that the daemon already holds is benign for the daemon's existing handle, but the next acquirer will create a fresh lock file and think it has exclusive access while the daemon is still writing the .json. This can corrupt the entry. Minimum mitigation: cache::Lock::try_acquire each target before unlinking, skip + report locked ones in the human/json output. Happy to land in a follow-up — the threat is narrow (concurrent cache clear + active daemon refresh) — but a one-line "may race against an active daemon refresh; rerun if so" in --help would set expectations.
Smaller stuff
run_cacheusesstd::process::exit(2)whencache_dir()is None; rest ofmain.rspropagatesio::Error(exit 1). Pick one — preferablyio::Error::other(...)for consistency.clear_allreturnsErrafter partial success. That's the right Unix convention, but worth a sentence in--helpso JSON consumers know they get both aremovedcount and a non-zero exit on partial failure.- JSONL for
cache listis fine; flagging in case you wantjq -s '.'-friendliness later, an array would be a one-liner. collect_cache_rowsandclear_allwalk the directory twice in theclearpath (once for prompt count, once for removal). Negligible at cache sizes we'll ever see, just noting for the file.
Tests
Coverage is excellent — collect_cache_rows_marks_unreadable_entries and clear_all_ignores_non_cache_extensions are exactly the cases I'd want pinned. One gap: no test for truncate with multi-byte input; if you keep the byte-slice version, please add a regression test (or just fix it and the test becomes trivial).
Open questions in the PR
- (1) JSONL vs array: JSONL is fine. Land as-is.
- (2) Home-dashboard fallback in
clear_one: see comment above — accept the limit, document it. - (3)
--forcefor locked entries: I'd rather seetry_acquire+ skip than--force, but either way it's out of scope for this PR.
Nice work overall — the tests around the drift contract and the unreadable-entry handling are the parts I'd most want a future maintainer to find.
…c/exit polish Addresses review feedback on unhappychoice#216: * Drop `main::sanitize_cache_key` and call `cache::sanitize` directly. Re-exposed as `pub fn sanitize` with `#[doc(hidden)]` (the binary crate can't see `pub(crate)` items from the library). Removes the silent-drift risk between the two copies; the contract test in `clear_one_matches_ cache_filename_layout` becomes a one-liner pin on the on-disk layout. * Make `truncate` codepoint-safe. The earlier `&s[..max - 1]` byte slice would panic if the cut landed mid-codepoint. Now walks `chars()`. Adds a regression test with a 3-codepoint / 9-byte CJK string. * `run_cache` now returns `io::Error::other(...)` when `cache_dir()` is `None`, matching the rest of `main.rs` (previously exited with code 2 while every other path exited with code 1). * Doc strings: - `list`: "Sorted by age descending" → "Oldest first (stale / orphan entries surface at the top)" to match the code comment and remove the "descending = newest first?" ambiguity in `--help`. - `clear`: document the home-vs-project dashboard resolution, the default-shape / no-locale caveat, the partial-removal exit semantics, and the daemon-refresh race window. - `--yes`: spell out that it has no effect when a widget id is given.
|
Thanks for the careful review — addressed in b2dbf13. Correctness
Behavior / UX
Out of scope (open question #3 + concurrency) Agreed Smoke gate
|
unhappychoice
left a comment
There was a problem hiding this comment.
All review items addressed cleanly. The cache::sanitize #[doc(hidden)] pub fn route is the right call given the binary/library crate split — keeps the contract single-sourced without leaking it into the public API. Multi-byte truncate regression test with 日本語テスト is a nice touch.
Function-length nitpicks: agreed with the author's read. clear_one and collect_cache_rows are cohesive sequential pipelines; splitting them would replace clear inline logic with a relay of single-use helpers. The ~10–15 line guideline is for surfacing mixed responsibilities, which isn't what's happening here.
Daemon-refresh race + try_acquire-based skip is fine as a follow-up.
LGTM.
Closes #40.
Adds a top-level
cachesubcommand for inspecting and managing the disk cache at$HOME/.splashboard/cache/.Subcommands
splashboard cache path— print the resolved cache directory.splashboard cache list [--json]— one row per.jsonentry plus any orphan.lockfiles, sorted oldest first. Columns:KEY · KIND · AGE(s) · TTL(s) · STATE (fresh/stale) · SIZE(B) · OUTCOME (ok/err/timeout). JSON mode emits one object per line.splashboard cache clear [--yes] [--json]— remove every.json+.lockfile in the cache dir. Confirms unless--yes. Files with other extensions (e.g..tmpleftovers) are not touched.splashboard cache clear <widget_id> [--json]— remove a single widget's entry plus its lock. Per the issue Open Questions, this uses Option 1: compute the cache key from the current config (viaresolve_dashboard_source). Works as long as the widget is still configured; reports a clear error if not. Cache schema is unchanged.Implementation notes
sanitizestep fromcache::Cache::path_for(currently module-private) insidemain.rs::sanitize_cache_key. A unit test (clear_one_matches_cache_filename_layout) pins the contract: the on-disk filenamemain.rscomputes for a key must equal whatcache.rswrites. Ifcache::sanitizeandmain::sanitize_cache_keyever drift, that test fires.localeandtimezoneon the synthesizedFetchContextare explicitlyNone—default_cache_keydoes not read them, and any fetcher that overridescache_keyto consume them produces keys we can't reproduce here without a full runtime pass anyway. Worth noting in case you want to expose them later.cache listis oldest-first so stale and orphan files surface at the top.Tests
7 new unit tests under
#[cfg(test)] mod tests:All 35 existing
splashboardbinary tests still pass.Smoke test
Open questions
--jsonoutput format I chose:cache listemits one JSON object per line (line-delimited),cache clearemits a single summary object. Happy to switch to a wrapping array if you prefer.--forceflag for stealing locks held by a running daemon —clear_allwill remove.lockfiles but it doesn't checkcache::Lock::try_acquirefirst. If you want safer concurrency around clear, happy to layer that on.Summary by CodeRabbit
New Features
cacheCLI withpath,list, andclearsubcommands.listshows cache entries with age/TTL/freshness/outcome, emits orphan lock files, supports JSON, and tolerates unreadable payloads.clearremoves per-widget or all cache files, supports confirmation bypass (--yes) and JSON summaries, and reports removals vs missing items; errors when widget not found or not cache-backed.Tests