cargo-port 0.4.0

A TUI for inspecting and managing Rust projects
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
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::SystemTime;

use sysinfo::Disks;
use tui_pane::PERF_LOG_TARGET;
use walkdir::WalkDir;

use super::BackgroundMsg;
use super::cargo_metadata::StreamingScanContext;
use crate::constants::CARGO_LOCK;
use crate::constants::CARGO_TOML;
use crate::constants::GIT_DIR;
use crate::constants::STORAGE_HEADROOM_AMPLE_BYTES;
use crate::constants::STORAGE_HEADROOM_LOW_BYTES;
use crate::constants::TARGET_DIR;
use crate::project::AbsolutePath;
use crate::project::RootItem;

/// Storage capacity shared by every visible project root.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum ProjectStorage {
    /// The volume query has not completed or could not map a project to a volume.
    #[default]
    Unknown,
    /// All visible projects reside on one mounted volume.
    Available(u64),
    /// Visible projects span more than one mounted volume.
    MultipleVolumes,
}

/// How much free space is left on the volume behind
/// [`ProjectStorage::Available`], banded so the project pane's Available row
/// can color it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum StorageHeadroom {
    /// Above [`STORAGE_HEADROOM_AMPLE_BYTES`] free.
    Ample,
    /// [`STORAGE_HEADROOM_LOW_BYTES`] up to [`STORAGE_HEADROOM_AMPLE_BYTES`]
    /// free.
    Low,
    /// Below [`STORAGE_HEADROOM_LOW_BYTES`] free.
    Critical,
}

impl From<u64> for StorageHeadroom {
    /// `available_bytes` is the writable capacity carried by
    /// [`ProjectStorage::Available`].
    fn from(available_bytes: u64) -> Self {
        if available_bytes > STORAGE_HEADROOM_AMPLE_BYTES {
            Self::Ample
        } else if available_bytes >= STORAGE_HEADROOM_LOW_BYTES {
            Self::Low
        } else {
            Self::Critical
        }
    }
}

/// Query the writable capacity shared by `paths` without walking their trees.
pub(crate) fn project_storage(paths: &[AbsolutePath]) -> ProjectStorage {
    let disks = Disks::new_with_refreshed_list();
    let mut volumes = HashMap::new();

    for path in paths {
        let Some(disk) = disks
            .list()
            .iter()
            .filter(|disk| path.starts_with(disk.mount_point()))
            .max_by_key(|disk| disk.mount_point().components().count())
        else {
            return ProjectStorage::Unknown;
        };
        volumes.insert(disk.mount_point().to_path_buf(), disk.available_space());
    }

    project_storage_for_volumes(&volumes)
}

fn project_storage_for_volumes(volumes: &HashMap<PathBuf, u64>) -> ProjectStorage {
    match volumes.len() {
        0 => ProjectStorage::Unknown,
        1 => volumes
            .values()
            .next()
            .copied()
            .map_or(ProjectStorage::Unknown, ProjectStorage::Available),
        _ => ProjectStorage::MultipleVolumes,
    }
}

pub(super) fn spawn_initial_disk_usage(
    scan_context: &StreamingScanContext,
    disk_entries: &[(String, AbsolutePath)],
) {
    for tree in group_disk_usage_trees(disk_entries) {
        spawn_disk_usage_tree(scan_context, tree);
    }
}

#[derive(Clone)]
pub(super) struct DiskUsageTree {
    pub(super) root_abs_path: AbsolutePath,
    pub(super) entries:       Vec<AbsolutePath>,
}

pub(super) fn group_disk_usage_trees(
    disk_entries: &[(String, AbsolutePath)],
) -> Vec<DiskUsageTree> {
    let mut sorted: Vec<AbsolutePath> = disk_entries.iter().map(|(_, p)| p.clone()).collect();
    sorted.sort_by(|left, right| {
        left.components()
            .count()
            .cmp(&right.components().count())
            .then_with(|| left.cmp(right))
    });

    let mut trees: Vec<DiskUsageTree> = Vec::new();
    for abs_path in sorted {
        if let Some(tree) = trees
            .iter_mut()
            .find(|tree| abs_path.starts_with(&tree.root_abs_path))
        {
            tree.entries.push(abs_path);
        } else {
            let root = abs_path.clone();
            trees.push(DiskUsageTree {
                root_abs_path: root,
                entries:       vec![abs_path],
            });
        }
    }
    trees
}

