conciliator 0.3.10

[WIP] Library for interactive CLI programs
Documentation
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! Edit text using `$EDITOR`
//!
//! [`Claw::edit`](crate::Claw::edit) will open the user's text editor with a temporary file containing some text for the user to edit.
//! After the editor exits, the file is read and its content returned.
//! Optionally, the content may be parsed and validated, such that any errors (i.e. TOML syntax errors) are reported to the user immediately and they are given the option to try again, until either the validation succeeds or the user aborts the procedure.
//!
//! # [`Edit`] & [`Editable`]
//!
//! The [`Edit`] trait defines how (if at all) a type is serialized *before* and deserialized / validated *after* editing.  
//! This crate provides 2 implementations: plain text editing on `&str` simply returning the string as the user has edited it, as well as the structured [`TomlEditor`], which serializes and then parses the item to be edited using [serde] and [toml].
//!
//! [`Editable`] serves as a "proxy" for [`Edit`] (it could have been called `IntoEdit`).
//! This way, any type can use a wrapper like [`TomlEditor`] instead of implementing [`Edit`] *itself* without forcing you to explicitly specify the wrapper every time.  
//! To make this even easier, the [`edit_as_toml`] macro  implements [`Editable`] for any `T: Serialize + DeserializeOwned`.  
//! Obviously, any type that is [`Edit`] directly is also [`Editable`].
//!
//! 
//! # Editor Program
//!
//! If the `$EDITOR` environment variable is set, it is used as the command to launch the editor (with the first and only argument being the path of the temporary file).
//! Otherwise, the user is given the option to specify a command to use.
//! If refused, this method returns [`Edited::Cancelled`].
//!
//! Notably, only a value that is an executable in the users `$PATH` will work.
//! This excludes aliases and commands with arguments like `subl -w` because that would require going through the shell.
//! If you encounter the error `No such file or directory (os error 2)`, this may be the reason.
//!
//! # Security
//!
//! [`Claw::edit`](crate::Claw::edit) should under no circumstances be used in a process (i.e. [`setuid`](https://en.wikipedia.org/wiki/Setuid) executables) with elevated privileges that the user does not otherwise have access to.
//!
//! # Examples
//!
//! Plain text:
//! ```
//! use conciliator::{Conciliator, edit::Edited};
//! let con = conciliator::init();
//! match con.edit("Test123 :^)") { 
//!     Edited::Ok(s) => con.status(format!("Edited:\n{s}")),
//!     Edited::Cancelled => con.info("Edit aborted!"), 
//!     Edited::Err(e) => con.error(format!("{e:?}")) 
//! }; 
//! ```
//! Using TOML:
//! ```
//! use serde::{Serialize, Deserialize};
//! use conciliator::{Conciliator, edit::{Edited, edit_as_toml}};
//! let con = conciliator::init();
//! 
//! #[derive(Debug, Serialize, Deserialize)]
//! struct Entry {
//!     id: usize,
//!     name: String
//! }
//! edit_as_toml!(Entry);
//! 
//! let entry = Entry {id: 3, name: "Entry".to_owned()};
//! 
//! match con.edit(entry) {
//!     Edited::Ok(s) => con.status(format!("Edited entry:\n{s:?}")),
//!     Edited::Cancelled => con.info("Edit aborted!"),
//!     Edited::Err(e) => con.error(format!("{e:?}"))
//! };
//! ```
use std::env;
use std::error::Error;
use std::fmt;
use std::ffi::OsString;
use std::io::{
	Error as IoError,
	Read,
	Seek,
	Write
};
use std::process::Command;

use serde::{Serialize, de::DeserializeOwned};
use tempfile::Builder;

use crate::{
	Claw,
	Conciliator,
	input::AbortRetryContinue,
	Paint
};
/// Name of the crate being compiled (credit: clap)
const CRATE_NAME: &str = env!("CARGO_PKG_NAME");

/// Proxy trait for [`Edit`]
///
/// Most types do not need to implement [`Edit`] themselves but can use a generic wrapper like [`TomlEditor`].
/// In almost all cases, each type will always use the same wrapper.
/// Because of this, it makes sense to implement an implicit wrapper choice for most types.
/// And if there is a case where a different wrapper has to be used, it can be specified explicitly, circumventing this trait.
///
/// See [`edit_as_toml!`] on how to implement this trait easily.
pub trait Editable {
	/// [`Edit`] type this converts to
	type E: Edit;
	/// Perform the conversion
	fn into_edit(self) -> Self::E;
}

