forgeFRENBrowse the repositories

roneocratesroneo-coresrcanswers.rs

98ff76d5794bbd1480ad719803187d2c40e42403

At commit 98ff76d

153 lines · 5.3 KiBRustRaw
  1. use std::collections::HashSet;
  2. use std::fs;
  3. use std::path::{Path, PathBuf};
  4. use indexmap::IndexMap;
  5. use serde_json::Value as JsonValue;
  6. use crate::config::{DEFAULT_ANSWERS_FILE, yaml_to_json};
  7. use crate::error::{Result, RoneoError};
  8. pub const ANSWERS_HEADER: &str =
  9. "# Changes here will be overwritten by Copier/Roneo; NEVER EDIT MANUALLY\n";
  10. /// Represents answers collected from a user and/or loaded from `.copier-answers.yml`.
  11. #[derive(Debug, Clone, Default)]
  12. pub struct AnswersMap {
  13. /// User answers to asked questions (persisted to `.copier-answers.yml` unless secret).
  14. pub user: IndexMap<String, JsonValue>,
  15. /// Default values of skipped (`when: false`) questions: available in render context
  16. /// but NOT persisted to `.copier-answers.yml` (matching Copier's exact behavior).
  17. pub default_only: IndexMap<String, JsonValue>,
  18. /// Metadata keys (underscore-prefixed, notably `_commit` and `_src_path`).
  19. pub metadata: IndexMap<String, JsonValue>,
  20. /// Names of secret questions that must never be persisted to disk.
  21. pub secrets: HashSet<String>,
  22. }
  23. impl AnswersMap {
  24. pub fn load(path: &Path) -> Result<Self> {
  25. let raw = fs::read_to_string(path).map_err(|e| RoneoError::io(path, e))?;
  26. Self::parse_yaml(&raw)
  27. }
  28. pub fn parse_yaml(raw: &str) -> Result<Self> {
  29. if raw.trim().is_empty() {
  30. return Ok(Self::default());
  31. }
  32. let yaml_val: serde_yaml_ng::Value = serde_yaml_ng::from_str(raw)?;
  33. let Some(mapping) = yaml_val.as_mapping() else {
  34. return Err(RoneoError::InvalidConfig(
  35. "Answers file must be a YAML mapping".into(),
  36. ));
  37. };
  38. let mut answers = Self::default();
  39. for (k, v) in mapping {
  40. let Some(key) = k.as_str() else {
  41. continue;
  42. };
  43. let json_val = yaml_to_json(v)?;
  44. if key.starts_with('_') {
  45. answers.metadata.insert(key.to_string(), json_val);
  46. } else {
  47. answers.user.insert(key.to_string(), json_val);
  48. }
  49. }
  50. Ok(answers)
  51. }
  52. /// Locate an answers file inside `dst_dir` (checking `preferred` first, then `.copier-answers.yml`).
  53. pub fn find_in_dir(dst_dir: &Path, preferred: Option<&Path>) -> Option<PathBuf> {
  54. if let Some(p) = preferred {
  55. let candidate = if p.is_absolute() {
  56. p.to_path_buf()
  57. } else {
  58. dst_dir.join(p)
  59. };
  60. if candidate.is_file() {
  61. return Some(candidate);
  62. }
  63. }
  64. let default = dst_dir.join(DEFAULT_ANSWERS_FILE);
  65. if default.is_file() {
  66. return Some(default);
  67. }
  68. // Also check `.copier-answers.yaml` as a convenient fallback.
  69. let alt = dst_dir.join(".copier-answers.yaml");
  70. if alt.is_file() {
  71. return Some(alt);
  72. }
  73. None
  74. }
  75. pub fn src_path(&self) -> Option<&str> {
  76. self.metadata.get("_src_path").and_then(JsonValue::as_str)
  77. }
  78. pub fn commit(&self) -> Option<&str> {
  79. self.metadata.get("_commit").and_then(JsonValue::as_str)
  80. }
  81. pub fn set_src_path(&mut self, src_path: impl Into<String>) {
  82. self.metadata
  83. .insert("_src_path".into(), JsonValue::String(src_path.into()));
  84. }
  85. pub fn set_commit(&mut self, commit: impl Into<String>) {
  86. self.metadata
  87. .insert("_commit".into(), JsonValue::String(commit.into()));
  88. }
  89. /// Combine metadata + skipped-question defaults + user answers (including secrets)
  90. /// for template rendering context.
  91. pub fn combined(&self) -> IndexMap<String, JsonValue> {
  92. let mut out = self.metadata.clone();
  93. for (k, v) in &self.default_only {
  94. out.insert(k.clone(), v.clone());
  95. }
  96. for (k, v) in &self.user {
  97. out.insert(k.clone(), v.clone());
  98. }
  99. out
  100. }
  101. /// Combine metadata + non-secret user answers for persisting to `.copier-answers.yml`
  102. /// and exposing as `_copier_answers` inside templates (sorted deterministically like Copier).
  103. pub fn persistable(&self) -> IndexMap<String, JsonValue> {
  104. let mut meta_entries: Vec<(&String, &JsonValue)> = self.metadata.iter().collect();
  105. meta_entries.sort_unstable_by(|a, b| a.0.cmp(b.0));
  106. let mut user_entries: Vec<(&String, &JsonValue)> = self
  107. .user
  108. .iter()
  109. .filter(|(k, _)| !self.secrets.contains(*k))
  110. .collect();
  111. user_entries.sort_unstable_by(|a, b| a.0.cmp(b.0));
  112. let mut out = IndexMap::with_capacity(meta_entries.len() + user_entries.len());
  113. for (k, v) in meta_entries.into_iter().chain(user_entries) {
  114. out.insert(k.clone(), v.clone());
  115. }
  116. out
  117. }
  118. /// Render the answers file YAML string.
  119. pub fn to_yaml_string(&self) -> Result<String> {
  120. let map = self.persistable();
  121. let yaml = serde_yaml_ng::to_string(&map)?;
  122. Ok(format!("{ANSWERS_HEADER}{yaml}"))
  123. }
  124. /// Save the answers file to disk.
  125. pub fn save(&self, path: &Path) -> Result<()> {
  126. if let Some(parent) = path.parent() {
  127. fs::create_dir_all(parent).map_err(|e| RoneoError::io(parent, e))?;
  128. }
  129. let content = self.to_yaml_string()?;
  130. fs::write(path, content).map_err(|e| RoneoError::io(path, e))
  131. }
  132. }