1use crate::answer::{Answer, QuestionAnswer, Value};
31use crate::types::{Error, QuestionOption, Validator};
32use serde::{Deserialize, Serialize};
33
34use crate::traits::async_traits::AllPrompts;
35use std::future::Future;
36use std::pin::Pin;
37
38#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
52#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
53#[serde(rename_all = "lowercase")]
54pub enum QuestionType {
55 Select,
56 MultiSelect,
57 Confirm,
58 Number,
59 Integer,
60 Input,
61 Password,
62 Editor,
63 Date,
64 DatePicker,
65 DateTime,
66 #[cfg(feature = "datetime-tz")]
67 DateTimeTz,
68 FilePicker,
69 #[serde(rename = "select_keyvalue")]
70 SelectKeyValue,
71 #[serde(rename = "multiselect_keyvalue")]
72 MultiSelectKeyValue,
73}
74
75#[derive(Debug, Clone, PartialEq, Serialize)]
80#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
81#[serde(untagged)]
82pub enum QuestionConfig {
83 Select { options: Vec<String> },
85 MultiSelect {
87 options: Vec<String>,
88 #[serde(skip_serializing_if = "Option::is_none")]
89 min_selections: Option<usize>,
90 #[serde(skip_serializing_if = "Option::is_none")]
91 max_selections: Option<usize>,
92 },
93 SelectKeyValue {
95 keyvalue_entries: Vec<(String, Answer)>,
96 },
97 MultiSelectKeyValue {
99 keyvalue_entries: Vec<(String, Answer)>,
100 #[serde(skip_serializing_if = "Option::is_none")]
101 min_selections: Option<usize>,
102 #[serde(skip_serializing_if = "Option::is_none")]
103 max_selections: Option<usize>,
104 },
105 Date {
107 #[serde(skip_serializing_if = "Option::is_none")]
108 default_value: Option<String>,
109 },
110 DatePicker {
112 #[serde(skip_serializing_if = "Option::is_none")]
113 min_date: Option<String>,
114 #[serde(skip_serializing_if = "Option::is_none")]
115 max_date: Option<String>,
116 #[serde(skip_serializing_if = "Option::is_none")]
117 default_value: Option<String>,
118 },
119 DateTime {
121 #[serde(skip_serializing_if = "Option::is_none")]
122 default_value: Option<String>,
123 },
124 #[cfg(feature = "datetime-tz")]
126 DateTimeTz {
127 #[serde(skip_serializing_if = "Option::is_none")]
128 default_value: Option<String>,
129 },
130 FilePicker {
132 #[serde(skip_serializing_if = "Option::is_none")]
133 starting_dir: Option<String>,
134 #[serde(skip_serializing_if = "Option::is_none")]
135 show_hidden: Option<bool>,
136 #[serde(skip_serializing_if = "Option::is_none")]
137 only_directories: Option<bool>,
138 #[serde(skip_serializing_if = "Option::is_none")]
139 only_files: Option<bool>,
140 #[serde(skip_serializing_if = "Option::is_none")]
141 extensions: Option<Vec<String>>,
142 #[serde(skip_serializing_if = "Option::is_none")]
143 multi_select: Option<bool>,
144 },
145 Confirm,
147 Input {
149 #[serde(skip_serializing_if = "Option::is_none")]
150 default_value: Option<String>,
151 },
152 Password,
154 Number {
156 #[serde(skip_serializing_if = "Option::is_none")]
157 default_value: Option<String>,
158 },
159 Integer {
161 #[serde(skip_serializing_if = "Option::is_none")]
162 default_value: Option<String>,
163 },
164 Editor,
166}
167
168#[derive(Serialize)]
176#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
177pub struct QuestionData {
178 #[serde(rename = "type")]
179 pub question_type: QuestionType,
180 pub prompt: String,
181 #[serde(flatten)]
182 pub config: QuestionConfig,
183 #[serde(skip_serializing_if = "Option::is_none")]
184 pub hint: Option<String>,
185 #[serde(skip_serializing_if = "Option::is_none")]
186 pub validator: Option<Validator>,
187 #[serde(skip)]
188 pub formatter: Option<crate::answer::AnswerFormatter>,
189}
190
191impl Clone for QuestionData {
192 fn clone(&self) -> Self {
193 QuestionData {
194 question_type: self.question_type.clone(),
195 prompt: self.prompt.clone(),
196 config: self.config.clone(),
197 hint: self.hint.clone(),
198 validator: self.validator.clone(),
199 formatter: self.formatter.clone(), }
201 }
202}
203
204impl QuestionData {
205 pub fn normalize_answer(&self, question_name: &str, answer: &Answer) -> Result<Answer, Error> {
210 let normalized = match (&self.config, answer) {
211 (QuestionConfig::Select { .. }, Answer::Text(Value::Single(_))) => answer.clone(),
212 (QuestionConfig::MultiSelect { .. }, Answer::Text(Value::Multiple(_))) => {
213 answer.clone()
214 }
215 (QuestionConfig::Confirm, Answer::Boolean(Value::Single(_))) => answer.clone(),
216 (QuestionConfig::Number { .. }, Answer::Number(Value::Single(_))) => answer.clone(),
217 (QuestionConfig::Number { .. }, Answer::Integer(n)) => {
218 Answer::Number(Value::Single(*n as f64))
219 }
220 (QuestionConfig::Integer { .. }, Answer::Integer(_)) => answer.clone(),
221 (QuestionConfig::Integer { .. }, Answer::Number(Value::Single(n))) => {
222 let n = crate::utils::integer::coerce_f64_to_i64(*n).map_err(Error::Validation)?;
223 Answer::Integer(n)
224 }
225 (QuestionConfig::Input { .. }, Answer::Text(Value::Single(_))) => answer.clone(),
226 (QuestionConfig::Password, Answer::Text(Value::Single(_))) => answer.clone(),
227 (QuestionConfig::Editor, Answer::Text(Value::Single(_))) => answer.clone(),
228 (QuestionConfig::Date { .. }, Answer::Text(Value::Single(s)))
229 | (QuestionConfig::DatePicker { .. }, Answer::Text(Value::Single(s))) => {
230 Answer::from_date_input(s.clone())?
231 }
232 #[cfg(feature = "datetime")]
233 (QuestionConfig::Date { .. }, Answer::Date(_))
234 | (QuestionConfig::DatePicker { .. }, Answer::Date(_)) => answer.clone(),
235 (QuestionConfig::DateTime { .. }, Answer::Text(Value::Single(s))) => {
236 Answer::from_datetime_input(s.clone())?
237 }
238 #[cfg(feature = "datetime")]
239 (QuestionConfig::DateTime { .. }, Answer::DateTime(_)) => answer.clone(),
240 #[cfg(feature = "datetime-tz")]
241 (QuestionConfig::DateTimeTz { .. }, Answer::Text(Value::Single(s))) => {
242 Answer::from_datetimetz_input(s.clone())?
243 }
244 #[cfg(feature = "datetime-tz")]
245 (QuestionConfig::DateTimeTz { .. }, Answer::DateTimeTz(_)) => answer.clone(),
246 (QuestionConfig::FilePicker { multi_select, .. }, file_answer) => {
247 match (multi_select.unwrap_or(false), file_answer) {
248 (true, Answer::Paths(_)) => answer.clone(),
249 (true, Answer::Path(path)) => Answer::Paths(vec![path.clone()]),
250 (true, Answer::Text(Value::Single(path))) => {
251 Answer::from_file_picker_results(vec![path.clone()], true)
252 }
253 (true, Answer::Text(Value::Multiple(paths))) => {
254 Answer::from_file_picker_results(paths.clone(), true)
255 }
256 (false, Answer::Path(_)) => answer.clone(),
257 (false, Answer::Text(Value::Single(path))) => {
258 Answer::from_file_picker_results(vec![path.clone()], false)
259 }
260 (false, Answer::Paths(paths)) if paths.len() == 1 => {
261 Answer::Path(paths[0].clone())
262 }
263 (false, Answer::Text(Value::Multiple(paths))) if paths.len() == 1 => {
264 Answer::from_file_picker_results(paths.clone(), false)
265 }
266 _ => {
267 return Err(Error::Validation(format!(
268 "Type mismatch for question '{}': expected {:?} but got {}",
269 question_name,
270 self.question_type,
271 answer.type_name()
272 )));
273 }
274 }
275 }
276 (QuestionConfig::SelectKeyValue { .. }, Answer::KeyValue(_)) => answer.clone(),
277 (QuestionConfig::MultiSelectKeyValue { .. }, Answer::KeyValue(_)) => answer.clone(),
278 _ => {
279 return Err(Error::Validation(format!(
280 "Type mismatch for question '{}': expected {:?} but got {}",
281 question_name,
282 self.question_type,
283 answer.type_name()
284 )));
285 }
286 };
287
288 Ok(normalized)
289 }
290}
291
292#[cfg(test)]
293mod tests {
294 use super::*;
295 #[cfg(feature = "datetime-tz")]
296 use crate::traits::async_traits::DateTimeTzPrompt;
297 use crate::traits::async_traits::{
298 AllPrompts, AsyncResult, AutocompletePrompt, ConfirmPrompt, DatePickerPrompt, DatePrompt,
299 DateTimePrompt, EditorPrompt, FilePickerPrompt, InputPrompt, LazyMultiSelectPrompt,
300 LazySelectPrompt, MultiSelectKeyValuePrompt, MultiSelectPrompt, NumberPrompt,
301 PasswordPrompt, QuestionnairePrompt, SelectKeyValuePrompt, SelectPrompt,
302 };
303 use crate::{Answers, AsyncValidator, OptionValue};
304
305 struct DirectBackend;
306
307 fn unsupported<'a, T>() -> AsyncResult<'a, T> {
308 Box::pin(async {
309 Err(Error::UnsupportedQuestionType(
310 "Not used by this direct question test backend".to_string(),
311 ))
312 })
313 }
314
315 impl SelectPrompt for DirectBackend {
316 fn select<'a>(
317 &'a self,
318 _prompt: String,
319 _options: Vec<OptionValue>,
320 _hint: Option<String>,
321 _filter_text: Option<String>,
322 _validator: Option<Validator>,
323 _async_validator: Option<AsyncValidator<'a, OptionValue>>,
324 ) -> AsyncResult<'a, OptionValue> {
325 unsupported()
326 }
327 }
328
329 impl MultiSelectPrompt for DirectBackend {}
330
331 impl ConfirmPrompt for DirectBackend {
332 fn confirm(&self, _prompt: String, _hint: Option<String>) -> AsyncResult<'_, bool> {
333 unsupported()
334 }
335 }
336
337 impl NumberPrompt for DirectBackend {
338 fn integer_input<'a>(
339 &'a self,
340 _prompt: String,
341 _hint: Option<String>,
342 _validator: Option<Validator>,
343 _default: Option<String>,
344 ) -> AsyncResult<'a, i64> {
345 Box::pin(async { Ok(42) })
346 }
347 }
348
349 impl InputPrompt for DirectBackend {
350 fn text_input<'a>(
351 &'a self,
352 _prompt: String,
353 _hint: Option<String>,
354 _validator: Option<Validator>,
355 _async_validator: Option<AsyncValidator<'a, String>>,
356 _default: Option<String>,
357 ) -> AsyncResult<'a, String> {
358 unsupported()
359 }
360 }
361
362 impl PasswordPrompt for DirectBackend {}
363 impl EditorPrompt for DirectBackend {}
364
365 impl DatePrompt for DirectBackend {
366 fn date_input<'a>(
367 &'a self,
368 _prompt: String,
369 _hint: Option<String>,
370 _validator: Option<Validator>,
371 _async_validator: Option<AsyncValidator<'a, String>>,
372 _default: Option<String>,
373 ) -> AsyncResult<'a, String> {
374 Box::pin(async { Ok("2025-01-02".to_string()) })
375 }
376 }
377
378 impl DatePickerPrompt for DirectBackend {
379 fn date_picker_prompt<'a>(
380 &'a self,
381 _prompt: String,
382 _hint: Option<String>,
383 _default: Option<String>,
384 _min_date: Option<String>,
385 _max_date: Option<String>,
386 _validator: Option<Validator>,
387 _async_validator: Option<AsyncValidator<'a, String>>,
388 ) -> AsyncResult<'a, String> {
389 Box::pin(async { Ok("2025-01-03".to_string()) })
390 }
391 }
392
393 impl DateTimePrompt for DirectBackend {
394 fn datetime_input<'a>(
395 &'a self,
396 _prompt: String,
397 _hint: Option<String>,
398 _validator: Option<Validator>,
399 _async_validator: Option<AsyncValidator<'a, String>>,
400 _default: Option<String>,
401 ) -> AsyncResult<'a, String> {
402 Box::pin(async { Ok("2025-01-02 03:04:05".to_string()) })
403 }
404 }
405
406 #[cfg(feature = "datetime-tz")]
407 impl DateTimeTzPrompt for DirectBackend {
408 fn datetimetz_input<'a>(
409 &'a self,
410 _prompt: String,
411 _hint: Option<String>,
412 _validator: Option<Validator>,
413 _async_validator: Option<AsyncValidator<'a, String>>,
414 _default: Option<String>,
415 ) -> AsyncResult<'a, String> {
416 Box::pin(async { Ok("2025-01-02T03:04:05+02:00".to_string()) })
417 }
418 }
419
420 impl FilePickerPrompt for DirectBackend {
421 fn file_picker_prompt<'a>(
422 &'a self,
423 _prompt: String,
424 _hint: Option<String>,
425 _starting_dir: Option<String>,
426 _show_hidden: bool,
427 _only_directories: bool,
428 _only_files: bool,
429 _extensions: Option<Vec<String>>,
430 multi_select: bool,
431 _async_validator: Option<AsyncValidator<'a, Vec<String>>>,
432 ) -> AsyncResult<'a, Vec<String>> {
433 Box::pin(async move {
434 if multi_select {
435 Ok(vec!["/tmp/a".to_string(), "/tmp/b".to_string()])
436 } else {
437 Ok(vec!["/tmp/a".to_string()])
438 }
439 })
440 }
441 }
442
443 impl SelectKeyValuePrompt for DirectBackend {}
444 impl MultiSelectKeyValuePrompt for DirectBackend {}
445 impl AutocompletePrompt for DirectBackend {}
446 impl LazySelectPrompt for DirectBackend {}
447 impl LazyMultiSelectPrompt for DirectBackend {}
448
449 impl QuestionnairePrompt for DirectBackend {
450 fn execute_questionnaire_async<'a>(
451 &'a self,
452 _questionnaire: &'a crate::questionnaire::Questionnaire,
453 _override_answers: Option<&'a Answers>,
454 ) -> AsyncResult<'a, Answers> {
455 unsupported()
456 }
457 }
458
459 impl AllPrompts for DirectBackend {}
460
461 #[test]
462 fn direct_integer_question_returns_integer_answer() {
463 smol::block_on(async {
464 let question = Question::Integer {
465 name: "port".to_string(),
466 prompt: "Port?".to_string(),
467 hint: None,
468 default_value: None,
469 };
470
471 let answer = question.ask_async(DirectBackend).await.unwrap();
472 assert_eq!(answer.question_name, "port");
473 assert_eq!(answer.value, Answer::Integer(42));
474 });
475 }
476
477 #[test]
478 fn normalize_answer_converts_serialized_integer_override() {
479 let question = QuestionData {
480 question_type: QuestionType::Integer,
481 prompt: "Port?".to_string(),
482 config: QuestionConfig::Integer {
483 default_value: None,
484 },
485 hint: None,
486 validator: None,
487 formatter: None,
488 };
489
490 let answer = question
491 .normalize_answer("port", &Answer::Number(Value::Single(8080.0)))
492 .unwrap();
493
494 assert_eq!(answer, Answer::Integer(8080));
495 }
496
497 #[test]
498 fn normalize_answer_converts_serialized_filepicker_override() {
499 let single = QuestionData {
500 question_type: QuestionType::FilePicker,
501 prompt: "Config?".to_string(),
502 config: QuestionConfig::FilePicker {
503 starting_dir: None,
504 show_hidden: None,
505 only_directories: None,
506 only_files: Some(true),
507 extensions: None,
508 multi_select: None,
509 },
510 hint: None,
511 validator: None,
512 formatter: None,
513 };
514
515 let answer = single
516 .normalize_answer(
517 "config",
518 &Answer::Text(Value::Single("/tmp/config.toml".to_string())),
519 )
520 .unwrap();
521 assert_eq!(
522 answer.as_path().unwrap(),
523 std::path::Path::new("/tmp/config.toml")
524 );
525
526 let multi = QuestionData {
527 question_type: QuestionType::FilePicker,
528 prompt: "Configs?".to_string(),
529 config: QuestionConfig::FilePicker {
530 starting_dir: None,
531 show_hidden: None,
532 only_directories: None,
533 only_files: Some(true),
534 extensions: None,
535 multi_select: Some(true),
536 },
537 hint: None,
538 validator: None,
539 formatter: None,
540 };
541
542 let answer = multi
543 .normalize_answer(
544 "configs",
545 &Answer::Text(Value::Multiple(vec![
546 "/tmp/a.toml".to_string(),
547 "/tmp/b.toml".to_string(),
548 ])),
549 )
550 .unwrap();
551 assert_eq!(answer.as_paths().unwrap().len(), 2);
552 }
553
554 #[test]
555 fn direct_filepicker_questions_return_path_answers() {
556 smol::block_on(async {
557 let single = Question::FilePicker {
558 name: "config".to_string(),
559 prompt: "Config?".to_string(),
560 starting_dir: None,
561 show_hidden: false,
562 only_directories: false,
563 only_files: true,
564 extensions: None,
565 multi_select: false,
566 hint: None,
567 };
568 let answer = single.ask_async(DirectBackend).await.unwrap();
569 assert_eq!(
570 answer.value.as_path().unwrap(),
571 std::path::Path::new("/tmp/a")
572 );
573
574 let multi = Question::FilePicker {
575 name: "configs".to_string(),
576 prompt: "Configs?".to_string(),
577 starting_dir: None,
578 show_hidden: false,
579 only_directories: false,
580 only_files: true,
581 extensions: None,
582 multi_select: true,
583 hint: None,
584 };
585 let answer = multi.ask_async(DirectBackend).await.unwrap();
586 assert_eq!(answer.value.as_paths().unwrap().len(), 2);
587 });
588 }
589
590 #[cfg(feature = "datetime")]
591 #[test]
592 fn direct_date_and_datetime_questions_return_typed_answers() {
593 smol::block_on(async {
594 let date = Question::Date {
595 name: "date".to_string(),
596 prompt: "Date?".to_string(),
597 hint: None,
598 default_value: None,
599 };
600 assert!(matches!(
601 date.ask_async(DirectBackend).await.unwrap().value,
602 Answer::Date(_)
603 ));
604
605 let datetime = Question::DateTime {
606 name: "datetime".to_string(),
607 prompt: "Datetime?".to_string(),
608 hint: None,
609 default_value: None,
610 };
611 assert!(matches!(
612 datetime.ask_async(DirectBackend).await.unwrap().value,
613 Answer::DateTime(_)
614 ));
615 });
616 }
617
618 #[cfg(feature = "datetime-tz")]
619 #[test]
620 fn direct_datetimetz_question_returns_typed_answer() {
621 smol::block_on(async {
622 let datetimetz = Question::DateTimeTz {
623 name: "datetimetz".to_string(),
624 prompt: "Datetime with timezone?".to_string(),
625 hint: None,
626 default_value: None,
627 };
628 assert!(matches!(
629 datetimetz.ask_async(DirectBackend).await.unwrap().value,
630 Answer::DateTimeTz(_)
631 ));
632 });
633 }
634
635 #[cfg(not(feature = "datetime"))]
636 #[test]
637 fn direct_temporal_questions_preserve_strings_without_datetime_feature() {
638 smol::block_on(async {
639 let date = Question::Date {
640 name: "date".to_string(),
641 prompt: "Date?".to_string(),
642 hint: None,
643 default_value: None,
644 };
645
646 let answer = date.ask_async(DirectBackend).await.unwrap();
647 assert_eq!(
648 answer.value,
649 Answer::Text(crate::answer::Value::Single("2025-01-02".to_string()))
650 );
651 });
652 }
653}
654
655impl std::fmt::Debug for QuestionData {
656 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
657 f.debug_struct("QuestionData")
658 .field("question_type", &self.question_type)
659 .field("prompt", &self.prompt)
660 .field("config", &self.config)
661 .field("hint", &self.hint)
662 .field("validator", &self.validator)
663 .field(
664 "formatter",
665 &self.formatter.as_ref().map(|_| "Some(formatter)"),
666 )
667 .finish()
668 }
669}
670
671impl<'de> serde::Deserialize<'de> for QuestionData {
672 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
673 where
674 D: serde::Deserializer<'de>,
675 {
676 #[derive(serde::Deserialize)]
677 struct Helper {
678 #[serde(rename = "type")]
679 question_type: QuestionType,
680 prompt: String,
681 hint: Option<String>,
682 validator: Option<Validator>,
683 #[serde(flatten)]
685 extra: serde_json::Value,
686 }
687
688 let helper = Helper::deserialize(deserializer)?;
689
690 let config = match helper.question_type {
692 QuestionType::Input => QuestionConfig::Input {
693 default_value: None,
694 },
695 QuestionType::Password => QuestionConfig::Password,
696 QuestionType::Number => QuestionConfig::Number {
697 default_value: None,
698 },
699 QuestionType::Integer => QuestionConfig::Integer {
700 default_value: None,
701 },
702 QuestionType::Confirm => QuestionConfig::Confirm,
703 QuestionType::Editor => QuestionConfig::Editor,
704
705 QuestionType::Select => {
706 #[derive(serde::Deserialize)]
707 struct SelectConfig {
708 options: Vec<String>,
709 }
710 let cfg: SelectConfig =
711 serde_json::from_value(helper.extra).map_err(serde::de::Error::custom)?;
712 QuestionConfig::Select {
713 options: cfg.options,
714 }
715 }
716
717 QuestionType::MultiSelect => {
718 #[derive(serde::Deserialize)]
719 struct MultiSelectConfig {
720 options: Vec<String>,
721 min_selections: Option<usize>,
722 max_selections: Option<usize>,
723 }
724 let cfg: MultiSelectConfig =
725 serde_json::from_value(helper.extra).map_err(serde::de::Error::custom)?;
726 QuestionConfig::MultiSelect {
727 options: cfg.options,
728 min_selections: cfg.min_selections,
729 max_selections: cfg.max_selections,
730 }
731 }
732
733 QuestionType::Date => {
734 #[derive(serde::Deserialize)]
735 struct DateConfig {
736 default_value: Option<String>,
737 }
738 let cfg: DateConfig =
739 serde_json::from_value(helper.extra).map_err(serde::de::Error::custom)?;
740 QuestionConfig::Date {
741 default_value: cfg.default_value,
742 }
743 }
744
745 QuestionType::DatePicker => {
746 #[derive(serde::Deserialize)]
747 struct DatePickerConfig {
748 min_date: Option<String>,
749 max_date: Option<String>,
750 default_value: Option<String>,
751 }
752 let cfg: DatePickerConfig =
753 serde_json::from_value(helper.extra).map_err(serde::de::Error::custom)?;
754 QuestionConfig::DatePicker {
755 min_date: cfg.min_date,
756 max_date: cfg.max_date,
757 default_value: cfg.default_value,
758 }
759 }
760
761 QuestionType::DateTime => {
762 #[derive(serde::Deserialize)]
763 struct DateTimeConfig {
764 default_value: Option<String>,
765 }
766 let cfg: DateTimeConfig =
767 serde_json::from_value(helper.extra).map_err(serde::de::Error::custom)?;
768 QuestionConfig::DateTime {
769 default_value: cfg.default_value,
770 }
771 }
772
773 #[cfg(feature = "datetime-tz")]
774 QuestionType::DateTimeTz => {
775 #[derive(serde::Deserialize)]
776 struct DateTimeTzConfig {
777 default_value: Option<String>,
778 }
779 let cfg: DateTimeTzConfig =
780 serde_json::from_value(helper.extra).map_err(serde::de::Error::custom)?;
781 QuestionConfig::DateTimeTz {
782 default_value: cfg.default_value,
783 }
784 }
785
786 QuestionType::FilePicker => {
787 #[derive(serde::Deserialize)]
788 struct FilePickerConfig {
789 starting_dir: Option<String>,
790 show_hidden: Option<bool>,
791 only_directories: Option<bool>,
792 only_files: Option<bool>,
793 extensions: Option<Vec<String>>,
794 multi_select: Option<bool>,
795 }
796 let cfg: FilePickerConfig =
797 serde_json::from_value(helper.extra).map_err(serde::de::Error::custom)?;
798 QuestionConfig::FilePicker {
799 starting_dir: cfg.starting_dir,
800 show_hidden: cfg.show_hidden,
801 only_directories: cfg.only_directories,
802 only_files: cfg.only_files,
803 extensions: cfg.extensions,
804 multi_select: cfg.multi_select,
805 }
806 }
807
808 QuestionType::SelectKeyValue => {
809 #[derive(serde::Deserialize)]
810 struct SelectKeyValueConfig {
811 keyvalue_entries: Vec<(String, Answer)>,
812 }
813 let cfg: SelectKeyValueConfig =
814 serde_json::from_value(helper.extra).map_err(serde::de::Error::custom)?;
815 QuestionConfig::SelectKeyValue {
816 keyvalue_entries: cfg.keyvalue_entries,
817 }
818 }
819
820 QuestionType::MultiSelectKeyValue => {
821 #[derive(serde::Deserialize)]
822 struct MultiSelectKeyValueConfig {
823 keyvalue_entries: Vec<(String, Answer)>,
824 min_selections: Option<usize>,
825 max_selections: Option<usize>,
826 }
827 let cfg: MultiSelectKeyValueConfig =
828 serde_json::from_value(helper.extra).map_err(serde::de::Error::custom)?;
829 QuestionConfig::MultiSelectKeyValue {
830 keyvalue_entries: cfg.keyvalue_entries,
831 min_selections: cfg.min_selections,
832 max_selections: cfg.max_selections,
833 }
834 }
835 };
836
837 Ok(QuestionData {
838 question_type: helper.question_type,
839 prompt: helper.prompt,
840 config,
841 hint: helper.hint,
842 validator: helper.validator,
843 formatter: None,
844 })
845 }
846}
847
848#[derive(Clone, Debug)]
849pub enum Question {
850 Select {
851 name: String,
852 prompt: String,
853 options: Vec<String>,
854 hint: Option<String>,
855 },
856 MultiSelect {
857 name: String,
858 prompt: String,
859 options: Vec<String>,
860 hint: Option<String>,
861 },
862 Confirm {
863 name: String,
864 prompt: String,
865 hint: Option<String>,
866 },
867 Number {
868 name: String,
869 prompt: String,
870 hint: Option<String>,
871 },
872 Integer {
873 name: String,
874 prompt: String,
875 hint: Option<String>,
876 default_value: Option<String>,
877 },
878 Input {
879 name: String,
880 prompt: String,
881 hint: Option<String>,
882 },
883 Password {
884 name: String,
885 prompt: String,
886 hint: Option<String>,
887 },
888 Editor {
889 name: String,
890 prompt: String,
891 hint: Option<String>,
892 },
893 Date {
894 name: String,
895 prompt: String,
896 hint: Option<String>,
897 default_value: Option<String>,
898 },
899 DatePicker {
900 name: String,
901 prompt: String,
902 hint: Option<String>,
903 default_value: Option<String>,
904 min_date: Option<String>,
905 max_date: Option<String>,
906 },
907 DateTime {
908 name: String,
909 prompt: String,
910 hint: Option<String>,
911 default_value: Option<String>,
912 },
913 #[cfg(feature = "datetime-tz")]
914 DateTimeTz {
915 name: String,
916 prompt: String,
917 hint: Option<String>,
918 default_value: Option<String>,
919 },
920 FilePicker {
921 name: String,
922 prompt: String,
923 starting_dir: Option<String>,
924 show_hidden: bool,
925 only_directories: bool,
926 only_files: bool,
927 extensions: Option<Vec<String>>,
928 multi_select: bool,
929 hint: Option<String>,
930 },
931 SelectKeyValue {
932 name: String,
933 prompt: String,
934 entries: Vec<(String, Answer)>,
935 hint: Option<String>,
936 },
937 MultiSelectKeyValue {
938 name: String,
939 prompt: String,
940 entries: Vec<(String, Answer)>,
941 hint: Option<String>,
942 },
943}
944
945impl Question {
946 pub fn name(&self) -> &str {
947 match self {
948 Question::Select { name, .. }
949 | Question::MultiSelect { name, .. }
950 | Question::Confirm { name, .. }
951 | Question::Number { name, .. }
952 | Question::Integer { name, .. }
953 | Question::Input { name, .. }
954 | Question::Password { name, .. }
955 | Question::Editor { name, .. }
956 | Question::Date { name, .. }
957 | Question::DatePicker { name, .. }
958 | Question::DateTime { name, .. }
959 | Question::FilePicker { name, .. }
960 | Question::SelectKeyValue { name, .. }
961 | Question::MultiSelectKeyValue { name, .. } => name,
962 #[cfg(feature = "datetime-tz")]
963 Question::DateTimeTz { name, .. } => name,
964 }
965 }
966
967 pub fn to_question_data(&self) -> QuestionData {
968 match self {
969 Question::Select {
970 prompt,
971 options,
972 hint,
973 ..
974 } => QuestionData {
975 question_type: QuestionType::Select,
976 prompt: prompt.clone(),
977 config: QuestionConfig::Select {
978 options: options.clone(),
979 },
980 hint: hint.clone(),
981 validator: None,
982 formatter: None,
983 },
984 Question::MultiSelect {
985 prompt,
986 options,
987 hint,
988 ..
989 } => QuestionData {
990 question_type: QuestionType::MultiSelect,
991 prompt: prompt.clone(),
992 config: QuestionConfig::MultiSelect {
993 options: options.clone(),
994 min_selections: None,
995 max_selections: None,
996 },
997 hint: hint.clone(),
998 validator: None,
999 formatter: None,
1000 },
1001 Question::Confirm { prompt, hint, .. } => QuestionData {
1002 question_type: QuestionType::Confirm,
1003 prompt: prompt.clone(),
1004 config: QuestionConfig::Confirm,
1005 hint: hint.clone(),
1006 validator: None,
1007 formatter: None,
1008 },
1009 Question::Number { prompt, hint, .. } => QuestionData {
1010 question_type: QuestionType::Number,
1011 prompt: prompt.clone(),
1012 config: QuestionConfig::Number {
1013 default_value: None,
1014 },
1015 hint: hint.clone(),
1016 validator: None,
1017 formatter: None,
1018 },
1019 Question::Integer {
1020 prompt,
1021 hint,
1022 default_value,
1023 ..
1024 } => QuestionData {
1025 question_type: QuestionType::Integer,
1026 prompt: prompt.clone(),
1027 config: QuestionConfig::Integer {
1028 default_value: default_value.clone(),
1029 },
1030 hint: hint.clone(),
1031 validator: None,
1032 formatter: None,
1033 },
1034 Question::Input { prompt, hint, .. } => QuestionData {
1035 question_type: QuestionType::Input,
1036 prompt: prompt.clone(),
1037 config: QuestionConfig::Input {
1038 default_value: None,
1039 },
1040 hint: hint.clone(),
1041 validator: None,
1042 formatter: None,
1043 },
1044 Question::Password { prompt, hint, .. } => QuestionData {
1045 question_type: QuestionType::Password,
1046 prompt: prompt.clone(),
1047 config: QuestionConfig::Password,
1048 hint: hint.clone(),
1049 validator: None,
1050 formatter: None,
1051 },
1052 Question::Editor { prompt, hint, .. } => QuestionData {
1053 question_type: QuestionType::Editor,
1054 prompt: prompt.clone(),
1055 config: QuestionConfig::Editor,
1056 hint: hint.clone(),
1057 validator: None,
1058 formatter: None,
1059 },
1060 Question::Date {
1061 prompt,
1062 hint,
1063 default_value,
1064 ..
1065 } => QuestionData {
1066 question_type: QuestionType::Date,
1067 prompt: prompt.clone(),
1068 config: QuestionConfig::Date {
1069 default_value: default_value.clone(),
1070 },
1071 hint: hint.clone(),
1072 validator: None,
1073 formatter: None,
1074 },
1075 Question::DatePicker {
1076 prompt,
1077 hint,
1078 default_value,
1079 min_date,
1080 max_date,
1081 ..
1082 } => QuestionData {
1083 question_type: QuestionType::DatePicker,
1084 prompt: prompt.clone(),
1085 config: QuestionConfig::DatePicker {
1086 min_date: min_date.clone(),
1087 max_date: max_date.clone(),
1088 default_value: default_value.clone(),
1089 },
1090 hint: hint.clone(),
1091 validator: None,
1092 formatter: None,
1093 },
1094 Question::DateTime {
1095 prompt,
1096 hint,
1097 default_value,
1098 ..
1099 } => QuestionData {
1100 question_type: QuestionType::DateTime,
1101 prompt: prompt.clone(),
1102 config: QuestionConfig::DateTime {
1103 default_value: default_value.clone(),
1104 },
1105 hint: hint.clone(),
1106 validator: None,
1107 formatter: None,
1108 },
1109 #[cfg(feature = "datetime-tz")]
1110 Question::DateTimeTz {
1111 prompt,
1112 hint,
1113 default_value,
1114 ..
1115 } => QuestionData {
1116 question_type: QuestionType::DateTimeTz,
1117 prompt: prompt.clone(),
1118 config: QuestionConfig::DateTimeTz {
1119 default_value: default_value.clone(),
1120 },
1121 hint: hint.clone(),
1122 validator: None,
1123 formatter: None,
1124 },
1125 Question::FilePicker {
1126 prompt,
1127 hint,
1128 starting_dir,
1129 show_hidden,
1130 only_directories,
1131 only_files,
1132 extensions,
1133 multi_select,
1134 ..
1135 } => QuestionData {
1136 question_type: QuestionType::FilePicker,
1137 prompt: prompt.clone(),
1138 config: QuestionConfig::FilePicker {
1139 starting_dir: starting_dir.clone(),
1140 show_hidden: Some(*show_hidden),
1141 only_directories: Some(*only_directories),
1142 only_files: Some(*only_files),
1143 extensions: extensions.clone(),
1144 multi_select: Some(*multi_select),
1145 },
1146 hint: hint.clone(),
1147 validator: None,
1148 formatter: None,
1149 },
1150 Question::SelectKeyValue {
1151 prompt,
1152 hint,
1153 entries,
1154 ..
1155 } => QuestionData {
1156 question_type: QuestionType::SelectKeyValue,
1157 prompt: prompt.clone(),
1158 config: QuestionConfig::SelectKeyValue {
1159 keyvalue_entries: entries.clone(),
1160 },
1161 hint: hint.clone(),
1162 validator: None,
1163 formatter: None,
1164 },
1165 Question::MultiSelectKeyValue {
1166 prompt,
1167 hint,
1168 entries,
1169 ..
1170 } => QuestionData {
1171 question_type: QuestionType::MultiSelectKeyValue,
1172 prompt: prompt.clone(),
1173 config: QuestionConfig::MultiSelectKeyValue {
1174 keyvalue_entries: entries.clone(),
1175 min_selections: None,
1176 max_selections: None,
1177 },
1178 hint: hint.clone(),
1179 validator: None,
1180 formatter: None,
1181 },
1182 }
1183 }
1184
1185 pub fn from_question_data(name: String, data: &QuestionData) -> Self {
1186 match &data.config {
1187 QuestionConfig::Select { options } => Question::Select {
1188 name,
1189 prompt: data.prompt.clone(),
1190 options: options.clone(),
1191 hint: data.hint.clone(),
1192 },
1193 QuestionConfig::MultiSelect { options, .. } => Question::MultiSelect {
1194 name,
1195 prompt: data.prompt.clone(),
1196 options: options.clone(),
1197 hint: data.hint.clone(),
1198 },
1199 QuestionConfig::Confirm => Question::Confirm {
1200 name,
1201 prompt: data.prompt.clone(),
1202 hint: data.hint.clone(),
1203 },
1204 QuestionConfig::Number { .. } => Question::Number {
1205 name,
1206 prompt: data.prompt.clone(),
1207 hint: data.hint.clone(),
1208 },
1209 QuestionConfig::Integer { default_value } => Question::Integer {
1210 name,
1211 prompt: data.prompt.clone(),
1212 hint: data.hint.clone(),
1213 default_value: default_value.clone(),
1214 },
1215 QuestionConfig::Input { .. } => Question::Input {
1216 name,
1217 prompt: data.prompt.clone(),
1218 hint: data.hint.clone(),
1219 },
1220 QuestionConfig::Password => Question::Password {
1221 name,
1222 prompt: data.prompt.clone(),
1223 hint: data.hint.clone(),
1224 },
1225 QuestionConfig::Editor => Question::Editor {
1226 name,
1227 prompt: data.prompt.clone(),
1228 hint: data.hint.clone(),
1229 },
1230 QuestionConfig::Date { default_value } => Question::Date {
1231 name,
1232 prompt: data.prompt.clone(),
1233 hint: data.hint.clone(),
1234 default_value: default_value.clone(),
1235 },
1236 QuestionConfig::DatePicker {
1237 min_date,
1238 max_date,
1239 default_value,
1240 } => Question::DatePicker {
1241 name,
1242 prompt: data.prompt.clone(),
1243 hint: data.hint.clone(),
1244 default_value: default_value.clone(),
1245 min_date: min_date.clone(),
1246 max_date: max_date.clone(),
1247 },
1248 QuestionConfig::DateTime { default_value } => Question::DateTime {
1249 name,
1250 prompt: data.prompt.clone(),
1251 hint: data.hint.clone(),
1252 default_value: default_value.clone(),
1253 },
1254 #[cfg(feature = "datetime-tz")]
1255 QuestionConfig::DateTimeTz { default_value } => Question::DateTimeTz {
1256 name,
1257 prompt: data.prompt.clone(),
1258 hint: data.hint.clone(),
1259 default_value: default_value.clone(),
1260 },
1261 QuestionConfig::FilePicker {
1262 starting_dir,
1263 show_hidden,
1264 only_directories,
1265 only_files,
1266 extensions,
1267 multi_select,
1268 } => Question::FilePicker {
1269 name,
1270 prompt: data.prompt.clone(),
1271 starting_dir: starting_dir.clone(),
1272 show_hidden: show_hidden.unwrap_or(false),
1273 only_directories: only_directories.unwrap_or(false),
1274 only_files: only_files.unwrap_or(false),
1275 extensions: extensions.clone(),
1276 multi_select: multi_select.unwrap_or(false),
1277 hint: data.hint.clone(),
1278 },
1279 QuestionConfig::SelectKeyValue { keyvalue_entries } => Question::SelectKeyValue {
1280 name,
1281 prompt: data.prompt.clone(),
1282 entries: keyvalue_entries.clone(),
1283 hint: data.hint.clone(),
1284 },
1285 QuestionConfig::MultiSelectKeyValue {
1286 keyvalue_entries, ..
1287 } => Question::MultiSelectKeyValue {
1288 name,
1289 prompt: data.prompt.clone(),
1290 entries: keyvalue_entries.clone(),
1291 hint: data.hint.clone(),
1292 },
1293 }
1294 }
1295
1296 pub fn ask_async<'a, B: AllPrompts + Send + 'a>(
1298 &'a self,
1299 backend: B,
1300 ) -> Pin<Box<dyn Future<Output = Result<QuestionAnswer, Error>> + Send + 'a>> {
1301 Box::pin(async move {
1302 match self {
1303 Question::Select {
1304 name,
1305 prompt,
1306 options,
1307 hint,
1308 } => {
1309 let option_values: Vec<QuestionOption> = options
1310 .iter()
1311 .map(|s| QuestionOption::new(s.clone()))
1312 .collect();
1313 let result = backend
1314 .select(
1315 prompt.clone(),
1316 option_values,
1317 hint.clone(),
1318 None, None, None, )
1322 .await?;
1323 use crate::answer::Value;
1324 Ok(QuestionAnswer {
1325 question_name: name.clone(),
1326 value: Answer::Text(Value::Single(result.value)),
1327 })
1328 }
1329 Question::MultiSelect {
1330 name,
1331 prompt,
1332 options,
1333 hint,
1334 } => {
1335 let option_values: Vec<QuestionOption> = options
1336 .iter()
1337 .map(|s| QuestionOption::new(s.clone()))
1338 .collect();
1339 let results = backend
1340 .multi_select(
1341 prompt.clone(),
1342 option_values,
1343 hint.clone(),
1344 None, None, None, )
1348 .await?;
1349 use crate::answer::Value;
1350 Ok(QuestionAnswer {
1351 question_name: name.clone(),
1352 value: Answer::Text(Value::Multiple(
1353 results.iter().map(|r| r.value.clone()).collect(),
1354 )),
1355 })
1356 }
1357 Question::Confirm { name, prompt, hint } => {
1358 let result = backend.confirm(prompt.clone(), hint.clone()).await?;
1359 use crate::answer::Value;
1360 Ok(QuestionAnswer {
1361 question_name: name.clone(),
1362 value: Answer::Boolean(Value::Single(result)),
1363 })
1364 }
1365 Question::Number { name, prompt, hint } => {
1366 let result = backend
1367 .number_input(prompt.clone(), hint.clone(), None, None, None)
1368 .await?;
1369 use crate::answer::Value;
1370 Ok(QuestionAnswer {
1371 question_name: name.clone(),
1372 value: Answer::Number(Value::Single(result)),
1373 })
1374 }
1375 Question::Integer {
1376 name,
1377 prompt,
1378 hint,
1379 default_value,
1380 } => {
1381 let result = backend
1382 .integer_input(prompt.clone(), hint.clone(), None, default_value.clone())
1383 .await?;
1384 Ok(QuestionAnswer {
1385 question_name: name.clone(),
1386 value: Answer::Integer(result),
1387 })
1388 }
1389 Question::Input { name, prompt, hint } => {
1390 let result = backend
1391 .text_input(prompt.clone(), hint.clone(), None, None, None)
1392 .await?;
1393 use crate::answer::Value;
1394 Ok(QuestionAnswer {
1395 question_name: name.clone(),
1396 value: Answer::Text(Value::Single(result)),
1397 })
1398 }
1399 Question::Password { name, prompt, hint } => {
1400 let result = backend
1401 .password_input(prompt.clone(), hint.clone(), None, None)
1402 .await?;
1403 use crate::answer::Value;
1404 Ok(QuestionAnswer {
1405 question_name: name.clone(),
1406 value: Answer::Text(Value::Single(result)),
1407 })
1408 }
1409 Question::Editor { name, prompt, hint } => {
1410 let result = backend
1411 .editor_input(prompt.clone(), hint.clone(), None, None)
1412 .await?;
1413 use crate::answer::Value;
1414 Ok(QuestionAnswer {
1415 question_name: name.clone(),
1416 value: Answer::Text(Value::Single(result)),
1417 })
1418 }
1419 Question::Date {
1420 name,
1421 prompt,
1422 hint,
1423 default_value,
1424 } => {
1425 let result = backend
1426 .date_input(
1427 prompt.clone(),
1428 hint.clone(),
1429 None,
1430 None,
1431 default_value.clone(),
1432 )
1433 .await?;
1434 Ok(QuestionAnswer {
1435 question_name: name.clone(),
1436 value: Answer::from_date_input(result)?,
1437 })
1438 }
1439 Question::DatePicker {
1440 name,
1441 prompt,
1442 hint,
1443 default_value,
1444 min_date,
1445 max_date,
1446 } => {
1447 let result = backend
1448 .date_picker_prompt(
1449 prompt.clone(),
1450 hint.clone(),
1451 default_value.clone(),
1452 min_date.clone(),
1453 max_date.clone(),
1454 None, None, )
1457 .await?;
1458 Ok(QuestionAnswer {
1459 question_name: name.clone(),
1460 value: Answer::from_date_input(result)?,
1461 })
1462 }
1463 Question::DateTime {
1464 name,
1465 prompt,
1466 hint,
1467 default_value,
1468 } => {
1469 let result = backend
1470 .datetime_input(
1471 prompt.clone(),
1472 hint.clone(),
1473 None,
1474 None,
1475 default_value.clone(),
1476 )
1477 .await?;
1478 Ok(QuestionAnswer {
1479 question_name: name.clone(),
1480 value: Answer::from_datetime_input(result)?,
1481 })
1482 }
1483 #[cfg(feature = "datetime-tz")]
1484 Question::DateTimeTz {
1485 name,
1486 prompt,
1487 hint,
1488 default_value,
1489 } => {
1490 let result = backend
1491 .datetimetz_input(
1492 prompt.clone(),
1493 hint.clone(),
1494 None,
1495 None,
1496 default_value.clone(),
1497 )
1498 .await?;
1499 Ok(QuestionAnswer {
1500 question_name: name.clone(),
1501 value: Answer::from_datetimetz_input(result)?,
1502 })
1503 }
1504 Question::FilePicker {
1505 name,
1506 prompt,
1507 starting_dir,
1508 show_hidden,
1509 only_directories,
1510 only_files,
1511 extensions,
1512 multi_select,
1513 hint,
1514 } => {
1515 let result = backend
1516 .file_picker_prompt(
1517 prompt.clone(),
1518 hint.clone(),
1519 starting_dir.clone(),
1520 *show_hidden,
1521 *only_directories,
1522 *only_files,
1523 extensions.clone(),
1524 *multi_select,
1525 None, )
1527 .await?;
1528 Ok(QuestionAnswer {
1529 question_name: name.clone(),
1530 value: Answer::from_file_picker_results(result, *multi_select),
1531 })
1532 }
1533 Question::SelectKeyValue {
1534 name,
1535 prompt,
1536 entries,
1537 hint,
1538 } => {
1539 let result = backend
1540 .select_keyvalue(
1541 prompt.clone(),
1542 entries.clone(),
1543 hint.clone(),
1544 None, None, )
1547 .await?;
1548 Ok(QuestionAnswer {
1549 question_name: name.clone(),
1550 value: Answer::KeyValue(result),
1551 })
1552 }
1553 Question::MultiSelectKeyValue {
1554 name,
1555 prompt,
1556 entries,
1557 hint,
1558 } => {
1559 let result = backend
1560 .multiselect_keyvalue(
1561 prompt.clone(),
1562 entries.clone(),
1563 hint.clone(),
1564 None, None, )
1567 .await?;
1568 Ok(QuestionAnswer {
1569 question_name: name.clone(),
1570 value: Answer::KeyValue(result),
1571 })
1572 }
1573 }
1574 })
1575 }
1576}