/// Types that can be [`edit`](crate::Claw::edit)ed
///
/// See the [module level docs](self) for more information.
pub trait Edit {
	/// Extension of the temporary file
	///
	/// This gives the text editor a chance to apply the correct syntax highlighting automatically.
	///
	/// Don't add a leading `.`, e.g. just `"toml"` or `"txt"`.
	const EXTENSION: &'static str;
	/// Type returned from editing
	///
	/// This could be different from the type that is "passed in" to the implementor.
	type T;
	/// [`Error`] for [`Edited::Err`]
	///
	/// Even though [`EditError`] (which is what is used for [`TomlEditor`]) is already generic, implementations are not required to use it.
	/// For example, the `impl Edit for &str` doesn't need to do any serializing and can only encounter IO errors - this is why its `Edit::Err` is simply [`std::io::Error`].
	///
	/// Note that this does not need to encompass errors encountered during the [`read`](Edit::read) method: any parsing errors are immediately reported for the user to fix.
	type Err: Error + From<IoError>;
	/// Write content into the file to be edited
	///
	/// This usually involves serializing the type.
	///
	/// This method is called only once to write to the new, empty, temporary file, but future versions may give users the ability to "reset" the file.
	/// As such it should be implemented assuming it may be called arbitrarily often.
	fn write<W: Write>(&self, w: &mut W) -> Result<(), Self::Err>;
	/// Read (and parse) the edited file, immediately reporting any errors encountered
	///
	/// Because it would be inconvenient to add yet another `Err` type and return a [`Result`] to be reported in [`Claw::edit`], errors this function encounters are to be reported immediately, using the reference to the [`Claw`] that invoked the edit (though it may be a different [`Conciliator`] implementor in future).
	/// This is because the user will be offered the option to amend the file if [`read`](Edit::read) returns `None`.
	/// The user will keep being offered this option until they either submit a file that can be parsed or they decide to abort the edit procedure.  
	/// This means that any errors this function is *expected* to encounter should be ones the user can recover from and if irrecoverable errors exist they should be rare and clearly communicated.
	fn read<C>(&self, content: String, con: &C) -> Option<Self::T>
		where C: Conciliator + ?Sized;
}


/// Outcome of the [`Claw::edit`](crate::Claw::edit) function
///
/// The set of errors in `Err` does not contain ones encountered during parsing of the file content.
/// See [`Edit::read`] for more info.
pub enum Edited<E: Edit> {
	/// Successfully edited
	Ok(E::T),
	/// Edit aborted by the user
	Cancelled,
	/// Error encountered at some point
	Err(E::Err)
}


/// Errors encountered during [`Claw::edit`](crate::Claw::edit)
///
/// Errors can occur at several points in the [`Claw::edit`](crate::Claw::edit) function, and most of them are [`std::io::Error`] from creating, reading, and writing files, but also from spawning the editor process.
///
///
/// Used by [`TomlEditor`], which can encounter a [`toml::ser::Error`] during serialization.
///
/// It is not mandatory to use this as the [`Error`] type for [`Edit::Err`].
#[derive(Debug)]
pub enum EditError<E: Error> {
	/// Error encountered during serialization
	Serialize(E),
	/// [`std::io::Error`] encountered at some point
	Io(IoError)
}

/// Wrapper type to [`Edit`] something using TOML
///
/// Implements [`Editable`] itself so it can be used explicitly like `con.edit(TomlEditor::new(thing))` or, more conveniently, [`Editable`] can be implemented for a particular type to wrap the type automatically when writing `con.edit(thing)`.
/// To this end, the macro [`edit_as_toml`] is provided.
///
/// Since this uses [`serde`], it requires the type to be [`Serialize`] and [`DeserializeOwned`].
/// The trait bound is specifically [`DeserializeOwned`] instead of [`Deserialize`](serde::Deserialize) because it has to outlive the content of the temporary file and cannot borrow from it.
pub struct TomlEditor<T: Serialize + DeserializeOwned> {
	thing: T
}

