Compare commits

19 Commits

Author SHA1 Message Date
Lukas Wölfer
140d5881af chore: add push command to bump script
All checks were successful
Rust / build_and_test (push) Successful in 23s
2026-01-30 18:17:43 +01:00
Lukas Wölfer
3d4fd8d048 chore: bump version to v0.3.0
All checks were successful
Release / build_release (push) Successful in 42s
Rust / build_and_test (push) Successful in 23s
2026-01-30 18:15:16 +01:00
Lukas Wölfer
cdc04ab266 style: add module documentation
Some checks failed
Rust / build_and_test (push) Has been cancelled
2026-01-30 18:14:41 +01:00
Lukas Wölfer
46aff0e6b1 feat: read checklist from file 2026-01-30 18:14:32 +01:00
Lukas Wölfer
cb99d74b4e chore: bump version to v0.2.0
All checks were successful
Release / build_release (push) Successful in 29s
Rust / build_and_test (push) Successful in 23s
2026-01-29 21:19:46 +01:00
Lukas Wölfer
56176b2659 feat: argument parsing and version cli flag
All checks were successful
Rust / build_and_test (push) Successful in 27s
2026-01-29 21:18:53 +01:00
Lukas Wölfer
e2ce929698 chore: bump script 2026-01-29 21:18:31 +01:00
Lukas Wölfer
924f989c05 feat: anyhow error handling
All checks were successful
Rust / build_and_test (push) Successful in 24s
2026-01-29 21:09:13 +01:00
Lukas Wölfer
f8b25e81bf test: improve testability of input events
All checks were successful
Rust / build_and_test (push) Successful in 22s
2026-01-29 20:54:43 +01:00
Lukas Wölfer
091fba232b ci: initialized
All checks were successful
Release / build_release (push) Successful in 39s
Rust / build_and_test (push) Successful in 23s
2026-01-29 20:03:13 +01:00
Lukas Wölfer
71f88cb6ea tests: improved testability 2026-01-24 09:41:22 +01:00
Lukas Wölfer
1e0a8c639a feat: mouse capture 2026-01-24 09:23:06 +01:00
Lukas Wölfer
a8c22061f0 style: linting 2026-01-24 09:22:51 +01:00
Lukas Wölfer
d9eaeb1848 style: Using clippy lints 2026-01-24 09:05:22 +01:00
Lukas Wölfer
0081e79492 refactor: move terminal guard to own file 2026-01-24 08:50:06 +01:00
Lukas Wölfer
15c792fc21 feat: handle crashes better for the terminal state 2026-01-24 08:46:31 +01:00
Lukas Wölfer
e8e68682d8 feat: ctrl-c handling 2026-01-23 23:37:36 +01:00
Lukas Wölfer
40167f0f23 feat: deselect items 2026-01-23 23:15:49 +01:00
Lukas Wölfer
1ce513b688 feat: use current versions of ratatui and crossterm 2026-01-23 23:15:40 +01:00
11 changed files with 1889 additions and 128 deletions

View File

@@ -0,0 +1,38 @@
name: Release
on:
push:
tags:
- 'v*.*.*'
jobs:
build_release:
runs-on: ubuntu-latest
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_SERVER: ${{ secrets.GITEA_SERVER }}
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: nightly
- name: Build release
run: |
cargo build --release
- name: Generate a changelog
uses: orhun/git-cliff-action@v4
id: git-cliff
with:
config: cliff.toml
args: --verbose --latest
github_token: ""
env:
OUTPUT: CHANGELOG.md
- uses: akkuman/gitea-release-action@v1
with:
files: |-
target/release/chkr
body: ${{ steps.git-cliff.outputs.content }}

View File

@@ -0,0 +1,13 @@
name: Rust
on: [push, pull_request]
jobs:
build_and_test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: nightly
- run: cargo test --all-features

1446
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,8 +1,31 @@
[package]
name = "chkr"
version = "0.1.0"
version = "0.3.0"
edition = "2024"
[dependencies]
crossterm = "0.26"
ratatui = { version = "0.20", features = ["crossterm"] }
crossterm = "0.29"
ratatui = { version = "0.30", features = ["crossterm"] }
anyhow = "1.0"
argh = "0.1.13"
[dev-dependencies]
insta = "1.33"
[lints.clippy]
pedantic = "warn"
unused_trait_names = "warn"
missing_docs_in_private_items = "warn"
empty_structs_with_brackets = "warn"
let_underscore_must_use = "warn"
arbitrary_source_item_ordering = "warn"
as_conversions = "warn"
default_constructed_unit_structs = "warn"
equatable_if_let = "warn"
indexing_slicing = "warn"
missing_assert_message = "warn"
panic_in_result_fn = "warn"
redundant_closure_for_method_calls = "warn"
str_to_string = "warn"
used_underscore_binding = "warn"
wildcard_enum_match_arm = "warn"

