Skip to main content

rust_bucket/
templates.rs

1// Embedded template management
2
3use rust_embed::RustEmbed;
4use std::fs;
5use std::path::PathBuf;
6use tempfile::TempDir;
7use thiserror::Error;
8
9/// Error type for template operations
10#[derive(Debug, Error)]
11pub enum TemplateError {
12    #[error("Failed to create temporary directory: {0}")]
13    TempDirCreation(#[from] std::io::Error),
14
15    #[error("Failed to extract template file '{path}': {source}")]
16    FileExtraction {
17        path: String,
18        source: std::io::Error,
19    },
20
21    #[error("Template file '{0}' not found in embedded templates")]
22    TemplateNotFound(String),
23}
24
25/// Embedded templates from the templates/ directory
26#[derive(RustEmbed)]
27#[folder = "templates/"]
28pub struct Templates;
29
30/// Extracts all embedded templates to a temporary directory.
31///
32/// Returns the path to the temporary directory containing all extracted templates.
33/// The temporary directory will be cleaned up when the returned `TempDir` is dropped.
34///
35/// # Errors
36///
37/// Returns `TemplateError` if:
38/// - The temporary directory cannot be created
39/// - Any template file cannot be extracted or written
40pub fn extract_to_temp() -> Result<(TempDir, PathBuf), TemplateError> {
41    let temp_dir = TempDir::new()?;
42    let temp_path = temp_dir.path().to_path_buf();
43
44    for file_path in Templates::iter() {
45        let file_data = Templates::get(&file_path)
46            .ok_or_else(|| TemplateError::TemplateNotFound(file_path.to_string()))?;
47
48        let target_path = temp_path.join(file_path.as_ref());
49
50        // Create parent directories if needed
51        if let Some(parent) = target_path.parent() {
52            fs::create_dir_all(parent).map_err(|e| TemplateError::FileExtraction {
53                path: file_path.to_string(),
54                source: e,
55            })?;
56        }
57
58        // Write the file
59        fs::write(&target_path, file_data.data.as_ref()).map_err(|e| {
60            TemplateError::FileExtraction {
61                path: file_path.to_string(),
62                source: e,
63            }
64        })?;
65    }
66
67    Ok((temp_dir, temp_path))
68}
69
70/// Returns the .gitignore entries that rust-bucket requires in the target repository.
71pub fn required_gitignore_lines() -> Vec<&'static str> {
72    vec![
73        ".beads/.br_history/",
74        ".beads/beads.db",
75        ".beads/beads.db-wal",
76    ]
77}
78
79pub fn managed_files() -> Vec<&'static str> {
80    vec![
81        "AGENTS.md",
82        "CLAUDE.md", // symlink to AGENTS.md, created separately
83        "RUST_STYLE_GUIDE.md",
84        "TESTING.md",
85        ".claude/agents/coordinator.md",
86        ".claude/agents/coding.md",
87        ".claude/agents/judge.md",
88        ".claude/agents/tidy.md",
89        ".claude/agents/reflection.md",
90        ".config/nextest.toml",
91        "deny.toml",
92        "rustfmt.toml",
93        ".devcontainer/Dockerfile",
94        ".devcontainer/devcontainer.json",
95        ".beads/config.yaml",
96        "justfile-rustbucket",
97    ]
98}
99
100/// Seed files are written into the target only if absent and are never
101/// overwritten on re-apply; the project owns them once present.
102///
103/// Each entry maps an embedded template path (relative to `templates/`) to its
104/// destination path (relative to the target directory). Seed templates must NOT
105/// appear in `managed_files()`, and `render()` skips them so they are written
106/// only via the seed-if-missing path.
107pub fn seed_files() -> Vec<(&'static str, &'static str)> {
108    vec![
109        ("ratchets.toml.liquid", "ratchets.toml"),
110        ("STYLE_GUIDE.md.liquid", "STYLE_GUIDE.md"),
111    ]
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117
118    #[test]
119    fn test_extract_to_temp() -> Result<(), Box<dyn std::error::Error>> {
120        let (_temp_dir, temp_path) = extract_to_temp()?;
121        assert!(temp_path.exists());
122        assert!(temp_path.is_dir());
123        Ok(())
124    }
125
126    #[test]
127    fn test_managed_files_not_empty() {
128        let files = managed_files();
129        assert!(!files.is_empty());
130        assert_eq!(files.len(), 16);
131    }
132
133    #[test]
134    fn test_managed_files_includes_expected() {
135        let files = managed_files();
136        assert!(files.contains(&"AGENTS.md"));
137        assert!(files.contains(&"RUST_STYLE_GUIDE.md"));
138        assert!(files.contains(&".config/nextest.toml"));
139        assert!(files.contains(&".devcontainer/Dockerfile"));
140    }
141
142    #[test]
143    fn test_seed_files_registers_ratchets_toml() {
144        let seeds = seed_files();
145        assert!(seeds.contains(&("ratchets.toml.liquid", "ratchets.toml")));
146    }
147
148    #[test]
149    fn test_seed_files_registers_style_guide() {
150        let seeds = seed_files();
151        assert!(seeds.contains(&("STYLE_GUIDE.md.liquid", "STYLE_GUIDE.md")));
152    }
153
154    #[test]
155    fn test_ratchets_toml_not_managed() {
156        let managed = managed_files();
157        assert!(!managed.contains(&"ratchets.toml"));
158        assert_eq!(managed.len(), 16);
159    }
160
161    #[test]
162    fn test_style_guide_not_managed() {
163        let managed = managed_files();
164        assert!(!managed.contains(&"STYLE_GUIDE.md"));
165        assert_eq!(managed.len(), 16);
166    }
167}