roneocratesroneo-coresrcanswers.rs
0518da6beb3fd562b82c5b5c2798b72e0d1591b2- use std::collections::HashSet;
- use std::fs;
- use std::path::{Path, PathBuf};
- use indexmap::IndexMap;
- use serde_json::Value as JsonValue;
- use crate::config::{DEFAULT_ANSWERS_FILE, yaml_to_json};
- use crate::error::{Result, RoneoError};
- pub const ANSWERS_HEADER: &str =
- "# Changes here will be overwritten by Copier/Roneo; NEVER EDIT MANUALLY\n";
- /// Represents answers collected from a user and/or loaded from `.copier-answers.yml`.
- #[derive(Debug, Clone, Default)]
- pub struct AnswersMap {
- /// User answers to asked questions (persisted to `.copier-answers.yml` unless secret).
- pub user: IndexMap<String, JsonValue>,
- /// Default values of skipped (`when: false`) questions: available in render context
- /// but NOT persisted to `.copier-answers.yml` (matching Copier's exact behavior).
- pub default_only: IndexMap<String, JsonValue>,
- /// Metadata keys (underscore-prefixed, notably `_commit` and `_src_path`).
- pub metadata: IndexMap<String, JsonValue>,
- /// Names of secret questions that must never be persisted to disk.
- pub secrets: HashSet<String>,
- }
- impl AnswersMap {
- pub fn load(path: &Path) -> Result<Self> {
- let raw = fs::read_to_string(path).map_err(|e| RoneoError::io(path, e))?;
- Self::parse_yaml(&raw)
- }
- pub fn parse_yaml(raw: &str) -> Result<Self> {
- if raw.trim().is_empty() {
- return Ok(Self::default());
- }
- let yaml_val: serde_yaml_ng::Value = serde_yaml_ng::from_str(raw)?;
- let Some(mapping) = yaml_val.as_mapping() else {
- return Err(RoneoError::InvalidConfig(
- "Answers file must be a YAML mapping".into(),
- ));
- };
- let mut answers = Self::default();
- for (k, v) in mapping {
- let Some(key) = k.as_str() else {
- continue;
- };
- let json_val = yaml_to_json(v)?;
- if key.starts_with('_') {
- answers.metadata.insert(key.to_string(), json_val);
- } else {
- answers.user.insert(key.to_string(), json_val);
- }
- }
- Ok(answers)
- }
- /// Locate an answers file inside `dst_dir` (checking `preferred` first, then `.copier-answers.yml`).
- pub fn find_in_dir(dst_dir: &Path, preferred: Option<&Path>) -> Option<PathBuf> {
- if let Some(p) = preferred {
- let candidate = if p.is_absolute() {
- p.to_path_buf()
- } else {
- dst_dir.join(p)
- };
- if candidate.is_file() {
- return Some(candidate);
- }
- }
- let default = dst_dir.join(DEFAULT_ANSWERS_FILE);
- if default.is_file() {
- return Some(default);
- }
- // Also check `.copier-answers.yaml` as a convenient fallback.
- let alt = dst_dir.join(".copier-answers.yaml");
- if alt.is_file() {
- return Some(alt);
- }
- None
- }
- pub fn src_path(&self) -> Option<&str> {
- self.metadata.get("_src_path").and_then(JsonValue::as_str)
- }
- pub fn commit(&self) -> Option<&str> {
- self.metadata.get("_commit").and_then(JsonValue::as_str)
- }
- pub fn set_src_path(&mut self, src_path: impl Into<String>) {
- self.metadata
- .insert("_src_path".into(), JsonValue::String(src_path.into()));
- }
- pub fn set_commit(&mut self, commit: impl Into<String>) {
- self.metadata
- .insert("_commit".into(), JsonValue::String(commit.into()));
- }
- /// Combine metadata + skipped-question defaults + user answers (including secrets)
- /// for template rendering context.
- pub fn combined(&self) -> IndexMap<String, JsonValue> {
- let mut out = self.metadata.clone();
- for (k, v) in &self.default_only {
- out.insert(k.clone(), v.clone());
- }
- for (k, v) in &self.user {
- out.insert(k.clone(), v.clone());
- }
- out
- }
- /// Combine metadata + non-secret user answers for persisting to `.copier-answers.yml`
- /// and exposing as `_copier_answers` inside templates (sorted deterministically like Copier).
- pub fn persistable(&self) -> IndexMap<String, JsonValue> {
- let mut meta_entries: Vec<(&String, &JsonValue)> = self.metadata.iter().collect();
- meta_entries.sort_unstable_by(|a, b| a.0.cmp(b.0));
- let mut user_entries: Vec<(&String, &JsonValue)> = self
- .user
- .iter()
- .filter(|(k, _)| !self.secrets.contains(*k))
- .collect();
- user_entries.sort_unstable_by(|a, b| a.0.cmp(b.0));
- let mut out = IndexMap::with_capacity(meta_entries.len() + user_entries.len());
- for (k, v) in meta_entries.into_iter().chain(user_entries) {
- out.insert(k.clone(), v.clone());
- }
- out
- }
- /// Render the answers file YAML string.
- pub fn to_yaml_string(&self) -> Result<String> {
- let map = self.persistable();
- let yaml = serde_yaml_ng::to_string(&map)?;
- Ok(format!("{ANSWERS_HEADER}{yaml}"))
- }
- /// Save the answers file to disk.
- pub fn save(&self, path: &Path) -> Result<()> {
- if let Some(parent) = path.parent() {
- fs::create_dir_all(parent).map_err(|e| RoneoError::io(parent, e))?;
- }
- let content = self.to_yaml_string()?;
- fs::write(path, content).map_err(|e| RoneoError::io(path, e))
- }
- }