rust_nrm/utils/
registries.rs

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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
use colored::*;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use tokio::fs;
use toml;

use super::speed_test::{SpeedTestResult, SpeedTester};
use super::Logger;

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Registry {
    pub registry: String,
    pub home: Option<String>,
}

#[derive(Debug, Clone)]
pub struct Store {
    pub registries: HashMap<String, Registry>,
}

impl Store {
    pub async fn load() -> Self {
        let config_path = get_config_path();
        Logger::info(&format!("Config file path: {}", config_path.display()));

        if !config_path.exists() {
            Logger::info("Config file not found, creating default configuration...");
            Self::create_default_config(&config_path).await;
        }

        match fs::read_to_string(&config_path).await {
            Ok(contents) => {
                match toml::from_str(&contents) {
                    Ok(registries) => Self { registries },
                    Err(e) => {
                        Logger::error(&format!("Failed to parse config file: {}", e));
                        Self::create_default_store()
                    }
                }
            }
            Err(e) => {
                Logger::error(&format!("Failed to read config file: {}", e));
                Self::create_default_store()
            }
        }
    }

    async fn create_default_config(config_path: &Path) {
        let default_registries = HashMap::from([
            (
                "npm".to_string(),
                Registry {
                    registry: "https://registry.npmjs.org/".to_string(),
                    home: Some("https://www.npmjs.org".to_string()),
                },
            ),
            (
                "yarn".to_string(),
                Registry {
                    registry: "https://registry.yarnpkg.com/".to_string(),
                    home: Some("https://yarnpkg.com".to_string()),
                },
            ),
            (
                "taobao".to_string(),
                Registry {
                    registry: "https://registry.npmmirror.com/".to_string(),
                    home: Some("https://npmmirror.com/".to_string()),
                },
            ),
            (
                "tencent".to_string(),
                Registry {
                    registry: "https://mirrors.cloud.tencent.com/npm/".to_string(),
                    home: Some("https://mirrors.cloud.tencent.com/npm/".to_string()),
                },
            ),
            (
                "npmMirror".to_string(),
                Registry {
                    registry: "https://skimdb.npmjs.com/registry/".to_string(),
                    home: Some("https://skimdb.npmjs.com".to_string()),
                },
            ),
            (
                "github".to_string(),
                Registry {
                    registry: "https://npm.pkg.github.com/".to_string(),
                    home: Some("https://github.com".to_string()),
                },
            ),
        ]);

        if let Some(parent) = config_path.parent() {
            if !parent.exists() {
                if let Err(e) = fs::create_dir_all(parent).await {
                    Logger::error(&format!("Failed to create config directory: {}", e));
                    return;
                }
            }
        }

        let toml = toml::to_string(&default_registries).unwrap();
        if let Err(e) = fs::write(config_path, toml).await {
            Logger::error(&format!("Failed to write default config: {}", e));
        }
    }

    fn create_default_store() -> Self {
        Self {
            registries: HashMap::from([
                (
                    "npm".to_string(),
                    Registry {
                        registry: "https://registry.npmjs.org/".to_string(),
                        home: Some("https://www.npmjs.org".to_string()),
                    },
                ),
                (
                    "yarn".to_string(),
                    Registry {
                        registry: "https://registry.yarnpkg.com/".to_string(),
                        home: Some("https://yarnpkg.com".to_string()),
                    },
                ),
                (
                    "taobao".to_string(),
                    Registry {
                        registry: "https://registry.npmmirror.com/".to_string(),
                        home: Some("https://npmmirror.com/".to_string()),
                    },
                ),
                (
                    "tencent".to_string(),
                    Registry {
                        registry: "https://mirrors.cloud.tencent.com/npm/".to_string(),
                        home: Some("https://mirrors.cloud.tencent.com/npm/".to_string()),
                    },
                ),
                (
                    "npmMirror".to_string(),
                    Registry {
                        registry: "https://skimdb.npmjs.com/registry/".to_string(),
                        home: Some("https://skimdb.npmjs.com".to_string()),
                    },
                ),
                (
                    "github".to_string(),
                    Registry {
                        registry: "https://npm.pkg.github.com/".to_string(),
                        home: Some("https://github.com".to_string()),
                    },
                ),
            ])
        }
    }

    pub async fn save(&self) {
        let config_path = get_config_path();
        let content = toml::to_string_pretty(&self.registries).unwrap();
        if let Err(e) = fs::write(&config_path, content).await {
            Logger::error(&format!("Failed to save config: {}", e));
        }
    }

    pub async fn get_current_registry(&self, is_local: bool) -> Option<String> {
        let npmrc_path = if is_local {
            ".npmrc".to_string()
        } else {
            dirs::home_dir()
                .map(|path| path.join(".npmrc").to_string_lossy().to_string())
                .expect("Failed to get home directory")
        };

        if Path::new(&npmrc_path).exists() {
            if let Ok(content) = fs::read_to_string(&npmrc_path).await {
                let re = Regex::new(r"(?m)^\s*registry\s*=\s*(.+?)\s*$").unwrap();
                if let Some(captures) = re.captures(&content) {
                    let registry_url = captures.get(1).unwrap().as_str().to_string();
                    // Find registry name by URL
                    for (name, registry) in &self.registries {
                        if registry.registry == registry_url {
                            return Some(name.clone());
                        }
                    }
                }
            }
        }
        None
    }

    pub async fn list_registries(&self) {
        Logger::list("Available registries:");

        // Get current registries
        let current_global = self.get_current_registry(false).await;
        let current_local = self.get_current_registry(true).await;

        for (name, registry) in self.registries.iter() {
            let mut tags = Vec::new();

            if let Some(current_global_name) = &current_global {
                if name == current_global_name {
                    tags.push("[GLOBAL]".white().on_blue());
                }
            }

            if let Some(current_local_name) = &current_local {
                if name == current_local_name {
                    tags.push("[LOCAL]".white().on_green());
                }
            }

            let tags_str = if !tags.is_empty() {
                format!(
                    " {}",
                    tags.iter()
                        .map(|t| t.to_string())
                        .collect::<Vec<_>>()
                        .join(" ")
                )
            } else {
                String::new()
            };

            println!(
                "{} -> {}{}",
                name.green().bold(),
                registry.registry.yellow(),
                tags_str
            );
        }
    }

    pub fn set_current_use(&mut self, name: &str, is_local: bool) {
        if self.registries.contains_key(name) {
            Logger::info(&format!(
                "Switched to registry: {} ({})",
                name.green().bold(),
                if is_local {
                    "local".yellow()
                } else {
                    "global".yellow()
                }
            ));
        } else {
            Logger::error(&format!("Registry not found: {}", name));
        }
    }

    pub async fn test_registry_speed(&self) -> Vec<SpeedTestResult> {
        let tester = SpeedTester::new();
        let registries: Vec<(String, String)> = self
            .registries
            .iter()
            .map(|(name, reg)| (name.clone(), reg.registry.clone()))
            .collect();

        tester.test_all(&registries).await
    }
}

fn get_config_path() -> PathBuf {
    let home = dirs::home_dir().expect("Could not find home directory");
    home.join(".config")
        .join("rust-nrm")
        .join("registries.toml")
}