forgeFRENParcourir les dépôts

roneocratesroneo-coresrcconfig.rs

98ff76d5794bbd1480ad719803187d2c40e42403

At commit 98ff76d

971 lines · 32.6 KiBRustRaw
  1. use std::fs;
  2. use std::path::{Path, PathBuf};
  3. use indexmap::IndexMap;
  4. use serde::{Deserialize, Serialize};
  5. use serde_yaml_ng::Value as YamlValue;
  6. use crate::error::{Result, RoneoError};
  7. use crate::filter::match_glob_path;
  8. use crate::fs_util::walk_dir_sorted;
  9. /// List-valued settings that Copier merges (concatenates) across multi-document YAML & `!include`.
  10. const MERGE_LIST_KEYS: &[&str] = &[
  11. "_exclude",
  12. "_skip_if_exists",
  13. "_secret_questions",
  14. "_jinja_extensions",
  15. "_roneo_plugins",
  16. "_tasks",
  17. "_migrations",
  18. ];
  19. /// Candidate template configuration filenames in precedence order.
  20. pub const CONFIG_FILENAMES: &[&str] = &["roneo.yml", "roneo.yaml", "copier.yml", "copier.yaml"];
  21. /// Default answers file name (100% Copier-compatible).
  22. pub const DEFAULT_ANSWERS_FILE: &str = ".copier-answers.yml";
  23. /// Default template file suffix.
  24. pub const DEFAULT_TEMPLATES_SUFFIX: &str = ".jinja";
  25. /// Default patterns always excluded unless negated with `!`.
  26. pub const DEFAULT_EXCLUDES: &[&str] = &[
  27. "copier.yaml",
  28. "copier.yml",
  29. "roneo.yaml",
  30. "roneo.yml",
  31. "~*",
  32. "*.py[co]",
  33. "__pycache__",
  34. ".git",
  35. ".DS_Store",
  36. ".svn",
  37. ];
  38. #[derive(Debug, Clone, Serialize, Deserialize)]
  39. pub struct TemplateConfig {
  40. pub settings: TemplateSettings,
  41. pub questions: IndexMap<String, Question>,
  42. pub config_path: Option<PathBuf>,
  43. }
  44. impl Default for TemplateConfig {
  45. fn default() -> Self {
  46. Self {
  47. settings: TemplateSettings::default(),
  48. questions: IndexMap::new(),
  49. config_path: None,
  50. }
  51. }
  52. }
  53. #[derive(Debug, Clone, Serialize, Deserialize)]
  54. pub struct TemplateSettings {
  55. pub subdirectory: Option<String>,
  56. pub answers_file: String,
  57. pub templates_suffix: String,
  58. pub exclude: Vec<String>,
  59. pub skip_if_exists: Vec<String>,
  60. pub preserve_symlinks: bool,
  61. pub secret_questions: Vec<String>,
  62. pub tasks: Vec<TaskSpec>,
  63. pub migrations: Vec<MigrationSpec>,
  64. pub envops: EnvOps,
  65. pub min_copier_version: Option<String>,
  66. pub message_before_copy: Option<String>,
  67. pub message_after_copy: Option<String>,
  68. pub message_before_update: Option<String>,
  69. pub message_after_update: Option<String>,
  70. pub jinja_extensions: Vec<String>,
  71. pub roneo_plugins: Vec<String>,
  72. pub external_data: IndexMap<String, String>,
  73. }
  74. impl Default for TemplateSettings {
  75. fn default() -> Self {
  76. Self {
  77. subdirectory: None,
  78. answers_file: DEFAULT_ANSWERS_FILE.to_string(),
  79. templates_suffix: DEFAULT_TEMPLATES_SUFFIX.to_string(),
  80. exclude: Vec::new(),
  81. skip_if_exists: Vec::new(),
  82. preserve_symlinks: false,
  83. secret_questions: Vec::new(),
  84. tasks: Vec::new(),
  85. migrations: Vec::new(),
  86. envops: EnvOps::default(),
  87. min_copier_version: None,
  88. message_before_copy: None,
  89. message_after_copy: None,
  90. message_before_update: None,
  91. message_after_update: None,
  92. jinja_extensions: Vec::new(),
  93. roneo_plugins: Vec::new(),
  94. external_data: IndexMap::new(),
  95. }
  96. }
  97. }
  98. #[derive(Debug, Clone, Serialize, Deserialize)]
  99. pub struct EnvOps {
  100. pub block_start_string: String,
  101. pub block_end_string: String,
  102. pub variable_start_string: String,
  103. pub variable_end_string: String,
  104. pub comment_start_string: String,
  105. pub comment_end_string: String,
  106. pub keep_trailing_newline: bool,
  107. pub trim_blocks: bool,
  108. pub lstrip_blocks: bool,
  109. }
  110. impl Default for EnvOps {
  111. fn default() -> Self {
  112. Self {
  113. block_start_string: "{%".to_string(),
  114. block_end_string: "%}".to_string(),
  115. variable_start_string: "{{".to_string(),
  116. variable_end_string: "}}".to_string(),
  117. comment_start_string: "{#".to_string(),
  118. comment_end_string: "#}".to_string(),
  119. keep_trailing_newline: true,
  120. trim_blocks: false,
  121. lstrip_blocks: false,
  122. }
  123. }
  124. }
  125. #[derive(Debug, Clone, Serialize, Deserialize)]
  126. pub enum CommandSpec {
  127. Shell(String),
  128. Args(Vec<String>),
  129. }
  130. #[derive(Debug, Clone, Serialize, Deserialize)]
  131. pub struct TaskSpec {
  132. pub command: CommandSpec,
  133. pub when: Option<String>,
  134. pub working_directory: Option<String>,
  135. #[serde(default)]
  136. pub extra_env: IndexMap<String, String>,
  137. }
  138. #[derive(Debug, Clone, Serialize, Deserialize)]
  139. pub struct MigrationSpec {
  140. pub version: Option<String>,
  141. pub before: Vec<TaskSpec>,
  142. pub after: Vec<TaskSpec>,
  143. pub command: Option<CommandSpec>,
  144. pub when: Option<String>,
  145. }
  146. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
  147. #[serde(rename_all = "lowercase")]
  148. pub enum QuestionType {
  149. #[default]
  150. Str,
  151. Int,
  152. Float,
  153. Bool,
  154. Yaml,
  155. Json,
  156. }
  157. #[derive(Debug, Clone, Serialize, Deserialize)]
  158. pub struct ChoiceSpec {
  159. pub label: String,
  160. pub value: serde_json::Value,
  161. }
  162. #[derive(Debug, Clone, Serialize, Deserialize)]
  163. pub struct Question {
  164. pub name: String,
  165. pub kind: QuestionType,
  166. /// Optional Jinja template expression for dynamic `type:` (e.g. `"{% if flag %}int{% else %}str{% endif %}"`).
  167. pub type_template: Option<String>,
  168. pub help: Option<String>,
  169. pub default: Option<serde_json::Value>,
  170. pub choices: Option<Vec<ChoiceSpec>>,
  171. /// Optional Jinja template expression returning a YAML/JSON list or mapping for dynamic `choices:`.
  172. pub choices_template: Option<String>,
  173. pub validator: Option<String>,
  174. pub when: Option<serde_json::Value>,
  175. /// Optional opt-in prompt condition (`ask: false` or Jinja expr, Copier v9.19.0 `#2849`).
  176. pub ask: Option<serde_json::Value>,
  177. pub secret: bool,
  178. pub multiselect: bool,
  179. pub multiline: bool,
  180. /// Optional raw `multiline` specification (bool or Jinja template string; defaults to `true` for YAML/JSON).
  181. pub multiline_expr: Option<serde_json::Value>,
  182. pub placeholder: Option<String>,
  183. /// Optional custom question prefix mark (Copier `qmark`, e.g. `"🚀"`).
  184. pub qmark: Option<String>,
  185. }
  186. impl TemplateConfig {
  187. /// Locate and parse the template configuration inside `template_root`.
  188. /// If no config file is present, returns a default empty configuration (matching Copier).
  189. pub fn load_from_dir(template_root: &Path) -> Result<Self> {
  190. let mut found = None;
  191. for name in CONFIG_FILENAMES {
  192. let candidate = template_root.join(name);
  193. if candidate.is_file() {
  194. found = Some(candidate);
  195. break;
  196. }
  197. }
  198. let Some(config_path) = found else {
  199. return Ok(Self::default());
  200. };
  201. let raw = fs::read_to_string(&config_path).map_err(|e| RoneoError::io(&config_path, e))?;
  202. let mut cfg = Self::parse_str_with_base(&raw, Some(template_root))?;
  203. cfg.config_path = Some(config_path);
  204. Ok(cfg)
  205. }
  206. /// Locate and parse the template configuration using an abstract in-memory file reader
  207. /// (e.g. directly from a `gix` commit tree without extracting to disk).
  208. pub fn load_from_reader<F>(read_file: &F) -> Result<Self>
  209. where
  210. F: Fn(&str) -> Option<String>,
  211. {
  212. Self::load_from_reader_with_glob(read_file, &|_| Vec::new())
  213. }
  214. /// Locate and parse the template configuration using an abstract file reader + glob expander.
  215. pub fn load_from_reader_with_glob<F, G>(read_file: &F, glob_files: &G) -> Result<Self>
  216. where
  217. F: Fn(&str) -> Option<String>,
  218. G: Fn(&str) -> Vec<String>,
  219. {
  220. for name in CONFIG_FILENAMES {
  221. if let Some(raw) = read_file(name) {
  222. let mut cfg = Self::parse_str_with_reader_and_glob(&raw, read_file, glob_files)?;
  223. cfg.config_path = Some(PathBuf::from(name));
  224. return Ok(cfg);
  225. }
  226. }
  227. Ok(Self::default())
  228. }
  229. /// Parse a Copier/Roneo YAML configuration string.
  230. pub fn parse_str(raw: &str) -> Result<Self> {
  231. Self::parse_str_with_base(raw, None)
  232. }
  233. /// Parse a Copier/Roneo YAML configuration string, resolving `!include <path>` directives
  234. /// (including glob patterns like `!include questions/*.yml`) relative to `base_dir`,
  235. /// rejecting any path or symlink escaping `base_dir` (Copier v9.17.2 security hardening).
  236. pub fn parse_str_with_base(raw: &str, base_dir: Option<&Path>) -> Result<Self> {
  237. let canon_base = base_dir.and_then(|b| fs::canonicalize(b).ok());
  238. let reader = |rel: &str| -> Option<String> {
  239. let root = base_dir?;
  240. let candidate = root.join(rel);
  241. if let Some(ref base_canon) = canon_base {
  242. let cand_canon = fs::canonicalize(&candidate).ok()?;
  243. if !cand_canon.starts_with(base_canon) {
  244. return None;
  245. }
  246. }
  247. fs::read_to_string(candidate).ok()
  248. };
  249. let globber = |pattern: &str| -> Vec<String> {
  250. let Some(root) = base_dir else {
  251. return Vec::new();
  252. };
  253. let mut matched = Vec::new();
  254. let _ = walk_dir_sorted(root, false, |entry| {
  255. if !entry.is_dir && match_glob_path(pattern, &entry.rel_path) {
  256. if let Some(ref base_canon) = canon_base
  257. && let Ok(cand_canon) = fs::canonicalize(&entry.abs_path)
  258. && !cand_canon.starts_with(base_canon)
  259. {
  260. return Ok(true);
  261. }
  262. matched.push(entry.rel_path.to_string_lossy().replace('\\', "/"));
  263. }
  264. Ok(true)
  265. });
  266. matched
  267. };
  268. Self::parse_str_with_reader_and_glob(raw, &reader, &globber)
  269. }
  270. /// Parse a Copier/Roneo YAML configuration string, resolving `!include <path>` via `read_file`.
  271. pub fn parse_str_with_reader<F>(raw: &str, read_file: &F) -> Result<Self>
  272. where
  273. F: Fn(&str) -> Option<String>,
  274. {
  275. Self::parse_str_with_reader_and_glob(raw, read_file, &|_| Vec::new())
  276. }
  277. /// Parse a Copier/Roneo YAML configuration string with both exact `!include` reading and glob expansion.
  278. pub fn parse_str_with_reader_and_glob<F, G>(
  279. raw: &str,
  280. read_file: &F,
  281. glob_files: &G,
  282. ) -> Result<Self>
  283. where
  284. F: Fn(&str) -> Option<String>,
  285. G: Fn(&str) -> Vec<String>,
  286. {
  287. let trimmed = raw.trim();
  288. if trimmed.is_empty() {
  289. return Ok(Self::default());
  290. }
  291. let mut merged: IndexMap<String, YamlValue> = IndexMap::new();
  292. parse_yaml_docs_into(trimmed, read_file, glob_files, &mut merged, 0)?;
  293. let mut settings = TemplateSettings::default();
  294. let mut questions = IndexMap::new();
  295. for (key, value) in merged {
  296. if key.starts_with('_') {
  297. parse_setting(&key, &value, &mut settings)?;
  298. } else {
  299. let mut question = parse_question(&key, &value)?;
  300. if settings.secret_questions.contains(&key) {
  301. question.secret = true;
  302. }
  303. questions.insert(key, question);
  304. }
  305. }
  306. // Apply `_secret_questions` even if declared after the questions.
  307. for secret_name in &settings.secret_questions {
  308. if let Some(q) = questions.get_mut(secret_name) {
  309. q.secret = true;
  310. }
  311. }
  312. Ok(Self {
  313. settings,
  314. questions,
  315. config_path: None,
  316. })
  317. }
  318. /// Returns whether this template requires `--trust` before running.
  319. pub fn requires_trust(&self) -> bool {
  320. !self.settings.tasks.is_empty()
  321. || !self.settings.migrations.is_empty()
  322. || !self.settings.jinja_extensions.is_empty()
  323. || !self.settings.roneo_plugins.is_empty()
  324. }
  325. }
  326. fn parse_yaml_docs_into<F, G>(
  327. raw: &str,
  328. read_file: &F,
  329. glob_files: &G,
  330. merged: &mut IndexMap<String, YamlValue>,
  331. depth: usize,
  332. ) -> Result<()>
  333. where
  334. F: Fn(&str) -> Option<String>,
  335. G: Fn(&str) -> Vec<String>,
  336. {
  337. if depth > 16 {
  338. return Err(RoneoError::InvalidConfig(
  339. "Maximum `!include` nesting depth exceeded".into(),
  340. ));
  341. }
  342. for doc in serde_yaml_ng::Deserializer::from_str(raw) {
  343. let value = YamlValue::deserialize(doc)?;
  344. if value.is_null() {
  345. continue;
  346. }
  347. // Handle Copier's `!include path/to/file.yml` and glob `!include questions/*.yml` YAML tags.
  348. if let YamlValue::Tagged(tagged) = &value
  349. && tagged.tag == "!include"
  350. && let Some(rel) = tagged.value.as_str()
  351. {
  352. let rel_path = Path::new(rel);
  353. if rel_path.is_absolute()
  354. || rel_path
  355. .components()
  356. .any(|c| matches!(c, std::path::Component::ParentDir))
  357. {
  358. return Err(RoneoError::InvalidConfig(format!(
  359. "YAML `!include` path '{rel}' must stay inside the template root"
  360. )));
  361. }
  362. if rel.contains(['*', '?', '[']) {
  363. let mut targets = glob_files(rel);
  364. targets.sort();
  365. for target in targets {
  366. if let Some(include_raw) = read_file(&target) {
  367. parse_yaml_docs_into(
  368. &include_raw,
  369. read_file,
  370. glob_files,
  371. merged,
  372. depth + 1,
  373. )?;
  374. }
  375. }
  376. } else {
  377. let include_raw = read_file(rel).ok_or_else(|| {
  378. RoneoError::InvalidConfig(format!("Failed to read `!include {rel}`"))
  379. })?;
  380. parse_yaml_docs_into(&include_raw, read_file, glob_files, merged, depth + 1)?;
  381. }
  382. continue;
  383. }
  384. let mapping = value.as_mapping().ok_or_else(|| {
  385. RoneoError::InvalidConfig("Top-level configuration must be a YAML mapping".into())
  386. })?;
  387. for (k, v) in mapping {
  388. let key = k.as_str().ok_or_else(|| {
  389. RoneoError::InvalidConfig("Top-level keys must be strings".into())
  390. })?;
  391. // Concatenate Copier's list-valued settings across multi-doc YAML / `!include`.
  392. if MERGE_LIST_KEYS.contains(&key)
  393. && let Some(YamlValue::Sequence(existing)) = merged.get_mut(key)
  394. && let Some(incoming) = v.as_sequence()
  395. {
  396. existing.extend(incoming.iter().cloned());
  397. continue;
  398. }
  399. merged.insert(key.to_string(), v.clone());
  400. }
  401. }
  402. Ok(())
  403. }
  404. fn parse_setting(key: &str, value: &YamlValue, settings: &mut TemplateSettings) -> Result<()> {
  405. match key {
  406. "_subdirectory" => {
  407. settings.subdirectory = yaml_to_opt_string(value, key)?;
  408. }
  409. "_answers_file" => {
  410. if let Some(s) = yaml_to_opt_string(value, key)? {
  411. settings.answers_file = s;
  412. }
  413. }
  414. "_templates_suffix" => {
  415. settings.templates_suffix = yaml_to_opt_string(value, key)?.unwrap_or_default();
  416. }
  417. "_exclude" => {
  418. settings.exclude = yaml_to_string_list(value, key)?;
  419. }
  420. "_skip_if_exists" => {
  421. settings.skip_if_exists = yaml_to_string_list(value, key)?;
  422. }
  423. "_preserve_symlinks" => {
  424. settings.preserve_symlinks = value
  425. .as_bool()
  426. .ok_or_else(|| RoneoError::InvalidConfig(format!("'{key}' must be a boolean")))?;
  427. }
  428. "_secret_questions" => {
  429. settings.secret_questions = yaml_to_string_list(value, key)?;
  430. }
  431. "_tasks" => {
  432. settings.tasks = parse_task_list(value, key)?;
  433. }
  434. "_migrations" => {
  435. settings.migrations = parse_migrations(value)?;
  436. }
  437. "_envops" => {
  438. parse_envops(value, &mut settings.envops)?;
  439. }
  440. "_min_copier_version" => {
  441. settings.min_copier_version = yaml_to_opt_string(value, key)?;
  442. }
  443. "_message_before_copy" => {
  444. settings.message_before_copy = yaml_to_opt_string(value, key)?;
  445. }
  446. "_message_after_copy" => {
  447. settings.message_after_copy = yaml_to_opt_string(value, key)?;
  448. }
  449. "_message_before_update" => {
  450. settings.message_before_update = yaml_to_opt_string(value, key)?;
  451. }
  452. "_message_after_update" => {
  453. settings.message_after_update = yaml_to_opt_string(value, key)?;
  454. }
  455. "_jinja_extensions" => {
  456. settings.jinja_extensions = yaml_to_string_list(value, key)?;
  457. }
  458. "_roneo_plugins" => {
  459. settings.roneo_plugins = yaml_to_string_list(value, key)?;
  460. }
  461. "_external_data" => {
  462. if let Some(map) = value.as_mapping() {
  463. for (k, v) in map {
  464. if let (Some(name), Some(path_str)) = (k.as_str(), v.as_str()) {
  465. settings
  466. .external_data
  467. .insert(name.to_string(), path_str.to_string());
  468. }
  469. }
  470. } else if !value.is_null() {
  471. return Err(RoneoError::InvalidConfig(
  472. "'_external_data' must be a mapping of key -> file path".into(),
  473. ));
  474. }
  475. }
  476. // Unknown `_` metadata keys (e.g. `_metadata`, `_external_data`) are preserved gracefully.
  477. _ => {}
  478. }
  479. Ok(())
  480. }
  481. fn parse_envops(value: &YamlValue, envops: &mut EnvOps) -> Result<()> {
  482. let Some(map) = value.as_mapping() else {
  483. return Err(RoneoError::InvalidConfig(
  484. "'_envops' must be a mapping".into(),
  485. ));
  486. };
  487. for (k, v) in map {
  488. let Some(key) = k.as_str() else {
  489. continue;
  490. };
  491. match key {
  492. "block_start_string" => {
  493. if let Some(s) = v.as_str() {
  494. envops.block_start_string = s.to_string();
  495. }
  496. }
  497. "block_end_string" => {
  498. if let Some(s) = v.as_str() {
  499. envops.block_end_string = s.to_string();
  500. }
  501. }
  502. "variable_start_string" => {
  503. if let Some(s) = v.as_str() {
  504. envops.variable_start_string = s.to_string();
  505. }
  506. }
  507. "variable_end_string" => {
  508. if let Some(s) = v.as_str() {
  509. envops.variable_end_string = s.to_string();
  510. }
  511. }
  512. "comment_start_string" => {
  513. if let Some(s) = v.as_str() {
  514. envops.comment_start_string = s.to_string();
  515. }
  516. }
  517. "comment_end_string" => {
  518. if let Some(s) = v.as_str() {
  519. envops.comment_end_string = s.to_string();
  520. }
  521. }
  522. "keep_trailing_newline" => {
  523. if let Some(b) = v.as_bool() {
  524. envops.keep_trailing_newline = b;
  525. }
  526. }
  527. "trim_blocks" => {
  528. if let Some(b) = v.as_bool() {
  529. envops.trim_blocks = b;
  530. }
  531. }
  532. "lstrip_blocks" => {
  533. if let Some(b) = v.as_bool() {
  534. envops.lstrip_blocks = b;
  535. }
  536. }
  537. _ => {}
  538. }
  539. }
  540. Ok(())
  541. }
  542. fn parse_task_list(value: &YamlValue, key: &str) -> Result<Vec<TaskSpec>> {
  543. if value.is_null() {
  544. return Ok(Vec::new());
  545. }
  546. let seq = value
  547. .as_sequence()
  548. .ok_or_else(|| RoneoError::InvalidConfig(format!("'{key}' must be a list")))?;
  549. let mut tasks = Vec::with_capacity(seq.len());
  550. for item in seq {
  551. tasks.push(parse_single_task(item, key)?);
  552. }
  553. Ok(tasks)
  554. }
  555. fn parse_single_task(item: &YamlValue, key: &str) -> Result<TaskSpec> {
  556. if let Some(cmd) = item.as_str() {
  557. return Ok(TaskSpec {
  558. command: CommandSpec::Shell(cmd.to_string()),
  559. when: None,
  560. working_directory: None,
  561. extra_env: IndexMap::new(),
  562. });
  563. }
  564. if let Some(args) = item.as_sequence() {
  565. let parsed = args
  566. .iter()
  567. .map(|a| {
  568. a.as_str().map(ToOwned::to_owned).ok_or_else(|| {
  569. RoneoError::InvalidConfig(format!("Task argument in '{key}' must be a string"))
  570. })
  571. })
  572. .collect::<Result<Vec<_>>>()?;
  573. return Ok(TaskSpec {
  574. command: CommandSpec::Args(parsed),
  575. when: None,
  576. working_directory: None,
  577. extra_env: IndexMap::new(),
  578. });
  579. }
  580. if let Some(map) = item.as_mapping() {
  581. let cmd_val = map
  582. .get(YamlValue::String("command".into()))
  583. .ok_or_else(|| {
  584. RoneoError::InvalidConfig(format!("Task mapping in '{key}' missing 'command'"))
  585. })?;
  586. let command = if let Some(s) = cmd_val.as_str() {
  587. CommandSpec::Shell(s.to_string())
  588. } else if let Some(seq) = cmd_val.as_sequence() {
  589. CommandSpec::Args(
  590. seq.iter()
  591. .map(|v| {
  592. v.as_str().map(ToOwned::to_owned).ok_or_else(|| {
  593. RoneoError::InvalidConfig(format!(
  594. "Task 'command' sequence in '{key}' must contain strings"
  595. ))
  596. })
  597. })
  598. .collect::<Result<Vec<_>>>()?,
  599. )
  600. } else {
  601. return Err(RoneoError::InvalidConfig(format!(
  602. "Task 'command' in '{key}' must be string or list of strings"
  603. )));
  604. };
  605. let when = map
  606. .get(YamlValue::String("when".into()))
  607. .and_then(yaml_scalar_to_string);
  608. let working_directory = map
  609. .get(YamlValue::String("working_directory".into()))
  610. .and_then(|v| v.as_str().map(ToOwned::to_owned));
  611. let mut extra_env = IndexMap::new();
  612. if let Some(env_map) = map
  613. .get(YamlValue::String("extra_env".into()))
  614. .and_then(YamlValue::as_mapping)
  615. {
  616. for (ek, ev) in env_map {
  617. if let (Some(k_str), Some(v_str)) = (ek.as_str(), yaml_scalar_to_string(ev)) {
  618. extra_env.insert(k_str.to_string(), v_str);
  619. }
  620. }
  621. }
  622. return Ok(TaskSpec {
  623. command,
  624. when,
  625. working_directory,
  626. extra_env,
  627. });
  628. }
  629. Err(RoneoError::InvalidConfig(format!(
  630. "Unsupported task definition in '{key}'"
  631. )))
  632. }
  633. fn parse_migrations(value: &YamlValue) -> Result<Vec<MigrationSpec>> {
  634. if value.is_null() {
  635. return Ok(Vec::new());
  636. }
  637. let seq = value
  638. .as_sequence()
  639. .ok_or_else(|| RoneoError::InvalidConfig("'_migrations' must be a list".into()))?;
  640. let mut migrations = Vec::with_capacity(seq.len());
  641. for item in seq {
  642. let map = item.as_mapping().ok_or_else(|| {
  643. RoneoError::InvalidConfig("Each entry in '_migrations' must be a mapping".into())
  644. })?;
  645. let version = map
  646. .get(YamlValue::String("version".into()))
  647. .and_then(yaml_scalar_to_string);
  648. let before = map
  649. .get(YamlValue::String("before".into()))
  650. .map(|v| parse_task_list(v, "_migrations.before"))
  651. .transpose()?
  652. .unwrap_or_default();
  653. let after = map
  654. .get(YamlValue::String("after".into()))
  655. .map(|v| parse_task_list(v, "_migrations.after"))
  656. .transpose()?
  657. .unwrap_or_default();
  658. let command = map
  659. .get(YamlValue::String("command".into()))
  660. .map(|v| parse_single_task(v, "_migrations.command").map(|t| t.command))
  661. .transpose()?;
  662. let when = map
  663. .get(YamlValue::String("when".into()))
  664. .and_then(yaml_scalar_to_string);
  665. migrations.push(MigrationSpec {
  666. version,
  667. before,
  668. after,
  669. command,
  670. when,
  671. });
  672. }
  673. Ok(migrations)
  674. }
  675. fn parse_question(name: &str, value: &YamlValue) -> Result<Question> {
  676. if let Some(map) = value.as_mapping() {
  677. let default = map
  678. .get(YamlValue::String("default".into()))
  679. .map(yaml_to_json)
  680. .transpose()?;
  681. let (kind, type_template) =
  682. if let Some(type_val) = map.get(YamlValue::String("type".into())) {
  683. let raw_type = type_val.as_str().ok_or_else(|| {
  684. RoneoError::InvalidConfig(format!("Question '{name}' 'type' must be a string"))
  685. })?;
  686. if raw_type.contains("{{") || raw_type.contains("{%") {
  687. (QuestionType::Str, Some(raw_type.to_string()))
  688. } else {
  689. (parse_question_type(raw_type)?, None)
  690. }
  691. } else if let Some(def) = &default {
  692. (infer_type_from_json(def), None)
  693. } else {
  694. (QuestionType::Str, None)
  695. };
  696. let help = map
  697. .get(YamlValue::String("help".into()))
  698. .and_then(|v| v.as_str().map(ToOwned::to_owned));
  699. let validator = map
  700. .get(YamlValue::String("validator".into()))
  701. .and_then(|v| v.as_str().map(ToOwned::to_owned));
  702. let when = map
  703. .get(YamlValue::String("when".into()))
  704. .map(yaml_to_json)
  705. .transpose()?;
  706. let ask = map
  707. .get(YamlValue::String("ask".into()))
  708. .map(yaml_to_json)
  709. .transpose()?;
  710. let secret = map
  711. .get(YamlValue::String("secret".into()))
  712. .and_then(YamlValue::as_bool)
  713. .unwrap_or(false);
  714. let multiselect = map
  715. .get(YamlValue::String("multiselect".into()))
  716. .and_then(YamlValue::as_bool)
  717. .unwrap_or(false);
  718. let multiline_expr = map
  719. .get(YamlValue::String("multiline".into()))
  720. .map(yaml_to_json)
  721. .transpose()?;
  722. let multiline = multiline_expr.as_ref().map_or(
  723. matches!(kind, QuestionType::Yaml | QuestionType::Json),
  724. |v| v.as_bool().unwrap_or(false),
  725. );
  726. let placeholder = map
  727. .get(YamlValue::String("placeholder".into()))
  728. .and_then(|v| v.as_str().map(ToOwned::to_owned));
  729. let qmark = map
  730. .get(YamlValue::String("qmark".into()))
  731. .and_then(|v| v.as_str().map(ToOwned::to_owned));
  732. let (choices, choices_template) =
  733. if let Some(ch_val) = map.get(YamlValue::String("choices".into())) {
  734. if let Some(tpl) = ch_val.as_str() {
  735. (None, Some(tpl.to_string()))
  736. } else {
  737. (Some(parse_choices(name, ch_val)?), None)
  738. }
  739. } else {
  740. (None, None)
  741. };
  742. Ok(Question {
  743. name: name.to_string(),
  744. kind,
  745. type_template,
  746. help,
  747. default,
  748. choices,
  749. choices_template,
  750. validator,
  751. when,
  752. ask,
  753. secret,
  754. multiselect,
  755. multiline,
  756. multiline_expr,
  757. placeholder,
  758. qmark,
  759. })
  760. } else {
  761. // Short-form question: `project_name: my-project`
  762. let default = yaml_to_json(value)?;
  763. let kind = infer_type_from_json(&default);
  764. Ok(Question {
  765. name: name.to_string(),
  766. kind,
  767. type_template: None,
  768. help: None,
  769. default: Some(default),
  770. choices: None,
  771. choices_template: None,
  772. validator: None,
  773. when: None,
  774. ask: None,
  775. secret: false,
  776. multiselect: false,
  777. multiline: matches!(kind, QuestionType::Yaml | QuestionType::Json),
  778. multiline_expr: None,
  779. placeholder: None,
  780. qmark: None,
  781. })
  782. }
  783. }
  784. pub fn parse_question_type(raw: &str) -> Result<QuestionType> {
  785. match raw.trim() {
  786. "str" | "string" => Ok(QuestionType::Str),
  787. "int" | "integer" => Ok(QuestionType::Int),
  788. "float" | "number" => Ok(QuestionType::Float),
  789. "bool" | "boolean" => Ok(QuestionType::Bool),
  790. "yaml" => Ok(QuestionType::Yaml),
  791. "json" => Ok(QuestionType::Json),
  792. other => Err(RoneoError::InvalidConfig(format!(
  793. "Unsupported question type '{other}'"
  794. ))),
  795. }
  796. }
  797. fn infer_type_from_json(val: &serde_json::Value) -> QuestionType {
  798. match val {
  799. serde_json::Value::Bool(_) => QuestionType::Bool,
  800. serde_json::Value::Number(n) => {
  801. if n.is_i64() || n.is_u64() {
  802. QuestionType::Int
  803. } else {
  804. QuestionType::Float
  805. }
  806. }
  807. serde_json::Value::Array(_) | serde_json::Value::Object(_) => QuestionType::Yaml,
  808. serde_json::Value::String(_) | serde_json::Value::Null => QuestionType::Str,
  809. }
  810. }
  811. pub fn parse_choices(name: &str, value: &YamlValue) -> Result<Vec<ChoiceSpec>> {
  812. if let Some(seq) = value.as_sequence() {
  813. let mut choices = Vec::with_capacity(seq.len());
  814. for item in seq {
  815. if let Some(pair) = item.as_sequence()
  816. && pair.len() == 2
  817. {
  818. let label = yaml_scalar_to_string(&pair[0]).unwrap_or_default();
  819. let val = yaml_to_json(&pair[1])?;
  820. choices.push(ChoiceSpec { label, value: val });
  821. continue;
  822. }
  823. let val = yaml_to_json(item)?;
  824. let label = json_display(&val);
  825. choices.push(ChoiceSpec { label, value: val });
  826. }
  827. Ok(choices)
  828. } else if let Some(map) = value.as_mapping() {
  829. let mut choices = Vec::with_capacity(map.len());
  830. for (k, v) in map {
  831. let label = yaml_scalar_to_string(k).unwrap_or_default();
  832. let val = yaml_to_json(v)?;
  833. choices.push(ChoiceSpec { label, value: val });
  834. }
  835. Ok(choices)
  836. } else {
  837. Err(RoneoError::InvalidConfig(format!(
  838. "Question '{name}' 'choices' must be a list or mapping"
  839. )))
  840. }
  841. }
  842. pub fn yaml_to_json(value: &YamlValue) -> Result<serde_json::Value> {
  843. Ok(serde_json::to_value(value)?)
  844. }
  845. pub fn json_display(value: &serde_json::Value) -> String {
  846. match value {
  847. serde_json::Value::String(s) => s.clone(),
  848. serde_json::Value::Bool(b) => b.to_string(),
  849. serde_json::Value::Number(n) => n.to_string(),
  850. serde_json::Value::Null => String::new(),
  851. other => other.to_string(),
  852. }
  853. }
  854. fn yaml_scalar_to_string(v: &YamlValue) -> Option<String> {
  855. match v {
  856. YamlValue::String(s) => Some(s.clone()),
  857. YamlValue::Bool(b) => Some(b.to_string()),
  858. YamlValue::Number(n) => Some(n.to_string()),
  859. _ => None,
  860. }
  861. }
  862. fn yaml_to_opt_string(value: &YamlValue, key: &str) -> Result<Option<String>> {
  863. if value.is_null() {
  864. return Ok(None);
  865. }
  866. value
  867. .as_str()
  868. .map(|s| Some(s.to_string()))
  869. .ok_or_else(|| RoneoError::InvalidConfig(format!("'{key}' must be a string")))
  870. }
  871. fn yaml_to_string_list(value: &YamlValue, key: &str) -> Result<Vec<String>> {
  872. if value.is_null() {
  873. return Ok(Vec::new());
  874. }
  875. let seq = value
  876. .as_sequence()
  877. .ok_or_else(|| RoneoError::InvalidConfig(format!("'{key}' must be a list of strings")))?;
  878. seq.iter()
  879. .map(|item| {
  880. item.as_str().map(ToOwned::to_owned).ok_or_else(|| {
  881. RoneoError::InvalidConfig(format!("Items in '{key}' must be strings"))
  882. })
  883. })
  884. .collect()
  885. }
  886. /// Parse a YAML/JSON document expected to be a key/value mapping (e.g. `--data-file`).
  887. pub fn parse_yaml_mapping(raw: &str) -> Result<IndexMap<String, serde_json::Value>> {
  888. let yaml_val: YamlValue = serde_yaml_ng::from_str(raw)?;
  889. let Some(map) = yaml_val.as_mapping() else {
  890. return Err(RoneoError::InvalidConfig(
  891. "Expected a YAML/JSON mapping".into(),
  892. ));
  893. };
  894. let mut out = IndexMap::with_capacity(map.len());
  895. for (k, v) in map {
  896. if let Some(key) = k.as_str() {
  897. out.insert(key.to_string(), yaml_to_json(v)?);
  898. }
  899. }
  900. Ok(out)
  901. }
  902. /// Parse a single CLI `--data KEY=VALUE` scalar/collection as YAML, falling back to a plain string.
  903. pub fn parse_yaml_cli_value(raw: &str) -> serde_json::Value {
  904. if let Ok(yaml_val) = serde_yaml_ng::from_str::<YamlValue>(raw)
  905. && let Ok(json_val) = yaml_to_json(&yaml_val)
  906. {
  907. return json_val;
  908. }
  909. serde_json::Value::String(raw.to_string())
  910. }