Skip to content

feat: "splashboard cache" management CLI — list, clear, path (#40) - #216

Merged
unhappychoice merged 5 commits into
unhappychoice:mainfrom
satyakwok:feat-cache-cli-40
May 11, 2026
Merged

unhappychoice merged 5 commits into
unhappychoice:mainfrom
satyakwok:feat-cache-cli-40

Conversation

@satyakwok

@satyakwok satyakwok commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

Closes #40.

Adds a top-level cache subcommand 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 .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.
  • splashboard cache clear [--yes] [--json] — remove every .json + .lock file in the cache dir. Confirms unless --yes. Files with other extensions (e.g. .tmp leftovers) 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 (via resolve_dashboard_source). Works as long as the widget is still configured; reports a clear error if not. Cache schema is unchanged.

Implementation notes

  • The widget-id path replicates the sanitize step from cache::Cache::path_for (currently module-private) inside main.rs::sanitize_cache_key. A unit 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 and main::sanitize_cache_key ever drift, that test fires.
  • locale and timezone on the synthesized FetchContext are explicitly None — default_cache_key does not read them, and any fetcher that overrides cache_key to 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.
  • Sort order for cache list is oldest-first so stale and orphan files surface at the top.

Tests

7 new unit tests under #[cfg(test)] mod tests:

test tests::clear_all_handles_missing_dir_quietly                       ... ok
test tests::clear_all_removes_json_and_lock_files                       ... ok
test tests::clear_one_matches_cache_filename_layout                     ... ok
test tests::collect_cache_rows_reads_entry_and_lock_files               ... ok
test tests::collect_cache_rows_returns_empty_for_missing_dir            ... ok
test tests::sanitize_cache_key_matches_alnum_dash_underscore_passthrough ... ok
test tests::sanitize_cache_key_replaces_path_and_control_chars          ... ok

test result: ok. 7 passed; 0 failed

All 35 existing splashboard binary tests still pass.

Smoke test

$ splashboard cache path
/home/user/.splashboard/cache

$ splashboard cache list
(empty)

$ splashboard cache clear --yes
(empty)

Open questions

  1. The --json output format I chose: cache list emits one JSON object per line (line-delimited), cache clear emits a single summary object. Happy to switch to a wrapping array if you prefer.
  2. For widget-id clear, I picked the home dashboard as the implicit fallback when not in a project-local context. Open to changing the resolution rule if you want it to error instead of falling back.
  3. I did NOT add a --force flag for stealing locks held by a running daemon — clear_all will remove .lock files but it doesn't check cache::Lock::try_acquire first. If you want safer concurrency around clear, happy to layer that on.

Summary by CodeRabbit

  • New Features

    • Added top-level cache CLI with path, list, and clear subcommands.
    • list shows cache entries with age/TTL/freshness/outcome, emits orphan lock files, supports JSON, and tolerates unreadable payloads.
    • clear removes 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

    • Added unit tests covering listing, clearing, edge cases, and output truncation.

Review Change Stack

…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.
@satyakwok
satyakwok requested a review from unhappychoice as a code owner May 11, 2026 19:39
@coderabbitai

coderabbitai Bot commented May 11, 2026 •

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: cf5aab58-008b-485a-96da-53854974c1bc

📥 Commits

Reviewing files that changed from the base of the PR and between 74c2ea4 and b2dbf13.

📒 Files selected for processing (2)
  • src/cache.rs
  • src/main.rs

📝 Walkthrough

Walkthrough

Adds a splashboard cache CLI with path, list, and clear subcommands to inspect and manage the on-disk widget cache; implements row collection, sanitised filename derivation, deletion logic, JSON/human output, and unit tests.

Changes

Cache Management CLI

Layer / File(s) Summary
Imports and command types
src/main.rs
Adds SystemTime and FetchContext imports; introduces Command::Cache and CacheSubcommand (Path, List { json }, Clear { widget_id, yes, json }).
Main command dispatcher
src/main.rs
Routes Some(Command::Cache { subcommand }) into run_cache(subcommand).
Cache subcommand routing
src/main.rs
run_cache() resolves the cache directory and dispatches to listing, clearing, or prints the path.
Cache list structure and handler
src/main.rs
Adds CacheListRow and run_cache_list() to collect rows, sort by age, and render either a table or newline-delimited JSON.
Cache directory traversal and row collection
src/main.rs
collect_cache_rows() reads the cache dir, computes file age from mtime, parses .json into CacheEntry for TTL/freshness/outcome (falls back to unreadable), treats .lock files as auxiliary rows, skips unknown extensions and subdirectories, and returns empty for missing dirs.
Cache clear routing
src/main.rs
run_cache_clear() dispatches to clear_all() or clear_one() based on widget_id.
Clear all cache implementation
src/main.rs
clear_all() targets .json and .lock files, optionally prompts unless --yes, deletes selected files, and reports removed/missing/errors in human or JSON output; returns non-zero on deletion failures.
Clear single widget cache implementation
src/main.rs
clear_one() derives the cache key from the current config and widget's disk-cache-capable fetcher, uses cache::sanitize to compute on-disk filenames, deletes .json and .lock variants, and reports removed vs missing; errors if widget absent or fetcher not disk-cached.
Sanitization and display helpers
src/cache.rs, src/main.rs
cache::sanitize made pub and #[doc(hidden)] for cross-module filename-stem derivation; truncate() added for grapheme-safe truncation with ellipsis handling.
Unit tests for cache operations
src/main.rs
Tests assert filename-layout compatibility, listing behavior (missing/populated dirs, unreadable JSON, unknown extensions, subdirs), clear-all selection and prompt behavior, clear-one filename expectation, and truncate() edge cases.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • unhappychoice/splashboard#28: Modifies the on-disk cache implementation and introduces Cache::path_for; related due to filename-sanitization compatibility checks.

Poem

🐰 I hopped through cache keys, neat and spry,
Sanitized names beneath the sky,
I list and clear with a polite little wink,
Truncate long keys before they blink,
Tests tucked in my pouch — tidy and spry.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main change: adding a new 'splashboard cache' management CLI with three subcommands (list, clear, path), which matches the primary objective of the PR.
Linked Issues check ✅ Passed All primary objectives from issue #40 are implemented: cache list with age/TTL/fresh/stale/size, cache clear with --yes confirmation, cache clear <widget_id> using current config, cache path command, .lock file handling, --json output support, and Option 1 for key-widget mapping.
Out of Scope Changes check ✅ Passed All changes are directly related to issue #40 objectives. The visibility change to cache::sanitize in src/cache.rs is a necessary implementation detail to support the new CLI functionality.
Docstring Coverage ✅ Passed Docstring coverage is 90.32% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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.

@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: 1

🧹 Nitpick comments (2)
src/main.rs (2)

628-722: ⚖️ Poor tradeoff

Function 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 value

Function 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

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a207d90d-f81a-4b0a-9915-e4a49552b38a

📥 Commits

Reviewing files that changed from the base of the PR and between b4947f9 and 74c2ea4.

📒 Files selected for processing (1)
  • src/main.rs

Comment thread src/main.rs Resolved
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.
@satyakwok

Copy link
Copy Markdown
Contributor Author

Thanks for the review — pushed 1eac161 addressing the actionable item:

Line 670 shape-override caveat ✅ — the had no cache entry error message now explicitly states the key was computed with default_shape() + no locale/timezone overrides, and points the user at splashboard cache list + manual delete as the fallback when their config overrides any of those. Same note added to the Clear subcommand help text so it surfaces via splashboard cache clear --help.

Two function-length nitpicks — skipped intentionally:

  • clear_one (628-722): CodeRabbit itself flagged this as ⚖️ Poor tradeoff. The proposed split (resolve_widget_and_fetcher → compute_cache_key → remove_cache_files → format_clear_output) would introduce four single-use helpers each called exactly once in sequence; net code length grows, the data flow becomes a parameter-pass relay, and no test surface is added that the current single function doesnt already cover. Happy to split if maintainer prefers though.
  • collect_cache_rows (479-550): CodeRabbit marked 💤 Low value. Same reasoning — the per-extension branch is cohesive and pulling it out would replace one inline match with two functions that pass now: SystemTime and per-file metadata around. Will split if you want it strictly to the guideline.

Both are cosmetic; final call yours.

@codecov

codecov Bot commented May 11, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 70.96774% with 117 lines in your changes missing coverage. Please review.
✅ Project coverage is 95.59%. Comparing base (b4947f9) to head (b2dbf13).
⚠️ Report is 9 commits behind head on main.

Files with missing lines Patch % Lines
src/main.rs 70.89% 117 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            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     
Files with missing lines Coverage Δ
src/cache.rs 97.25% <100.00%> (ø)
src/main.rs 86.66% <70.89%> (-12.01%) ⬇️

... and 18 files 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.

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.
@satyakwok

Copy link
Copy Markdown
Contributor Author

Pushed 3b45780:

Clippy fixes (CI was hitting -D warnings):

  • clippy::unnecessary_sort_by → switched to sort_by_key(|r| std::cmp::Reverse(r.age_seconds))
  • clippy::print_literal → inlined the trailing OUTCOME literal directly into the format string

Coverage boost: 35 → 46 tests (+11) targeting the codecov gaps:

  • clear_all empty-dir + non-cache-extension preservation branches
  • truncate (short / exact-length / long / one-char-cap edge cases)
  • collect_cache_rows (skip unknown extensions, mark unreadable JSON, skip subdirectories)
  • run_cache_list (both json + human modes, empty + populated)

cargo clippy --all-targets -- -D warnings: clean.
cargo test --bin splashboard: 46 passed, 0 failed.

Re-running CI now.

@unhappychoice unhappychoice left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

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 --yes to a flag that only exists on the no-id arm (different subcommand struct), or
  • keep the current shape and note in --help that 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_cache uses std::process::exit(2) when cache_dir() is None; rest of main.rs propagates io::Error (exit 1). Pick one — preferably io::Error::other(...) for consistency.
  • clear_all returns Err after partial success. That's the right Unix convention, but worth a sentence in --help so JSON consumers know they get both a removed count and a non-zero exit on partial failure.
  • JSONL for cache list is fine; flagging in case you want jq -s '.'-friendliness later, an array would be a one-liner.
  • collect_cache_rows and clear_all walk the directory twice in the clear path (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) --force for locked entries: I'd rather see try_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.
@satyakwok

Copy link
Copy Markdown
Contributor Author

Thanks for the careful review — addressed in b2dbf13.

Correctness

  • truncate now walks chars() instead of byte-slicing. Added truncate_handles_multi_byte_codepoints_without_panicking using a 3-codepoint / 9-byte CJK string (the cut at max - 1 = 3 would have landed mid-codepoint with the old impl).
  • Dropped main::sanitize_cache_key. The binary crate can't reach pub(crate) items from the library (separate crates), so I exposed cache::sanitize as pub fn with #[doc(hidden)] — same intent (signals "internal, don't depend on this from outside") while still letting main.rs call it. The contract test became a one-liner (assert_eq!(cache::path_for(...), dir.join(format!("{}.json", cache::sanitize(key))))); dropped the two now-redundant sanitize_cache_key_* tests since cache::path_for_sanitizes_unsafe_chars already covers the path-traversal defense.
  • list doc string now reads "Oldest first (stale / orphan entries surface at the top)" — same wording as the in-function comment, matches what --help users actually see.

Behavior / UX

  • --yes doc updated to spell out that it has no effect when a widget id is given. Left the shape as-is per your "either way" call — restructuring Clear into two subcommand variants felt heavier than the bug warranted.
  • clear doc gained two paragraphs: (a) the home-vs-project resolution behavior and the workaround (run from a directory that resolves to the right dashboard, or cache list + manual delete), (b) the daemon-refresh race caveat: "may race against an active daemon refresh; rerun if so. (A future release may add lock-aware skipping.)"
  • clear_all partial-success → exit non-zero is now called out in the doc so JSON consumers know to read both removed and the exit status.
  • run_cache's cache_dir() is None path now returns Err(io::Error::other(...)) instead of process::exit(2) — matches the rest of main.rs.

Out of scope (open question #3 + concurrency)

Agreed try_acquire + skip-locked is the right shape, not --force. Will land in a follow-up PR; the doc note is the placeholder until then.

Smoke gate

cargo build / cargo test (2054 lib + 45 + 12 + 3 = 2114 tests) / cargo clippy -D warnings / cargo fmt --check — all clean. splashboard cache clear --help and cache list --help both visually verified.

@unhappychoice unhappychoice left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

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.

@unhappychoice
unhappychoice merged commit b159a53 into unhappychoice:main May 11, 2026
7 checks passed
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.

ops: "splashboard cache" management CLI (list / clear)

2 participants