1use std::io;
7
8use crossterm::cursor::{Hide, MoveToColumn, MoveUp, Show};
9use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
10use crossterm::execute;
11use crossterm::terminal::{self, Clear, ClearType, disable_raw_mode, enable_raw_mode};
12use ratatui::backend::CrosstermBackend;
13use ratatui::layout::{Constraint, Direction, Layout};
14use ratatui::style::{Color, Modifier, Style};
15use ratatui::text::{Line, Span};
16use ratatui::widgets::{Block, Borders, Cell, Paragraph, Row, Table, TableState};
17use ratatui::{Terminal, TerminalOptions, Viewport};
18
19use crate::git::RepoInfo;
20use crate::ui::fuzzy;
21
22const CHROME_ROWS: u16 = 4;
24const MIN_HEIGHT: u16 = 6;
26const MAX_HEIGHT: u16 = 20;
28
29struct TerminalGuard;
34
35impl TerminalGuard {
36 fn enter() -> crate::Result<Self> {
37 enable_raw_mode()?;
38 execute!(io::stderr(), Hide)?;
39 Ok(Self)
40 }
41}
42
43impl Drop for TerminalGuard {
44 fn drop(&mut self) {
45 let _ = execute!(io::stderr(), Show);
46 let _ = disable_raw_mode();
47 }
48}
49
50#[cfg(unix)]
59struct StdoutToTty {
60 saved: libc::c_int,
61}
62
63#[cfg(unix)]
64impl StdoutToTty {
65 fn install() -> crate::Result<Self> {
66 use std::fs::OpenOptions;
67 use std::io::Write as _;
68 use std::os::unix::io::AsRawFd;
69
70 io::stdout().flush().ok();
71 let saved = unsafe { libc::dup(libc::STDOUT_FILENO) };
72 if saved < 0 {
73 return Err(io::Error::last_os_error().into());
74 }
75 let tty = match OpenOptions::new().write(true).open("/dev/tty") {
76 Ok(f) => f,
77 Err(e) => {
78 unsafe { libc::close(saved) };
79 return Err(e.into());
80 }
81 };
82 let rc = unsafe { libc::dup2(tty.as_raw_fd(), libc::STDOUT_FILENO) };
83 if rc < 0 {
84 let e = io::Error::last_os_error();
85 unsafe { libc::close(saved) };
86 return Err(e.into());
87 }
88 Ok(Self { saved })
89 }
90}
91
92#[cfg(unix)]
93impl Drop for StdoutToTty {
94 fn drop(&mut self) {
95 use std::io::Write as _;
96 io::stdout().flush().ok();
97 unsafe {
98 libc::dup2(self.saved, libc::STDOUT_FILENO);
99 libc::close(self.saved);
100 }
101 }
102}
103
104pub fn select(infos: &[RepoInfo]) -> crate::Result<Option<usize>> {
105 #[cfg(unix)]
109 let _stdout_redirect = StdoutToTty::install()?;
110 let _guard = TerminalGuard::enter()?;
111
112 let (_, term_h) = terminal::size().unwrap_or((80, 24));
113 let height = picker_height(term_h, infos.len());
114
115 let backend = CrosstermBackend::new(io::stderr());
116 let mut terminal = Terminal::with_options(
117 backend,
118 TerminalOptions {
119 viewport: Viewport::Inline(height),
120 },
121 )?;
122
123 let result = run_loop(&mut terminal, infos);
124 drop(terminal);
125
126 let _ = execute!(
133 io::stderr(),
134 MoveToColumn(0),
135 MoveUp(height.saturating_sub(1)),
136 Clear(ClearType::FromCursorDown),
137 );
138
139 result
140}
141
142fn picker_height(term_h: u16, repo_count: usize) -> u16 {
143 let ideal = (repo_count as u16).saturating_add(CHROME_ROWS + 1);
144 let capped = ideal.clamp(MIN_HEIGHT, MAX_HEIGHT);
145 let cap_by_term = term_h.saturating_sub(1).max(MIN_HEIGHT);
146 capped.min(cap_by_term)
147}
148
149fn run_loop(
150 terminal: &mut Terminal<CrosstermBackend<io::Stderr>>,
151 infos: &[RepoInfo],
152) -> crate::Result<Option<usize>> {
153 let mut filter = String::new();
154 let mut state = TableState::default();
155 state.select(Some(0));
156
157 loop {
158 let filtered = apply_filter(infos, &filter);
159 clamp_selection(&mut state, filtered.len());
160
161 terminal.draw(|f| draw(f, infos, &filtered, &filter, &mut state))?;
162
163 let Event::Key(KeyEvent {
164 code,
165 modifiers,
166 kind,
167 ..
168 }) = event::read()?
169 else {
170 continue;
171 };
172 if kind != KeyEventKind::Press {
173 continue;
174 }
175
176 match code {
177 KeyCode::Esc => return Ok(None),
178 KeyCode::Char('c') if modifiers.contains(KeyModifiers::CONTROL) => return Ok(None),
179 KeyCode::Enter => {
180 if let Some(cur) = state.selected() {
181 if let Some(&idx) = filtered.get(cur) {
182 return Ok(Some(idx));
183 }
184 }
185 }
186 KeyCode::Up => move_selection(&mut state, -1, filtered.len()),
187 KeyCode::Down => move_selection(&mut state, 1, filtered.len()),
188 KeyCode::PageUp => move_selection(&mut state, -10, filtered.len()),
189 KeyCode::PageDown => move_selection(&mut state, 10, filtered.len()),
190 KeyCode::Home => {
191 if filtered.is_empty() {
192 state.select(None);
193 } else {
194 state.select(Some(0));
195 }
196 }
197 KeyCode::End => {
198 if filtered.is_empty() {
199 state.select(None);
200 } else {
201 state.select(Some(filtered.len() - 1));
202 }
203 }
204 KeyCode::Backspace => {
205 filter.pop();
206 }
207 KeyCode::Char(c) => filter.push(c),
208 _ => {}
209 }
210 }
211}
212
213fn apply_filter(infos: &[RepoInfo], filter: &str) -> Vec<usize> {
214 if filter.is_empty() {
215 return (0..infos.len()).collect();
216 }
217 infos
218 .iter()
219 .enumerate()
220 .filter(|(_, r)| {
221 fuzzy::matches(filter, &r.name)
222 || fuzzy::matches(filter, &r.org)
223 || fuzzy::matches(filter, &r.branch)
224 || fuzzy::matches(filter, &r.author)
225 })
226 .map(|(i, _)| i)
227 .collect()
228}
229
230fn clamp_selection(state: &mut TableState, len: usize) {
231 if len == 0 {
232 state.select(None);
233 return;
234 }
235 let cur = state.selected().unwrap_or(0);
236 state.select(Some(cur.min(len - 1)));
237}
238
239fn move_selection(state: &mut TableState, delta: i32, len: usize) {
240 if len == 0 {
241 return;
242 }
243 let cur = state.selected().unwrap_or(0) as i32;
244 let next = (cur + delta).clamp(0, len as i32 - 1) as usize;
245 state.select(Some(next));
246}
247
248fn draw(
249 f: &mut ratatui::Frame,
250 infos: &[RepoInfo],
251 filtered: &[usize],
252 filter: &str,
253 state: &mut TableState,
254) {
255 let chunks = Layout::default()
256 .direction(Direction::Vertical)
257 .constraints([
258 Constraint::Length(1), Constraint::Min(2), Constraint::Length(2), ])
262 .split(f.area());
263
264 let counter = format!("{}/{}", filtered.len(), infos.len());
265 let filter_line = Paragraph::new(Line::from(vec![
266 Span::styled(" filter: ", Style::default().fg(Color::DarkGray)),
267 Span::styled(
268 filter,
269 Style::default()
270 .fg(Color::Yellow)
271 .add_modifier(Modifier::BOLD),
272 ),
273 Span::styled(
274 "▏",
275 Style::default()
276 .fg(Color::Yellow)
277 .add_modifier(Modifier::SLOW_BLINK),
278 ),
279 Span::raw(" "),
280 Span::styled(counter, Style::default().fg(Color::DarkGray)),
281 ]));
282 f.render_widget(filter_line, chunks[0]);
283
284 let header = Row::new(vec!["REPO", "ORG", "BRANCH", "AUTHOR", "SHA", "STATUS"]).style(
285 Style::default()
286 .fg(Color::DarkGray)
287 .add_modifier(Modifier::BOLD),
288 );
289
290 let rows: Vec<Row> = filtered.iter().map(|&i| build_row(&infos[i])).collect();
291
292 let table = Table::new(
293 rows,
294 [
295 Constraint::Percentage(24),
296 Constraint::Percentage(14),
297 Constraint::Percentage(20),
298 Constraint::Percentage(16),
299 Constraint::Length(8),
300 Constraint::Percentage(16),
301 ],
302 )
303 .header(header)
304 .row_highlight_style(
305 Style::default()
306 .bg(Color::DarkGray)
307 .add_modifier(Modifier::BOLD),
308 )
309 .highlight_symbol("▶ ")
310 .block(
311 Block::default()
312 .borders(Borders::TOP)
313 .border_style(Style::default().fg(Color::DarkGray)),
314 );
315 f.render_stateful_widget(table, chunks[1], state);
316
317 let hint = Paragraph::new(Line::from(vec![
318 Span::raw(" "),
319 Span::styled("↑↓", Style::default().fg(Color::Cyan)),
320 Span::raw(" move "),
321 Span::styled("type", Style::default().fg(Color::Cyan)),
322 Span::raw(" filter "),
323 Span::styled("enter", Style::default().fg(Color::Cyan)),
324 Span::raw(" cd "),
325 Span::styled("esc", Style::default().fg(Color::Cyan)),
326 Span::raw(" quit"),
327 ]))
328 .block(
329 Block::default()
330 .borders(Borders::TOP)
331 .border_style(Style::default().fg(Color::DarkGray)),
332 );
333 f.render_widget(hint, chunks[2]);
334}
335
336fn build_row(info: &RepoInfo) -> Row<'static> {
337 Row::new(vec![
338 Cell::from(info.name.clone()),
339 Cell::from(info.org.clone()).style(Style::default().fg(Color::Blue)),
340 Cell::from(info.branch.clone()).style(Style::default().fg(Color::Magenta)),
341 Cell::from(info.author.clone()).style(Style::default().fg(Color::Gray)),
342 Cell::from(info.sha.clone()).style(Style::default().fg(Color::DarkGray)),
343 Cell::from(status_line(info)),
344 ])
345}
346
347fn status_line(info: &RepoInfo) -> Line<'static> {
348 let mut spans: Vec<Span<'static>> = Vec::new();
349 if info.dirty > 0 {
350 spans.push(Span::styled(
351 format!("{} changed", info.dirty),
352 Style::default().fg(Color::Yellow),
353 ));
354 } else {
355 spans.push(Span::styled("clean", Style::default().fg(Color::Green)));
356 }
357 if info.ahead > 0 {
358 spans.push(Span::raw(" "));
359 spans.push(Span::styled(
360 format!("↑{}", info.ahead),
361 Style::default().fg(Color::Cyan),
362 ));
363 }
364 if info.behind > 0 {
365 spans.push(Span::raw(" "));
366 spans.push(Span::styled(
367 format!("↓{}", info.behind),
368 Style::default().fg(Color::Red),
369 ));
370 }
371 Line::from(spans)
372}
373
374#[cfg(test)]
375mod tests {
376 use super::*;
377
378 fn ri(name: &str, org: &str, branch: &str, author: &str) -> RepoInfo {
379 RepoInfo {
380 name: name.into(),
381 path: format!("/tmp/{name}"),
382 branch: branch.into(),
383 sha: "abc1234".into(),
384 ahead: 0,
385 behind: 0,
386 dirty: 0,
387 org: org.into(),
388 author: author.into(),
389 }
390 }
391
392 #[test]
393 fn empty_filter_returns_all() {
394 let infos = vec![ri("a", "o", "main", "-"), ri("b", "o", "main", "-")];
395 assert_eq!(apply_filter(&infos, ""), vec![0, 1]);
396 }
397
398 #[test]
399 fn filter_matches_name_org_or_branch() {
400 let infos = vec![
401 ri("api-gateway", "acme", "main", "-"),
402 ri("billing-svc", "acme", "feat/x", "-"),
403 ri("website", "personal", "main", "-"),
404 ];
405 assert_eq!(apply_filter(&infos, "bill"), vec![1]);
406 assert_eq!(apply_filter(&infos, "person"), vec![2]);
407 assert_eq!(apply_filter(&infos, "feat"), vec![1]);
408 }
409
410 #[test]
411 fn filter_matches_author() {
412 let infos = vec![
413 ri("api-gateway", "acme", "main", "Oscar García"),
414 ri("billing-svc", "acme", "feat/x", "Ada Lovelace"),
415 ];
416 assert_eq!(apply_filter(&infos, "oscar"), vec![0]);
417 assert_eq!(apply_filter(&infos, "ada"), vec![1]);
418 }
419
420 #[test]
421 fn clamp_selection_handles_empty() {
422 let mut s = TableState::default();
423 s.select(Some(5));
424 clamp_selection(&mut s, 0);
425 assert_eq!(s.selected(), None);
426 }
427
428 #[test]
429 fn clamp_selection_caps_at_last() {
430 let mut s = TableState::default();
431 s.select(Some(10));
432 clamp_selection(&mut s, 3);
433 assert_eq!(s.selected(), Some(2));
434 }
435
436 #[test]
437 fn move_selection_clamps_edges() {
438 let mut s = TableState::default();
439 s.select(Some(0));
440 move_selection(&mut s, -1, 5);
441 assert_eq!(s.selected(), Some(0));
442 move_selection(&mut s, 100, 5);
443 assert_eq!(s.selected(), Some(4));
444 }
445
446 #[test]
447 fn picker_height_scales_with_repo_count() {
448 assert_eq!(picker_height(50, 1), MIN_HEIGHT);
450 assert_eq!(picker_height(50, 10), 10 + CHROME_ROWS + 1);
452 assert_eq!(picker_height(50, 100), MAX_HEIGHT);
454 }
455
456 #[test]
457 fn picker_height_respects_short_terminal() {
458 let h = picker_height(8, 20);
460 assert_eq!(h, 7);
461 }
462}