cargo-trim 0.7.0

Binary application to cleanup $CARGO_HOME cache
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
use crate::{
    config_file::ConfigFile,
    crate_detail::CrateDetail,
    dir_path::DirPath,
    utils::{clear_version_value, get_size},
};
use serde::Deserialize;
use std::{
    env,
    ffi::OsStr,
    fs,
    path::{Path, PathBuf},
};

// struct store Cargo.toml file location
pub(crate) struct CargoTomlLocation {
    path: Vec<PathBuf>,
}

impl CargoTomlLocation {
    pub(crate) fn new() -> Self {
        Self { path: Vec::new() }
    }

    pub(crate) fn add_path(&mut self, path: PathBuf) {
        self.path.push(path);
    }

    pub(crate) fn append(&mut self, mut lock_location: Self) {
        self.path.append(&mut lock_location.path);
    }

    pub(crate) fn location_path(&self) -> &Vec<PathBuf> {
        &self.path
    }
}

#[derive(Clone, Deserialize)]
struct LockData {
    package: Option<Vec<Package>>,
}

impl LockData {
    fn package(&self) -> &Option<Vec<Package>> {
        &self.package
    }
}

#[derive(Clone, Deserialize)]
struct Package {
    name: String,
    version: String,
    source: Option<String>,
}

impl Package {
    fn name(&self) -> &str {
        &self.name
    }

    fn version(&self) -> &str {
        &self.version
    }

    fn source(&self) -> &Option<String> {
        &self.source
    }
}

// struct to store all crate list detail with its type
pub(crate) struct CrateList {
    installed_bin: Vec<String>,
    installed_crate_registry: Vec<String>,
    installed_crate_git: Vec<String>,
    old_crate_registry: Vec<String>,
    old_crate_git: Vec<String>,
    used_crate_registry: Vec<String>,
    used_crate_git: Vec<String>,
    orphan_crate_registry: Vec<String>,
    orphan_crate_git: Vec<String>,
    cargo_toml_location: CargoTomlLocation,
}

