use std::fs; use std::path::{Path, PathBuf}; use indexmap::IndexMap; use serde::{Deserialize, Serialize}; use serde_yaml_ng::Value as YamlValue; use crate::error::{Result, RoneoError}; use crate::filter::match_glob_path; use crate::fs_util::walk_dir_sorted; /// List-valued settings that Copier merges (concatenates) across multi-document YAML & `!include`. const MERGE_LIST_KEYS: &[&str] = &[ "_exclude", "_skip_if_exists", "_secret_questions", "_jinja_extensions", "_roneo_plugins", "_tasks", "_migrations", ]; /// Candidate template configuration filenames in precedence order. pub const CONFIG_FILENAMES: &[&str] = &["roneo.yml", "roneo.yaml", "copier.yml", "copier.yaml"]; /// Default answers file name (100% Copier-compatible). pub const DEFAULT_ANSWERS_FILE: &str = ".copier-answers.yml"; /// Default template file suffix. pub const DEFAULT_TEMPLATES_SUFFIX: &str = ".jinja"; /// Default patterns always excluded unless negated with `!`. pub const DEFAULT_EXCLUDES: &[&str] = &[ "copier.yaml", "copier.yml", "roneo.yaml", "roneo.yml", "~*", "*.py[co]", "__pycache__", ".git", ".DS_Store", ".svn", ]; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TemplateConfig { pub settings: TemplateSettings, pub questions: IndexMap, pub config_path: Option, } impl Default for TemplateConfig { fn default() -> Self { Self { settings: TemplateSettings::default(), questions: IndexMap::new(), config_path: None, } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TemplateSettings { pub subdirectory: Option, pub answers_file: String, pub templates_suffix: String, pub exclude: Vec, pub skip_if_exists: Vec, pub preserve_symlinks: bool, pub secret_questions: Vec, pub tasks: Vec, pub migrations: Vec, pub envops: EnvOps, pub min_copier_version: Option, pub message_before_copy: Option, pub message_after_copy: Option, pub message_before_update: Option, pub message_after_update: Option, pub jinja_extensions: Vec, pub roneo_plugins: Vec, pub external_data: IndexMap, } impl Default for TemplateSettings { fn default() -> Self { Self { subdirectory: None, answers_file: DEFAULT_ANSWERS_FILE.to_string(), templates_suffix: DEFAULT_TEMPLATES_SUFFIX.to_string(), exclude: Vec::new(), skip_if_exists: Vec::new(), preserve_symlinks: false, secret_questions: Vec::new(), tasks: Vec::new(), migrations: Vec::new(), envops: EnvOps::default(), min_copier_version: None, message_before_copy: None, message_after_copy: None, message_before_update: None, message_after_update: None, jinja_extensions: Vec::new(), roneo_plugins: Vec::new(), external_data: IndexMap::new(), } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct EnvOps { pub block_start_string: String, pub block_end_string: String, pub variable_start_string: String, pub variable_end_string: String, pub comment_start_string: String, pub comment_end_string: String, pub keep_trailing_newline: bool, pub trim_blocks: bool, pub lstrip_blocks: bool, } impl Default for EnvOps { fn default() -> Self { Self { block_start_string: "{%".to_string(), block_end_string: "%}".to_string(), variable_start_string: "{{".to_string(), variable_end_string: "}}".to_string(), comment_start_string: "{#".to_string(), comment_end_string: "#}".to_string(), keep_trailing_newline: true, trim_blocks: false, lstrip_blocks: false, } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum CommandSpec { Shell(String), Args(Vec), } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TaskSpec { pub command: CommandSpec, pub when: Option, pub working_directory: Option, #[serde(default)] pub extra_env: IndexMap, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct MigrationSpec { pub version: Option, pub before: Vec, pub after: Vec, pub command: Option, pub when: Option, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] #[serde(rename_all = "lowercase")] pub enum QuestionType { #[default] Str, Int, Float, Bool, Yaml, Json, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ChoiceSpec { pub label: String, pub value: serde_json::Value, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Question { pub name: String, pub kind: QuestionType, /// Optional Jinja template expression for dynamic `type:` (e.g. `"{% if flag %}int{% else %}str{% endif %}"`). pub type_template: Option, pub help: Option, pub default: Option, pub choices: Option>, /// Optional Jinja template expression returning a YAML/JSON list or mapping for dynamic `choices:`. pub choices_template: Option, pub validator: Option, pub when: Option, /// Optional opt-in prompt condition (`ask: false` or Jinja expr, Copier v9.19.0 `#2849`). pub ask: Option, pub secret: bool, pub multiselect: bool, pub multiline: bool, /// Optional raw `multiline` specification (bool or Jinja template string; defaults to `true` for YAML/JSON). pub multiline_expr: Option, pub placeholder: Option, /// Optional custom question prefix mark (Copier `qmark`, e.g. `"🚀"`). pub qmark: Option, } impl TemplateConfig { /// Locate and parse the template configuration inside `template_root`. /// If no config file is present, returns a default empty configuration (matching Copier). pub fn load_from_dir(template_root: &Path) -> Result { let mut found = None; for name in CONFIG_FILENAMES { let candidate = template_root.join(name); if candidate.is_file() { found = Some(candidate); break; } } let Some(config_path) = found else { return Ok(Self::default()); }; let raw = fs::read_to_string(&config_path).map_err(|e| RoneoError::io(&config_path, e))?; let mut cfg = Self::parse_str_with_base(&raw, Some(template_root))?; cfg.config_path = Some(config_path); Ok(cfg) } /// Locate and parse the template configuration using an abstract in-memory file reader /// (e.g. directly from a `gix` commit tree without extracting to disk). pub fn load_from_reader(read_file: &F) -> Result where F: Fn(&str) -> Option, { Self::load_from_reader_with_glob(read_file, &|_| Vec::new()) } /// Locate and parse the template configuration using an abstract file reader + glob expander. pub fn load_from_reader_with_glob(read_file: &F, glob_files: &G) -> Result where F: Fn(&str) -> Option, G: Fn(&str) -> Vec, { for name in CONFIG_FILENAMES { if let Some(raw) = read_file(name) { let mut cfg = Self::parse_str_with_reader_and_glob(&raw, read_file, glob_files)?; cfg.config_path = Some(PathBuf::from(name)); return Ok(cfg); } } Ok(Self::default()) } /// Parse a Copier/Roneo YAML configuration string. pub fn parse_str(raw: &str) -> Result { Self::parse_str_with_base(raw, None) } /// Parse a Copier/Roneo YAML configuration string, resolving `!include ` directives /// (including glob patterns like `!include questions/*.yml`) relative to `base_dir`, /// rejecting any path or symlink escaping `base_dir` (Copier v9.17.2 security hardening). pub fn parse_str_with_base(raw: &str, base_dir: Option<&Path>) -> Result { let canon_base = base_dir.and_then(|b| fs::canonicalize(b).ok()); let reader = |rel: &str| -> Option { let root = base_dir?; let candidate = root.join(rel); if let Some(ref base_canon) = canon_base { let cand_canon = fs::canonicalize(&candidate).ok()?; if !cand_canon.starts_with(base_canon) { return None; } } fs::read_to_string(candidate).ok() }; let globber = |pattern: &str| -> Vec { let Some(root) = base_dir else { return Vec::new(); }; let mut matched = Vec::new(); let _ = walk_dir_sorted(root, false, |entry| { if !entry.is_dir && match_glob_path(pattern, &entry.rel_path) { if let Some(ref base_canon) = canon_base && let Ok(cand_canon) = fs::canonicalize(&entry.abs_path) && !cand_canon.starts_with(base_canon) { return Ok(true); } matched.push(entry.rel_path.to_string_lossy().replace('\\', "/")); } Ok(true) }); matched }; Self::parse_str_with_reader_and_glob(raw, &reader, &globber) } /// Parse a Copier/Roneo YAML configuration string, resolving `!include ` via `read_file`. pub fn parse_str_with_reader(raw: &str, read_file: &F) -> Result where F: Fn(&str) -> Option, { Self::parse_str_with_reader_and_glob(raw, read_file, &|_| Vec::new()) } /// Parse a Copier/Roneo YAML configuration string with both exact `!include` reading and glob expansion. pub fn parse_str_with_reader_and_glob( raw: &str, read_file: &F, glob_files: &G, ) -> Result where F: Fn(&str) -> Option, G: Fn(&str) -> Vec, { let trimmed = raw.trim(); if trimmed.is_empty() { return Ok(Self::default()); } let mut merged: IndexMap = IndexMap::new(); parse_yaml_docs_into(trimmed, read_file, glob_files, &mut merged, 0)?; let mut settings = TemplateSettings::default(); let mut questions = IndexMap::new(); for (key, value) in merged { if key.starts_with('_') { parse_setting(&key, &value, &mut settings)?; } else { let mut question = parse_question(&key, &value)?; if settings.secret_questions.contains(&key) { question.secret = true; } questions.insert(key, question); } } // Apply `_secret_questions` even if declared after the questions. for secret_name in &settings.secret_questions { if let Some(q) = questions.get_mut(secret_name) { q.secret = true; } } Ok(Self { settings, questions, config_path: None, }) } /// Returns whether this template requires `--trust` before running. pub fn requires_trust(&self) -> bool { !self.settings.tasks.is_empty() || !self.settings.migrations.is_empty() || !self.settings.jinja_extensions.is_empty() || !self.settings.roneo_plugins.is_empty() } } fn parse_yaml_docs_into( raw: &str, read_file: &F, glob_files: &G, merged: &mut IndexMap, depth: usize, ) -> Result<()> where F: Fn(&str) -> Option, G: Fn(&str) -> Vec, { if depth > 16 { return Err(RoneoError::InvalidConfig( "Maximum `!include` nesting depth exceeded".into(), )); } for doc in serde_yaml_ng::Deserializer::from_str(raw) { let value = YamlValue::deserialize(doc)?; if value.is_null() { continue; } // Handle Copier's `!include path/to/file.yml` and glob `!include questions/*.yml` YAML tags. if let YamlValue::Tagged(tagged) = &value && tagged.tag == "!include" && let Some(rel) = tagged.value.as_str() { let rel_path = Path::new(rel); if rel_path.is_absolute() || rel_path .components() .any(|c| matches!(c, std::path::Component::ParentDir)) { return Err(RoneoError::InvalidConfig(format!( "YAML `!include` path '{rel}' must stay inside the template root" ))); } if rel.contains(['*', '?', '[']) { let mut targets = glob_files(rel); targets.sort(); for target in targets { if let Some(include_raw) = read_file(&target) { parse_yaml_docs_into( &include_raw, read_file, glob_files, merged, depth + 1, )?; } } } else { let include_raw = read_file(rel).ok_or_else(|| { RoneoError::InvalidConfig(format!("Failed to read `!include {rel}`")) })?; parse_yaml_docs_into(&include_raw, read_file, glob_files, merged, depth + 1)?; } continue; } let mapping = value.as_mapping().ok_or_else(|| { RoneoError::InvalidConfig("Top-level configuration must be a YAML mapping".into()) })?; for (k, v) in mapping { let key = k.as_str().ok_or_else(|| { RoneoError::InvalidConfig("Top-level keys must be strings".into()) })?; // Concatenate Copier's list-valued settings across multi-doc YAML / `!include`. if MERGE_LIST_KEYS.contains(&key) && let Some(YamlValue::Sequence(existing)) = merged.get_mut(key) && let Some(incoming) = v.as_sequence() { existing.extend(incoming.iter().cloned()); continue; } merged.insert(key.to_string(), v.clone()); } } Ok(()) } fn parse_setting(key: &str, value: &YamlValue, settings: &mut TemplateSettings) -> Result<()> { match key { "_subdirectory" => { settings.subdirectory = yaml_to_opt_string(value, key)?; } "_answers_file" => { if let Some(s) = yaml_to_opt_string(value, key)? { settings.answers_file = s; } } "_templates_suffix" => { settings.templates_suffix = yaml_to_opt_string(value, key)?.unwrap_or_default(); } "_exclude" => { settings.exclude = yaml_to_string_list(value, key)?; } "_skip_if_exists" => { settings.skip_if_exists = yaml_to_string_list(value, key)?; } "_preserve_symlinks" => { settings.preserve_symlinks = value .as_bool() .ok_or_else(|| RoneoError::InvalidConfig(format!("'{key}' must be a boolean")))?; } "_secret_questions" => { settings.secret_questions = yaml_to_string_list(value, key)?; } "_tasks" => { settings.tasks = parse_task_list(value, key)?; } "_migrations" => { settings.migrations = parse_migrations(value)?; } "_envops" => { parse_envops(value, &mut settings.envops)?; } "_min_copier_version" => { settings.min_copier_version = yaml_to_opt_string(value, key)?; } "_message_before_copy" => { settings.message_before_copy = yaml_to_opt_string(value, key)?; } "_message_after_copy" => { settings.message_after_copy = yaml_to_opt_string(value, key)?; } "_message_before_update" => { settings.message_before_update = yaml_to_opt_string(value, key)?; } "_message_after_update" => { settings.message_after_update = yaml_to_opt_string(value, key)?; } "_jinja_extensions" => { settings.jinja_extensions = yaml_to_string_list(value, key)?; } "_roneo_plugins" => { settings.roneo_plugins = yaml_to_string_list(value, key)?; } "_external_data" => { if let Some(map) = value.as_mapping() { for (k, v) in map { if let (Some(name), Some(path_str)) = (k.as_str(), v.as_str()) { settings .external_data .insert(name.to_string(), path_str.to_string()); } } } else if !value.is_null() { return Err(RoneoError::InvalidConfig( "'_external_data' must be a mapping of key -> file path".into(), )); } } // Unknown `_` metadata keys (e.g. `_metadata`, `_external_data`) are preserved gracefully. _ => {} } Ok(()) } fn parse_envops(value: &YamlValue, envops: &mut EnvOps) -> Result<()> { let Some(map) = value.as_mapping() else { return Err(RoneoError::InvalidConfig( "'_envops' must be a mapping".into(), )); }; for (k, v) in map { let Some(key) = k.as_str() else { continue; }; match key { "block_start_string" => { if let Some(s) = v.as_str() { envops.block_start_string = s.to_string(); } } "block_end_string" => { if let Some(s) = v.as_str() { envops.block_end_string = s.to_string(); } } "variable_start_string" => { if let Some(s) = v.as_str() { envops.variable_start_string = s.to_string(); } } "variable_end_string" => { if let Some(s) = v.as_str() { envops.variable_end_string = s.to_string(); } } "comment_start_string" => { if let Some(s) = v.as_str() { envops.comment_start_string = s.to_string(); } } "comment_end_string" => { if let Some(s) = v.as_str() { envops.comment_end_string = s.to_string(); } } "keep_trailing_newline" => { if let Some(b) = v.as_bool() { envops.keep_trailing_newline = b; } } "trim_blocks" => { if let Some(b) = v.as_bool() { envops.trim_blocks = b; } } "lstrip_blocks" => { if let Some(b) = v.as_bool() { envops.lstrip_blocks = b; } } _ => {} } } Ok(()) } fn parse_task_list(value: &YamlValue, key: &str) -> Result> { if value.is_null() { return Ok(Vec::new()); } let seq = value .as_sequence() .ok_or_else(|| RoneoError::InvalidConfig(format!("'{key}' must be a list")))?; let mut tasks = Vec::with_capacity(seq.len()); for item in seq { tasks.push(parse_single_task(item, key)?); } Ok(tasks) } fn parse_single_task(item: &YamlValue, key: &str) -> Result { if let Some(cmd) = item.as_str() { return Ok(TaskSpec { command: CommandSpec::Shell(cmd.to_string()), when: None, working_directory: None, extra_env: IndexMap::new(), }); } if let Some(args) = item.as_sequence() { let parsed = args .iter() .map(|a| { a.as_str().map(ToOwned::to_owned).ok_or_else(|| { RoneoError::InvalidConfig(format!("Task argument in '{key}' must be a string")) }) }) .collect::>>()?; return Ok(TaskSpec { command: CommandSpec::Args(parsed), when: None, working_directory: None, extra_env: IndexMap::new(), }); } if let Some(map) = item.as_mapping() { let cmd_val = map .get(YamlValue::String("command".into())) .ok_or_else(|| { RoneoError::InvalidConfig(format!("Task mapping in '{key}' missing 'command'")) })?; let command = if let Some(s) = cmd_val.as_str() { CommandSpec::Shell(s.to_string()) } else if let Some(seq) = cmd_val.as_sequence() { CommandSpec::Args( seq.iter() .map(|v| { v.as_str().map(ToOwned::to_owned).ok_or_else(|| { RoneoError::InvalidConfig(format!( "Task 'command' sequence in '{key}' must contain strings" )) }) }) .collect::>>()?, ) } else { return Err(RoneoError::InvalidConfig(format!( "Task 'command' in '{key}' must be string or list of strings" ))); }; let when = map .get(YamlValue::String("when".into())) .and_then(yaml_scalar_to_string); let working_directory = map .get(YamlValue::String("working_directory".into())) .and_then(|v| v.as_str().map(ToOwned::to_owned)); let mut extra_env = IndexMap::new(); if let Some(env_map) = map .get(YamlValue::String("extra_env".into())) .and_then(YamlValue::as_mapping) { for (ek, ev) in env_map { if let (Some(k_str), Some(v_str)) = (ek.as_str(), yaml_scalar_to_string(ev)) { extra_env.insert(k_str.to_string(), v_str); } } } return Ok(TaskSpec { command, when, working_directory, extra_env, }); } Err(RoneoError::InvalidConfig(format!( "Unsupported task definition in '{key}'" ))) } fn parse_migrations(value: &YamlValue) -> Result> { if value.is_null() { return Ok(Vec::new()); } let seq = value .as_sequence() .ok_or_else(|| RoneoError::InvalidConfig("'_migrations' must be a list".into()))?; let mut migrations = Vec::with_capacity(seq.len()); for item in seq { let map = item.as_mapping().ok_or_else(|| { RoneoError::InvalidConfig("Each entry in '_migrations' must be a mapping".into()) })?; let version = map .get(YamlValue::String("version".into())) .and_then(yaml_scalar_to_string); let before = map .get(YamlValue::String("before".into())) .map(|v| parse_task_list(v, "_migrations.before")) .transpose()? .unwrap_or_default(); let after = map .get(YamlValue::String("after".into())) .map(|v| parse_task_list(v, "_migrations.after")) .transpose()? .unwrap_or_default(); let command = map .get(YamlValue::String("command".into())) .map(|v| parse_single_task(v, "_migrations.command").map(|t| t.command)) .transpose()?; let when = map .get(YamlValue::String("when".into())) .and_then(yaml_scalar_to_string); migrations.push(MigrationSpec { version, before, after, command, when, }); } Ok(migrations) } fn parse_question(name: &str, value: &YamlValue) -> Result { if let Some(map) = value.as_mapping() { let default = map .get(YamlValue::String("default".into())) .map(yaml_to_json) .transpose()?; let (kind, type_template) = if let Some(type_val) = map.get(YamlValue::String("type".into())) { let raw_type = type_val.as_str().ok_or_else(|| { RoneoError::InvalidConfig(format!("Question '{name}' 'type' must be a string")) })?; if raw_type.contains("{{") || raw_type.contains("{%") { (QuestionType::Str, Some(raw_type.to_string())) } else { (parse_question_type(raw_type)?, None) } } else if let Some(def) = &default { (infer_type_from_json(def), None) } else { (QuestionType::Str, None) }; let help = map .get(YamlValue::String("help".into())) .and_then(|v| v.as_str().map(ToOwned::to_owned)); let validator = map .get(YamlValue::String("validator".into())) .and_then(|v| v.as_str().map(ToOwned::to_owned)); let when = map .get(YamlValue::String("when".into())) .map(yaml_to_json) .transpose()?; let ask = map .get(YamlValue::String("ask".into())) .map(yaml_to_json) .transpose()?; let secret = map .get(YamlValue::String("secret".into())) .and_then(YamlValue::as_bool) .unwrap_or(false); let multiselect = map .get(YamlValue::String("multiselect".into())) .and_then(YamlValue::as_bool) .unwrap_or(false); let multiline_expr = map .get(YamlValue::String("multiline".into())) .map(yaml_to_json) .transpose()?; let multiline = multiline_expr.as_ref().map_or( matches!(kind, QuestionType::Yaml | QuestionType::Json), |v| v.as_bool().unwrap_or(false), ); let placeholder = map .get(YamlValue::String("placeholder".into())) .and_then(|v| v.as_str().map(ToOwned::to_owned)); let qmark = map .get(YamlValue::String("qmark".into())) .and_then(|v| v.as_str().map(ToOwned::to_owned)); let (choices, choices_template) = if let Some(ch_val) = map.get(YamlValue::String("choices".into())) { if let Some(tpl) = ch_val.as_str() { (None, Some(tpl.to_string())) } else { (Some(parse_choices(name, ch_val)?), None) } } else { (None, None) }; Ok(Question { name: name.to_string(), kind, type_template, help, default, choices, choices_template, validator, when, ask, secret, multiselect, multiline, multiline_expr, placeholder, qmark, }) } else { // Short-form question: `project_name: my-project` let default = yaml_to_json(value)?; let kind = infer_type_from_json(&default); Ok(Question { name: name.to_string(), kind, type_template: None, help: None, default: Some(default), choices: None, choices_template: None, validator: None, when: None, ask: None, secret: false, multiselect: false, multiline: matches!(kind, QuestionType::Yaml | QuestionType::Json), multiline_expr: None, placeholder: None, qmark: None, }) } } pub fn parse_question_type(raw: &str) -> Result { match raw.trim() { "str" | "string" => Ok(QuestionType::Str), "int" | "integer" => Ok(QuestionType::Int), "float" | "number" => Ok(QuestionType::Float), "bool" | "boolean" => Ok(QuestionType::Bool), "yaml" => Ok(QuestionType::Yaml), "json" => Ok(QuestionType::Json), other => Err(RoneoError::InvalidConfig(format!( "Unsupported question type '{other}'" ))), } } fn infer_type_from_json(val: &serde_json::Value) -> QuestionType { match val { serde_json::Value::Bool(_) => QuestionType::Bool, serde_json::Value::Number(n) => { if n.is_i64() || n.is_u64() { QuestionType::Int } else { QuestionType::Float } } serde_json::Value::Array(_) | serde_json::Value::Object(_) => QuestionType::Yaml, serde_json::Value::String(_) | serde_json::Value::Null => QuestionType::Str, } } pub fn parse_choices(name: &str, value: &YamlValue) -> Result> { if let Some(seq) = value.as_sequence() { let mut choices = Vec::with_capacity(seq.len()); for item in seq { if let Some(pair) = item.as_sequence() && pair.len() == 2 { let label = yaml_scalar_to_string(&pair[0]).unwrap_or_default(); let val = yaml_to_json(&pair[1])?; choices.push(ChoiceSpec { label, value: val }); continue; } let val = yaml_to_json(item)?; let label = json_display(&val); choices.push(ChoiceSpec { label, value: val }); } Ok(choices) } else if let Some(map) = value.as_mapping() { let mut choices = Vec::with_capacity(map.len()); for (k, v) in map { let label = yaml_scalar_to_string(k).unwrap_or_default(); let val = yaml_to_json(v)?; choices.push(ChoiceSpec { label, value: val }); } Ok(choices) } else { Err(RoneoError::InvalidConfig(format!( "Question '{name}' 'choices' must be a list or mapping" ))) } } pub fn yaml_to_json(value: &YamlValue) -> Result { Ok(serde_json::to_value(value)?) } pub fn json_display(value: &serde_json::Value) -> String { match value { serde_json::Value::String(s) => s.clone(), serde_json::Value::Bool(b) => b.to_string(), serde_json::Value::Number(n) => n.to_string(), serde_json::Value::Null => String::new(), other => other.to_string(), } } fn yaml_scalar_to_string(v: &YamlValue) -> Option { match v { YamlValue::String(s) => Some(s.clone()), YamlValue::Bool(b) => Some(b.to_string()), YamlValue::Number(n) => Some(n.to_string()), _ => None, } } fn yaml_to_opt_string(value: &YamlValue, key: &str) -> Result> { if value.is_null() { return Ok(None); } value .as_str() .map(|s| Some(s.to_string())) .ok_or_else(|| RoneoError::InvalidConfig(format!("'{key}' must be a string"))) } fn yaml_to_string_list(value: &YamlValue, key: &str) -> Result> { if value.is_null() { return Ok(Vec::new()); } let seq = value .as_sequence() .ok_or_else(|| RoneoError::InvalidConfig(format!("'{key}' must be a list of strings")))?; seq.iter() .map(|item| { item.as_str().map(ToOwned::to_owned).ok_or_else(|| { RoneoError::InvalidConfig(format!("Items in '{key}' must be strings")) }) }) .collect() } /// Parse a YAML/JSON document expected to be a key/value mapping (e.g. `--data-file`). pub fn parse_yaml_mapping(raw: &str) -> Result> { let yaml_val: YamlValue = serde_yaml_ng::from_str(raw)?; let Some(map) = yaml_val.as_mapping() else { return Err(RoneoError::InvalidConfig( "Expected a YAML/JSON mapping".into(), )); }; let mut out = IndexMap::with_capacity(map.len()); for (k, v) in map { if let Some(key) = k.as_str() { out.insert(key.to_string(), yaml_to_json(v)?); } } Ok(out) } /// Parse a single CLI `--data KEY=VALUE` scalar/collection as YAML, falling back to a plain string. pub fn parse_yaml_cli_value(raw: &str) -> serde_json::Value { if let Ok(yaml_val) = serde_yaml_ng::from_str::(raw) && let Ok(json_val) = yaml_to_json(&yaml_val) { return json_val; } serde_json::Value::String(raw.to_string()) }