/// Implement [`Editable`] for a type `T: Serialize + DeserializeOwned`
///
/// The generated [`Editable::into_edit`] simply wraps `Self` with [`TomlEditor`].
///
/// This macro supports plain structs as well as structs with generic parameters.
/// In the first case, simply do `edit_as_toml!(MyType)`.
/// In the second case, there are a few limitations: all the generic parameters declared will be passed to the type, *and* all trait constraints must be passed in the form of `T: Trait` (will be passed to a `where` clause).
/// It's not possible to write `T: Serialize + DeserializeOwned`, write `T: Serialize, T: DeserializeOwned` instead.  
/// Finally, because the item will be deserialized from a short-lived string, there is no way to specify a lifetime.
///
/// In any case, this macro is provided only for convenience, implementing [`Editable`] is trivial.
///
/// Simple form:
/// ```
/// use serde::{Serialize, Deserialize};
///# use conciliator::Conciliator;
/// use conciliator::edit::{Edited, edit_as_toml};
///# let con = conciliator::init();
/// 
/// #[derive(Debug, Serialize, Deserialize)]
/// struct Entry {
///     id: usize,
///     name: String
/// }
/// edit_as_toml!(Entry);
/// 
/// let entry = Entry {id: 3, name: "Entry".to_owned()};
/// 
/// match con.edit(entry) {
///     Edited::Ok(s) => con.status(format!("Edited entry:\n{s:?}")),
///     Edited::Cancelled => con.info("Edit aborted!"),
///     Edited::Err(e) => con.error(format!("{e:?}"))
/// };
/// ```
///
/// With generics:
/// ```
/// use serde::{
///     Serialize,
///     Deserialize,
///     de::DeserializeOwned
/// };
///# use conciliator::Conciliator;
///# use conciliator::edit::{Edited, edit_as_toml};
///# let con = conciliator::init();
/// 
/// #[derive(Debug, Serialize, Deserialize)]
/// struct Entry<T> {
///     id: usize,
///     name: String,
///     thing: T
/// }
/// edit_as_toml!(
///     Entry<T>,
///     T: Serialize,
///     T: DeserializeOwned
/// );
/// 
/// let entry = Entry {
///     id: 3,
///     name: "Entry".to_owned(),
///     thing: 99
/// };
/// 
/// match con.edit(entry) {
///     Edited::Ok(s) => con.status(format!("Edited entry:\n{s:?}")),
///     Edited::Cancelled => con.info("Edit aborted!"),
///     Edited::Err(e) => con.error(format!("{e:?}"))
/// };
/// ```
#[macro_export]
macro_rules! edit_as_toml {
	($x:ident) => {
		impl $crate::edit::Editable for $x {
			type E = $crate::edit::TomlEditor<Self>;
			fn into_edit(self) -> Self::E {Self::E::new(self)}
		}
	};
	($x:ident< $($i:ident),* >, $($i2:ident: $tp:path),*) => {
		impl< $($i,)* > $crate::edit::Editable for $x< $($i),* >
			where $( $i2: $tp ),*
		{
			type E = $crate::edit::TomlEditor<Self>;
			fn into_edit(self) -> Self::E {Self::E::new(self)}
		}
	};
}
#[doc(inline)]
pub use edit_as_toml;


/// Function backing [`Claw::edit`]
///
/// Creates a temporary file, [`write`](Edit::write)s to it, invokes the text editor on it and [`read`](Edit::read)s it back after.
pub(crate) fn edit<E: Edit>(con: &Claw, editor: E) -> Edited<E> {
	let command = match get_editor_command(con) {
		Some(c) => c,
		None => return Edited::Cancelled
	};

	let try_block = || {
		let mut file = Builder::new()
			.prefix(&format!("{CRATE_NAME}_edit_"))
			.suffix(&format!(".{}", E::EXTENSION))
			.rand_bytes(8)
			.tempfile()?;

		editor.write(&mut file)?;
		file.as_file().sync_data()?;

		let time_before = file.as_file().metadata()?.modified()?;
		Ok((file, time_before))
	};

	let (mut file, time_before) = match try_block() {
		Ok((f, t)) => (f, t),
		Err(e) => return Edited::Err(e)
	};

	loop {
		let try_block = || {
			// run editor
			let editor_exit = Command::new(&command)
				.arg(file.path())
				.status()?;
			let time_after = file.as_file().metadata()?.modified()?;
			Ok((editor_exit, time_after))
		};

		let (editor_exit, time_after) = match try_block() {
			Ok((e, s)) => (e, s),
			Err(e) => return Edited::Err(e)
		};

		if !editor_exit.success() {
			con.error("Editor ")
				.push_bold(&command.to_string_lossy())
				.push_plain(" failed! (")
				.push_delta(&editor_exit)
				.push_plain(")");
			match con.input(AbortRetryContinue::Abort) {
				AbortRetryContinue::Abort => return Edited::Cancelled,
				AbortRetryContinue::Retry => continue,
				AbortRetryContinue::Continue => {}
			}
		}

		if time_before >= time_after {
			con.warn("File not edited!");
			match con.input(AbortRetryContinue::Abort) {
				AbortRetryContinue::Abort => return Edited::Cancelled,
				AbortRetryContinue::Retry => continue,
				AbortRetryContinue::Continue => {}
			}
		}

		let mut res = String::new();
		if let Err(e) = file.rewind() {return Edited::Err(e.into())}
		if let Err(e) = file.read_to_string(&mut res) {
			return Edited::Err(e.into())
		}

		// deserialize
		if let Some(thing) = editor.read(res, con) {
			break Edited::Ok(thing)
		}

		match con.confirm(true, "Retry?") {
			true => continue,
			false => break Edited::Cancelled
		}
	}
}

