Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3d4fd8d048 | ||
|
|
cdc04ab266 | ||
|
|
46aff0e6b1 | ||
|
|
cb99d74b4e | ||
|
|
56176b2659 | ||
|
|
e2ce929698 | ||
|
|
924f989c05 | ||
|
|
f8b25e81bf |
42
Cargo.lock
generated
42
Cargo.lock
generated
@@ -23,6 +23,38 @@ version = "1.0.100"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61"
|
||||
|
||||
[[package]]
|
||||
name = "argh"
|
||||
version = "0.1.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "34ff18325c8a36b82f992e533ece1ec9f9a9db446bd1c14d4f936bac88fcd240"
|
||||
dependencies = [
|
||||
"argh_derive",
|
||||
"argh_shared",
|
||||
"rust-fuzzy-search",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "argh_derive"
|
||||
version = "0.1.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "adb7b2b83a50d329d5d8ccc620f5c7064028828538bdf5646acd60dc1f767803"
|
||||
dependencies = [
|
||||
"argh_shared",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.114",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "argh_shared"
|
||||
version = "0.1.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a464143cc82dedcdc3928737445362466b7674b5db4e2eb8e869846d6d84f4f6"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "atomic"
|
||||
version = "0.6.1"
|
||||
@@ -115,8 +147,10 @@ checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
|
||||
|
||||
[[package]]
|
||||
name = "chkr"
|
||||
version = "0.1.0"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"argh",
|
||||
"crossterm",
|
||||
"insta",
|
||||
"ratatui",
|
||||
@@ -989,6 +1023,12 @@ version = "0.8.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58"
|
||||
|
||||
[[package]]
|
||||
name = "rust-fuzzy-search"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a157657054ffe556d8858504af8a672a054a6e0bd9e8ee531059100c0fa11bb2"
|
||||
|
||||
[[package]]
|
||||
name = "rustc_version"
|
||||
version = "0.4.1"
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
[package]
|
||||
name = "chkr"
|
||||
version = "0.1.0"
|
||||
version = "0.3.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
crossterm = "0.29"
|
||||
ratatui = { version = "0.30", features = ["crossterm"] }
|
||||
anyhow = "1.0"
|
||||
argh = "0.1.13"
|
||||
|
||||
[dev-dependencies]
|
||||
insta = "1.33"
|
||||
|
||||
16
scripts/bump.sh
Normal file
16
scripts/bump.sh
Normal file
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
VERSION="$(git cliff --bumped-version)"
|
||||
VERSION_CLEAN="${VERSION#v}"
|
||||
sed -i "s/^version = \".*\"/version = \"${VERSION_CLEAN}\"/" Cargo.toml
|
||||
cargo check
|
||||
echo Press Y to commit version bump to ${VERSION_CLEAN}
|
||||
read -r CONFIRM
|
||||
if [ "${CONFIRM}" != "Y" ]; then
|
||||
echo Aborting
|
||||
exit 1
|
||||
fi
|
||||
git commit -am "chore: bump version to ${VERSION}"
|
||||
git tag -am "Version ${VERSION}" "${VERSION}"
|
||||
28
src/event_source.rs
Normal file
28
src/event_source.rs
Normal file
@@ -0,0 +1,28 @@
|
||||
//! Abstraction around event sourcing for the checklist application.
|
||||
use anyhow::Result;
|
||||
use crossterm::event::{self, Event};
|
||||
use std::time::Duration;
|
||||
|
||||
/// An abstraction around event sourcing so we can inject events in tests.
|
||||
pub trait EventSource {
|
||||
/// Polls for an event for up to `timeout`, returning `Ok(true)` if an event is
|
||||
/// available, `Ok(false)` if the timeout elapsed without an event, or an `Err`
|
||||
/// if polling failed.
|
||||
fn poll(&mut self, timeout: Duration) -> Result<bool>;
|
||||
|
||||
/// Reads the next available event, or returns an `Err` if reading fails.
|
||||
fn read(&mut self) -> Result<Event>;
|
||||
}
|
||||
|
||||
/// Production implementation that delegates to `crossterm::event`.
|
||||
pub struct CrosstermEventSource;
|
||||
|
||||
impl EventSource for CrosstermEventSource {
|
||||
fn poll(&mut self, timeout: Duration) -> Result<bool> {
|
||||
Ok(event::poll(timeout).map_err(Box::new)?)
|
||||
}
|
||||
|
||||
fn read(&mut self) -> Result<Event> {
|
||||
Ok(event::read().map_err(Box::new)?)
|
||||
}
|
||||
}
|
||||
138
src/main.rs
138
src/main.rs
@@ -1,24 +1,56 @@
|
||||
//! A simple terminal checklist application.
|
||||
mod event_source;
|
||||
mod terminal_guard;
|
||||
/// UI components (todo list)
|
||||
mod todo_list;
|
||||
|
||||
use anyhow::{Context as _, Result, anyhow, bail};
|
||||
use argh::FromArgs;
|
||||
use core::time::Duration;
|
||||
use crossterm::event::{self, EnableMouseCapture, Event, KeyCode};
|
||||
use crossterm::execute;
|
||||
use crossterm::terminal::{EnterAlternateScreen, enable_raw_mode};
|
||||
use event_source::{CrosstermEventSource, EventSource};
|
||||
use ratatui::Terminal;
|
||||
use ratatui::backend::Backend;
|
||||
use ratatui::backend::CrosstermBackend;
|
||||
use std::io::{self, Read as _};
|
||||
use terminal_guard::TerminalModeGuard;
|
||||
use todo_list::TodoList;
|
||||
|
||||
#[allow(clippy::wildcard_enum_match_arm)]
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut input = String::new();
|
||||
io::stdin().read_to_string(&mut input)?;
|
||||
#[derive(FromArgs)]
|
||||
/// chkr - terminal checklist
|
||||
struct Args {
|
||||
/// load checklist from file instead of stdin
|
||||
#[argh(option, short = 'f', long = "file")]
|
||||
file: Option<String>,
|
||||
|
||||
/// print version and exit
|
||||
#[argh(switch, short = 'V', long = "version")]
|
||||
version: bool,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args: Args = argh::from_env();
|
||||
|
||||
if args.version {
|
||||
println!("v{}", env!("CARGO_PKG_VERSION"));
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let input: String = if let Some(path) = args.file {
|
||||
std::fs::read_to_string(&path).with_context(|| format!("reading file {path}"))?
|
||||
} else {
|
||||
let mut input = String::new();
|
||||
io::stdin()
|
||||
.read_to_string(&mut input)
|
||||
.context("reading stdin")?;
|
||||
input
|
||||
};
|
||||
|
||||
if input.trim().is_empty() {
|
||||
eprintln!("Provide text via stdin (pipe or heredoc). Example: \n cat file.txt | chkr");
|
||||
eprintln!(
|
||||
"Provide text via stdin (pipe or heredoc), or use --file. Example: \n cat file.txt | chkr"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -28,22 +60,43 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
.collect();
|
||||
let mut todo = TodoList::with_lines(lines);
|
||||
|
||||
enable_raw_mode()?;
|
||||
enable_raw_mode().context("enable raw mode")?;
|
||||
let mut stdout = std::io::stdout();
|
||||
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
|
||||
execute!(stdout, EnterAlternateScreen, EnableMouseCapture).context("enter alternate screen")?;
|
||||
|
||||
let mode_guard = TerminalModeGuard;
|
||||
|
||||
let backend = CrosstermBackend::new(stdout);
|
||||
let mut terminal = Terminal::new(backend)?;
|
||||
let mut terminal = Terminal::new(backend).context("create terminal")?;
|
||||
|
||||
run_app(&mut terminal, &mut CrosstermEventSource, &mut todo)
|
||||
.map_err(|e| anyhow!("running app: {e}"))?;
|
||||
|
||||
drop(mode_guard);
|
||||
terminal.show_cursor().context("show cursor")?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run the app loop using an abstract `EventSource` so tests can inject events.
|
||||
/// # Errors
|
||||
/// If terminal drawing or event sourcing fails.
|
||||
pub fn run_app<B: Backend, E: EventSource>(
|
||||
terminal: &mut Terminal<B>,
|
||||
event_source: &mut E,
|
||||
todo: &mut TodoList,
|
||||
) -> Result<()>
|
||||
where
|
||||
<B as Backend>::Error: 'static + Sync + Send,
|
||||
{
|
||||
loop {
|
||||
terminal.draw(|f| {
|
||||
todo.draw(f);
|
||||
})?;
|
||||
|
||||
if event::poll(Duration::from_millis(100))? {
|
||||
match event::read()? {
|
||||
if event_source.poll(Duration::from_millis(100))? {
|
||||
#[allow(clippy::wildcard_enum_match_arm)]
|
||||
match event_source.read()? {
|
||||
Event::Key(key) => match key.code {
|
||||
KeyCode::Char('q') => break,
|
||||
KeyCode::Up => {
|
||||
@@ -59,7 +112,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
KeyCode::Char(' ') => {
|
||||
if let Some(i) = todo.state.selected() {
|
||||
let Some(marked_cell) = todo.marked.get_mut(i) else {
|
||||
return Err("Index out of bounds".into());
|
||||
bail!("Index out of bounds");
|
||||
};
|
||||
if !*marked_cell {
|
||||
let next = todo.lines.len().min(i + 1);
|
||||
@@ -93,8 +146,63 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
}
|
||||
|
||||
drop(mode_guard);
|
||||
terminal.show_cursor()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::panic_in_result_fn)]
|
||||
use super::*;
|
||||
use crate::todo_list::TodoList;
|
||||
use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
|
||||
use ratatui::Terminal;
|
||||
use ratatui::backend::TestBackend;
|
||||
use std::collections::VecDeque;
|
||||
use std::time::Duration;
|
||||
|
||||
struct MockEventSource {
|
||||
events: VecDeque<Event>,
|
||||
}
|
||||
|
||||
impl MockEventSource {
|
||||
fn new(events: Vec<Event>) -> Self {
|
||||
Self {
|
||||
events: VecDeque::from(events),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::event_source::EventSource for MockEventSource {
|
||||
fn poll(&mut self, _timeout: Duration) -> Result<bool> {
|
||||
Ok(!self.events.is_empty())
|
||||
}
|
||||
|
||||
fn read(&mut self) -> Result<Event> {
|
||||
Ok(self.events.pop_front().expect("no events left"))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pressing_down_moves_selection() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let lines = vec!["one".to_owned(), "two".to_owned(), "three".to_owned()];
|
||||
let mut todo = TodoList::with_lines(lines);
|
||||
|
||||
// prepare events: Down then 'q' to exit
|
||||
let down = Event::Key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
|
||||
let quit = Event::Key(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE));
|
||||
let mut source = MockEventSource::new(vec![down, quit]);
|
||||
|
||||
let backend = TestBackend::new(80, 24);
|
||||
let mut terminal = Terminal::new(backend)?;
|
||||
|
||||
// initially selection is Some(0)
|
||||
assert_eq!(todo.state.selected(), Some(0));
|
||||
|
||||
run_app(&mut terminal, &mut source, &mut todo)?;
|
||||
|
||||
// after pressing Down we expect selection to move to 1
|
||||
assert_eq!(todo.state.selected(), Some(1));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,38 +1,21 @@
|
||||
//! Todo list UI component for the checklist application.
|
||||
use ratatui::style::Style;
|
||||
use ratatui::widgets::{Block, Borders, List, ListItem, ListState};
|
||||
// use Frame via the crate root type `ratatui::Frame` in the signature below
|
||||
|
||||
/// A simple todo/list view that owns the lines, marked flags and selection state.
|
||||
pub struct TodoList {
|
||||
/// The text lines in the todo list.
|
||||
pub lines: Vec<String>,
|
||||
/// Flags indicating whether each corresponding line is marked.
|
||||
pub marked: Vec<bool>,
|
||||
/// Stateful selection for the list widget.
|
||||
pub state: ListState,
|
||||
/// Title displayed above the list widget.
|
||||
pub title: String,
|
||||
}
|
||||
|
||||
impl TodoList {
|
||||
/// Create a new `TodoList` from lines.
|
||||
pub fn new(lines: Vec<String>) -> Self {
|
||||
let mut state = ListState::default();
|
||||
if !lines.is_empty() {
|
||||
state.select(Some(0));
|
||||
}
|
||||
|
||||
Self {
|
||||
lines,
|
||||
marked: vec![false; state.selected().map(|_| 0).unwrap_or(0)],
|
||||
state,
|
||||
title: "Lines (space to mark, q to quit)".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Convenience constructor that ensures marked has same length as lines.
|
||||
pub fn with_lines(lines: Vec<String>) -> Self {
|
||||
let mut s = Self::new(lines);
|
||||
s.marked = vec![false; s.lines.len()];
|
||||
s
|
||||
}
|
||||
|
||||
/// Draw the list into a `ratatui` frame.
|
||||
pub fn draw(&mut self, f: &mut ratatui::Frame<'_>) {
|
||||
let size = f.area();
|
||||
@@ -53,4 +36,26 @@ impl TodoList {
|
||||
|
||||
f.render_stateful_widget(list, size, &mut self.state);
|
||||
}
|
||||
|
||||
/// Create a new `TodoList` from lines.
|
||||
pub fn new(lines: Vec<String>) -> Self {
|
||||
let mut state = ListState::default();
|
||||
if !lines.is_empty() {
|
||||
state.select(Some(0));
|
||||
}
|
||||
|
||||
Self {
|
||||
lines,
|
||||
marked: vec![false; state.selected().map_or(0, |_| 0)],
|
||||
state,
|
||||
title: "Lines (space to mark, q to quit)".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Convenience constructor that ensures marked has same length as lines.
|
||||
pub fn with_lines(lines: Vec<String>) -> Self {
|
||||
let mut s = Self::new(lines);
|
||||
s.marked = vec![false; s.lines.len()];
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ fn render_list_into_buffer(
|
||||
width: u16,
|
||||
height: u16,
|
||||
) -> Buffer {
|
||||
let backend = TestBackend::new(width.into(), height.into());
|
||||
let backend = TestBackend::new(width, height);
|
||||
let mut terminal = Terminal::new(backend).expect("create terminal");
|
||||
|
||||
let lines_vec: Vec<ListItem> = lines
|
||||
@@ -45,8 +45,8 @@ fn render_list_into_buffer(
|
||||
|
||||
// Extract the underlying backend buffer (clone to own it)
|
||||
let backend = terminal.backend();
|
||||
let buf = backend.buffer().clone();
|
||||
buf
|
||||
|
||||
backend.buffer().clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user