Skip to main content

clone_lib/projectmanager/vscode/
mod.rs

1use serde::{Deserialize, Serialize};
2use std::fs;
3use std::path::PathBuf;
4
5#[derive(Serialize, Deserialize, Debug, Clone)]
6#[serde(rename_all = "camelCase")]
7struct Entry {
8    name: String,
9    root_path: PathBuf,
10    paths: Vec<PathBuf>,
11    tags: Vec<String>,
12    enabled: Option<bool>,
13}
14
15impl Default for Entry {
16    fn default() -> Self {
17        Entry {
18            name: "".to_string(),
19            root_path: "".into(),
20            paths: [].to_vec(),
21            tags: [].to_vec(),
22            enabled: Some(true),
23        }
24    }
25}
26
27pub fn add_project(
28    target_path: PathBuf,
29    workspace: PathBuf,
30    group: String,
31    name: String,
32    debug: bool,
33) {
34    // Read the JSON file
35    let json_data = fs::read_to_string(&target_path).unwrap_or("[]".to_string());
36    let mut entries: Vec<Entry> =
37        serde_json::from_str(&json_data).expect("JSON was not well-formed");
38    let mut code_workspace = workspace.clone();
39    if workspace.extension().is_none() {
40        let mut workspace_path = workspace.clone();
41        workspace_path.set_extension("code-workspace");
42        if workspace_path.exists() {
43            code_workspace = workspace_path;
44        }
45    }
46    let must_add = !entries.iter().any(|e| e.root_path == code_workspace);
47    if debug && !must_add {
48        println!("Entry already exist {:?}.", code_workspace);
49    }
50    // Create a new entry from the provided parameters
51    if must_add {
52        let new_entry = Entry {
53            name,
54            root_path: code_workspace,
55            tags: [group].to_vec(),
56            ..Entry::default()
57        };
58
59        // Append the new entry to the array in the JSON data
60        entries.push(new_entry.clone());
61        // Write the updated JSON data back to the file
62        let updated_data =
63            serde_json::to_string_pretty(&entries).expect("Failed to serialize JSON");
64        let _ = fs::create_dir_all(target_path.parent().unwrap());
65        fs::write(&target_path, updated_data).expect("Unable to write file");
66        if debug {
67            println!("Entry added {:#?}", new_entry);
68        }
69    }
70}