fn spawn_disk_usage_tree(scan_context: &StreamingScanContext, tree: DiskUsageTree) {
    let handle = scan_context.client.handle.clone();
    let sender = scan_context.sender.clone();
    let disk_limit = Arc::clone(&scan_context.disk_limit);

    handle.spawn(async move {
        let queue_started = std::time::Instant::now();
        let Ok(_permit) = disk_limit.acquire_owned().await else {
            return;
        };
        let queue_elapsed = queue_started.elapsed();
        tracing::trace!(
            target: PERF_LOG_TARGET,
            elapsed_ms = tui_pane::perf_log_ms(queue_elapsed.as_millis()),
            abs_path = %tree.root_abs_path.display(),
            rows = tree.entries.len(),
            "tokio_disk_queue_wait"
        );
        let run_started = std::time::Instant::now();
        let tree_for_walk = tree.clone();
        let Ok(results) =
            tokio::task::spawn_blocking(move || dir_sizes_for_tree(&tree_for_walk)).await
        else {
            return;
        };
        tracing::trace!(
            target: PERF_LOG_TARGET,
            elapsed_ms = tui_pane::perf_log_ms(run_started.elapsed().as_millis()),
            abs_path = %tree.root_abs_path.display(),
            rows = tree.entries.len(),
            "tokio_disk_usage"
        );
        let _ = sender.send(BackgroundMsg::DiskUsageBatch {
            root_path: tree.root_abs_path,
            entries:   results,
        });
    });
}

/// Per-project disk size breakdown emitted by the tree walker.
///
/// `total = in_project_target + in_project_non_target` by construction —
/// preserves the `disk_usage_bytes` formula for every owner (target is
/// in-tree) and naturally shrinks for a sharer (its `in_project_target
/// == 0` because the real target lives elsewhere under the workspace's
/// redirected `target_directory`).
///
/// "Is this file inside a `target/` subtree?" uses the literal
/// basename heuristic (any ancestor path component named `target`).
/// A workspace that redirects via `CARGO_TARGET_DIR` /
/// `.cargo/config.toml` ends up with `in_project_target = 0` for its
/// members — the sharer semantics.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct DirSizes {
    pub total:                 u64,
    pub in_project_target:     u64,
    pub in_project_non_target: u64,
    /// Newest mtime among lint-relevant source files (`*.rs`, `Cargo.toml`,
    /// `Cargo.lock`) outside `target/` and `.git/`. Collected from the same
    /// `Metadata` the size walk already reads, so it costs no extra syscalls.
    /// The startup staleness check (`App::kick_off_startup_lints`) compares it
    /// against the last lint's start time. `None` when the tree holds no such
    /// file.
    pub max_source_mtime:      Option<SystemTime>,
}

impl DirSizes {
    fn add_file(&mut self, bytes: u64, file_path: &Path, modified: Option<SystemTime>) {
        self.total += bytes;
        if file_lives_under_target(file_path) {
            self.in_project_target += bytes;
        } else {
            self.in_project_non_target += bytes;
        }
        if let Some(modified) = modified
            && is_lint_source(file_path)
            && !file_in_excluded_dir(file_path)
        {
            self.max_source_mtime = Some(
                self.max_source_mtime
                    .map_or(modified, |current| current.max(modified)),
            );
        }
    }
}

fn file_lives_under_target(path: &Path) -> bool {
    path.components().any(|c| c.as_os_str() == TARGET_DIR)
}

/// Skip `target/` and `.git/` when collecting the newest source mtime — build
/// artifacts and git internals churn on every build/commit and would falsely
/// mark a project stale. Matches the watcher's lint-trigger exclusions.
fn file_in_excluded_dir(path: &Path) -> bool {
    path.components().any(|c| {
        let part = c.as_os_str();
        part == TARGET_DIR || part == GIT_DIR
    })
}

/// The file set whose mtime feeds the startup staleness check — the same set
/// the watcher re-lints on: Rust sources plus the manifest and lockfile.
fn is_lint_source(path: &Path) -> bool {
    match path.file_name().and_then(|name| name.to_str()) {
        Some(CARGO_TOML | CARGO_LOCK) => true,
        _ => path.extension().is_some_and(|ext| ext == "rs"),
    }
}