/// Returns `$EDITOR` if it is set, otherwise asks the user for a command to use.
/// Returns `None` if the user refuses to provide a text editor.
///
/// The main reason for doing it this way was getting rid off [`EditError`]`::EditorUnset` - because we give the user a chance to remedy the issue it is fair to return [`Edited::Cancelled`] if they refuse.
///
/// This does not check in any way whether the provided command is valid.
fn get_editor_command(con: &Claw) -> Option<OsString> {
	let editor = env::var_os("EDITOR");
	if editor.is_some() {return editor}

	con.error("$EDITOR environment variable is not set!");
	con.info("A text editor is required to edit a temporary file");

	con.confirm(false, "Enter a command to use as the editor program?")
		.then(|| con.input("Enter editor command"))
		.map(Into::into)
}


/*
 *	EDITED
 */

impl<E: Edit> Edited<E> {
	/// Returns the contained `T` if available, otherwise panics
	pub fn unwrap(self) -> E::T {
		match self {
			Self::Ok(t) => t,
			Self::Cancelled => panic!("Edit aborted!"),
			Self::Err(e) => panic!("Edit failed: {e}")
		}
	}

	/// Returns `Some(T)` if the edit succeeded, `None` if it was cancelled.
	/// Panics if `self` is `Self::Err`.
	pub fn unwrap_option(self) -> Option<E::T> {
		match self {
			Self::Ok(t) => Some(t),
			Self::Cancelled => None,
			Self::Err(e) => panic!("Edit failed: {e}")
		}
	}
}


/*
 *	EDIT ERROR
 */

impl<E: Error> From<IoError> for EditError<E> {
	fn from(e: IoError) -> Self {Self::Io(e)}
}

impl<E: Error> Error for EditError<E> {}

impl<E: Error> fmt::Display for EditError<E> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match self {
			Self::Serialize(e) => fmt::Display::fmt(&e, f),
			Self::Io(e) => e.fmt(f)
		}
	}
}

/*
 *	TOML EDITOR
 */

impl<T: Serialize + DeserializeOwned> TomlEditor<T> {
	/// Wrap something to be edited
	pub fn new(thing: T) -> Self {Self {thing}}
}

impl<T: Serialize + DeserializeOwned> Edit for TomlEditor<T> {
	const EXTENSION: &'static str = "toml";
	type T = T;
	type Err = EditError<toml::ser::Error>;
	fn write<W: Write>(&self, w: &mut W) -> Result<(), Self::Err> {
		let mut buf = String::new();
		let ser = toml::Serializer::pretty(&mut buf);
		if let Err(e) = self.thing.serialize(ser) {
			return Err(EditError::Serialize(e))
		}
		w.write_all(buf.as_bytes())?;
		Ok(())
	}
	fn read<C>(&self, content: String, con: &C) -> Option<Self::T>
		where C: Conciliator + ?Sized
	{
		toml::from_str(&content)
			.map_err(|e| {con
				.error("Failed to parse file as TOML: ")
				.push_plain(&e);
			})
			.ok()
	}

}

/*
 *	EDIT STRING
 */

/// Edit a plain string, no serialization or parsing
impl<'s> Edit for &'s str {
	const EXTENSION: &'static str = "txt";
	type T = String;
	type Err = IoError;
	fn write<W: Write>(&self, w: &mut W) -> Result<(), IoError> {
		w.write_all(self.as_bytes())
	}
	fn read<C>(&self, content: String, _con: &C) -> Option<Self::T>
		where C: Conciliator + ?Sized
	{
		Some(content)
	}
}

/*
 *	EDITABLE
 */

impl<T: Edit> Editable for T {
	type E = Self;
	fn into_edit(self) -> Self {self}
}