Skip to main content

dot/commands/
init.rs

1use std::fs;
2use std::path::Path;
3
4use crate::commands::Command;
5use crate::error::{Error, Result};
6use crate::manifest::MANIFEST_FILE;
7
8pub struct InitCommand;
9
10impl InitCommand {
11    pub fn new() -> Self {
12        Self
13    }
14}
15
16impl Default for InitCommand {
17    fn default() -> Self {
18        Self::new()
19    }
20}
21
22impl Command for InitCommand {
23    fn execute(self) -> Result<()> {
24        let path = Path::new(MANIFEST_FILE);
25        if path.exists() {
26            return Err(Error::AlreadyExists(path.to_path_buf()));
27        }
28        fs::write(path, "")?;
29        println!("Initialized empty dot repository");
30        Ok(())
31    }
32}
33
34#[cfg(test)]
35mod tests {
36    use super::*;
37    use tempfile::TempDir;
38
39    /// Test helper that initializes a manifest at a specific path
40    fn init_at(path: &Path) -> Result<()> {
41        if path.exists() {
42            return Err(Error::AlreadyExists(path.to_path_buf()));
43        }
44        fs::write(path, "")?;
45        Ok(())
46    }
47
48    #[test]
49    fn creates_manifest_file() {
50        let temp = TempDir::new().unwrap();
51        let manifest_path = temp.path().join(MANIFEST_FILE);
52
53        init_at(&manifest_path).unwrap();
54
55        assert!(manifest_path.exists());
56    }
57
58    #[test]
59    fn fails_if_manifest_exists() {
60        let temp = TempDir::new().unwrap();
61        let manifest_path = temp.path().join(MANIFEST_FILE);
62        fs::write(&manifest_path, "").unwrap();
63
64        let result = init_at(&manifest_path);
65
66        assert!(matches!(result, Err(Error::AlreadyExists(_))));
67    }
68}