diff --git a/crates/cli/src/init.rs b/crates/cli/src/init.rs index c36deb08..ca1b68f2 100644 --- a/crates/cli/src/init.rs +++ b/crates/cli/src/init.rs @@ -1,27 +1,28 @@ -use std::path::PathBuf; - use kxio::fs::FileSystem; pub fn run(fs: FileSystem) { let file_name = ".git-next.toml"; - let pathbuf = PathBuf::from(file_name); - let Ok(exists) = fs.path_exists(&pathbuf) else { - eprintln!("Could not check if file exist: {}", file_name); - return; - }; - if exists { - eprintln!( - "The configuration file already exists at {} - not overwritting it.", - file_name - ); - } else { - match fs.file_write(&pathbuf, include_str!("../../../default.toml")) { - Ok(_) => { - println!("Created a default configuration file at {}", file_name); - } - Err(e) => { - eprintln!("Failed to write to the configuration file: {}", e) + let pathbuf = fs.base().join(file_name); + match fs.path_exists(&pathbuf) { + Ok(exists) => { + if exists { + eprintln!( + "The configuration file already exists at {} - not overwritting it.", + file_name + ); + } else { + match fs.file_write(&pathbuf, include_str!("../../../default.toml")) { + Ok(_) => { + println!("Created a default configuration file at {}", file_name); + } + Err(e) => { + eprintln!("Failed to write to the configuration file: {}", e) + } + } } } + Err(err) => { + eprintln!("Could not check if file exist: {} - {err:?}", file_name); + } } } diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index b16f13b2..e067bed2 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -1,5 +1,8 @@ mod init; +#[cfg(test)] +mod tests; + use std::path::PathBuf; use clap::Parser; diff --git a/crates/cli/src/tests.rs b/crates/cli/src/tests.rs new file mode 100644 index 00000000..0980089c --- /dev/null +++ b/crates/cli/src/tests.rs @@ -0,0 +1,40 @@ +type TestResult = Result<(), Box>; + +mod init { + use super::*; + #[test] + fn should_not_update_file_if_it_exists() -> TestResult { + let fs = kxio::fs::temp()?; + let file = fs.base().join(".git-next.toml"); + fs.file_write(&file, "contents")?; + + crate::init::run(fs.clone()); + + assert_eq!( + fs.file_read_to_string(&file)?, + "contents", + "The file has been changed" + ); + + Ok(()) + } + + #[test] + fn should_create_default_file_if_not_exists() -> TestResult { + let fs = kxio::fs::temp()?; + + crate::init::run(fs.clone()); + + let file = fs.base().join(".git-next.toml"); + + assert!(fs.path_exists(&file)?, "The file has not been created"); + + assert_eq!( + fs.file_read_to_string(&file)?, + include_str!("../../../default.toml"), + "The file does not match the default template" + ); + + Ok(()) + } +}