forgeFRENBrowse the repositories

roneocratesroneo-clisrcprompter.rs

98ff76d5794bbd1480ad719803187d2c40e42403

At commit 98ff76d

143 lines · 4.6 KiBRustRaw
  1. use std::borrow::Cow;
  2. use std::path::Path;
  3. use inquire::error::InquireError;
  4. use inquire::{Confirm, Editor, MultiSelect, Password, Select, Text};
  5. use roneo_core::config::ChoiceSpec;
  6. use roneo_core::{OverwriteChoice, PromptRequest, Prompter, Result, RoneoError};
  7. use serde_json::Value as JsonValue;
  8. use crate::style;
  9. #[derive(Debug, Default)]
  10. pub struct TerminalPrompter;
  11. impl Prompter for TerminalPrompter {
  12. fn prompt_string(&self, req: &PromptRequest) -> Result<String> {
  13. let msg = format_prompt_message(req);
  14. if req.secret {
  15. let mut prompt = Password::new(&msg).without_confirmation();
  16. if let Some(help) = &req.placeholder {
  17. prompt = prompt.with_help_message(help);
  18. }
  19. return prompt.prompt().map_err(map_inquire_err);
  20. }
  21. if req.multiline {
  22. let mut editor = Editor::new(&msg);
  23. if let Some(def) = &req.default_display {
  24. editor = editor.with_predefined_text(def);
  25. }
  26. return editor.prompt().map_err(map_inquire_err);
  27. }
  28. let mut prompt = Text::new(&msg);
  29. if let Some(def) = &req.default_display {
  30. prompt = prompt.with_default(def);
  31. }
  32. if let Some(ph) = &req.placeholder {
  33. prompt = prompt.with_placeholder(ph);
  34. }
  35. prompt.prompt().map_err(map_inquire_err)
  36. }
  37. fn prompt_bool(&self, req: &PromptRequest, default: bool) -> Result<bool> {
  38. let msg = format_prompt_message(req);
  39. Confirm::new(&msg)
  40. .with_default(default)
  41. .prompt()
  42. .map_err(map_inquire_err)
  43. }
  44. fn prompt_select(
  45. &self,
  46. req: &PromptRequest,
  47. choices: &[ChoiceSpec],
  48. default_idx: Option<usize>,
  49. ) -> Result<JsonValue> {
  50. let msg = format_prompt_message(req);
  51. let labels: Vec<&str> = choices.iter().map(|c| c.label.as_str()).collect();
  52. let mut prompt = Select::new(&msg, labels);
  53. if let Some(idx) = default_idx {
  54. prompt = prompt.with_starting_cursor(idx);
  55. }
  56. let picked_label = prompt.prompt().map_err(map_inquire_err)?;
  57. let choice = choices
  58. .iter()
  59. .find(|c| c.label == picked_label)
  60. .ok_or_else(|| RoneoError::InvalidAnswer {
  61. question: req.name.clone(),
  62. message: "Selected choice not found".into(),
  63. })?;
  64. Ok(choice.value.clone())
  65. }
  66. fn prompt_multiselect(
  67. &self,
  68. req: &PromptRequest,
  69. choices: &[ChoiceSpec],
  70. defaults: &[usize],
  71. ) -> Result<Vec<JsonValue>> {
  72. let msg = format_prompt_message(req);
  73. let labels: Vec<&str> = choices.iter().map(|c| c.label.as_str()).collect();
  74. let prompt = MultiSelect::new(&msg, labels).with_default(defaults);
  75. let picked_labels = prompt.prompt().map_err(map_inquire_err)?;
  76. Ok(picked_labels
  77. .into_iter()
  78. .filter_map(|label| {
  79. choices
  80. .iter()
  81. .find(|c| c.label == label)
  82. .map(|c| c.value.clone())
  83. })
  84. .collect())
  85. }
  86. fn show_validation_error(&self, question: &str, error: &str) {
  87. eprintln!(
  88. " {} {}: {}",
  89. style::red_bold("✗"),
  90. style::bold(question),
  91. style::red(error)
  92. );
  93. }
  94. fn confirm_overwrite(&self, path: &Path) -> Result<OverwriteChoice> {
  95. let prompt = format!("Overwrite '{}'?", path.display());
  96. let options = vec!["No (skip)", "Yes", "Yes to all", "Quit"];
  97. let picked = Select::new(&prompt, options)
  98. .with_starting_cursor(0)
  99. .prompt()
  100. .map_err(map_inquire_err)?;
  101. Ok(match picked {
  102. "Yes" => OverwriteChoice::Yes,
  103. "Yes to all" => OverwriteChoice::All,
  104. "Quit" => OverwriteChoice::Quit,
  105. _ => OverwriteChoice::No,
  106. })
  107. }
  108. }
  109. fn format_prompt_message(req: &PromptRequest) -> Cow<'_, str> {
  110. match req
  111. .qmark
  112. .as_deref()
  113. .map(str::trim)
  114. .filter(|s| !s.is_empty())
  115. {
  116. Some(qmark) => Cow::Owned(format!("{qmark} {}", req.message)),
  117. None => Cow::Borrowed(&req.message),
  118. }
  119. }
  120. fn map_inquire_err(err: InquireError) -> RoneoError {
  121. match err {
  122. InquireError::OperationCanceled | InquireError::OperationInterrupted => {
  123. RoneoError::UserAborted
  124. }
  125. other => RoneoError::InvalidAnswer {
  126. question: "prompt".into(),
  127. message: other.to_string(),
  128. },
  129. }
  130. }