1use 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#[derive(Debug)]
13pub struct ApplyResult {
14 pub files_generated: Vec<PathBuf>,
15 pub verification: VerifyReport,
16}
17
18#[derive(Debug, Error)]
20pub enum ApplyError {
21 #[error("Not a Rust crate: Cargo.toml not found in target directory")]
23 NotRustCrate,
24
25 #[error("Not a git repository: .git/ directory not found")]
27 NotGitRepo,
28
29 #[error("Conflicting files detected: {}", .0.iter().map(|p| p.display().to_string()).collect::<Vec<_>>().join(", "))]
31 ConflictingFiles(Vec<PathBuf>),
32
33 #[error("Configuration error: {0}")]
35 ConfigError(#[from] ConfigError),
36
37 #[error("Generator error: {0}")]
39 GeneratorError(#[from] GeneratorError),
40
41 #[error("Verification error: {0}")]
43 VerifyError(#[from] VerifyError),
44
45 #[error("Template error: {0}")]
47 TemplateError(#[from] TemplateError),
48
49 #[error("CLI error: {0}")]
51 CliError(#[from] cli::CliError),
52}
53
54pub 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
122pub 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 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 fs::create_dir(path.join(".git")).unwrap();
202
203 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 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 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}