impl CrateList {
    // create list of all types of crate present in directory
    #[allow(clippy::too_many_lines)]
    pub(crate) fn create_list(
        dir_path: &DirPath,
        config_file: &ConfigFile,
        crate_detail: &mut CrateDetail,
    ) -> Self {
        let bin_dir = dir_path.bin_dir().as_path();
        let cache_dir = dir_path.cache_dir();
        let src_dir = dir_path.src_dir();
        let checkout_dir = dir_path.checkout_dir().as_path();
        let db_dir = dir_path.db_dir().as_path();

        // list installed crates
        let installed_bin = get_installed_bin(bin_dir, crate_detail);
        let installed_crate_registry =
            get_installed_crate_registry(src_dir, cache_dir, crate_detail);
        let installed_crate_git = get_installed_crate_git(checkout_dir, db_dir, crate_detail);

        // list old registry crate
        let mut old_crate_registry = Vec::new();
        let mut version_removed_crate = remove_version(&installed_crate_registry);
        version_removed_crate.sort();
        if !version_removed_crate.is_empty() {
            let mut common_crate_version = Vec::new();
            // check a two version of same crate if crate has two version then it is added
            // to vec and checked to determine old crate version
            for i in 0..(version_removed_crate.len() - 1) {
                let (name, version) = &version_removed_crate[i];
                let (next_name, _) = &version_removed_crate[i + 1];
                if name == next_name {
                    common_crate_version.push((version, i));
                } else {
                    common_crate_version.push((version, i));
                    let mut latest_version = version;
                    // this is used to check which version is latest since we have sorted string so
                    // 0.10.0 will come before 0.9.0. so it need to be done to properly determine
                    // latest version
                    for (common_version, _) in &common_crate_version {
                        if semver::Version::parse(latest_version)
                            < semver::Version::parse(common_version)
                        {
                            latest_version = common_version;
                        }
                    }
                    for (crate_version, position) in &common_crate_version {
                        if crate_version.as_str() != latest_version {
                            old_crate_registry
                                .push(installed_crate_registry.get(*position).unwrap().to_string());
                        }
                    }
                    common_crate_version = vec![]
                }
            }
        }
        old_crate_registry.sort();
        old_crate_registry.dedup();

        // list old git crate
        let mut old_crate_git = Vec::new();
        let mut full_name_list = Vec::new();
        // analyze each crates of db dir and create list of head rev value
        for crates in fs::read_dir(db_dir).expect("failed to read db dir") {
            let entry = crates.unwrap().path();
            let path = entry.as_path();
            let file_name = path.file_name().unwrap().to_str().unwrap();
            let name = file_name.rsplitn(2, '-').collect::<Vec<&str>>();
            let mut rev_value = latest_rev_value(path);
            rev_value.retain(|c| c != '\'');
            let full_name = format!("{}-{}", name[1], rev_value);
            full_name_list.push(full_name)
        }
        for crate_name in &installed_crate_git {
            if !crate_name.contains("-HEAD") {
                // check if crate is in rev value else list that crate as old crate
                if !full_name_list.contains(crate_name) {
                    old_crate_git.push(crate_name.to_string());
                }
            }
        }
        old_crate_git.sort();
        old_crate_git.dedup();

        // list all used crates in rust program
        let mut used_crate_registry = Vec::new();
        let mut used_crate_git = Vec::new();
        let mut cargo_toml_location = CargoTomlLocation::new();
        let config_directory = config_file.directory().to_owned();
        // read a Cargo.lock file and determine out a used registry and git crate
        for path in &config_directory {
            let list_cargo_toml = list_cargo_toml(Path::new(path), &config_file);
            let (mut registry_crate, mut git_crate) = read_content(list_cargo_toml.location_path());
            cargo_toml_location.append(list_cargo_toml);
            used_crate_registry.append(&mut registry_crate);
            used_crate_git.append(&mut git_crate);
        }
        used_crate_registry.sort();
        used_crate_registry.dedup();
        used_crate_git.sort();
        used_crate_registry.dedup();

        // list orphan crates. If crate is not used then it is orphan
        let mut orphan_crate_registry = Vec::new();
        let mut orphan_crate_git = Vec::new();
        for crates in &installed_crate_registry {
            if !used_crate_registry.contains(crates) {
                orphan_crate_registry.push(crates.to_string());
            }
        }
        for crates in &installed_crate_git {
            if crates.contains("-HEAD") {
                let split_installed = crates.rsplitn(2, '-').collect::<Vec<&str>>();
                if used_crate_git.is_empty() {
                    orphan_crate_git.push(crates.to_string());
                }
                let mut used_in_project = false;
                for used in &used_crate_git {
                    if used.contains(split_installed[1]) {
                        used_in_project = true;
                        // Break if found to be used one time no need to check for other
                        break;
                    }
                }
                if !used_in_project {
                    orphan_crate_git.push(crates.to_string());
                }
            } else if !used_crate_git.contains(crates) {
                orphan_crate_git.push(crates.to_string());
            }
        }
        orphan_crate_registry.sort();
        orphan_crate_registry.dedup();
        orphan_crate_git.sort();
        orphan_crate_git.dedup();

        Self {
            installed_bin,
            installed_crate_registry,
            installed_crate_git,
            old_crate_registry,
            old_crate_git,
            used_crate_registry,
            used_crate_git,
            orphan_crate_registry,
            orphan_crate_git,
            cargo_toml_location,
        }
    }

    // provide list of installed bin
    pub(crate) fn installed_bin(&self) -> &Vec<String> {
        &self.installed_bin
    }

    // provide list of installed registry
    pub(crate) fn installed_registry(&self) -> &Vec<String> {
        &self.installed_crate_registry
    }

    // provide list of old registry
    pub(crate) fn old_registry(&self) -> &Vec<String> {
        &self.old_crate_registry
    }

    // provide list of used registry
    pub(crate) fn used_registry(&self) -> &Vec<String> {
        &self.used_crate_registry
    }

    // provide list o orphan registry
    pub(crate) fn orphan_registry(&self) -> &Vec<String> {
        &self.orphan_crate_registry
    }

    // provide list of installed git
    pub(crate) fn installed_git(&self) -> &Vec<String> {
        &self.installed_crate_git
    }

    // provide list of old git
    pub(crate) fn old_git(&self) -> &Vec<String> {
        &self.old_crate_git
    }

    // provide list of used git
    pub(crate) fn used_git(&self) -> &Vec<String> {
        &self.used_crate_git
    }

    // provide list of orphan git
    pub(crate) fn orphan_git(&self) -> &Vec<String> {
        &self.orphan_crate_git
    }

    // list out path of directory which contains cargo lock file
    pub(crate) fn cargo_toml_location(&self) -> &CargoTomlLocation {
        &self.cargo_toml_location
    }
}

