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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use anyhow::Result;
use serde_derive::{Deserialize, Serialize};
use url::Url;
#[derive(Debug, Deserialize)]
pub struct Cargo {
pub package: Option<Package>,
}
impl Cargo {
/// 读取 Cargo.toml 解析成 Cargo
///
/// # Example
///
/// ```no_run
/// mod config
///
/// use std::path::Path;
/// use anyhow::Result
/// use config::Cargo
///
/// fn main() -> Result<()> {
/// let path = Path::new("Cargo.toml");
/// let cargo = Cargo::from_path(path)?;
///
/// Ok(())
/// }
/// ```
pub fn from_path<P>(path: P) -> Result<Cargo>
where
P: AsRef<Path>,
{
let s = fs::read_to_string(path)?;
let cargo: Cargo = toml::from_str(&s)?;
Ok(cargo)
}
}
#[derive(Debug, Deserialize)]
pub struct CargoLock {
pub package: Option<Vec<Package>>,
}
impl CargoLock {
/// 读取 Cargo.lock 解析成 CargoLock
///
/// # Example
///
/// ```no_run
/// mod config
///
/// use std::path::Path;
/// use anyhow::Result
/// use config::CargoLock
///
/// fn main() -> Result<()> {
/// let path = Path::new("Cargo.lock");
/// let cargo_lock = CargoLock::from_path(path)?;
///
/// Ok(())
/// }
/// ```
pub fn from_path<P>(path: P) -> Result<CargoLock>
where
P: AsRef<Path>,
{
let s = fs::read_to_string(path)?;
let cargo_lock: CargoLock = toml::from_str(&s)?;
Ok(cargo_lock)
}
}
#[derive(Debug, Deserialize)]
pub struct Package {
// rust 第三方包名称
pub name: String,
// rust 第三方包版本
pub version: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Workspace {
// 生成 code-workspace 中的 "folder" 配置
pub folders: Option<Vec<WorkspaceFolder>>,
// 生成 code-workspace 中的 "settings" 配置
pub settings: Option<WorkspaceSettings>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CargoCfg {
source: Option<HashMap<String, Source>>,
}
impl CargoCfg {
/// 读取 $HOME/.cargo/config.toml 解析成 CargoCfg
///
/// # Example
///
/// ```no_run
/// mod config
///
/// use std::path::Path;
/// use anyhow::Result
/// use config::CargoCfg
///
/// fn main() -> Result<()> {
/// let cargo_lock = CargoCfg::read()?;
///
/// Ok(())
/// }
/// ```
pub fn read() -> Result<CargoCfg> {
let home = dirs::home_dir().expect("no home directory");
let mut path = home.join(".cargo").join("config.toml");
if !path.exists() {
path = home.join(".cargo").join("config")
}
let s = fs::read_to_string(path)?;
let cargo_cfg: CargoCfg = toml::from_str(&s)?;
Ok(cargo_cfg)
}
pub fn registry(&self) -> Option<String> {
if self.source.is_none() {
return None;
}
if let Some(source) = &self.source {
let value = source.get("crates-io");
if let Some(registry) = value {
let replace_with = registry.replace_with.clone().unwrap_or("".to_string());
if replace_with == "" {
if let Some(host) = ®istry.registry {
let url = Url::parse(&host).ok()?;
return url.host_str().and_then(|s| Some(s.to_string()));
}
} else {
let replace_source = source.get(&replace_with);
if let Some(registry) = replace_source {
let url = Url::parse(®istry.registry.clone().unwrap_or("".to_string()))
.ok()?;
return url.host_str().and_then(|s| Some(s.to_string()));
}
}
}
}
None
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Source {
registry: Option<String>,
#[serde(rename(deserialize = "replace-with"))]
replace_with: Option<String>,
}
impl Workspace {
/// # Example
/// ```no_run
/// mod config
///
/// use std::path::{Path, PathBuf};
/// use anyhow::{Ok, Result}
/// use config::{CargoLock, Workspace}
///
/// fn main() -> Result<()> {
/// let path = Path::new("Cargo.lock");
/// let cargo_lock = CargoLock::from_path(path)?;
///
/// let rustup = PathBuf::from_str(rustup_path);
/// let registry = PathBuf::from_str(registry_path);
///
/// let ws = Workspace::from(rustup, registry, &cargo_lock)?;
///
/// OK(())
/// }
/// ```
pub fn from<P>(rustup: P, registry: P, lock: &CargoLock) -> Result<Workspace>
where
P: AsRef<Path>,
{
let mut folders: Vec<WorkspaceFolder> = Vec::new();
let mut deps = HashMap::new();
let mut file_excludes = HashMap::new();
let mut rust_exclude_dirs = Vec::new();
if registry.as_ref().exists() {
if let Some(ref packages) = lock.package {
for pack in packages {
let pack_name = pack.name.clone() + "-" + pack.version.as_str();
deps.insert(pack_name, ());
}
}
let rustup_string = rustup.as_ref().to_path_buf().to_string_lossy().to_string();
let registry_string = registry
.as_ref()
.to_path_buf()
.clone()
.to_string_lossy()
.to_string();
for p in fs::read_dir(registry.as_ref())? {
let entry = p.unwrap();
let file_name = entry.file_name().to_string_lossy().to_string();
if !deps.contains_key(&file_name) {
file_excludes.insert(file_name.clone(), true);
}
}
rust_exclude_dirs.push(registry_string.clone());
rust_exclude_dirs.push(rustup_string.clone());
folders.push(WorkspaceFolder {
name: "".to_string(),
path: ".".to_string(),
});
folders.push(WorkspaceFolder {
name: "Stdlib".to_string(),
path: rustup_string.clone(),
});
folders.push(WorkspaceFolder {
name: "External Libraries".to_string(),
path: registry_string.clone(),
});
}
let settings = WorkspaceSettings {
file_excludes: Some(file_excludes),
rust_exclude_dirs: Some(rust_exclude_dirs),
};
let ws = Workspace {
folders: Some(folders),
settings: Some(settings),
};
Ok(ws)
}
/// # Example
/// ```no_run
/// mod config
///
/// use std::path::{Path, PathBuf};
/// use anyhow::{Ok, Result}
/// use config::{CargoLock, Workspace}
///
/// fn main() -> Result<()> {
/// let path = Path::new("Cargo.lock");
/// let cargo_lock = CargoLock::from_path(path)?;
///
/// let rustup = PathBuf::from_str(rustup_path);
/// let registry = PathBuf::from_str(registry_path);
///
/// let ws = Workspace::from(rustup, registry, &cargo_lock)?;
/// let target = "simple.code-workspace";
/// ws.apply(target.to_string())?;
///
/// OK(())
/// }
/// ```
pub fn apply(&self, path: String) -> Result<()> {
let text = serde_json::to_string_pretty(&self)?;
fs::write(path, text)?;
Ok(())
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct WorkspaceFolder {
pub name: String,
pub path: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct WorkspaceSettings {
// 因为 vscode workspace 配置文件中不支持多级目录,
// 如果要实现和 Clion 相同的功能,需要改变思路,先
// 在 folders 中加载本地所有包,再使用 "files.exclude"
// 忽略非本项目的其他包。
#[serde(rename = "files.exclude")]
file_excludes: Option<HashMap<String, bool>>,
// 生成 rust-analyzer.files.excludeDirs 配置
// 因为工作区中加载所有 .cargo 目录下的第三方包,
// 会导致 rust-analyzer 在项目启动加载所有包,
// 使用该配置告诉 rust-analyzer 忽略加载
#[serde(rename = "rust-analyzer.files.excludeDirs")]
rust_exclude_dirs: Option<Vec<String>>,
}
mod test {
#[allow(unused)]
use std::path::Path;
#[allow(unused)]
use crate::config::{Cargo, CargoCfg, CargoLock, Workspace};
#[test]
fn test_from_cargo() {
let path = Path::new("Cargo.toml");
let cargo = Cargo::from_path(path).unwrap();
assert!(cargo.package.is_some());
}
#[test]
fn test_from_cargo_lock() {
let path = Path::new("Cargo.lock");
let cargo = CargoLock::from_path(path).unwrap();
assert!(cargo.package.is_some());
}
#[test]
fn test_read_cargo_config() {
let cargo = CargoCfg::read().unwrap();
println!("{:?}", cargo.registry());
}
#[test]
fn test_from_workspace() {
let rustup = Path::new("rustup").to_path_buf();
let registry = Path::new("registry").to_path_buf();
let path = Path::new("Cargo.lock");
let cargo = CargoLock::from_path(path).unwrap();
let ws = Workspace::from(rustup, registry, &cargo).unwrap();
assert!(ws.folders.is_some());
assert!(ws.settings.is_some());
}
#[test]
fn test_from_workspace_failure() {
let ws =
Workspace::from(Path::new(""), Path::new(""), &CargoLock { package: None }).unwrap();
let folders = ws.folders;
assert!(folders.unwrap().is_empty());
let settings = ws.settings.unwrap();
assert!(settings.file_excludes.unwrap().is_empty());
assert!(settings.rust_exclude_dirs.unwrap().is_empty());
}
}