lexa_prompt/
for_loop.rs

1// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
2// ┃ Copyright: (c) 2023, Mike 'PhiSyX' S. (https://github.com/PhiSyX)         ┃
3// ┃ SPDX-License-Identifier: MPL-2.0                                          ┃
4// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
5// ┃                                                                           ┃
6// ┃  This Source Code Form is subject to the terms of the Mozilla Public      ┃
7// ┃  License, v. 2.0. If a copy of the MPL was not distributed with this      ┃
8// ┃  file, You can obtain one at https://mozilla.org/MPL/2.0/.                ┃
9// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
10
11use std::{error, fmt, str};
12
13use inquire::validator::Validation;
14use inquire::CustomUserError;
15
16use crate::confirm;
17
18// -------- //
19// Fonction //
20// -------- //
21
22pub fn for_loop<Output>(
23	message: impl fmt::Display,
24	validator: fn(&str) -> Result<Validation, CustomUserError>,
25) -> Vec<Output>
26where
27	Output: str::FromStr,
28	Output::Err: Into<Box<dyn error::Error + Send + Sync>>,
29	Output::Err: fmt::Display,
30{
31	let mut responses = Vec::default();
32
33	loop {
34		let msg = format!("{message}:");
35
36		let response = match inquire::Text::new(&msg)
37			.with_validator(validator)
38			.prompt()
39			.and_then(|s| {
40				s.parse::<Output>().map_err(|err| {
41					let custom_err = <_ as Into<CustomUserError>>::into(err);
42					inquire::InquireError::Custom(custom_err)
43				})
44			}) {
45			| Ok(response) => response,
46			| Err(err) => {
47				log::error!("{err}");
48				break;
49			}
50		};
51
52		responses.push(response);
53
54		if !confirm("  Continuer") {
55			break;
56		}
57	}
58
59	responses
60}
61
62pub fn for_loop2<Output>(
63	message: impl fmt::Display,
64	validator: fn(&str) -> Result<Validation, CustomUserError>,
65) -> Vec<Output>
66where
67	Output: crate::interface::Prompt,
68{
69	let mut responses = Vec::default();
70
71	loop {
72		let msg = format!("{message}:");
73
74		let response = match inquire::Text::new(&msg)
75			.with_validator(validator)
76			.prompt()
77			.and_then(|_| {
78				Output::prompt().map_err(|err| {
79					let custom_err = <_ as Into<CustomUserError>>::into(err.to_string());
80					inquire::InquireError::Custom(custom_err)
81				})
82			}) {
83			| Ok(response) => response,
84			| Err(err) => {
85				log::error!("{err}");
86				break;
87			}
88		};
89
90		responses.push(response);
91
92		if !confirm("  Continuer") {
93			break;
94		}
95	}
96
97	responses
98}