Skip to content

feat(install): add splashboard install one-shot onboarding (#58) - #98

Merged
unhappychoice merged 2 commits into
mainfrom
feat/install-subcommand
Apr 24, 2026
Merged

unhappychoice merged 2 commits into
mainfrom
feat/install-subcommand

Conversation

@unhappychoice

@unhappychoice unhappychoice commented Apr 23, 2026 •

Copy link
Copy Markdown
Owner

Closes #58.

Summary

  • Adds splashboard install — detects the shell from $SHELL, opens a fullscreen gallery picker (preview + description per preset) so the user can see each themed preset rendered with sample data before committing, writes $HOME/.splashboard/home.dashboard.toml + project.dashboard.toml, preserves any existing settings.toml, and appends a marker-delimited block to the shell rc that sources splashboard init <shell>.
  • Non-TTY / scripted bootstrap: --shell <bash|zsh|fish|powershell> --home-template <name> --project-template <name> --yes. --yes also gates overwriting existing dashboards (with .bak sidecars) and creating a missing rc file.
  • Idempotent rc wiring: a second run replaces the existing marker block in place instead of stacking duplicates; no-op when the block is already current.
  • README's install section now leads with splashboard install; splashboard init <shell> remains the low-level escape hatch for users who want to own the rc edit themselves.

Template catalog (#77) and config split (#82) land-ready — this PR just plugs into the existing src/templates/ and the home.dashboard.toml / project.dashboard.toml filenames.

Test plan

  • cargo fmt --all -- --check
  • cargo clippy --all-targets -- -D warnings
  • cargo test (485 tests pass; 16 new install tests cover shell detection, rc append/replace/idempotency, dashboard write-with-backup, settings preservation, and an end-to-end install::run() scenario against a scratch home dir)
  • Manual smoke test in a real TTY — confirmed by opening a throwaway SPLASHBOARD_HOME and running splashboard install --shell zsh --home-template home_splash --project-template project_github_activity --yes; files land correctly and the summary prints.
  • Manual TTY picker interaction (home → project selection, arrow navigation, Esc to cancel) — not covered by automated tests; reviewer can verify by running the command without template flags.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added an interactive one-shot splashboard install that auto-detects your shell, offers template/theme previews and toggles, supports a scripted non‑TTY mode with deterministic flags, and updates your shell rc idempotently (creates .bak backups when replacing files).
  • Documentation

    • Updated install and getting-started docs with the new installer flow, examples (interactive and non‑interactive), files written to ~/.splashboard, and rerender guidance.

@coderabbitai

coderabbitai Bot commented Apr 23, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR adds a one-shot splashboard install command with an interactive TTY picker and non‑TTY scripted mode, auto-detects or accepts an explicit shell, selects home/project templates and theme, writes starter settings.toml plus home.dashboard.toml/project.dashboard.toml into ~/.splashboard/, and idempotently wires the shell rc with a marker block. Documentation and preview tooling for the picker were also added.

Changes

Cohort / File(s) Summary
Documentation
README.md, docs-site/src/content/docs/guides/getting-started.md
Replace install docs with splashboard install flow, document interactive picker, files written to ~/.splashboard/, idempotent rc marker behavior, and non‑TTY scripted flags/examples.
Install core
src/install/mod.rs
New installer entrypoint: pub struct InstallOptions and pub fn run(...) that resolves shell/home dir, validates inputs, invokes picker (TTY) or requires templates (non‑TTY), writes files with .bak semantics, calls rc wiring, and reports per-file outcomes.
Interactive picker UI
src/install/picker.rs
Full‑screen alternate‑screen TUI picker and confirmation flow (up to 4 screens): template pair, theme preview (from home template), bg/wait toggle, and final confirmation; cancels map to Interrupted.
Preview engine
src/install/preview.rs
Template preview builder that converts templates to deterministic widget payloads, freezes animated renderers into static render specs, and draws themed previews for picker display.
RC wiring
src/install/rc.rs
Idempotent marker‑delimited rc wiring: resolve rc path, create or replace/append marker block preserving other content, report RcReport/RcAction, and include unit tests for append/replace/no‑op/creation cases.
CLI integration
src/main.rs, src/lib.rs
Adds install CLI subcommand (flags: shell, home_template, project_template, theme, no_bg, wait) and exports new install module.
Shell utilities
src/shell.rs
Add detect_shell (env best‑effort), default_rc_path, source_line, as_str, and derive PartialEq/Eq; includes tests for detection and rc path behavior.

Sequence Diagram(s)

sequenceDiagram
    actor User as User
    participant CLI as splashboard (install)
    participant Picker as TTY Picker
    participant Preview as Template Preview
    participant FS as Filesystem
    participant RC as RC Wiring

    User->>CLI: run `splashboard install [--flags]`
    CLI->>CLI: detect shell (env or override)
    alt TTY interactive
        CLI->>Picker: open gallery (needs templates/settings)
        Picker->>Preview: request template preview
        Preview-->>Picker: rendered preview
        User->>Picker: choose templates/theme/settings
        Picker-->>CLI: return Selection
    else non‑TTY scripted
        CLI->>CLI: validate required flags (--home-template/--project-template)
    end
    CLI->>FS: create ~/.splashboard/ (if needed)
    CLI->>FS: write settings.toml / home.dashboard.toml / project.dashboard.toml (.bak semantics)
    CLI->>RC: wire_shell_rc(shell, override)
    RC->>FS: read/modify rc file (append/replace/skip)
    RC-->>CLI: RcReport
    CLI-->>User: print summary of file outcomes and next steps
Loading

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly Related Issues

Possibly Related PRs

Poem

🐰 In a burrow of TOML I neatly hide,

Pick home or project, come take a ride.
One hop in the picker, one install command —
Files appear tidy and rc's gently tanned.
Hop on, dear user — your shell's wired by hand.

🚥 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 summarizes the main addition: a new 'splashboard install' one-shot onboarding subcommand that automates shell rc wiring and starter config setup.
Linked Issues check ✅ Passed The PR implements all core objectives: shell detection, interactive template gallery picker in TTY, scriptable mode with flags, idempotent rc wiring with markers, dashboard/settings writes with .bak backups, and keeps splashboard init as snippet emitter.
Out of Scope Changes check ✅ Passed All changes directly support the install subcommand: README updates document the new workflow, shell.rs provides detection/rc-path utilities, picker.rs/preview.rs implement the interactive gallery, rc.rs handles idempotent wiring, and main.rs/lib.rs wire the CLI—no unrelated modifications.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% 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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/install-subcommand

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 56.46209% with 603 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (main@54f941f). Learn more about missing BASE report.
⚠️ Report is 5 commits behind head on main.

Files with missing lines Patch % Lines
src/install/picker.rs 0.00% 460 Missing ⚠️
src/install/mod.rs 86.13% 71 Missing ⚠️
src/install/rc.rs 79.72% 29 Missing ⚠️
src/install/preview.rs 88.38% 18 Missing ⚠️
src/main.rs 0.00% 18 Missing ⚠️
src/shell.rs 92.78% 7 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##             main      #98   +/-   ##
=======================================
  Coverage        ?   76.67%           
=======================================
  Files           ?       86           
  Lines           ?    14287           
  Branches        ?        0           
=======================================
  Hits            ?    10955           
  Misses          ?     3332           
  Partials        ?        0           
Files with missing lines Coverage Δ
src/shell.rs 94.69% <92.78%> (ø)
src/install/preview.rs 88.38% <88.38%> (ø)
src/main.rs 24.63% <0.00%> (ø)
src/install/rc.rs 79.72% <79.72%> (ø)
src/install/mod.rs 86.13% <86.13%> (ø)
src/install/picker.rs 0.00% <0.00%> (ø)
🚀 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.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
README.md (1)

146-156: ⚠️ Potential issue | 🟡 Minor

Filesystem layout diagram is stale relative to splashboard install.

The install section now states the installer writes home.dashboard.toml + project.dashboard.toml + settings.toml to $HOME/.splashboard/, but this tree still shows a single config.toml as "global config" and omits settings.toml. New readers following the install flow will find no config.toml on disk and the diagram will look inconsistent with the getting-started guide.

📝 Suggested diagram refresh
 $HOME/.splashboard/
-├── config.toml        # global config
+├── settings.toml              # global settings (theme, bg, wait_for_fresh, …)
+├── home.dashboard.toml        # home dashboard (new shells, non-repo cd)
+├── project.dashboard.toml     # fallback project dashboard (repos without local .splashboard/)
 ├── trust.toml         # trust store (path + sha256 entries)
 ├── cache/             # per-widget cache (key.json + key.lock)
 └── store/             # ReadStore files — $HOME/.splashboard/store/<id>.<ext>

The snippet on L65-96 (# $HOME/.splashboard/config.toml) is also worth pointing at home.dashboard.toml for the same reason.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@README.md` around lines 146 - 156, Update the README filesystem diagram to
match the installer output: replace the single global config "config.toml" with
the actual files written by the installer (home.dashboard.toml,
project.dashboard.toml and settings.toml), keep trust.toml, cache/ and store/
entries, and explicitly show where per-repo configs (./.splashboard/config.toml
or ./.splashboard.toml) live; also update the earlier snippet that references
"$HOME/.splashboard/config.toml" (the L65-96 section) to point at
home.dashboard.toml instead so the examples and install flow are consistent.
🧹 Nitpick comments (3)
src/install/picker.rs (1)

291-322: Nit: double-Option return type is easy to misread.

io::Result<Option<Option<&'static str>>> encodes "cancel vs selection" in the outer Option and "default theme vs named preset" in the inner. It works but reads awkwardly at every callsite. Consider a two-variant enum (ThemePick::Cancelled / ThemePick::Chose(Option<&'static str>)) or a dedicated PickResult<T>.

Non-blocking — current callers handle it fine via let Some(theme) = run_theme_picker(...)?.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/install/picker.rs` around lines 291 - 322, The return type of
run_theme_picker is hard to read as io::Result<Option<Option<&'static str>>>;
replace it with a small enum (e.g. ThemePick with variants Cancelled and
Chose(Option<&'static str>)) and change run_theme_picker's signature to
io::Result<ThemePick>, update the function to return ThemePick::Cancelled or
ThemePick::Chose(Some(key)) / ThemePick::Chose(None) where it currently returns
Ok(None) / Ok(Some(...)) and adjust all callers to match the new enum
(pattern-match the ThemePick instead of nested Options).
src/shell.rs (1)

53-64: classify_shell_path only splits on / — Windows paths with \ fall through.

If $SHELL on Windows/WSL-ish edge cases points at e.g. C:\Program Files\Git\bin\bash.exe, rsplit('/') yields the full string and split('.') then returns "c:\\program files\\git\\bin\\bash", which won't match any arm. The comment at L55 anticipates zsh.exe but doesn't cover backslash separators. Low-severity because $SHELL on Windows is almost always POSIX-style (msys/Cygwin), and the $PSModulePath fallback handles native PowerShell.

♻️ Handle both separators
-    let name = path.rsplit('/').next().unwrap_or(path).to_ascii_lowercase();
+    let name = path
+        .rsplit(|c| c == '/' || c == '\\')
+        .next()
+        .unwrap_or(path)
+        .to_ascii_lowercase();
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/shell.rs` around lines 53 - 64, The function classify_shell_path only
splits on '/' so Windows-style paths with '\' don't yield the correct basename;
update classify_shell_path to normalize extraction of the executable name and
strip the extension using std::path::Path APIs (e.g.,
Path::new(path).file_stem().and_then(|s| s.to_str()).map(|s|
s.to_ascii_lowercase())) instead of rsplit('/')/split('.'), then match that bare
name against the Shell variants (Shell::Bash, Shell::Zsh, Shell::Fish,
Shell::Powershell) to correctly handle both POSIX and Windows paths (including
.exe).
src/install/mod.rs (1)

354-372: Dead empty block with an orphan comment.

if !wrote_general { /* comment only */ } (lines 356-358) has no effect; the comment describes behavior that doesn't happen here. Drop the whole if so future readers aren't left wondering what was meant to live in it.

♻️ Proposed cleanup
     let needs_theme_section = choices.theme.is_some() || !choices.bg;
     if needs_theme_section {
-        if !wrote_general {
-            // Otherwise the only section boundary below is the theme block.
-        }
         out.push_str("[theme]\n");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/install/mod.rs` around lines 354 - 372, Remove the dead conditional block
that only contains a comment: delete the `if !wrote_general { /* Otherwise the
only section boundary below is the theme block. */ }` block so the theme
emission code (the `needs_theme_section` check and subsequent writes) is not
preceded by an empty/orphaned `if`; reference `needs_theme_section`,
`wrote_general`, and `choices.theme` to locate the code and ensure no other
logic is changed.
🤖 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/install/mod.rs`:
- Around line 68-71: The CLI currently skips both the settings picker and
merge_settings_flags when destinations.settings.exists() is true, silently
dropping --theme/--bg/--wait; adjust the logic so that presence of these flags
(e.g. check opts.theme/is_some, opts.bg/is_some, opts.wait/is_some) is detected
even when settings exists and trigger either merge_settings_flags or emit a
diagnostic/warning. Specifically, preserve or call merge_settings_flags (or at
minimum set settings_choices) when flags_present is true regardless of
settings_needed, and ensure write_settings returns a status that print_summary
(which checks settings_choices) will include so users see a message that their
flags were applied or were ignored with a clear warning.
- Around line 301-309: The backup rename currently uses std::fs::rename(path,
&backup) which can overwrite an existing backup on Unix or fail on Windows;
change the logic in the same function (the block that computes backup =
path.with_extension(backup_extension(path)) and calls std::fs::rename) to first
compute a unique backup path (e.g., implement a helper unique_backup_path that
probes backup, backup.1, backup.2, … until a free filename is found) and then
rename to that unique path (or alternatively skip the rename if the initial
backup exists), and ensure you push that unique backup into the backups vector
and still return WriteOutcome::Overwrote.
- Around line 80-113: The picker is never pre-seeded with the provided flags;
opts.home_template and opts.project_template are only used as fallbacks after
picker::run returns None. Fix by resolving the flag templates early (call
select_template for opts.home_template and opts.project_template) and populate
picker::Needs.templates (the need_templates value passed into picker::run) with
those resolved values so the picker is pre-seeded; keep using
pre_home/home_for_theme_preview only for preview rendering and remove relying on
selection fallback logic that uses select_template after picker::run.

In `@src/install/picker.rs`:
- Around line 52-112: Create an RAII guard that owns the terminal and restores
state in Drop to cover panics and partial failures: define a struct (e.g.,
TerminalGuard or TerminalStateGuard) that contains
Terminal<CrosstermBackend<Stdout>> and implements Drop to call
disable_raw_mode(), execute!(backend_mut(), LeaveAlternateScreen) and
show_cursor(), swallowing errors in Drop; change enter_terminal() to construct
raw mode, enter alternate screen, build the Terminal and return the guard
(owning the Terminal) instead of a bare Terminal; update run() to keep the guard
in scope while calling run_screens so cleanup always runs on panic or early
returns, and remove or adapt exit_terminal() to either be a no-op or a method on
the guard for explicit early cleanup.

In `@src/install/rc.rs`:
- Around line 116-160: find_block currently pairs the first MARKER_OPEN with the
next MARKER_CLOSE, which allows a stray open to swallow user content; modify
find_block to detect a second MARKER_OPEN between the found open and the found
close (i.e., check if contents[after_open..close_abs] contains MARKER_OPEN) and
treat that as malformed by returning an error-like result instead of a valid
range; add a new Outcome::Malformed (or propagate an error) and update
replace_or_append to handle Outcome::Malformed by refusing to edit and returning
the Malformed outcome so the caller can surface a clear "rc looks corrupted,
refusing to edit" message; update tests (e.g.,
malformed_rc_with_stray_open_does_not_lose_content) to assert no splicing occurs
when a stray MARKER_OPEN is present.

---

Outside diff comments:
In `@README.md`:
- Around line 146-156: Update the README filesystem diagram to match the
installer output: replace the single global config "config.toml" with the actual
files written by the installer (home.dashboard.toml, project.dashboard.toml and
settings.toml), keep trust.toml, cache/ and store/ entries, and explicitly show
where per-repo configs (./.splashboard/config.toml or ./.splashboard.toml) live;
also update the earlier snippet that references "$HOME/.splashboard/config.toml"
(the L65-96 section) to point at home.dashboard.toml instead so the examples and
install flow are consistent.

---

Nitpick comments:
In `@src/install/mod.rs`:
- Around line 354-372: Remove the dead conditional block that only contains a
comment: delete the `if !wrote_general { /* Otherwise the only section boundary
below is the theme block. */ }` block so the theme emission code (the
`needs_theme_section` check and subsequent writes) is not preceded by an
empty/orphaned `if`; reference `needs_theme_section`, `wrote_general`, and
`choices.theme` to locate the code and ensure no other logic is changed.

In `@src/install/picker.rs`:
- Around line 291-322: The return type of run_theme_picker is hard to read as
io::Result<Option<Option<&'static str>>>; replace it with a small enum (e.g.
ThemePick with variants Cancelled and Chose(Option<&'static str>)) and change
run_theme_picker's signature to io::Result<ThemePick>, update the function to
return ThemePick::Cancelled or ThemePick::Chose(Some(key)) /
ThemePick::Chose(None) where it currently returns Ok(None) / Ok(Some(...)) and
adjust all callers to match the new enum (pattern-match the ThemePick instead of
nested Options).

In `@src/shell.rs`:
- Around line 53-64: The function classify_shell_path only splits on '/' so
Windows-style paths with '\' don't yield the correct basename; update
classify_shell_path to normalize extraction of the executable name and strip the
extension using std::path::Path APIs (e.g.,
Path::new(path).file_stem().and_then(|s| s.to_str()).map(|s|
s.to_ascii_lowercase())) instead of rsplit('/')/split('.'), then match that bare
name against the Shell variants (Shell::Bash, Shell::Zsh, Shell::Fish,
Shell::Powershell) to correctly handle both POSIX and Windows paths (including
.exe).
🪄 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: d8ba5514-0ef3-4196-a477-098da4a293cf

📥 Commits

Reviewing files that changed from the base of the PR and between 005c895 and 372f699.

📒 Files selected for processing (9)
  • README.md
  • docs-site/src/content/docs/guides/getting-started.md
  • src/install/mod.rs
  • src/install/picker.rs
  • src/install/preview.rs
  • src/install/rc.rs
  • src/lib.rs
  • src/main.rs
  • src/shell.rs

Comment thread src/install/mod.rs Resolved
Comment thread src/install/mod.rs Resolved
Comment thread src/install/mod.rs
Comment on lines +301 to +309
let backup = path.with_extension(backup_extension(path));
std::fs::rename(path, &backup)?;
backups.push(backup);
std::fs::write(path, body)?;
return Ok(WriteOutcome::Overwrote);
}
std::fs::write(path, body)?;
Ok(WriteOutcome::Created)
}

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

