/
editor.rs
400 lines (357 loc) · 10.7 KB
/
editor.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
use std::{
env,
fs::File,
io::{self, Read, Seek, SeekFrom, Write},
process::Command,
};
use ui::{backend::Backend, events::EventIterator, style::Stylize, widgets, Validation, Widget};
use super::{Filter, Options, Transform, Validate};
use crate::{Answer, Answers, Question};
#[derive(Debug)]
pub(super) struct Editor<'a> {
extension: Option<String>,
default: Option<String>,
editor: Command,
filter: Filter<'a, String>,
validate: Validate<'a, str>,
transform: Transform<'a, str>,
}
impl<'a> Default for Editor<'a> {
fn default() -> Self {
Self {
editor: get_editor(),
extension: None,
default: None,
filter: Filter::None,
validate: Validate::None,
transform: Transform::None,
}
}
}
#[cfg(unix)]
fn split(command: &str) -> Option<Vec<String>> {
shell_words::split(command).ok()
}
#[cfg(windows)]
fn split(command: &str) -> Option<Vec<String>> {
Some(winsplit::split(command))
}
fn get_editor() -> Command {
let editor_args = env::var_os("VISUAL")
.or_else(|| env::var_os("EDITOR"))
.and_then(|editor_command| editor_command.to_str().map(split))
.flatten()
.unwrap_or_else(|| {
if cfg!(windows) {
vec!["notepad".into()]
} else {
vec!["vim".into()]
}
});
let mut command = Command::new(&editor_args[0]);
command.args(&editor_args[1..]);
command
}
struct EditorPrompt<'a, 'e> {
prompt: widgets::Prompt<&'a str>,
file: File,
ans: String,
editor: Editor<'e>,
answers: &'a Answers,
}
impl Widget for EditorPrompt<'_, '_> {
fn render<B: Backend>(
&mut self,
layout: &mut ui::layout::Layout,
backend: &mut B,
) -> io::Result<()> {
self.prompt.render(layout, backend)
}
fn height(&mut self, layout: &mut ui::layout::Layout) -> u16 {
self.prompt.height(layout)
}
fn cursor_pos(&mut self, layout: ui::layout::Layout) -> (u16, u16) {
// Cannot return this directly since we want to remove the extra space at the end
let (x, y) = self.prompt.cursor_pos(layout);
if x == 0 {
(layout.width - 1, y - 1)
} else {
(x - 1, y)
}
}
fn handle_key(&mut self, _: ui::events::KeyEvent) -> bool {
false
}
}
fn map_err(err: io::Error) -> widgets::Text<String> {
widgets::Text::new(err.to_string())
}
impl ui::Prompt for EditorPrompt<'_, '_> {
type ValidateErr = widgets::Text<String>;
type Output = String;
fn validate(&mut self) -> Result<Validation, Self::ValidateErr> {
if !self.editor.editor.status().map_err(map_err)?.success() {
return Err(map_err(io::Error::new(
io::ErrorKind::Other,
"Could not open editor",
)));
}
self.ans.clear();
self.file.read_to_string(&mut self.ans).map_err(map_err)?;
self.file.seek(SeekFrom::Start(0)).map_err(map_err)?;
if let Validate::Sync(ref mut validate) = self.editor.validate {
validate(&self.ans, self.answers)
.map_err(|err| map_err(io::Error::new(io::ErrorKind::InvalidInput, err)))?;
}
Ok(Validation::Finish)
}
fn finish(self) -> Self::Output {
match self.editor.filter {
Filter::Sync(filter) => filter(self.ans, self.answers),
_ => self.ans,
}
}
}
impl Editor<'_> {
pub(crate) fn ask<B: Backend, E: EventIterator>(
mut self,
message: String,
on_esc: ui::OnEsc,
answers: &Answers,
b: &mut B,
events: &mut E,
) -> ui::Result<Option<Answer>> {
let mut builder = tempfile::Builder::new();
if let Some(ref extension) = self.extension {
builder.suffix(extension);
}
let mut file = builder.tempfile()?;
if let Some(ref default) = self.default {
file.write_all(default.as_bytes())?;
file.seek(SeekFrom::Start(0))?;
file.flush()?;
}
let transform = self.transform.take();
let (file, path) = file.into_parts();
// `path` cannot be passed by ownership as it needs to live until the prompt has finished
// asking. On drop, path will delete the file
self.editor.arg(&path);
let ans = ui::Input::new(
EditorPrompt {
prompt: widgets::Prompt::new(&*message)
.with_hint("Press <enter> to launch your preferred editor.")
.with_delim(widgets::Delimiter::None),
editor: self,
file,
ans: String::new(),
answers,
},
b,
)
.on_esc(on_esc)
.run(events)?;
crate::write_final!(transform, message, ans [ref], answers, b, |_ans| b
.write_styled(&"Received".dark_grey())?)
}
}
/// The builder for the [`Question::editor`] prompt.
///
/// Once the user exits their editor, the contents of the temporary file are read in as the
/// result. The editor to use can be specified by the [`editor`] method. If unspecified, the editor
/// is determined by the `$VISUAL` or `$EDITOR` environment variables. If neither of those are
/// present, `vim` (for unix) or `notepad` (for windows) is used.
///
/// <img
/// src="https://raw.githubusercontent.com/lutetium-vanadium/requestty/master/assets/editor.gif"
/// style="max-height: 30rem"
/// />
///
/// See the various methods for more details on each available option.
///
/// # Examples
///
/// ```
/// use requestty::Question;
///
/// let editor = Question::editor("description")
/// .message("Please enter a short description about yourself")
/// .extension(".md")
/// .build();
/// ```
///
/// [`editor`]: EditorBuilder::editor
#[derive(Debug)]
pub struct EditorBuilder<'a> {
opts: Options<'a>,
editor: Editor<'a>,
}
impl<'a> EditorBuilder<'a> {
pub(crate) fn new(name: String) -> Self {
EditorBuilder {
opts: Options::new(name),
editor: Default::default(),
}
}
crate::impl_options_builder! {
message
/// # Examples
///
/// ```
/// use requestty::Question;
///
/// let editor = Question::editor("description")
/// .message("Please enter a short description about yourself")
/// .build();
/// ```
when
/// # Examples
///
/// ```
/// use requestty::{Question, Answers};
///
/// let editor = Question::editor("description")
/// .when(|previous_answers: &Answers| match previous_answers.get("anonymous") {
/// Some(ans) => !ans.as_bool().unwrap(),
/// None => true,
/// })
/// .build();
/// ```
ask_if_answered
/// # Examples
///
/// ```
/// use requestty::{Question, Answers};
///
/// let editor = Question::editor("description")
/// .ask_if_answered(true)
/// .build();
/// ```
on_esc
/// # Examples
///
/// ```
/// use requestty::{Question, Answers, OnEsc};
///
/// let editor = Question::editor("description")
/// .on_esc(OnEsc::Terminate)
/// .build();
/// ```
}
/// Set a default value for the file
///
/// If set, when the user first opens the file, it will contain the `default` value. Subsequent
/// times will contain what was last written.
///
/// # Examples
///
/// ```
/// use requestty::Question;
///
/// let editor = Question::editor("description")
/// .default("My name is ")
/// .build();
/// ```
pub fn default<I: Into<String>>(mut self, default: I) -> Self {
self.editor.default = Some(default.into());
self
}
/// Set an extension on the temporary file
///
/// If set, the extension will be concatenated with the randomly generated filename. This is a
/// useful way to signify accepted styles of input, and provide syntax highlighting on supported
/// editors.
///
/// # Examples
///
/// ```
/// use requestty::Question;
///
/// let editor = Question::editor("description")
/// .extension(".md")
/// .build();
/// ```
pub fn extension<I: Into<String>>(mut self, extension: I) -> Self {
self.editor.extension = Some(extension.into());
self
}
/// Use a specific editor instead of the default editor
///
/// If unspecified, the editor is determined by the `$VISUAL` or `$EDITOR` environment
/// variables. If neither of those are present, `vim` (for unix) or `notepad` (for windows) is
/// used.
///
/// # Examples
///
/// ```no_run
/// use std::process::Command;
/// use requestty::Question;
///
/// # fn get_preffered_editor() -> Command { todo!() }
///
/// let editor = Question::editor("description")
/// .editor(get_preffered_editor())
/// .build();
/// ```
pub fn editor<E: Into<Command>>(mut self, editor: E) -> Self {
self.editor.editor = editor.into();
self
}
crate::impl_filter_builder! {
/// # Examples
///
/// ```
/// # fn parse_markdown(s: String) -> String { s }
/// use requestty::Question;
///
/// let editor = Question::editor("description")
/// .filter(|description, previous_answers| parse_markdown(description))
/// .build();
/// ```
String; editor
}
crate::impl_validate_builder! {
/// # Examples
///
/// ```
/// use requestty::Question;
///
/// let editor = Question::editor("description")
/// .validate(|description, previous_answers| if description.lines().count() >= 2 {
/// Ok(())
/// } else {
/// Err("Please enter a few lines".to_owned())
/// })
/// .build();
/// ```
str; editor
}
crate::impl_transform_builder! {
/// # Examples
///
/// ```
/// use requestty::Question;
///
/// let editor = Question::editor("description")
/// .transform(|description, previous_answers, backend| {
/// write!(backend, "\n{}", description)
/// })
/// .build();
/// ```
str; editor
}
/// Consumes the builder returning a [`Question`]
///
/// [`Question`]: crate::question::Question
pub fn build(self) -> Question<'a> {
Question::new(self.opts, super::QuestionKind::Editor(self.editor))
}
}
impl<'a> From<EditorBuilder<'a>> for Question<'a> {
/// Consumes the builder returning a [`Question`]
///
/// [`Question`]: crate::question::Question
fn from(builder: EditorBuilder<'a>) -> Self {
builder.build()
}
}
// TODO: figure out a way to write tests for this