forgeFRENBrowse the repositories

roneocratesroneo-coresrcprompt.rs

0518da6beb3fd562b82c5b5c2798b72e0d1591b2

At commit 0518da6

585 lines · 20.6 KiBRustRaw
  1. use std::path::Path;
  2. use indexmap::IndexMap;
  3. use serde_json::Value as JsonValue;
  4. use crate::answers::AnswersMap;
  5. use crate::config::{
  6. ChoiceSpec, Question, QuestionType, TemplateConfig, json_display, parse_choices,
  7. parse_question_type,
  8. };
  9. use crate::error::{Result, RoneoError};
  10. use crate::plugin::ExtensionRegistry;
  11. use crate::renderer::{TemplateRenderer, UNSET_SENTINEL, parse_truthy_str};
  12. /// Details passed to a `Prompter` implementation when asking the user a question.
  13. #[derive(Debug, Clone)]
  14. pub struct PromptRequest {
  15. pub name: String,
  16. pub kind: QuestionType,
  17. pub message: String,
  18. pub default_display: Option<String>,
  19. pub placeholder: Option<String>,
  20. pub secret: bool,
  21. pub multiselect: bool,
  22. pub multiline: bool,
  23. pub qmark: Option<String>,
  24. }
  25. /// User response when asked whether to overwrite an existing destination file.
  26. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  27. pub enum OverwriteChoice {
  28. Yes,
  29. No,
  30. All,
  31. Quit,
  32. }
  33. /// Interactive (or scripted/mock) prompt backend decoupled from `roneo-core`.
  34. pub trait Prompter {
  35. fn prompt_string(&self, req: &PromptRequest) -> Result<String>;
  36. fn prompt_bool(&self, req: &PromptRequest, default: bool) -> Result<bool>;
  37. fn prompt_select(
  38. &self,
  39. req: &PromptRequest,
  40. choices: &[ChoiceSpec],
  41. default_idx: Option<usize>,
  42. ) -> Result<JsonValue>;
  43. fn prompt_multiselect(
  44. &self,
  45. req: &PromptRequest,
  46. choices: &[ChoiceSpec],
  47. defaults: &[usize],
  48. ) -> Result<Vec<JsonValue>>;
  49. fn show_validation_error(&self, question: &str, error: &str);
  50. /// Ask whether to overwrite an existing differing file in interactive mode.
  51. fn confirm_overwrite(&self, _path: &Path) -> Result<OverwriteChoice> {
  52. Ok(OverwriteChoice::No)
  53. }
  54. }
  55. /// Non-interactive prompter that never touches stdin/stdout; always relies on defaults/data.
  56. #[derive(Debug, Default)]
  57. pub struct NonInteractivePrompter;
  58. impl Prompter for NonInteractivePrompter {
  59. fn prompt_string(&self, req: &PromptRequest) -> Result<String> {
  60. req.default_display
  61. .clone()
  62. .ok_or_else(|| RoneoError::InvalidAnswer {
  63. question: req.name.clone(),
  64. message: "No default value available in non-interactive mode (pass `-d key=value`)"
  65. .into(),
  66. })
  67. }
  68. fn prompt_bool(&self, _req: &PromptRequest, default: bool) -> Result<bool> {
  69. Ok(default)
  70. }
  71. fn prompt_select(
  72. &self,
  73. req: &PromptRequest,
  74. choices: &[ChoiceSpec],
  75. default_idx: Option<usize>,
  76. ) -> Result<JsonValue> {
  77. let idx = default_idx.unwrap_or(0);
  78. choices
  79. .get(idx)
  80. .map(|c| c.value.clone())
  81. .ok_or_else(|| RoneoError::InvalidAnswer {
  82. question: req.name.clone(),
  83. message: "No choices available".into(),
  84. })
  85. }
  86. fn prompt_multiselect(
  87. &self,
  88. _req: &PromptRequest,
  89. choices: &[ChoiceSpec],
  90. defaults: &[usize],
  91. ) -> Result<Vec<JsonValue>> {
  92. Ok(defaults
  93. .iter()
  94. .filter_map(|&i| choices.get(i).map(|c| c.value.clone()))
  95. .collect())
  96. }
  97. fn show_validation_error(&self, _question: &str, _error: &str) {}
  98. }
  99. pub struct AnswerCollectionOptions<'a> {
  100. pub data: &'a IndexMap<String, JsonValue>,
  101. pub previous_answers: Option<&'a AnswersMap>,
  102. pub user_defaults: Option<&'a IndexMap<String, JsonValue>>,
  103. pub initial_context: Option<&'a IndexMap<String, JsonValue>>,
  104. pub extensions: Option<&'a ExtensionRegistry>,
  105. pub use_defaults: bool,
  106. pub skip_answered: bool,
  107. pub ask_questions: &'a [String],
  108. }
  109. /// Evaluate all questions in `config` in order and produce a populated `AnswersMap`.
  110. pub fn collect_answers(
  111. config: &TemplateConfig,
  112. renderer: &TemplateRenderer,
  113. prompter: &dyn Prompter,
  114. opts: &AnswerCollectionOptions<'_>,
  115. ) -> Result<AnswersMap> {
  116. let mut answers = AnswersMap::default();
  117. if let Some(prev) = opts.previous_answers {
  118. answers.metadata.clone_from(&prev.metadata);
  119. }
  120. // Track current rendering context as answers are collected.
  121. let mut ctx = IndexMap::<String, JsonValue>::new();
  122. if let Some(init) = opts.initial_context {
  123. for (k, v) in init {
  124. ctx.insert(k.clone(), v.clone());
  125. }
  126. }
  127. ctx.insert("_copier_phase".into(), JsonValue::String("prompt".into()));
  128. for (k, v) in opts.data {
  129. ctx.insert(k.clone(), v.clone());
  130. }
  131. run_prompt_hooks(opts.extensions, &mut ctx)?;
  132. for (name, raw_question) in &config.questions {
  133. if raw_question.secret {
  134. answers.secrets.insert(name.clone());
  135. }
  136. // Resolve dynamic templated `type:` if present.
  137. let mut effective_q: std::borrow::Cow<'_, Question> =
  138. std::borrow::Cow::Borrowed(raw_question);
  139. if let Some(type_tpl) = &raw_question.type_template {
  140. let rendered_type =
  141. renderer.render_str(type_tpl, &ctx, &format!("question:{name}.type"))?;
  142. let resolved_kind = parse_question_type(&rendered_type)?;
  143. effective_q.to_mut().kind = resolved_kind;
  144. }
  145. let question: &Question = &effective_q;
  146. // 1. Evaluate `when` condition.
  147. if let Some(when_val) = &question.when {
  148. let should_ask =
  149. renderer.eval_condition(when_val, &ctx, &format!("question:{name}.when"))?;
  150. if !should_ask {
  151. // Keep explicit override or rendered default in render context, but do NOT
  152. // persist skipped (`when: false`) question defaults into `.copier-answers.yml`
  153. // (matching Copier).
  154. let mut mutated = false;
  155. if let Some(provided) = opts.data.get(name) {
  156. let coerced = coerce_value(question, provided)?;
  157. ctx.insert(name.clone(), coerced.clone());
  158. answers.user.insert(name.clone(), coerced);
  159. mutated = true;
  160. } else if let Some(def) = resolve_default(question, None, None, renderer, &ctx)? {
  161. ctx.insert(name.clone(), def.clone());
  162. answers.default_only.insert(name.clone(), def);
  163. mutated = true;
  164. }
  165. if mutated {
  166. run_prompt_hooks(opts.extensions, &mut ctx)?;
  167. }
  168. continue;
  169. }
  170. }
  171. // 2. Render choices (choice labels and string values may contain Jinja).
  172. let rendered_choices = render_choices(question, renderer, &ctx)?;
  173. // 3. Resolve effective default (previous answer > user settings default > question default).
  174. let prev_val = opts.previous_answers.and_then(|p| p.user.get(name));
  175. let user_def = opts.user_defaults.and_then(|d| d.get(name));
  176. let default_val = resolve_default(question, prev_val, user_def, renderer, &ctx)?;
  177. // 4. Explicit CLI/data override?
  178. if let Some(provided) = opts.data.get(name) {
  179. let coerced = coerce_value(question, provided)?;
  180. validate_answer(
  181. question,
  182. &coerced,
  183. rendered_choices.as_deref(),
  184. renderer,
  185. &ctx,
  186. )?;
  187. ctx.insert(name.clone(), coerced.clone());
  188. answers.user.insert(name.clone(), coerced);
  189. run_prompt_hooks(opts.extensions, &mut ctx)?;
  190. continue;
  191. }
  192. // 5. Auto-accept default if `--defaults`, `ask: false`, or `--skip-answered` with previous answer,
  193. // unless the user explicitly forced this question via `--ask <glob>` (Copier v9.17 / v9.19).
  194. let explicitly_asked = opts
  195. .ask_questions
  196. .iter()
  197. .any(|pat| crate::filter::glob_match(pat, name));
  198. let should_ask = match &question.ask {
  199. Some(expr) => renderer.eval_condition(expr, &ctx, &format!("question:{name}.ask"))?,
  200. None => true,
  201. };
  202. let auto_use_default = !explicitly_asked
  203. && (!should_ask || opts.use_defaults || (opts.skip_answered && prev_val.is_some()));
  204. if auto_use_default {
  205. let chosen = if let Some(val) = default_val {
  206. val
  207. } else if let Some(choices) = &rendered_choices
  208. && let Some(first) = choices.first()
  209. {
  210. if question.multiselect {
  211. JsonValue::Array(Vec::new())
  212. } else {
  213. first.value.clone()
  214. }
  215. } else if question.kind == QuestionType::Bool {
  216. JsonValue::Bool(false)
  217. } else {
  218. return Err(RoneoError::InvalidAnswer {
  219. question: name.clone(),
  220. message:
  221. "Question has no default value; pass `-d key=value` or run interactively"
  222. .into(),
  223. });
  224. };
  225. validate_answer(
  226. question,
  227. &chosen,
  228. rendered_choices.as_deref(),
  229. renderer,
  230. &ctx,
  231. )?;
  232. ctx.insert(name.clone(), chosen.clone());
  233. answers.user.insert(name.clone(), chosen);
  234. run_prompt_hooks(opts.extensions, &mut ctx)?;
  235. continue;
  236. }
  237. // 6. Ask interactively (looping on validation error).
  238. let help_msg = match &question.help {
  239. Some(h) => renderer.render_str(h, &ctx, &format!("question:{name}.help"))?,
  240. None => format!("{name}?"),
  241. };
  242. let placeholder = match &question.placeholder {
  243. Some(p) => {
  244. Some(renderer.render_str(p, &ctx, &format!("question:{name}.placeholder"))?)
  245. }
  246. None => None,
  247. };
  248. let multiline = match &question.multiline_expr {
  249. Some(expr) => {
  250. renderer.eval_condition(expr, &ctx, &format!("question:{name}.multiline"))?
  251. }
  252. None => matches!(question.kind, QuestionType::Yaml | QuestionType::Json),
  253. };
  254. let req = PromptRequest {
  255. name: name.clone(),
  256. kind: question.kind,
  257. message: help_msg,
  258. default_display: default_val.as_ref().map(json_display),
  259. placeholder,
  260. secret: question.secret,
  261. multiselect: question.multiselect,
  262. multiline,
  263. qmark: question.qmark.clone(),
  264. };
  265. let answer_val = loop {
  266. let candidate = if let Some(choices) = &rendered_choices {
  267. if question.multiselect {
  268. let default_indices = default_val
  269. .as_ref()
  270. .and_then(JsonValue::as_array)
  271. .map_or_default(|arr| {
  272. choices
  273. .iter()
  274. .enumerate()
  275. .filter_map(|(i, c)| arr.contains(&c.value).then_some(i))
  276. .collect::<Vec<_>>()
  277. });
  278. let picked = prompter.prompt_multiselect(&req, choices, &default_indices)?;
  279. JsonValue::Array(picked)
  280. } else {
  281. let default_idx = default_val
  282. .as_ref()
  283. .and_then(|d| choices.iter().position(|c| &c.value == d));
  284. prompter.prompt_select(&req, choices, default_idx)?
  285. }
  286. } else if question.kind == QuestionType::Bool {
  287. let def_bool = default_val
  288. .as_ref()
  289. .and_then(JsonValue::as_bool)
  290. .unwrap_or(false);
  291. JsonValue::Bool(prompter.prompt_bool(&req, def_bool)?)
  292. } else {
  293. let raw = prompter.prompt_string(&req)?;
  294. match parse_raw_answer(question, &raw) {
  295. Ok(v) => v,
  296. Err(e) => {
  297. prompter.show_validation_error(name, &e.to_string());
  298. continue;
  299. }
  300. }
  301. };
  302. match validate_answer(
  303. question,
  304. &candidate,
  305. rendered_choices.as_deref(),
  306. renderer,
  307. &ctx,
  308. ) {
  309. Ok(()) => break candidate,
  310. Err(RoneoError::InvalidAnswer { message, .. }) => {
  311. prompter.show_validation_error(name, &message);
  312. }
  313. Err(e) => return Err(e),
  314. }
  315. };
  316. ctx.insert(name.clone(), answer_val.clone());
  317. answers.user.insert(name.clone(), answer_val);
  318. run_prompt_hooks(opts.extensions, &mut ctx)?;
  319. }
  320. // Preserve extra `-d` data keys that weren't declared as questions (Copier allows extra data).
  321. for (k, v) in opts.data {
  322. if !answers.user.contains_key(k) && !k.starts_with('_') {
  323. answers.user.insert(k.clone(), v.clone());
  324. }
  325. }
  326. Ok(answers)
  327. }
  328. fn run_prompt_hooks(
  329. extensions: Option<&ExtensionRegistry>,
  330. ctx: &mut IndexMap<String, JsonValue>,
  331. ) -> Result<()> {
  332. if let Some(exts) = extensions
  333. && !exts.is_empty()
  334. {
  335. exts.run_context_hooks("prompt", ctx)?;
  336. }
  337. Ok(())
  338. }
  339. fn resolve_default(
  340. question: &Question,
  341. prev_val: Option<&JsonValue>,
  342. user_def: Option<&JsonValue>,
  343. renderer: &TemplateRenderer,
  344. ctx: &IndexMap<String, JsonValue>,
  345. ) -> Result<Option<JsonValue>> {
  346. if let Some(prev) = prev_val {
  347. return Ok(Some(coerce_value(question, prev)?));
  348. }
  349. if let Some(udef) = user_def {
  350. return Ok(Some(coerce_value(question, udef)?));
  351. }
  352. let Some(def) = &question.default else {
  353. return Ok(None);
  354. };
  355. let rendered_default = render_json_strings(
  356. def,
  357. renderer,
  358. ctx,
  359. &format!("question:{}.default", question.name),
  360. )?;
  361. if rendered_default.as_str() == Some(UNSET_SENTINEL) {
  362. return Ok(None);
  363. }
  364. Ok(Some(coerce_value(question, &rendered_default)?))
  365. }
  366. fn render_choices(
  367. question: &Question,
  368. renderer: &TemplateRenderer,
  369. ctx: &IndexMap<String, JsonValue>,
  370. ) -> Result<Option<Vec<ChoiceSpec>>> {
  371. let dynamic_choices: Option<Vec<ChoiceSpec>> = if let Some(tpl) = &question.choices_template {
  372. let yaml_text =
  373. renderer.render_str(tpl, ctx, &format!("question:{}.choices", question.name))?;
  374. let yaml_val: serde_yaml_ng::Value = serde_yaml_ng::from_str(&yaml_text)?;
  375. Some(parse_choices(&question.name, &yaml_val)?)
  376. } else {
  377. None
  378. };
  379. let Some(choices) = dynamic_choices.as_deref().or(question.choices.as_deref()) else {
  380. return Ok(None);
  381. };
  382. let mut out = Vec::with_capacity(choices.len());
  383. for (i, choice) in choices.iter().enumerate() {
  384. let label = renderer.render_str(
  385. &choice.label,
  386. ctx,
  387. &format!("question:{}.choices[{i}].label", question.name),
  388. )?;
  389. let value = render_json_strings(
  390. &choice.value,
  391. renderer,
  392. ctx,
  393. &format!("question:{}.choices[{i}].value", question.name),
  394. )?;
  395. let coerced = if question.multiselect {
  396. value
  397. } else {
  398. coerce_value(question, &value)?
  399. };
  400. out.push(ChoiceSpec {
  401. label,
  402. value: coerced,
  403. });
  404. }
  405. Ok(Some(out))
  406. }
  407. fn render_json_strings(
  408. val: &JsonValue,
  409. renderer: &TemplateRenderer,
  410. ctx: &IndexMap<String, JsonValue>,
  411. label: &str,
  412. ) -> Result<JsonValue> {
  413. match val {
  414. JsonValue::String(s) => Ok(JsonValue::String(renderer.render_str(s, ctx, label)?)),
  415. JsonValue::Array(items) => {
  416. let mut out = Vec::with_capacity(items.len());
  417. for item in items {
  418. out.push(render_json_strings(item, renderer, ctx, label)?);
  419. }
  420. Ok(JsonValue::Array(out))
  421. }
  422. other => Ok(other.clone()),
  423. }
  424. }
  425. pub fn parse_raw_answer(question: &Question, raw: &str) -> Result<JsonValue> {
  426. let name = &question.name;
  427. match question.kind {
  428. QuestionType::Str => Ok(JsonValue::String(raw.to_string())),
  429. QuestionType::Int => {
  430. raw.trim()
  431. .parse::<i64>()
  432. .map(JsonValue::from)
  433. .map_err(|_| RoneoError::InvalidAnswer {
  434. question: name.clone(),
  435. message: format!("Expected an integer, got '{raw}'"),
  436. })
  437. }
  438. QuestionType::Float => {
  439. raw.trim()
  440. .parse::<f64>()
  441. .map(JsonValue::from)
  442. .map_err(|_| RoneoError::InvalidAnswer {
  443. question: name.clone(),
  444. message: format!("Expected a number, got '{raw}'"),
  445. })
  446. }
  447. QuestionType::Bool => Ok(JsonValue::Bool(parse_truthy_str(raw))),
  448. QuestionType::Yaml => {
  449. let y: serde_yaml_ng::Value =
  450. serde_yaml_ng::from_str(raw).map_err(|e| RoneoError::InvalidAnswer {
  451. question: name.clone(),
  452. message: format!("Invalid YAML: {e}"),
  453. })?;
  454. Ok(serde_json::to_value(y)?)
  455. }
  456. QuestionType::Json => serde_json::from_str(raw).map_err(|e| RoneoError::InvalidAnswer {
  457. question: name.clone(),
  458. message: format!("Invalid JSON: {e}"),
  459. }),
  460. }
  461. }
  462. fn coerce_value(question: &Question, value: &JsonValue) -> Result<JsonValue> {
  463. if question.multiselect {
  464. return match value {
  465. JsonValue::Array(_) => Ok(value.clone()),
  466. JsonValue::String(s) => {
  467. if let Ok(yaml_val) = serde_yaml_ng::from_str::<serde_yaml_ng::Value>(s)
  468. && let Ok(JsonValue::Array(arr)) = serde_json::to_value(yaml_val)
  469. {
  470. return Ok(JsonValue::Array(arr));
  471. }
  472. Ok(JsonValue::Array(vec![value.clone()]))
  473. }
  474. other => Ok(JsonValue::Array(vec![other.clone()])),
  475. };
  476. }
  477. if value.is_null() {
  478. return Ok(JsonValue::Null);
  479. }
  480. match (question.kind, value) {
  481. (
  482. QuestionType::Yaml | QuestionType::Json | QuestionType::Int | QuestionType::Float,
  483. JsonValue::String(s),
  484. ) => parse_raw_answer(question, s),
  485. (QuestionType::Str, JsonValue::String(_))
  486. | (QuestionType::Bool, JsonValue::Bool(_))
  487. | (QuestionType::Float, JsonValue::Number(_))
  488. | (QuestionType::Yaml | QuestionType::Json, _) => Ok(value.clone()),
  489. (QuestionType::Str, other) => Ok(JsonValue::String(json_display(other))),
  490. (QuestionType::Int, JsonValue::Number(n)) if n.is_i64() => Ok(value.clone()),
  491. (QuestionType::Bool, JsonValue::String(s)) => Ok(JsonValue::Bool(parse_truthy_str(s))),
  492. _ => parse_raw_answer(question, &json_display(value)),
  493. }
  494. }
  495. fn validate_answer(
  496. question: &Question,
  497. value: &JsonValue,
  498. choices: Option<&[ChoiceSpec]>,
  499. renderer: &TemplateRenderer,
  500. ctx: &IndexMap<String, JsonValue>,
  501. ) -> Result<()> {
  502. if let Some(allowed) = choices {
  503. if question.multiselect {
  504. if let Some(arr) = value.as_array() {
  505. for item in arr {
  506. if !allowed.iter().any(|c| &c.value == item) {
  507. return Err(RoneoError::InvalidAnswer {
  508. question: question.name.clone(),
  509. message: format!(
  510. "Value '{}' is not one of the allowed choices",
  511. json_display(item)
  512. ),
  513. });
  514. }
  515. }
  516. }
  517. } else if !allowed.iter().any(|c| &c.value == value) {
  518. return Err(RoneoError::InvalidAnswer {
  519. question: question.name.clone(),
  520. message: format!(
  521. "Value '{}' is not one of the allowed choices",
  522. json_display(value)
  523. ),
  524. });
  525. }
  526. }
  527. if let Some(validator_tpl) = &question.validator {
  528. let mut check_ctx = ctx.clone();
  529. check_ctx.insert(question.name.clone(), value.clone());
  530. let msg = renderer.render_str(
  531. validator_tpl,
  532. &check_ctx,
  533. &format!("question:{}.validator", question.name),
  534. )?;
  535. let trimmed = msg.trim();
  536. if !trimmed.is_empty() {
  537. return Err(RoneoError::InvalidAnswer {
  538. question: question.name.clone(),
  539. message: trimmed.to_string(),
  540. });
  541. }
  542. }
  543. Ok(())
  544. }