Backup file is overwritten on repeat --yes runs (data loss + Windows error).

std::fs::rename(path, &backup) silently overwrites an existing destination on Unix and returns an error on Windows. On the second install --yes, home.dashboard.toml.bak from the first run gets clobbered (user's original hand-edited config is lost) or the install aborts on Windows. Consider suffixing with a timestamp / numeric counter, or skipping the rename if the .bak already exists.

🛡️ Possible fix sketch
-        let backup = path.with_extension(backup_extension(path));
-        std::fs::rename(path, &backup)?;
+        let backup = unique_backup_path(path);
+        std::fs::rename(path, &backup)?;
         backups.push(backup);

…with unique_backup_path probing .bak, .bak.1, .bak.2, … until it finds a free slot.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/install/mod.rs` around lines 301 - 309, The backup rename currently uses
std::fs::rename(path, &backup) which can overwrite an existing backup on Unix or
fail on Windows; change the logic in the same function (the block that computes
backup = path.with_extension(backup_extension(path)) and calls std::fs::rename)
to first compute a unique backup path (e.g., implement a helper
unique_backup_path that probes backup, backup.1, backup.2, … until a free
filename is found) and then rename to that unique path (or alternatively skip
the rename if the initial backup exists), and ensure you push that unique backup
into the backups vector and still return WriteOutcome::Overwrote.

Comment thread src/install/picker.rs
Comment on lines +52 to +112
pub(crate) fn run(
needs: Needs,
home_for_theme_preview: Option<&'static Template>,
) -> io::Result<Option<Selection>> {
let mut terminal = enter_terminal()?;
let result = run_screens(&mut terminal, needs, home_for_theme_preview);
exit_terminal(terminal)?;
result
}

fn run_screens(
terminal: &mut Terminal<CrosstermBackend<Stdout>>,
needs: Needs,
home_for_theme_preview: Option<&'static Template>,
) -> io::Result<Option<Selection>> {
let templates = if needs.templates {
let Some(pair) = run_template_picker_pair(terminal)? else {
return Ok(None);
};
Some(pair)
} else {
None
};

let settings = if needs.settings {
// For the theme picker preview we want the home template the user just picked (or
// the one they supplied via flag). Fall back to the first home template in the
// catalog when neither is available so the preview still shows something.
let preview_template = templates
.as_ref()
.map(|p| p.home)
.or(home_for_theme_preview)
.or_else(|| for_context(TemplateContext::Home).next());
let Some(choices) = run_settings_pickers(terminal, preview_template)? else {
return Ok(None);
};
Some(choices)
} else {
None
};

Ok(Some(Selection {
templates,
settings,
}))
}

fn enter_terminal() -> io::Result<Terminal<CrosstermBackend<Stdout>>> {
enable_raw_mode()?;
let mut out = stdout();
execute!(out, EnterAlternateScreen)?;
let backend = CrosstermBackend::new(stdout());
Terminal::new(backend)
}

fn exit_terminal(mut terminal: Terminal<CrosstermBackend<Stdout>>) -> io::Result<()> {
disable_raw_mode()?;
execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
terminal.show_cursor()?;
Ok(())
}

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

Terminal state isn't restored on panic or on a partial enter_terminal failure.

Two linked reliability gaps in the enter/exit dance:

  1. run() at L56-59: if run_screens panics (e.g. a ratatui draw closure unwinds on an unexpected backend error), the stack unwinds past exit_terminal, leaving raw mode enabled and the alternate screen still active. The user's next keystroke lands in a terminal that no longer echoes, and their scrollback is hidden — often requiring reset.
  2. enter_terminal at L99-105: enable_raw_mode()? runs first; if the subsequent execute!(out, EnterAlternateScreen) or Terminal::new(backend) fails, the ? returns early without disabling raw mode.

A Drop guard is the idiomatic Rust fix — ties the cleanup to stack unwinding so both the panic path and the error path benefit without threading cleanup through every return.

🛡️ RAII guard sketch
+struct TerminalGuard;
+
+impl TerminalGuard {
+    fn enter() -> io::Result<(Self, Terminal<CrosstermBackend<Stdout>>)> {
+        enable_raw_mode()?;
+        let guard = TerminalGuard; // raw mode now owned by the guard
+        execute!(stdout(), EnterAlternateScreen)?;
+        let terminal = Terminal::new(CrosstermBackend::new(stdout()))?;
+        Ok((guard, terminal))
+    }
+}
+
+impl Drop for TerminalGuard {
+    fn drop(&mut self) {
+        // Best-effort: swallow errors because we're on the unwind path.
+        let _ = disable_raw_mode();
+        let _ = execute!(stdout(), LeaveAlternateScreen);
+    }
+}
+
 pub(crate) fn run(
     needs: Needs,
     home_for_theme_preview: Option<&'static Template>,
 ) -> io::Result<Option<Selection>> {
-    let mut terminal = enter_terminal()?;
-    let result = run_screens(&mut terminal, needs, home_for_theme_preview);
-    exit_terminal(terminal)?;
-    result
+    let (_guard, mut terminal) = TerminalGuard::enter()?;
+    let result = run_screens(&mut terminal, needs, home_for_theme_preview);
+    // Guard drop handles raw mode + alt screen. Show cursor explicitly for the happy path.
+    let _ = terminal.show_cursor();
+    result
 }

The guard approach also means enter_terminal's partial-failure path (raw mode enabled, alt screen failed) cleans up automatically.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/install/picker.rs` around lines 52 - 112, Create an RAII guard that owns
the terminal and restores state in Drop to cover panics and partial failures:
define a struct (e.g., TerminalGuard or TerminalStateGuard) that contains
Terminal<CrosstermBackend<Stdout>> and implements Drop to call
disable_raw_mode(), execute!(backend_mut(), LeaveAlternateScreen) and
show_cursor(), swallowing errors in Drop; change enter_terminal() to construct
raw mode, enter alternate screen, build the Terminal and return the guard
(owning the Terminal) instead of a bare Terminal; update run() to keep the guard
in scope while calling run_screens so cleanup always runs on panic or early
returns, and remove or adapt exit_terminal() to either be a no-op or a method on
the guard for explicit early cleanup.

Comment thread src/install/rc.rs
Comment on lines +116 to +160
fn replace_or_append(contents: &str, block: &str) -> Outcome {
match find_block(contents) {
Some((start, end)) => {
let existing_block = &contents[start..end];
if existing_block.trim_end() == block.trim_end() {
return Outcome::UpToDate;
}
let mut new = String::with_capacity(contents.len() + block.len());
new.push_str(&contents[..start]);
new.push_str(block);
new.push_str(&contents[end..]);
Outcome::Replaced(new)
}
None => {
let mut new = String::with_capacity(contents.len() + block.len() + 1);
new.push_str(contents);
if !contents.ends_with('\n') && !contents.is_empty() {
new.push('\n');
}
if !contents.is_empty() {
new.push('\n');
}
new.push_str(block);
Outcome::Appended(new)
}
}
}

/// Returns the byte range `[start, end)` covering the full marker block including its
/// trailing newline (if any), or `None` when the block isn't present. The range is
/// inclusive of the open marker line and exclusive of the line after the close marker,
/// so splicing `contents[..start] + new_block + contents[end..]` keeps surrounding
/// whitespace intact.
fn find_block(contents: &str) -> Option<(usize, usize)> {
let start = contents.find(MARKER_OPEN)?;
let after_open = start + MARKER_OPEN.len();
let close_rel = contents[after_open..].find(MARKER_CLOSE)?;
let close_abs = after_open + close_rel;
// Consume up to and including the newline that terminates the close marker line.
let end = contents[close_abs..]
.find('\n')
.map(|nl| close_abs + nl + 1)
.unwrap_or(contents.len());
Some((start, end))
}

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

Data-loss risk if rc contains a stray MARKER_OPEN without a matching MARKER_CLOSE.

find_block finds the first MARKER_OPEN, then searches forward for the next MARKER_CLOSE. If a user's rc has an unclosed # >>> splashboard >>> (partial edit, aborted previous run, manual deletion of the close line), the sequence is:

  1. First invocation: find_block returns None (no close after the stray open), so replace_or_append takes the None branch and appends a fresh block at the bottom.
  2. Second invocation: find_block now finds the stray open at the top and pairs it with the close marker of the block that was just appended — (start, end) spans everything between them.
  3. Replaced splices contents[..start] + block + contents[end..] → all user rc content between the stray open and the new block is silently deleted.

Worth hardening find_block to reject the malformed case (multiple MARKER_OPEN between start and the next CLOSE) and either refuse to edit or return an error the caller can surface.

🛡️ Suggested defensive check
 fn find_block(contents: &str) -> Option<(usize, usize)> {
     let start = contents.find(MARKER_OPEN)?;
     let after_open = start + MARKER_OPEN.len();
     let close_rel = contents[after_open..].find(MARKER_CLOSE)?;
     let close_abs = after_open + close_rel;
+    // Reject the malformed case where another MARKER_OPEN appears before the close —
+    // replacing across it would eat user content that lives between the two opens.
+    if contents[after_open..close_abs].contains(MARKER_OPEN) {
+        return None; // caller should surface this rather than silently overwrite
+    }
     let end = contents[close_abs..]
         .find('\n')
         .map(|nl| close_abs + nl + 1)
         .unwrap_or(contents.len());
     Some((start, end))
 }

You'll likely want a dedicated Outcome::Malformed / RcAction::Malformed (or an io::Error) rather than falling through to Appended when this triggers, so the user sees "rc looks corrupted, refusing to edit" instead of a silent second stacked block.

Test worth adding:

#[test]
fn malformed_rc_with_stray_open_does_not_lose_content() {
    let block = format_block(Shell::Zsh);
    let stale = format!("{MARKER_OPEN}\nuser content\nmore content\n{block}");
    // Assert we don't produce a splice that drops "user content" / "more content".
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/install/rc.rs` around lines 116 - 160, find_block currently pairs the
first MARKER_OPEN with the next MARKER_CLOSE, which allows a stray open to
swallow user content; modify find_block to detect a second MARKER_OPEN between
the found open and the found close (i.e., check if
contents[after_open..close_abs] contains MARKER_OPEN) and treat that as
malformed by returning an error-like result instead of a valid range; add a new
Outcome::Malformed (or propagate an error) and update replace_or_append to
handle Outcome::Malformed by refusing to edit and returning the Malformed
outcome so the caller can surface a clear "rc looks corrupted, refusing to edit"
message; update tests (e.g., malformed_rc_with_stray_open_does_not_lose_content)
to assert no splicing occurs when a stray MARKER_OPEN is present.

Closes #58. `splashboard install` detects the shell, walks through four
previewed pickers — home template, project template, theme, bg/wait
toggles — shows a review-and-confirm page, then writes the starter
`home.dashboard.toml` + `project.dashboard.toml` + `settings.toml` to
`$HOME/.splashboard/` and appends a marker-delimited block to the shell rc
sourcing `splashboard init <shell>`.

Key design points:

- **Previews driven by sample data.** Each picker renders the real ratatui
  layout engine with fetcher `sample_body()` outputs, so the visual matches
  what the user will see post-install with zero network / filesystem I/O
  during selection.
- **Theme picker re-renders the home template** under the highlighted preset
  so users pick by combined look rather than naked palette names.
- **Single alt-screen session** across all five screens — no flicker between
  picker steps.
- **Idempotent file writes.** Every destination (dashboards, settings, shell
  rc) renames the existing file to a `.bak` sidecar before writing the new
  content; identical content short-circuits to `Unchanged` so re-runs with
  the same flags don't churn backups. No `--yes` gate — the `.bak` is the
  safety net, so the flag would only be friction.
- **Scripted path skips the picker and confirmation** when all inputs arrive
  via flags (`--shell`, `--home-template`, `--project-template`, `--theme`,
  `--no-bg`, `--wait`), keeping dotfile bootstrap deterministic.

Other touches: README install section rewritten around `splashboard install`,
Getting Started guide documents all five picker screens + the scripted flow,
`splashboard init <shell>` stays as the low-level escape hatch.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@unhappychoice
unhappychoice force-pushed the feat/install-subcommand branch from bc63471 to f86efb3 Compare April 24, 2026 01:16
- `shell::classify_shell_path` splits on both `/` and `\` so Windows-style
  `$SHELL` values (`C:\Program Files\PowerShell\7\pwsh.exe`, cygwin /
  WSL shims) classify correctly. `std::path::Path` is platform-aware and
  would leave `\`-paths as one opaque segment on Unix, so we split manually.
  Added a regression test.
- `picker::run_theme_picker` replaces the `io::Result<Option<Option<&str>>>`
  return type with a dedicated `ThemePick` enum (`Cancelled` vs
  `Chose(Option<&str>)`). Makes the intent of the inner `None` (= "user
  picked default, write no preset line") readable at the call site.

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

🧹 Nitpick comments (3)
docs-site/src/content/docs/guides/getting-started.md (1)

25-42: Minor docs inaccuracy: the “Defaults” screen doesn’t render a preview.

Line 25–27 tells users “four gallery pickers — each with a live preview,” but the 4th picker (the bg / wait_for_fresh toggle screen) has no preview pane in src/install/picker.rs::draw_toggle_frame — only header / list / footer. Either reword the intro to scope “live preview” to the first three screens, or clarify that the toggles screen is a form rather than a gallery.

📝 Proposed wording tweak
-The installer auto-detects your shell and walks you through four gallery
-pickers — each with a live preview rendered from the shipped templates and
-your chosen theme — followed by a final confirmation page:
+The installer auto-detects your shell and walks you through four screens —
+the first three are gallery pickers with a live preview rendered from the
+shipped templates and your chosen theme; the fourth is a toggle form —
+followed by a final confirmation page:
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs-site/src/content/docs/guides/getting-started.md` around lines 25 - 42,
Update the Getting Started intro so it doesn't claim all four gallery pickers
have live previews: change the phrasing around "four gallery pickers — each with
a live preview" to indicate that only the first three screens render a live
preview and that the fourth "Defaults" screen (rendered by draw_toggle_frame) is
a toggle/form without a preview; alternatively, rephrase to call the fourth
screen a form for toggles (bg / wait_for_fresh) rather than a gallery so the
docs match the implementation in draw_toggle_frame.
src/install/mod.rs (1)

378-402: Dead if !wrote_general block — nothing inside, wrote_general read nowhere else.

The variable is set at L382 but its only consumer is an if with a comment-only body. Either act on it (e.g. emit a blank-line separator between [general] and [theme]) or drop the variable and the empty conditional.

♻️ Drop-or-act cleanup
-    let mut wrote_general = false;
     if choices.wait != SettingsChoices::DEFAULT.wait {
         out.push_str("[general]\n");
         out.push_str(&format!("wait_for_fresh = {}\n\n", choices.wait));
-        wrote_general = true;
     }
     let needs_theme_section = choices.theme.is_some() || !choices.bg;
     if needs_theme_section {
-        if !wrote_general {
-            // Otherwise the only section boundary below is the theme block.
-        }
         out.push_str("[theme]\n");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/install/mod.rs` around lines 378 - 402, The variable wrote_general is set
when writing the [general] block but only used in an empty conditional before
emitting [theme]; fix by making that conditional emit a separator newline so a
blank line is written between the [general] and [theme] sections: inside the
existing if !wrote_general check (referencing wrote_general, choices.wait, and
the needs_theme_section/theme block) call out.push('\n'); before pushing
"[theme]\n"; this preserves the intended section boundary formatting;
alternatively, if you prefer removing dead code, delete wrote_general and the
empty if entirely and ensure spacing is correct when both sections are present.
src/shell.rs (1)

77-91: Avoid the dirs crate for home-dir resolution.

Based on learnings: "Use $HOME/.splashboard/ as the single user-visible state directory for all platforms; do not use XDG paths or the dirs crate". Reading $HOME directly (with USERPROFILE as the Windows fallback for PowerShell) keeps the crate off the dep tree and stays consistent with how the rest of the codebase resolves home paths.

♻️ Drop-in replacement sketch
 pub fn default_rc_path(shell: Shell) -> Option<PathBuf> {
-    let home = dirs::home_dir()?;
+    let home = std::env::var_os("HOME")
+        .or_else(|| std::env::var_os("USERPROFILE"))
+        .map(PathBuf::from)?;
     Some(match shell {

If dirs isn’t needed anywhere else after this, it can also be pruned from Cargo.toml.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/shell.rs` around lines 77 - 91, Replace the use of dirs::home_dir() in
default_rc_path with direct environment lookups: read HOME via
std::env::var_os("HOME") and, for Windows/PowerShell fallback, use
std::env::var_os("USERPROFILE") if HOME is not set; return None if neither is
present. Keep the existing match on Shell (Shell::Bash, Shell::Zsh, Shell::Fish,
Shell::Powershell) and build PathBufs from the resolved home value as before;
after this change you can remove the dirs dependency if it's unused elsewhere.
🤖 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/install/mod.rs`:
- Around line 370-376: The preamble in build_settings_toml is incorrect: update
the string pushed in build_settings_toml (where out.push_str(...) is called) to
remove the reference to a non-existent "--yes" flag and to accurately describe
that re-running the installer will create a backup (settings.toml.bak) and
rewrite the file when contents differ; keep the note that the file is safe to
edit by hand but clarify that the installer will back up and update on changes
rather than "leaving this file alone."

In `@src/shell.rs`:
- Around line 210-218: The test
default_rc_path_for_known_shells_ends_in_expected_file panics if
HOME/USERPROFILE is unset because it calls default_rc_path(...).unwrap(); change
the test to avoid unwrap by either asserting via map_or (e.g.,
assert!(default_rc_path(Shell::Zsh).map_or(true, |p| p.ends_with(".zshrc"))))
for each Shell, or set a temporary HOME/USERPROFILE inside the test while
acquiring paths::TEST_ENV_LOCK to serialize env mutation; update the assertions
for Shell::Bash and Shell::Fish similarly and reference default_rc_path and
Shell in the test.

---

Nitpick comments:
In `@docs-site/src/content/docs/guides/getting-started.md`:
- Around line 25-42: Update the Getting Started intro so it doesn't claim all
four gallery pickers have live previews: change the phrasing around "four
gallery pickers — each with a live preview" to indicate that only the first
three screens render a live preview and that the fourth "Defaults" screen
(rendered by draw_toggle_frame) is a toggle/form without a preview;
alternatively, rephrase to call the fourth screen a form for toggles (bg /
wait_for_fresh) rather than a gallery so the docs match the implementation in
draw_toggle_frame.

In `@src/install/mod.rs`:
- Around line 378-402: The variable wrote_general is set when writing the
[general] block but only used in an empty conditional before emitting [theme];
fix by making that conditional emit a separator newline so a blank line is
written between the [general] and [theme] sections: inside the existing if
!wrote_general check (referencing wrote_general, choices.wait, and the
needs_theme_section/theme block) call out.push('\n'); before pushing
"[theme]\n"; this preserves the intended section boundary formatting;
alternatively, if you prefer removing dead code, delete wrote_general and the
empty if entirely and ensure spacing is correct when both sections are present.

In `@src/shell.rs`:
- Around line 77-91: Replace the use of dirs::home_dir() in default_rc_path with
direct environment lookups: read HOME via std::env::var_os("HOME") and, for
Windows/PowerShell fallback, use std::env::var_os("USERPROFILE") if HOME is not
set; return None if neither is present. Keep the existing match on Shell
(Shell::Bash, Shell::Zsh, Shell::Fish, Shell::Powershell) and build PathBufs
from the resolved home value as before; after this change you can remove the
dirs dependency if it's unused elsewhere.
🪄 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: 66dbb8eb-a3d1-4a51-90d1-283642da75f7

📥 Commits

Reviewing files that changed from the base of the PR and between 372f699 and 294b2a2.

📒 Files selected for processing (9)
  • README.md
  • docs-site/src/content/docs/guides/getting-started.md
  • src/install/mod.rs
  • src/install/picker.rs
  • src/install/preview.rs
  • src/install/rc.rs
  • src/lib.rs
  • src/main.rs
  • src/shell.rs
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/lib.rs
  • src/main.rs
  • README.md

Comment thread src/install/mod.rs
Comment on lines +370 to +376
fn build_settings_toml(choices: SettingsChoices) -> String {
let mut out = String::new();
out.push_str(
"# Written by `splashboard install`. User preferences that apply to every dashboard.\n\
# Safe to edit by hand. Re-running `splashboard install` leaves this file alone\n\
# unless you pass `--yes`, which backs it up as `settings.toml.bak` before rewriting.\n\n",
);

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

Generated settings.toml preamble references a --yes flag that doesn’t exist and mis-describes re-run behavior.

InstallOptions has no yes field and the CLI doesn’t expose --yes; the installer always .baks + rewrites on content-diff, never "leaves this file alone." The preamble currently tells users the opposite. This will trip up anyone reading their own ~/.splashboard/settings.toml looking for the flag, and misleads about what a re-run does.

📝 Suggested preamble fix
     out.push_str(
         "# Written by `splashboard install`. User preferences that apply to every dashboard.\n\
-         # Safe to edit by hand. Re-running `splashboard install` leaves this file alone\n\
-         # unless you pass `--yes`, which backs it up as `settings.toml.bak` before rewriting.\n\n",
+         # Safe to edit by hand. Re-running `splashboard install` with different choices\n\
+         # renames this file to `settings.toml.bak` before writing the new content; an\n\
+         # identical re-run is a no-op.\n\n",
     );
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/install/mod.rs` around lines 370 - 376, The preamble in
build_settings_toml is incorrect: update the string pushed in
build_settings_toml (where out.push_str(...) is called) to remove the reference
to a non-existent "--yes" flag and to accurately describe that re-running the
installer will create a backup (settings.toml.bak) and rewrite the file when
contents differ; keep the note that the file is safe to edit by hand but clarify
that the installer will back up and update on changes rather than "leaving this
file alone."

Comment thread src/shell.rs
Comment on lines +210 to +218
#[test]
fn default_rc_path_for_known_shells_ends_in_expected_file() {
let rc = default_rc_path(Shell::Zsh).unwrap();
assert!(rc.ends_with(".zshrc"));
let rc = default_rc_path(Shell::Bash).unwrap();
assert!(rc.ends_with(".bashrc"));
let rc = default_rc_path(Shell::Fish).unwrap();
assert!(rc.ends_with("config.fish"));
}

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

Test will panic when $HOME/USERPROFILE is unset in CI.

default_rc_path(...).unwrap() relies on dirs::home_dir() (or your replacement) succeeding; in minimal CI sandboxes neither env var is guaranteed. If the test is kept as-is, consider assert!(default_rc_path(Shell::Zsh).map_or(true, |p| p.ends_with(".zshrc"))) or setting $HOME inside the test (with paths::TEST_ENV_LOCK guard — as per coding guidelines: "Tests that mutate process environment variables must take paths::TEST_ENV_LOCK to serialize with other tests").

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/shell.rs` around lines 210 - 218, The test
default_rc_path_for_known_shells_ends_in_expected_file panics if
HOME/USERPROFILE is unset because it calls default_rc_path(...).unwrap(); change
the test to avoid unwrap by either asserting via map_or (e.g.,
assert!(default_rc_path(Shell::Zsh).map_or(true, |p| p.ends_with(".zshrc"))))
for each Shell, or set a temporary HOME/USERPROFILE inside the test while
acquiring paths::TEST_ENV_LOCK to serialize env mutation; update the assertions
for Shell::Bash and Shell::Fish similarly and reference default_rc_path and
Shell in the test.

@unhappychoice
unhappychoice merged commit 38b6f8b into main Apr 24, 2026
7 checks passed
@unhappychoice
unhappychoice deleted the feat/install-subcommand branch April 24, 2026 02:37
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.

feat: "splashboard install" — one-shot setup (rc wiring + starter config from template)

1 participant