-
Notifications
You must be signed in to change notification settings - Fork 2
/
cli.rs
191 lines (175 loc) · 5.87 KB
/
cli.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
use std::env::ArgsOs;
use std::io::{self, Stderr, Stdout, Write};
use std::process::exit;
use std::time::Duration;
use crossterm::{
cursor,
event::{self, Event, KeyCode, KeyEvent, KeyModifiers},
execute, queue, style,
terminal::{self, ClearType},
};
use crate::args::{Parser, HELP};
use crate::error::Result;
use crate::finder::Finder;
use crate::{Error, MatchedPath};
pub fn safe_exit(code: i32, stdout: Stdout, stderr: Stderr) {
let _ = stdout.lock().flush();
let _ = stderr.lock().flush();
exit(code)
}
pub fn entrypoint(args: ArgsOs, stdout: &mut impl Write, stderr: &mut impl Write) -> Result<()> {
let args = Parser::new(args).parse()?;
if args.help {
print_help(stdout)?;
return Ok(());
}
let (_, mut rows) = terminal::size()?;
let mut query = args.query;
let mut paths = find_paths(&args.starting_point, &query, rows - 1)?;
let mut selection: u16 = 0;
let mut state = State::QueryChanged;
initialize_terminal(stdout)?;
loop {
match state {
State::QueryChanged => output_on_terminal(stdout, &query, &paths[..], selection)?,
State::PathsChanged => {
output_on_terminal(stdout, &query, &paths[..], selection)?;
state = State::Ready;
}
State::SelectionChanged => {
output_on_terminal(stdout, &query, &paths[..], selection)?;
state = State::Ready;
}
_ => (),
}
if event::poll(Duration::from_millis(300))? {
let ev = event::read()?;
// TODO: Support uppercase
if let Event::Key(KeyEvent {
code: KeyCode::Char(c),
modifiers: KeyModifiers::NONE,
}) = ev
{
query.push(c);
state = State::QueryChanged;
} else if ev == Event::Key(KeyCode::Backspace.into()) {
query.pop();
state = State::QueryChanged;
} else if ev == Event::Key(KeyCode::Up.into()) {
if selection > 0 {
selection -= 1;
}
state = State::SelectionChanged;
} else if ev == Event::Key(KeyCode::Down.into()) {
if selection < (rows - 1) {
selection += 1;
}
state = State::SelectionChanged;
} else if ev == Event::Key(KeyCode::Enter.into()) {
let path: &MatchedPath = paths.get(selection as usize).unwrap(); // TODO: Do not use unwrap()
state = State::Invoke(&path);
break;
} else if ev
== Event::Key(KeyEvent {
code: KeyCode::Char('c'),
modifiers: KeyModifiers::CONTROL,
})
|| ev == Event::Key(KeyCode::Esc.into())
{
// CTRL-C does not send SIGINT even on UNIX/Linux because it's in Raw mode.
// Also, we handle Esc as the same.
break;
} else if let Event::Resize(_, r) = ev {
rows = r;
state = State::PathsChanged;
}
} else if let State::QueryChanged = state {
paths = find_paths(&args.starting_point, &query, rows - 1)?;
state = State::PathsChanged;
selection = 0;
}
}
execute!(stdout, terminal::LeaveAlternateScreen)?;
terminal::disable_raw_mode()?;
if let State::Invoke(path) = state {
// TODO: Decide which we should pass: relative or absolute.
let path = &path.relative;
let output = invoke(&args.exec, &path)?;
stdout.write_all(&output.stdout)?;
stderr.write_all(&output.stderr)?;
if !output.status.success() {
return Err(Error::exec(&format!(
"Failed to execute command `{} {}`",
args.exec, path,
)));
}
}
Ok(())
}
enum State<'a> {
Ready,
QueryChanged,
PathsChanged,
SelectionChanged,
Invoke(&'a MatchedPath),
}
fn print_help(buffer: &mut impl Write) -> io::Result<()> {
buffer.write_all(format!("{}\n", HELP).as_bytes())?;
buffer.flush()
}
fn initialize_terminal(stdout: &mut impl Write) -> Result<()> {
queue!(stdout, terminal::EnterAlternateScreen, style::ResetColor,)?;
stdout.flush()?;
terminal::enable_raw_mode()?;
Ok(())
}
fn output_on_terminal(
stdout: &mut impl Write,
query: &str,
paths: &[MatchedPath],
selection: u16,
) -> Result<()> {
queue!(
stdout,
cursor::MoveTo(0, 0),
terminal::Clear(ClearType::FromCursorDown),
style::Print("Search: "),
style::Print(query),
cursor::SavePosition,
cursor::MoveToNextLine(1),
)?;
for (idx, path) in paths.iter().enumerate() {
let idx = idx as u16;
let prefix = if idx == selection { "> " } else { " " };
queue!(
stdout,
style::Print(format!("{}{}", prefix, path)),
cursor::MoveToNextLine(1),
)?;
}
queue!(stdout, cursor::RestorePosition)?;
stdout.flush()?;
Ok(())
}
fn find_paths(starting_point: &str, query: &str, limit: u16) -> Result<Vec<MatchedPath>> {
let mut paths = Vec::with_capacity(100); // TODO: Tune this capacity later.
// TODO: Sort
for path in Finder::new(starting_point, query)?.take(limit.into()) {
let path = path?;
paths.push(path);
}
Ok(paths)
}
fn invoke(exec: &str, path: &str) -> Result<std::process::Output> {
let mut exec = exec.split_whitespace();
let program = exec
.next()
.ok_or_else(|| Error::args("\"exec\" cannot be processed with empty string"))?;
let mut command = std::process::Command::new(program);
for arg in exec {
command.arg(arg);
}
command.arg(path);
let output = command.output()?;
Ok(output)
}