27
scripts/bump.sh Normal file
View File

@@ -0,0 +1,27 @@
#!/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}"
echo Press Y to push commit and tag
read -r CONFIRM
if [ "${CONFIRM}" != "Y" ]; then
echo Aborting
exit 1
fi
git push
git push --tags

28
src/event_source.rs Normal file
View 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)?)
}
}

View File

@@ -1,101 +1,144 @@
use std::io::{self, Read, Stdout};
use std::time::Duration;
//! A simple terminal checklist application.
mod event_source;
mod terminal_guard;
mod todo_list;
use crossterm::event::{self, Event, KeyCode};
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, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};
use crossterm::terminal::{EnterAlternateScreen, enable_raw_mode};
use event_source::{CrosstermEventSource, EventSource};
use ratatui::Terminal;
use ratatui::backend::Backend;
use ratatui::backend::CrosstermBackend;
use ratatui::layout::{Constraint, Direction, Layout};
use ratatui::style::{Color, Modifier, Style};
use ratatui::terminal::Terminal;
use ratatui::widgets::{Block, Borders, List, ListItem, ListState};
use std::io::{self, Read as _};
use terminal_guard::TerminalModeGuard;
use todo_list::TodoList;
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>,
if input.trim().is_empty() {
eprintln!("Provide text via stdin (pipe or heredoc). Example: \n cat file.txt | chkr");
/// 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 lines: Vec<String> = input.lines().map(|s| s.to_string()).collect();
let mut marked = vec![false; lines.len()];
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
};
enable_raw_mode()?;
let mut stdout = std::io::stdout();
execute!(stdout, EnterAlternateScreen)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
let mut state = ListState::default();
if !lines.is_empty() {
state.select(Some(0));
if input.trim().is_empty() {
eprintln!(
"Provide text via stdin (pipe or heredoc), or use --file. Example: \n cat file.txt | chkr"
);
return Ok(());
}
let lines: Vec<String> = input
.lines()
.map(std::string::ToString::to_string)
.collect();
let mut todo = TodoList::with_lines(lines);
enable_raw_mode().context("enable raw mode")?;
let mut stdout = std::io::stdout();
execute!(stdout, EnterAlternateScreen, EnableMouseCapture).context("enter alternate screen")?;
let mode_guard = TerminalModeGuard;
let backend = CrosstermBackend::new(stdout);
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| {
let size = f.size();
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Min(0)].as_ref())
.split(size);
let items: Vec<ListItem> = lines
.iter()
.enumerate()
.map(|(i, l)| {
let prefix = if marked[i] { "[x]" } else { "[ ]" };
ListItem::new(format!("{} {}", prefix, l))
})
.collect();
let list = List::new(items)
.block(
Block::default()
.borders(Borders::ALL)
.title("Lines (space to mark, q to quit)"),
)
.highlight_style(
Style::default()
.fg(Color::White)
.bg(Color::Blue)
.add_modifier(Modifier::BOLD),
);
f.render_stateful_widget(list, chunks[0], &mut state);
todo.draw(f);
})?;
// Event handling
if event::poll(Duration::from_millis(100))?
&& let Event::Key(key) = event::read()?
{
match key.code {
KeyCode::Char('q') => break,
KeyCode::Up => {
if let Some(i) = state.selected()
&& i > 0
{
state.select(Some(i - 1));
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 => {
if let Some(i) = todo.state.selected() {
todo.state.select(Some(i.saturating_sub(1)));
}
}
}
KeyCode::Down => {
if let Some(i) = state.selected()
&& i + 1 < lines.len()
{
state.select(Some(i + 1));
KeyCode::Down => {
if let Some(i) = todo.state.selected() {
todo.state.select(Some((i + 1).min(todo.lines.len() - 1)));
}
}
}
KeyCode::Char(' ') => {
if let Some(i) = state.selected()
&& i < marked.len()
{
marked[i] = true;
// move cursor down
let next = if i + 1 < lines.len() { i + 1 } else { i };
state.select(Some(next));
KeyCode::Char(' ') => {
if let Some(i) = todo.state.selected() {
let Some(marked_cell) = todo.marked.get_mut(i) else {
bail!("Index out of bounds");
};
if !*marked_cell {
let next = todo.lines.len().min(i + 1);
todo.state.select(Some(next));
}
*marked_cell = !*marked_cell;
}
}
KeyCode::Char('c') if key.modifiers.contains(event::KeyModifiers::CONTROL) => {
break;
}
_ => {}
},
Event::Mouse(s) => {
if s.kind == event::MouseEventKind::Down(event::MouseButton::Left) {
let area = terminal.size()?;
if let Some(row_idx) = s
.row
.checked_sub(area.height + 1)
.filter(|_| s.row < area.height.saturating_add(area.height))
{
let idx = usize::from(row_idx);
if idx < todo.lines.len() {
todo.state.select(Some(idx));
}
}
}
}
_ => {}
@@ -103,10 +146,63 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
}
}
disable_raw_mode()?;
let mut stdout: Stdout = std::io::stdout();
execute!(stdout, LeaveAlternateScreen)?;
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(())
}
}

23
src/terminal_guard.rs Normal file
View File

@@ -0,0 +1,23 @@
//! A guard that restores the terminal state on drop.
use crossterm::cursor::Show;
use crossterm::execute;
use crossterm::terminal::{LeaveAlternateScreen, disable_raw_mode};
/// A guard that ensures the terminal is restored to its original state
/// when dropped.
#[derive(Default, Debug)]
pub struct TerminalModeGuard;
impl TerminalModeGuard {}
impl Drop for TerminalModeGuard {
#[allow(
clippy::let_underscore_must_use,
reason = "We want to ignore errors during cleanup."
)]
fn drop(&mut self) {
let _ = disable_raw_mode();
let mut stdout = std::io::stdout();
let _ = execute!(stdout, LeaveAlternateScreen, Show);
}
}

