snip_cli/actions/
list_snippets.rs

1use crate::models::identifier_model::Identifier;
2use crate::models::snippet_model::Snippet;
3use anyhow::Context;
4use std::collections::HashMap;
5use std::fs;
6use std::path::Path;
7
8pub fn list_snippets(file_path: &str, list_option: Identifier) -> anyhow::Result<String> {
9    let path = Path::new(file_path);
10
11    let snippets: HashMap<String, Snippet> = if path.exists() && path.metadata()?.len() > 0 {
12        let file_contents =
13            fs::read_to_string(file_path).context("Failed to read the snippets file")?;
14        serde_json::from_str(&file_contents).context("Failed to parse the snippets file")?
15    } else {
16        return Err(anyhow::anyhow!("Snippet file not found or is empty"));
17    };
18    let mut output = String::new();
19    match list_option {
20        Identifier::Key => {
21            for key in snippets.keys() {
22                output.push_str(&format!("{}\n", key));
23            }
24        }
25        Identifier::Prefix => {
26            for snippet in snippets.values() {
27                output.push_str(&format!("{}\n", snippet.prefix));
28            }
29        }
30    }
31
32    Ok(output)
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38    use anyhow::Result;
39    use std::collections::HashMap;
40    use std::fs;
41    use tempfile::NamedTempFile;
42
43    #[test]
44    fn test_list_snippets() -> Result<()> {
45        let test_file = NamedTempFile::new()?;
46        let test_path = test_file.path().to_str().unwrap();
47
48        // Setup test snippets
49        let snippets = HashMap::from([
50            (
51                "key1".to_string(),
52                Snippet {
53                    prefix: "prefix1".to_string(),
54                    description: "desc1".to_string(),
55                    body: vec!["body1".to_string()],
56                },
57            ),
58            (
59                "key2".to_string(),
60                Snippet {
61                    prefix: "prefix2".to_string(),
62                    description: "desc2".to_string(),
63                    body: vec!["body2".to_string()],
64                },
65            ),
66        ]);
67        fs::write(test_path, serde_json::to_string(&snippets)?)?;
68
69        // Call the list_snippets function
70        let output = list_snippets(test_path, Identifier::Key)?;
71
72        // Assert the results
73        assert!(output.contains("key1"));
74        assert!(output.contains("key2"));
75
76        Ok(())
77    }
78}