1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use tokio::fs;

use crate::dotfile::Dotfile;

#[derive(Debug, Serialize, Deserialize)]
pub struct SlfIndex {
    dotfiles: HashMap<String, Dotfile>,
    target_directory: PathBuf,
}

impl SlfIndex {
    pub async fn new<P: AsRef<Path>>(target_directory: P) -> Result<Self> {
        let target_directory = target_directory.as_ref().to_path_buf();
        fs::create_dir_all(&target_directory)
            .await
            .context("Failed to create target directory")?;

        Ok(Self {
            dotfiles: HashMap::new(),
            target_directory,
        })
    }
    pub async fn add_ref<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
        let path_str = path
            .as_ref()
            .to_str()
            .ok_or_else(|| anyhow::anyhow!("Invalid path"))?;
        let expanded_path = shellexpand::tilde(path_str);
        let path_buf = PathBuf::from(expanded_path.as_ref());

        if !path_buf.exists() {
            return Err(anyhow::anyhow!(
                "File does not exist: {}",
                path_buf.display()
            ));
        }

        let dotfile = Dotfile::new(path_buf.clone(), self.target_directory.clone()).await?;
        let name = dotfile.name().to_string();

        if self.dotfiles.contains_key(&name) {
            return Err(anyhow::anyhow!(
                "Dotfile already exists: {}",
                path_buf.display()
            ));
        }

        self.dotfiles.insert(name, dotfile);
        Ok(())
    }

    pub fn remove_ref(&mut self, name: &str) -> Result<()> {
        // let name = name.as_ref();
        self.dotfiles
            .remove(name)
            .ok_or_else(|| anyhow::anyhow!("Dotfile not found: {}", name))?;
        Ok(())
    }

    pub fn list(&self) -> impl Iterator<Item = (&String, &Dotfile)> {
        let mut sorted_keys: Vec<_> = self.dotfiles.keys().collect();
        sorted_keys.sort();
        sorted_keys
            .into_iter()
            .map(|key| (key, &self.dotfiles[key]))
    }

    pub async fn do_sync(&self) -> Result<()> {
        let target_dir = self.target_directory.clone();

        fs::create_dir_all(&target_dir)
            .await
            .context("Failed to create output directory")?;

        for dotfile in self.dotfiles.values() {
            let target_path = target_dir.join(dotfile.name());
            dotfile
                .create_symlink()
                .await
                .with_context(|| format!("Failed to sync dotfile: {}", dotfile.name()))?;
            println!(
                "Synced: {} -> {}",
                dotfile.source().display(),
                target_path.display()
            );
        }
        Ok(())
    }
}