Skip to main content

rust_bucket/
apply.rs

1// Apply command implementation for first-time and subsequent runs
2
3use crate::cli;
4use crate::config::{Config, ConfigError};
5use crate::generator::{self, GeneratorError};
6use crate::templates::{self, TemplateError};
7use crate::verify::{self, VerifyError, VerifyReport};
8use std::path::{Path, PathBuf};
9use thiserror::Error;
10
11/// Result of applying rust-bucket to a target directory
12#[derive(Debug)]
13pub struct ApplyResult {
14    pub files_generated: Vec<PathBuf>,
15    pub verification: VerifyReport,
16}
17
18/// Errors that can occur during the apply operation
19#[derive(Debug, Error)]
20pub enum ApplyError {
21    /// Target directory is not a Rust crate (no Cargo.toml found)
22    #[error("Not a Rust crate: Cargo.toml not found in target directory")]
23    NotRustCrate,
24
25    /// Target directory is not a git repository (no .git/ found)
26    #[error("Not a git repository: .git/ directory not found")]
27    NotGitRepo,
28
29    /// Conflicting files exist in the target directory
30    #[error("Conflicting files detected: {}", .0.iter().map(|p| p.display().to_string()).collect::<Vec<_>>().join(", "))]
31    ConflictingFiles(Vec<PathBuf>),
32
33    /// Configuration-related error
34    #[error("Configuration error: {0}")]
35    ConfigError(#[from] ConfigError),
36
37    /// Template generation error
38    #[error("Generator error: {0}")]
39    GeneratorError(#[from] GeneratorError),
40
41    /// Verification error
42    #[error("Verification error: {0}")]
43    VerifyError(#[from] VerifyError),
44
45    /// Template extraction error
46    #[error("Template error: {0}")]
47    TemplateError(#[from] TemplateError),
48
49    /// CLI interaction error
50    #[error("CLI error: {0}")]
51    CliError(#[from] cli::CliError),
52}
53
54/// Apply rust-bucket to a target directory for the first time.
55///
56/// Implements the first-time flow described in ARCHITECTURE.md.
57///
58/// # Arguments
59///
60/// * `target_dir` - The target directory to apply rust-bucket to
61/// * `force` - If true, overwrite existing managed files; if false, fail on conflicts
62///
63/// # Errors
64///
65/// Returns `ApplyError` if:
66/// - The target is not a Rust crate (no Cargo.toml)
67/// - The target is not a git repository (no .git/)
68/// - Conflicting files exist and force is false
69/// - Any step in the process fails (config save, template extraction, rendering, verification)
70pub fn apply_init(target_dir: &Path, force: bool) -> Result<ApplyResult, ApplyError> {
71    let cargo_toml = target_dir.join("Cargo.toml");
72    if !cargo_toml.exists() {
73        return Err(ApplyError::NotRustCrate);
74    }
75
76    let git_dir = target_dir.join(".git");
77    if !git_dir.exists() {
78        return Err(ApplyError::NotGitRepo);
79    }
80
81    let conflicts = generator::check_conflicts(target_dir);
82    if !conflicts.is_empty() {
83        if !force {
84            return Err(ApplyError::ConflictingFiles(conflicts));
85        }
86        eprintln!(
87            "Warning: Overwriting {} existing file(s) due to --force flag",
88            conflicts.len()
89        );
90    }
91
92    let test_timeout = cli::prompt_test_timeout()?;
93
94    let config = Config {
95        rust_bucket_version: env!("CARGO_PKG_VERSION").to_string(),
96        test_timeout,
97        project_name: "Rust-Bucket".to_string(),
98    };
99
100    let config_path = target_dir.join("rust-bucket.toml");
101    config.save(&config_path)?;
102
103    let (_temp_dir, temp_path) = templates::extract_to_temp()?;
104
105    let mut files_generated = generator::render(&temp_path, target_dir, &config, force)?;
106
107    let claude_symlink = generator::create_claude_symlink(target_dir)?;
108    files_generated.push(claude_symlink);
109
110    generator::ensure_gitignore(target_dir)?;
111
112    generator::seed_style_guide(target_dir)?;
113
114    let verification = verify::run_all(target_dir)?;
115
116    Ok(ApplyResult {
117        files_generated,
118        verification,
119    })
120}
121
122/// Apply rust-bucket to a target directory in update mode (subsequent runs).
123///
124/// Implements the update flow described in ARCHITECTURE.md.
125///
126/// # Arguments
127///
128/// * `target_dir` - The target directory to update rust-bucket files in
129///
130/// # Errors
131///
132/// Returns `ApplyError` if:
133/// - The target is not a Rust crate (no Cargo.toml)
134/// - The target is not a git repository (no .git/)
135/// - The rust-bucket.toml config file cannot be loaded
136/// - Any step in the process fails (config save, template extraction, rendering, verification)
137pub fn apply_update(target_dir: &Path) -> Result<ApplyResult, ApplyError> {
138    let cargo_toml = target_dir.join("Cargo.toml");
139    if !cargo_toml.exists() {
140        return Err(ApplyError::NotRustCrate);
141    }
142
143    let git_dir = target_dir.join(".git");
144    if !git_dir.exists() {
145        return Err(ApplyError::NotGitRepo);
146    }
147
148    let config_path = target_dir.join("rust-bucket.toml");
149    let mut config = Config::load(&config_path)?;
150
151    let current_version = env!("CARGO_PKG_VERSION");
152    if config.rust_bucket_version != current_version {
153        eprintln!(
154            "Note: Config was last generated with rust-bucket v{}, updating to v{}",
155            config.rust_bucket_version, current_version
156        );
157    }
158
159    config.rust_bucket_version = current_version.to_string();
160
161    config.save(&config_path)?;
162
163    let (_temp_dir, temp_path) = templates::extract_to_temp()?;
164
165    let mut files_generated = generator::render(&temp_path, target_dir, &config, true)?;
166
167    let claude_symlink = generator::create_claude_symlink(target_dir)?;
168    files_generated.push(claude_symlink);
169
170    generator::ensure_gitignore(target_dir)?;
171
172    generator::seed_style_guide(target_dir)?;
173
174    let verification = verify::run_all(target_dir)?;
175
176    Ok(ApplyResult {
177        files_generated,
178        verification,
179    })
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185    use std::fs;
186    use tempfile::TempDir;
187
188    fn create_test_rust_crate(path: &Path) {
189        // Create Cargo.toml
190        fs::write(
191            path.join("Cargo.toml"),
192            r#"[package]
193name = "test-crate"
194version = "0.1.0"
195edition = "2021"
196"#,
197        )
198        .unwrap();
199
200        // Create .git directory
201        fs::create_dir(path.join(".git")).unwrap();
202
203        // Create src directory with lib.rs
204        let src_dir = path.join("src");
205        fs::create_dir(&src_dir).unwrap();
206        fs::write(src_dir.join("lib.rs"), "// test lib\n").unwrap();
207    }
208
209    #[test]
210    fn test_apply_init_not_rust_crate() {
211        let temp_dir = TempDir::new().unwrap();
212        let result = apply_init(temp_dir.path(), false);
213
214        assert!(result.is_err());
215        assert!(
216            matches!(result.unwrap_err(), ApplyError::NotRustCrate),
217            "Expected NotRustCrate error"
218        );
219    }
220
221    #[test]
222    fn test_apply_init_not_git_repo() {
223        let temp_dir = TempDir::new().unwrap();
224
225        // Create Cargo.toml but not .git
226        fs::write(
227            temp_dir.path().join("Cargo.toml"),
228            "[package]\nname = \"test\"",
229        )
230        .unwrap();
231
232        let result = apply_init(temp_dir.path(), false);
233
234        assert!(result.is_err());
235        assert!(
236            matches!(result.unwrap_err(), ApplyError::NotGitRepo),
237            "Expected NotGitRepo error"
238        );
239    }
240
241    #[test]
242    fn test_apply_init_conflicts_without_force() {
243        let temp_dir = TempDir::new().unwrap();
244        create_test_rust_crate(temp_dir.path());
245
246        // Create a conflicting file
247        fs::write(temp_dir.path().join("AGENTS.md"), "existing content").unwrap();
248
249        let result = apply_init(temp_dir.path(), false);
250
251        assert!(result.is_err());
252        let err = result.unwrap_err();
253        assert!(
254            matches!(&err, ApplyError::ConflictingFiles(_)),
255            "Expected ConflictingFiles error"
256        );
257        if let ApplyError::ConflictingFiles(conflicts) = err {
258            assert!(!conflicts.is_empty());
259            assert!(
260                conflicts
261                    .iter()
262                    .any(|p| p.file_name().unwrap() == "AGENTS.md")
263            );
264        }
265    }
266}