use anyhow::{bail, Result};
use console::style;
use std::fs;
use std::path::Path;
use crate::utils;
use crate::Config;
pub fn init(project_name: Option<String>) -> Result<()> {
let base = Path::new(".repo-tasks");
if base.exists() {
bail!("Repository already initialized");
}
let statuses = ["todo", "in-progress", "testing", "done"];
for status in &statuses {
let path = base.join("tasks").join(status);
fs::create_dir_all(&path)?;
}
let config = Config::default(project_name.clone());
config.write()?;
let project_display = project_name.unwrap_or_else(|| config.project_name.clone());
utils::success(&format!(
"Initialized repo-tasks for '{}'",
style(&project_display).bold()
));
println!(" {}", style("Created .repo-tasks/config.json").dim());
println!(
" {}",
style("Created task directories: todo, in-progress, testing, done").dim()
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::env;
use tempfile::TempDir;
#[test]
fn test_init_creates_structure() {
let temp_dir = TempDir::new().unwrap();
let original_dir = env::current_dir().unwrap();
env::set_current_dir(&temp_dir).unwrap();
let result = init(Some("test-project".to_string()));
assert!(result.is_ok(), "init failed: {:?}", result.err());
assert!(Path::new(".repo-tasks/tasks/todo").exists());
assert!(Path::new(".repo-tasks/tasks/in-progress").exists());
assert!(Path::new(".repo-tasks/tasks/testing").exists());
assert!(Path::new(".repo-tasks/tasks/done").exists());
assert!(Path::new(".repo-tasks/config.json").exists());
env::set_current_dir(&original_dir).unwrap();
}
#[test]
#[ignore]
fn test_init_fails_if_already_initialized() {
let temp_dir = TempDir::new().unwrap();
let original_dir = env::current_dir().unwrap();
env::set_current_dir(&temp_dir).unwrap();
let first_result = init(Some("test-project".to_string()));
assert!(first_result.is_ok());
let second_result = init(Some("test-project".to_string()));
env::set_current_dir(&original_dir).unwrap();
assert!(second_result.is_err());
assert!(second_result
.unwrap_err()
.to_string()
.contains("already initialized"));
}
}