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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
use auth_git2::GitAuthenticator;
use dirs::config_dir;
use git2::{Error, Repository};
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};

pub mod projectmanager;
use crate::projectmanager::{nvim, vscode};

const DEFAULT_REGEX: &str = r"(?m)^(?:https?://|git@)?([^/:]+)[/:]([^/]+)/([^\.]+)(?:\.git)?$";

#[derive(Serialize, Deserialize, Debug)]
#[serde(default)]
pub struct AppConfig {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vscode_path_prefix: Option<String>,
    pub workspaces_dir: PathBuf,
    pub nvim_projectmanager_path: PathBuf,
    pub vscode_projectmanager_path: PathBuf,
    pub regex: String,
}

impl AppConfig {
    pub fn load() -> Self {
        let config_path = Self::config_path();
        if config_path.exists() {
            let config_data = fs::read_to_string(config_path).expect("Unable to read config file");
            toml::from_str(&config_data).expect("Invalid config file")
        } else {
            // Default configuration
            Self::default()
        }
    }

    pub fn save(&self) {
        let config_path = Self::config_path();
        println!("Saving configfile to: {:?}", config_path);
        let config_data = toml::to_string(self).expect("Unable to serialize config");
        fs::create_dir_all(config_path.parent().unwrap())
            .expect("Failed to create config directory");
        fs::write(config_path, config_data).expect("Unable to write config file");
    }

    fn config_path() -> PathBuf {
        config_dir().unwrap().join("clone").join("config.toml")
    }
}

impl Default for AppConfig {
    fn default() -> Self {
        match detect_current_os() {
            "wsl" => {
                if let Some(username) = get_wsl_user_name() {
                    let win_user_home_path = format!("/mnt/c/Users/{}", username);
                    let wsl_user_home_path =
                        std::env::var("HOME").expect("'HOME' environment variable must be set.");
                    let wsl_distro_name = std::env::var("WSL_DISTRO_NAME").expect(
                        "'WSL_DISTRO_NAME' environment variable must be set in WSL environment.",
                    );

                    AppConfig {
                            vscode_path_prefix: Some(format!("vscode-remote://wsl+{}", wsl_distro_name)),
                            workspaces_dir: format!("{}/workspaces", wsl_user_home_path).into(),
                            nvim_projectmanager_path: format!("{}/.local/share/nvim/lazy/projectmgr.nvim/projects.json", wsl_user_home_path).into(),
                            vscode_projectmanager_path: format!("{}/AppData/Roaming/Code/User/globalStorage/alefragnani.project-manager/projects.json", win_user_home_path).into(),
                            regex: DEFAULT_REGEX.to_string()
                        }
                } else {
                    panic!("Cannot get WSL username in a WSL environment, that must never happen, that mean powershell.exe didn't exist or didn't provide the environment variable $env:USERNAME.");
                }
            }
            "macos" => {
                let user_home_path =
                    std::env::var("HOME").expect("'HOME' environment variable must be set.");
                AppConfig {
                    vscode_path_prefix: None,
                    workspaces_dir: format!("{}/workspaces", user_home_path).into(),
                    nvim_projectmanager_path: format!("{}/.local/share/nvim/lazy/projectmgr.nvim/projects.json", user_home_path).into(),
                    vscode_projectmanager_path: format!("{}/Library/Application Support/Code/User/globalStorage/alefragnani.project-manager/projects.json", user_home_path).into(),
                    regex: DEFAULT_REGEX.to_string()
                }
            }
            "windows" => {
                let user_home_path = std::env::var("USERPROFILE")
                    .expect("'USERPROFILE' environment variable must be set.");
                AppConfig {
                    vscode_path_prefix: None,
                        workspaces_dir: format!("{}/workspaces", user_home_path).into(),
                        nvim_projectmanager_path: format!("{}/AppData/Roaming/nvim/", user_home_path).into(),
                        vscode_projectmanager_path: format!("{}/AppData/Roaming/Code/User/globalStorage/alefragnani.project-manager/projects.json", user_home_path).into(),
                        regex: DEFAULT_REGEX.to_string()
                    }
            }
            _linux => {
                let user_home_path =
                    std::env::var("HOME").expect("'HOME' environment variable must be set.");
                AppConfig {
                    vscode_path_prefix: None,
                    workspaces_dir: format!("{}/workspaces", user_home_path).into(),
                    nvim_projectmanager_path: format!("{}/.local/share/nvim/lazy/projectmgr.nvim/projects.json", user_home_path).into(),
                    vscode_projectmanager_path:format!("{}/.config/Code/User/globalStorage/alefragnani.project-manager/projects.json", user_home_path).into(),
                    regex: DEFAULT_REGEX.to_string()
                }
            }
        }
    }
}

pub fn parse_repo_url(url: &str, regex: &str) -> Result<(String, String, String), ()> {
    let parser = Regex::new(regex).unwrap();
    if let Some(result) = parser.captures(url) {
        let host = &result[1];
        let group = &result[2];
        let name = &result[3];
        Ok((host.to_string(), group.to_string(), name.to_string()))
    } else {
        Err(())
    }
}

pub fn clone_repo(url: &str, repo_path: &Path) -> Result<Repository, Error> {
    if repo_path.exists() {
        Err(Error::new(
            git2::ErrorCode::Exists,
            git2::ErrorClass::Filesystem,
            format!("repository already exist at {:?}", repo_path),
        ))
    } else {
        //fs::create_dir_all(&repo_path).expect("Failed to create directories");
        let auth = GitAuthenticator::default();
        match auth.clone_repo(url, &repo_path) {
            Ok(repo) => {
                println!("Cloned into {:?}", repo_path);
                Ok(repo)
            }
            Err(e) => Err(e),
        }
    }
}

pub fn detect_current_os() -> &'static str {
    match std::env::consts::OS {
        "linux" => match detect_wsl_with_envs() {
            true => "wsl",
            false => "linux",
        },
        os => os,
    }
}

fn _detect_wsl_with_powershell() -> bool {
    if let Some(_output) = get_wsl_user_name() {
        true
    } else {
        false
    }
}

fn get_wsl_user_name() -> Option<String> {
    if let Ok(output_utf8) = std::process::Command::new("powershell.exe")
        .arg("-c")
        .arg("echo $env:USERNAME")
        .output()
    {
        if let Ok(output) = String::from_utf8(output_utf8.stdout) {
            Some(output.trim().to_string())
        } else {
            None
        }
    } else {
        None
    }
}

fn detect_wsl_with_envs() -> bool {
    std::env::var("WSL_DISTRO_NAME").is_ok()
}

pub fn add_project_to_nvim(
    target_path: PathBuf,
    workspace: PathBuf,
    host: String,
    group: String,
    name: String,
    debug: bool,
) {
    nvim::add_project(target_path, workspace, host, group, name, debug)
}
pub fn add_project_to_vscode(
    target_path: PathBuf,
    workspace: PathBuf,
    host: String,
    group: String,
    name: String,
    debug: bool,
) {
    vscode::add_project(target_path, workspace, host, group, name, debug)
}