// List out cargo.toml file present directories by recursively analyze all
// folder present in directory
fn list_cargo_toml(path: &Path, config_file: &ConfigFile) -> CargoTomlLocation {
    let mut cargo_trim_list = CargoTomlLocation::new();
    if path.exists() {
        if path.is_dir() {
            for entry in std::fs::read_dir(path)
                .expect("failed to read directory while trying to find cargo.toml")
            {
                let sub_path_buf = entry.unwrap().path();
                let sub = sub_path_buf.as_path();
                if sub.is_dir() {
                    if need_to_be_ignored(path, config_file) {
                        continue;
                    }
                    let kids_list = list_cargo_toml(sub, config_file);
                    cargo_trim_list.append(kids_list);
                }
                if sub.is_file() && sub.file_name() == Some(OsStr::new("Cargo.toml")) {
                    cargo_trim_list.add_path(path.to_path_buf());
                }
            }
        } else if path.is_file() && path.file_name() == Some(OsStr::new("Cargo.toml")) {
            cargo_trim_list.add_path(path.to_path_buf());
        }
    }
    cargo_trim_list
}

// check if directory should be scanned for listing crates or not
fn need_to_be_ignored(path: &Path, config_file: &ConfigFile) -> bool {
    let file_name = path.file_name().unwrap().to_str().unwrap();
    let is_file_name_ignored = config_file
        .ignore_file_name()
        .contains(&file_name.to_owned());
    let file_is_hidden = file_name.starts_with('.') && !config_file.scan_hidden_folder();
    let target_dir_name = env::var("CARGO_BUILD_TARGET_DIR").unwrap_or_else(|_| {
        env::var("CARGO_TARGET_DIR").unwrap_or_else(|_| String::from("target"))
    });
    let file_is_target = file_name == target_dir_name && !config_file.scan_target_folder();
    is_file_name_ignored || file_is_hidden || file_is_target
}

// Read out content of cargo.lock file to list out crates present so can be used
// for orphan clean
fn read_content(list: &[PathBuf]) -> (Vec<String>, Vec<String>) {
    let mut present_crate_registry = Vec::new();
    let mut present_crate_git = Vec::new();
    for lock in list.iter() {
        let mut lock_folder = lock.clone();
        lock_folder.push("Cargo.lock");
        if lock_folder.exists() {
            let lock_file = lock_folder
                .to_str()
                .expect("Failed to convert lock_folder to str");
            let file_content = std::fs::read_to_string(lock_file)
                .expect("failed to read cargo lock content to string");
            let cargo_lock_data: LockData =
                toml::from_str(&file_content).expect("Failed to convert to Toml format");
            if let Some(packages) = cargo_lock_data.package() {
                for package in packages {
                    if let Some(source) = package.source() {
                        let name = package.name();
                        let version = package.version();
                        if source.contains("registry+") {
                            let full_name = format!("{}-{}", name, version);
                            present_crate_registry.push(full_name);
                        }
                        if source.contains("git+") {
                            if source.contains("?rev=")
                                || source.contains("?branch=")
                                || source.contains("?tag=")
                            {
                                let split_url: Vec<&str> = if source.contains("?rev=") {
                                    source.split("?rev=").collect()
                                } else if source.contains("?branch=") {
                                    source.split("?branch=").collect()
                                } else {
                                    source.split("?tag=").collect()
                                };
                                let rev_sha: Vec<&str> = split_url[1].split('#').collect();
                                let rev_value = rev_sha[1];
                                let rev_short_form = &rev_value[..=6];
                                let full_name = format!("{}-{}", name, rev_short_form);
                                present_crate_git.push(full_name);
                            } else {
                                let rev_sha: Vec<&str> = source.split('#').collect();
                                let rev_value = rev_sha[1];
                                let rev_short_form = &rev_value[..=6];
                                let full_name = format!("{}-{}", name, rev_short_form);
                                present_crate_git.push(full_name);
                            }
                        }
                    }
                }
            }
        }
    }
    (present_crate_registry, present_crate_git)
}

// Function used to remove version from installed_crate_registry list so can be
// used for old clean flag
fn remove_version(installed_crate_registry: &[String]) -> Vec<(String, String)> {
    let mut removed_version = Vec::new();
    installed_crate_registry.iter().for_each(|crate_full_name| {
        let data = clear_version_value(crate_full_name);
        removed_version.push(data);
    });
    removed_version
}

// list installed bin
fn get_installed_bin(bin_dir: &Path, crate_detail: &mut CrateDetail) -> Vec<String> {
    let mut installed_bin = Vec::new();
    if bin_dir.exists() {
        for entry in fs::read_dir(bin_dir).expect("failed to read bin directory") {
            let entry = entry.unwrap().path();
            let bin_size = get_size(&entry).expect("failed to get size of bin directory");
            let file_name = entry
                .file_name()
                .expect("failed to get file name from bin directory");
            let bin_name = file_name.to_str().unwrap().to_string();
            crate_detail.add_bin(bin_name.to_owned(), bin_size);
            installed_bin.push(bin_name)
        }
    }
    installed_bin.sort();
    installed_bin
}

