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
use std::fs;
use std::path::PathBuf;

use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(default)]
pub struct Entry {
    commandexit: Option<String>,
    commandstart: Option<String>,
    path: PathBuf,
    name: String,
    current: u8,
}

impl Default for Entry {
    fn default() -> Self {
        Entry {
            name: "".to_string(),
            path: PathBuf::from(""),
            current: 0,
            commandstart: Some("NvimTreeToggle".to_string()),
            commandexit: Some("".to_string()),
        }
    }
}

pub fn add_project(
    target_path: PathBuf,
    workspace: PathBuf,
    host: String,
    group: String,
    name: String,
    debug: bool,
) {
    // Read the JSON file
    let json_data = fs::read_to_string(&target_path).unwrap_or("[]".to_string());

    let mut entries: Vec<Entry> =
        serde_json::from_str(&json_data).expect("JSON was not well-formed");
    let must_add = !entries.iter().any(|e| e.path == workspace);

    if debug && !must_add {
        println!("Entry already exist {:?}.", workspace);
    }
    // Create a new entry from the provided parameters
    if must_add {
        // Create a new entry from the provided parameters
        let new_entry = Entry {
            name: format!("{}/{}/{}", host, group, name),
            path: workspace,
            ..Entry::default()
        };

        // Append the new entry to the array in the JSON data
        entries.push(new_entry.clone());

        // Write the updated JSON data back to the file
        let updated_data =
            serde_json::to_string_pretty(&entries).expect("Failed to serialize JSON");
        let _ = fs::create_dir_all(&target_path.parent().unwrap());
        fs::write(&target_path, updated_data).expect("Unable to write file");
        if debug {
            println!("Entry added {:#?}", new_entry);
        }
    }
}