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
#![deny(missing_docs)]
extern crate rpassword;
extern crate tempfile;
extern crate termios;
use interactive::Interactive;
use std::{env, io};
use std::ffi::OsStr;
use std::fs::File;
use std::io::{Read, Write};
use std::process::Command;
use tempfile::TempDir;
mod interactive;
mod util;
pub fn ask(q: &str) -> io::Result<()> {
print!("\u{1B}[1m{}\u{1B}[0m", q);
io::stdout().flush()
}
pub fn password() -> io::Result<String> {
rpassword::read_password()
}
pub fn text() -> io::Result<String> {
let mut out = String::new();
io::stdin().read_line(&mut out)?;
if let Some(newline) = out.find('\n') {
out.truncate(newline);
}
Ok(out)
}
pub fn yesno(default: bool) -> io::Result<Option<bool>> {
let s = text()?.to_lowercase();
Ok(if s.is_empty() {
Some(default)
} else if "yes".starts_with(&s) {
Some(true)
} else if "no".starts_with(&s) {
Some(false)
} else {
None
})
}
pub fn editor(name: &str, message: &[u8]) -> io::Result<String> {
let dir = TempDir::new()?;
let path = dir.path().join(name);
File::create(&path)?.write_all(message)?;
let editor = env::var_os("VISUAL").or_else(|| env::var_os("EDITOR"));
let editor = match editor {
Some(ref editor) => editor,
None => OsStr::new("vi"),
};
Command::new(editor)
.arg(&path)
.spawn()?
.wait()?;
let mut out = String::new();
File::open(&path)?.read_to_string(&mut out)?;
Ok(out)
}
#[derive(Clone, Copy, Debug)]
pub struct Boxes<'a> {
pub on: &'a str,
pub off: &'a str,
}
impl<'a> Default for Boxes<'a> {
fn default() -> Self {
Self { on: "🢂", off: " " }
}
}
pub fn choose<S: AsRef<str>>(boxes: Boxes, items: &[S]) -> io::Result<usize> {
assert!(items.len() > 0);
let stdin = io::stdin();
let mut stdin = stdin.bytes();
let mut selected = 0;
let interactive = Interactive::start();
loop {
for (i, item) in items.iter().enumerate() {
println!(
"{} {}",
if i == selected { boxes.on } else { boxes.off },
item.as_ref(),
);
}
match util::or2ro(stdin.next())? {
Some(0x1B) => match util::or2ro(stdin.next())? {
Some(0x5B) => match util::or2ro(stdin.next())? {
Some(0x41) => {
selected = selected.saturating_sub(1);
},
Some(0x42) => {
selected = selected.saturating_add(1)
.min(items.len() - 1);
},
None => break,
Some(_) => (),
},
None => break,
Some(_) => (),
},
Some(0x0A) => break,
None => break,
Some(_) => (),
}
interactive.up(items.len());
interactive.clear_right();
}
Ok(selected)
}