fn dir_sizes_for_tree(tree: &DiskUsageTree) -> Vec<(AbsolutePath, DirSizes)> {
    let mut totals: HashMap<AbsolutePath, DirSizes> = tree
        .entries
        .iter()
        .map(|abs_path| (abs_path.clone(), DirSizes::default()))
        .collect();

    for entry in WalkDir::new(&tree.root_abs_path).into_iter().flatten() {
        if !entry.file_type().is_file() {
            continue;
        }
        let Ok(metadata) = entry.metadata() else {
            continue;
        };
        let bytes = metadata.len();
        let modified = metadata.modified().ok();
        let file_path = entry.path();
        let mut current = file_path.parent();
        while let Some(dir) = current {
            if let Some(sizes) = totals.get_mut(dir) {
                sizes.add_file(bytes, file_path, modified);
            }
            if dir == tree.root_abs_path.as_path() {
                break;
            }
            current = dir.parent();
        }
    }

    tree.entries
        .iter()
        .map(|abs_path| {
            let sizes = totals.get(abs_path.as_path()).copied().unwrap_or_default();
            (abs_path.clone(), sizes)
        })
        .collect()
}

pub(crate) fn disk_usage_batch_for_item(item: &RootItem) -> Vec<(AbsolutePath, DirSizes)> {
    let entries = item
        .collect_project_info()
        .into_iter()
        .map(|(path, _)| path)
        .collect();
    let tree = DiskUsageTree {
        root_abs_path: item.path().clone(),
        entries,
    };
    dir_sizes_for_tree(&tree)
}

#[cfg(test)]
#[allow(
    clippy::expect_used,
    reason = "tests should panic on unexpected values"
)]
mod tests {
    use super::*;

    #[test]
    fn project_storage_uses_one_volume_capacity() {
        let volumes = HashMap::from([(PathBuf::from("/"), 123_u64)]);

        assert_eq!(
            project_storage_for_volumes(&volumes),
            ProjectStorage::Available(123)
        );
    }

    #[test]
    fn storage_headroom_bands_available_bytes() {
        assert_eq!(
            StorageHeadroom::from(STORAGE_HEADROOM_AMPLE_BYTES + 1),
            StorageHeadroom::Ample
        );
        assert_eq!(
            StorageHeadroom::from(STORAGE_HEADROOM_AMPLE_BYTES),
            StorageHeadroom::Low,
            "the ample threshold itself is still only low headroom"
        );
        assert_eq!(
            StorageHeadroom::from(STORAGE_HEADROOM_LOW_BYTES),
            StorageHeadroom::Low
        );
        assert_eq!(
            StorageHeadroom::from(STORAGE_HEADROOM_LOW_BYTES - 1),
            StorageHeadroom::Critical
        );
    }

    #[test]
    fn project_storage_marks_multiple_volumes_without_summing_them() {
        let volumes = HashMap::from([
            (PathBuf::from("/"), 123_u64),
            (PathBuf::from("/Volumes/external"), 456_u64),
        ]);

        assert_eq!(
            project_storage_for_volumes(&volumes),
            ProjectStorage::MultipleVolumes
        );
    }

    #[test]
    fn group_disk_usage_trees_merges_nested_projects_under_one_root() {
        let trees = group_disk_usage_trees(&[
            ("~/rust/bevy".to_string(), "/home/user/rust/bevy".into()),
            (
                "~/rust/bevy/crates/bevy_ecs".to_string(),
                "/home/user/rust/bevy/crates/bevy_ecs".into(),
            ),
            (
                "~/rust/bevy/tools/ci".to_string(),
                "/home/user/rust/bevy/tools/ci".into(),
            ),
            ("~/rust/hana".to_string(), "/home/user/rust/hana".into()),
        ]);

        assert_eq!(trees.len(), 2);
        assert_eq!(
            trees[0].root_abs_path,
            *crate::project::normalize_test_path(Path::new("/home/user/rust/bevy"))
        );
        assert_eq!(trees[0].entries.len(), 3);
        assert_eq!(
            trees[1].root_abs_path,
            *crate::project::normalize_test_path(Path::new("/home/user/rust/hana"))
        );
        assert_eq!(trees[1].entries.len(), 1);
    }