61
src/todo_list.rs Normal file
View File

@@ -0,0 +1,61 @@
//! 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 {
/// Draw the list into a `ratatui` frame.
pub fn draw(&mut self, f: &mut ratatui::Frame<'_>) {
let size = f.area();
let items: Vec<ListItem> = self
.lines
.iter()
.zip(self.marked.iter())
.map(|(text, marked)| {
let prefix = if *marked { 'x' } else { ' ' };
ListItem::new(format!("[{prefix}] {text}"))
})
.collect();
let list = List::new(items)
.block(Block::default().borders(Borders::ALL).title(&*self.title))
.highlight_style(Style::default().bold().yellow().on_dark_gray());
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
}
}

View File

@@ -0,0 +1,23 @@
---
source: tests/ui_snapshot.rs
assertion_line: 50
expression: out
---
Buffer {
area: Rect { x: 0, y: 0, width: 40, height: 10 },
content: [
"┌Lines (space to mark, q to quit)──────┐",
"│[ ] first │",
"│[x] second │",
"│[ ] third │",
"│ │",
"│ │",
"│ │",
"│ │",
"│ │",
"└──────────────────────────────────────┘",
],
styles: [
x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
]
}

61
tests/ui_snapshot.rs Normal file
View File

@@ -0,0 +1,61 @@
use ratatui::Terminal;
use ratatui::backend::TestBackend;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Style;
use ratatui::widgets::{Block, Borders, List, ListItem, ListState};
fn render_list_into_buffer(
lines: &[&str],
marked: &[bool],
selected: Option<usize>,
width: u16,
height: u16,
) -> Buffer {
let backend = TestBackend::new(width, height);
let mut terminal = Terminal::new(backend).expect("create terminal");
let lines_vec: Vec<ListItem> = lines
.iter()
.zip(marked.iter())
.map(|(text, marked)| {
let prefix = if *marked { 'x' } else { ' ' };
ListItem::new(format!("[{prefix}] {text}"))
})
.collect();
let mut state = ListState::default();
state.select(selected);
terminal
.draw(|f| {
let size = Rect::new(0, 0, width, height);
let list = List::new(lines_vec.clone())
.block(
Block::default()
.borders(Borders::ALL)
.title("Lines (space to mark, q to quit)"),
)
.highlight_style(Style::default());
f.render_stateful_widget(list, size, &mut state);
})
.expect("draw");
// Extract the underlying backend buffer (clone to own it)
let backend = terminal.backend();
backend.buffer().clone()
}
#[test]
fn ui_snapshot_basic() {
let lines = ["first", "second", "third"];
let marked = [false, true, false];
let buf = render_list_into_buffer(&lines, &marked, Some(1), 40, 10);
// Use the buffer's debug representation for snapshotting
let out = format!("{buf:#?}");
insta::assert_snapshot!(out);
}