// list all installed registry crates
fn get_installed_crate_registry(
    src_dir: &Path,
    cache_dir: &Path,
    crate_detail: &mut CrateDetail,
) -> Vec<String> {
    let mut installed_crate_registry = Vec::new();
    // read src dir to get installed crate
    if src_dir.exists() {
        for entry in fs::read_dir(src_dir).expect("failed to read src directory") {
            let registry = entry.unwrap().path();
            for entry in fs::read_dir(registry).expect("failed to read registry folder") {
                let entry = entry.unwrap().path();
                let crate_size = get_size(&entry).expect("failed to get registry crate size");
                let file_name = entry
                    .file_name()
                    .expect("failed to get file name form main entry");
                let crate_name = file_name.to_str().unwrap();
                crate_detail.add_registry_crate_source(crate_name.to_owned(), crate_size);
                installed_crate_registry.push(crate_name.to_owned())
            }
        }
    }
    // read cache dir to get installed crate
    if cache_dir.exists() {
        for entry in fs::read_dir(cache_dir).expect("failed to read cache dir") {
            let registry = entry.unwrap().path();
            for entry in fs::read_dir(registry).expect("failed to read cache dir registry folder") {
                let entry = entry.unwrap().path();
                let file_name = entry
                    .file_name()
                    .expect("failed to get file name from cache dir");
                let crate_size = get_size(&entry).expect("failed to get size");
                let crate_name = file_name.to_str().unwrap();
                let split_name = crate_name.rsplitn(2, '.').collect::<Vec<&str>>();
                crate_detail.add_registry_crate_archive(split_name[1].to_owned(), crate_size);
                installed_crate_registry.push(split_name[1].to_owned());
            }
        }
    }
    installed_crate_registry.sort();
    installed_crate_registry.dedup();
    installed_crate_registry
}

// list all installed git crates
fn get_installed_crate_git(
    checkout_dir: &Path,
    db_dir: &Path,
    crate_detail: &mut CrateDetail,
) -> Vec<String> {
    let mut installed_crate_git = Vec::new();
    if checkout_dir.exists() {
        // read checkout dir to list crate name in form of crate_name-rev_sha
        for entry in fs::read_dir(checkout_dir).expect("failed to read checkout directory") {
            let entry = entry.unwrap().path();
            let path = entry.as_path();
            let file_path = path
                .file_name()
                .expect("failed to obtain checkout directory sub folder file name");
            for git_sha_entry in fs::read_dir(path).expect("failed to read checkout dir sub folder")
            {
                let git_sha_entry = git_sha_entry.unwrap().path();
                let crate_size = get_size(&git_sha_entry).expect("failed to get folder size");
                let git_sha_file_name = git_sha_entry.file_name().expect("failed to get file name");
                let git_sha = git_sha_file_name.to_str().unwrap();
                let file_name = file_path.to_str().unwrap();
                let split_name = file_name.rsplitn(2, '-').collect::<Vec<&str>>();
                let full_name = format!("{}-{}", split_name[1], git_sha);
                crate_detail.add_git_crate_archive(full_name.to_owned(), crate_size);
                installed_crate_git.push(full_name)
            }
        }
    }
    // read a database directory to list a git crate in form of crate_name-HEAD
    if db_dir.exists() {
        for entry in fs::read_dir(db_dir).expect("failed to read db dir") {
            let entry = entry.unwrap().path();
            let crate_size = get_size(&entry).expect("failed to get size of db dir folders");
            let file_name = entry.file_name().expect("failed to get file name");
            let file_name = file_name.to_str().unwrap();
            let split_name = file_name.rsplitn(2, '-').collect::<Vec<&str>>();
            let full_name = format!("{}-HEAD", split_name[1]);
            crate_detail.add_git_crate_source(full_name.to_owned(), crate_size);
            installed_crate_git.push(full_name);
        }
    }
    installed_crate_git.sort();
    installed_crate_git.dedup();
    installed_crate_git
}

// get latest commit rev value from git repository
fn latest_rev_value(path: &Path) -> String {
    let output = std::process::Command::new("git")
        .arg("log")
        .arg("--pretty=format:'%h'")
        .arg("--max-count=1")
        .current_dir(path)
        .output()
        .expect("failed to execute process");
    std::str::from_utf8(&output.stdout)
        .expect("stdout is not utf8")
        .to_string()
}