    #[test]
    fn dir_sizes_for_tree_accumulates_root_and_child_sizes_from_one_walk() {
        let tmp = tempfile::tempdir().expect("create nested disk-usage test tempdir");
        let root: AbsolutePath = tmp.path().join("bevy").into();
        let child: AbsolutePath = root.join("crates").join("bevy_ecs").into();
        std::fs::create_dir_all(&*child).expect("create nested project directory");
        std::fs::write(root.join("root.txt"), vec![0_u8; 5])
            .expect("write root disk-usage fixture file");
        std::fs::write(child.join("child.txt"), vec![0_u8; 7])
            .expect("write child disk-usage fixture file");

        let sizes = dir_sizes_for_tree(&DiskUsageTree {
            root_abs_path: root.clone(),
            entries:       vec![root.clone(), child.clone()],
        });
        let sizes: HashMap<AbsolutePath, DirSizes> = sizes.into_iter().collect();

        assert_eq!(sizes.get(root.as_path()).map(|s| s.total), Some(12));
        assert_eq!(sizes.get(child.as_path()).map(|s| s.total), Some(7));
    }

    #[test]
    fn dir_sizes_for_tree_splits_target_and_non_target_bytes_in_one_pass() {
        // Confirm the single-pass walker partitions bytes between
        // `in_project_target` and `in_project_non_target` based on
        // whether any ancestor path component is named `target`. A file
        // at `<root>/target/debug/foo` is counted as in-target; one at
        // `<root>/src/main.rs` is not.
        let tmp = tempfile::tempdir().expect("create target-split test tempdir");
        let root: AbsolutePath = tmp.path().join("proj").into();
        let src = root.join("src");
        let target_debug = root.join("target").join("debug");
        std::fs::create_dir_all(&src).expect("create source directory");
        std::fs::create_dir_all(&target_debug).expect("create target debug directory");
        std::fs::write(src.join("main.rs"), vec![0_u8; 3]).expect("write source fixture file");
        std::fs::write(target_debug.join("proj"), vec![0_u8; 17])
            .expect("write target fixture file");

        let sizes = dir_sizes_for_tree(&DiskUsageTree {
            root_abs_path: root.clone(),
            entries:       vec![root],
        });
        let (_, entry) = &sizes[0];
        assert_eq!(entry.total, 20, "total bytes = 3 (src) + 17 (target)");
        assert_eq!(entry.in_project_target, 17, "target bytes isolated");
        assert_eq!(
            entry.in_project_non_target, 3,
            "non-target bytes exclude the target/ subtree"
        );
        assert_eq!(
            entry.in_project_target + entry.in_project_non_target,
            entry.total,
            "breakdown always sums to total"
        );
    }

    #[test]
    fn dir_sizes_for_tree_captures_newest_source_mtime_excluding_build_artifacts() {
        let tmp = tempfile::tempdir().expect("create source-mtime test tempdir");
        let root: AbsolutePath = tmp.path().join("proj").into();
        let src = root.join("src");
        let target_debug = root.join("target").join("debug");
        std::fs::create_dir_all(&src).expect("create source directory");
        std::fs::create_dir_all(&target_debug).expect("create target debug directory");

        let base = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000);
        let older = base;
        let newer = base + std::time::Duration::from_secs(45);
        let newest = base + std::time::Duration::from_secs(90);

        let touch = |path: &Path, mtime: SystemTime| {
            std::fs::write(path, b"x").expect("write mtime fixture file");
            let file = std::fs::OpenOptions::new()
                .write(true)
                .open(path)
                .expect("open mtime fixture file");
            file.set_modified(mtime)
                .expect("set mtime fixture timestamp");
        };

        touch(&root.join("Cargo.toml"), older);
        touch(&src.join("lib.rs"), newer);
        // Excluded from the source mtime even though they are newest: a build
        // artifact under `target/` and a non-source file.
        touch(&target_debug.join("proj"), newest);
        touch(&root.join("README.md"), newest);

        let sizes = dir_sizes_for_tree(&DiskUsageTree {
            root_abs_path: root.clone(),
            entries:       vec![root],
        });
        let (_, dir) = &sizes[0];
        assert_eq!(
            dir.max_source_mtime,
            Some(newer),
            "newest source mtime ignores target/ and non-source files"
        );
    }
}