cargo-port 0.0.2

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
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
use std::collections::HashMap;
use std::fmt;
use std::io;
use std::path::Path;
use std::process::Command;

use serde::Deserialize;
use serde::Serialize;
use toml::Table;
use toml::Value;

/// Whether a project is a plain clone or a fork (has an "upstream" remote).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum GitOrigin {
    /// A local-only repo (no origin remote).
    Local,
    /// A plain git clone (has "origin" remote).
    Clone,
    /// A fork (has an "upstream" remote).
    Fork,
}

impl GitOrigin {
    pub const fn icon(self) -> &'static str {
        match self {
            Self::Local => "",
            Self::Clone => "",
            Self::Fork => "",
        }
    }

    pub const fn label(self) -> &'static str {
        match self {
            Self::Local => "local",
            Self::Clone => "clone",
            Self::Fork => "fork",
        }
    }
}

/// Git metadata for a project: origin type, owner, repo URL, and current branch.
#[derive(Debug, Clone, Serialize)]
pub struct GitInfo {
    /// Whether this is a clone or a fork.
    pub origin:              GitOrigin,
    /// The current branch name.
    pub branch:              Option<String>,
    /// The GitHub/GitLab owner (e.g. "natepiano").
    pub owner:               Option<String>,
    /// The HTTPS URL to the repository.
    pub url:                 Option<String>,
    /// ISO 8601 date of the first commit (inception).
    pub first_commit:        Option<String>,
    /// ISO 8601 date of the most recent commit.
    pub last_commit:         Option<String>,
    /// Commits ahead and behind the upstream tracking branch (ahead, behind).
    pub ahead_behind:        Option<(usize, usize)>,
    /// The repo's default branch name resolved from `origin/HEAD`.
    pub default_branch:      Option<String>,
    /// Commits ahead and behind `origin/{default_branch}`.
    pub ahead_behind_origin: Option<(usize, usize)>,
    /// Commits ahead and behind the local `{default_branch}`.
    pub ahead_behind_local:  Option<(usize, usize)>,
}

impl GitInfo {
    /// Detect git info for a project directory.
    pub fn detect(project_dir: &Path) -> Option<Self> {
        if !project_dir.join(".git").exists() {
            return None;
        }

        let remote_output = Command::new("git")
            .args(["remote"])
            .current_dir(project_dir)
            .output()
            .ok()?;
        let remotes = String::from_utf8_lossy(&remote_output.stdout);
        let has_origin = remotes.lines().any(|line| line.trim() == "origin");
        let has_upstream = remotes.lines().any(|line| line.trim() == "upstream");
        let origin = if !has_origin {
            GitOrigin::Local
        } else if has_upstream {
            GitOrigin::Fork
        } else {
            GitOrigin::Clone
        };

        let url_output = Command::new("git")
            .args(["remote", "get-url", "origin"])
            .current_dir(project_dir)
            .output()
            .ok()?;
        let raw_url = String::from_utf8_lossy(&url_output.stdout)
            .trim()
            .to_string();

        let (owner, url) = parse_remote_url(&raw_url);

        let branch = Command::new("git")
            .args(["rev-parse", "--abbrev-ref", "HEAD"])
            .current_dir(project_dir)
            .output()
            .ok()
            .and_then(|o| {
                let b = String::from_utf8_lossy(&o.stdout).trim().to_string();
                if b.is_empty() { None } else { Some(b) }
            });

        let ahead_behind = parse_ahead_behind(project_dir, "HEAD...@{upstream}");

        // Resolve the repo's default branch from origin/HEAD (e.g. "origin/main").
        let default_branch = Command::new("git")
            .args(["symbolic-ref", "refs/remotes/origin/HEAD", "--short"])
            .current_dir(project_dir)
            .output()
            .ok()
            .and_then(|o| {
                let s = String::from_utf8_lossy(&o.stdout).trim().to_string();
                // Comes back as "origin/main" — strip the "origin/" prefix.
                s.strip_prefix("origin/")
                    .filter(|b| !b.is_empty())
                    .map(str::to_string)
            });

        // Compare HEAD against the default branch when it differs from the current branch.
        let not_on_default = default_branch
            .as_deref()
            .filter(|db| branch.as_deref() != Some(*db));
        let ahead_behind_origin = not_on_default
            .and_then(|db| parse_ahead_behind(project_dir, &format!("HEAD...origin/{db}")));
        let ahead_behind_local =
            not_on_default.and_then(|db| parse_ahead_behind(project_dir, &format!("HEAD...{db}")));

        let first_commit = Command::new("git")
            .args(["log", "--reverse", "--format=%aI", "--diff-filter=A"])
            .current_dir(project_dir)
            .output()
            .ok()
            .and_then(|o| {
                String::from_utf8_lossy(&o.stdout)
                    .lines()
                    .next()
                    .filter(|s| !s.is_empty())
                    .map(std::string::ToString::to_string)
            });

        let last_commit = Command::new("git")
            .args(["log", "-1", "--format=%aI"])
            .current_dir(project_dir)
            .output()
            .ok()
            .and_then(|o| {
                let s = String::from_utf8_lossy(&o.stdout).trim().to_string();
                if s.is_empty() { None } else { Some(s) }
            });

        Some(Self {
            origin,
            branch,
            owner,
            url,
            first_commit,
            last_commit,
            ahead_behind,
            default_branch,
            ahead_behind_origin,
            ahead_behind_local,
        })
    }
}

/// Parse `git rev-list --left-right --count` output into `(ahead, behind)`.
fn parse_ahead_behind(project_dir: &Path, revspec: &str) -> Option<(usize, usize)> {
    Command::new("git")
        .args(["rev-list", "--left-right", "--count", revspec])
        .current_dir(project_dir)
        .output()
        .ok()
        .and_then(|o| {
            let s = String::from_utf8_lossy(&o.stdout);
            let mut parts = s.trim().split('\t');
            let ahead = parts.next()?.parse::<usize>().ok()?;
            let behind = parts.next()?.parse::<usize>().ok()?;
            Some((ahead, behind))
        })
}

/// Extract the owner and HTTPS URL from a git remote URL.
///
/// Handles:
/// - `https://github.com/owner/repo.git`
/// - `git@github.com:owner/repo.git`
fn parse_remote_url(raw: &str) -> (Option<String>, Option<String>) {
    // SSH: git@github.com:owner/repo.git
    if let Some(after_at) = raw.strip_prefix("git@")
        && let Some((host, path)) = after_at.split_once(':')
    {
        let path = path.strip_suffix(".git").unwrap_or(path);
        let owner = path.split('/').next().map(|s| (*s).to_string());
        let url = format!("https://{host}/{path}");
        return (owner, Some(url));
    }

    // HTTPS: https://github.com/owner/repo.git
    if raw.starts_with("https://") || raw.starts_with("http://") {
        let clean = raw.strip_suffix(".git").unwrap_or(raw);
        // Extract owner from path: https://host/owner/repo
        let owner = clean.split('/').nth(3).map(|s| (*s).to_string());
        return (owner, Some((*clean).to_string()));
    }

    (None, None)
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ProjectType {
    Binary,
    Library,
    ProcMacro,
    BuildScript,
}

impl fmt::Display for ProjectType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Binary => write!(f, "binary"),
            Self::Library => write!(f, "library"),
            Self::ProcMacro => write!(f, "proc-macro"),
            Self::BuildScript => write!(f, "build-script"),
        }
    }
}

/// A group of examples in a subdirectory, or root-level examples (empty category).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExampleGroup {
    /// Subdirectory name, or empty for root-level examples.
    pub category: String,
    pub names:    Vec<String>,
}

/// Serde default helper that returns `true`.
const fn default_true() -> bool { true }

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RustProject {
    /// Display path (e.g. `~/rust/bevy`).
    pub path:          String,
    /// Absolute filesystem path for operations that need to access the project on disk.
    #[serde(skip)]
    pub abs_path:      String,
    pub name:          Option<String>,
    pub version:       Option<String>,
    pub description:   Option<String>,
    pub worktree_name: Option<String>,
    /// Whether this project has a `[workspace]` section.
    #[serde(default)]
    pub is_workspace:  bool,
    pub types:         Vec<ProjectType>,
    pub examples:      Vec<ExampleGroup>,
    pub benches:       Vec<String>,
    pub test_count:    usize,
    /// Whether this project is a Rust project (has `Cargo.toml`).
    #[serde(default = "default_true")]
    pub is_rust:       bool,
}

impl RustProject {
    /// Total number of examples across all groups.
    pub fn example_count(&self) -> usize { self.examples.iter().map(|g| g.names.len()).sum() }

    /// Language icon for the project list.
    pub const fn lang_icon(&self) -> &'static str { if self.is_rust { "🦀" } else { "  " } }

    /// Display name for the project list.
    /// Shows `name (worktree_dir)` for worktrees, just `name` otherwise.
    /// Falls back to the last path component for workspace-only projects.
    pub fn display_name(&self) -> String {
        let name = self
            .name
            .as_deref()
            .unwrap_or_else(|| self.path.rsplit('/').next().unwrap_or(&self.path));
        self.worktree_name
            .as_ref()
            .map_or_else(|| name.to_string(), |wt| format!("{name} ({wt})"))
    }
}

pub enum ProjectParseError {
    ReadError(io::Error),
    ParseError(toml::de::Error),
}

impl fmt::Display for ProjectParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ReadError(e) => write!(f, "read error: {e}"),
            Self::ParseError(e) => write!(f, "parse error: {e}"),
        }
    }
}

impl RustProject {
    pub fn from_cargo_toml(cargo_toml_path: &Path) -> Result<Self, ProjectParseError> {
        let contents =
            std::fs::read_to_string(cargo_toml_path).map_err(ProjectParseError::ReadError)?;
        let table: Table = contents.parse().map_err(ProjectParseError::ParseError)?;

        let project_dir = cargo_toml_path.parent().unwrap_or(cargo_toml_path);

        let path_str = home_relative_path(project_dir);

        let name = table
            .get("package")
            .and_then(|p| p.get("name"))
            .and_then(|n| n.as_str())
            .map(|s| (*s).to_string());

        let version = table
            .get("package")
            .and_then(|p| p.get("version"))
            .map(|v| {
                v.as_str().map_or_else(
                    || {
                        if v.get("workspace").and_then(Value::as_bool) == Some(true) {
                            "(workspace)".to_string()
                        } else {
                            "-".to_string()
                        }
                    },
                    |s| (*s).to_string(),
                )
            });

        let description = table
            .get("package")
            .and_then(|p| p.get("description"))
            .and_then(|n| n.as_str())
            .map(|s| (*s).to_string());

        // A `.git` file (not directory) indicates a git worktree
        let worktree_name = detect_worktree_name(project_dir);

        let is_workspace = table.get("workspace").is_some();
        let types = detect_types(&table, project_dir);
        let examples = collect_examples(&table, project_dir);
        let benches = collect_target_names(&table, project_dir, "bench", "benches");
        let test_count = count_targets(&table, project_dir, "test", "tests");

        let abs_path = project_dir.display().to_string();

        Ok(Self {
            path: path_str,
            abs_path,
            name,
            version,
            description,
            worktree_name,
            is_workspace,
            types,
            examples,
            benches,
            test_count,
            is_rust: true,
        })
    }

    /// Create a project entry for a non-Rust git repository (no `Cargo.toml`).
    pub fn from_git_dir(project_dir: &Path) -> Self {
        let name = project_dir
            .file_name()
            .map(|n| n.to_string_lossy().to_string());
        let path = home_relative_path(project_dir);
        let abs_path = project_dir.display().to_string();
        let worktree_name = detect_worktree_name(project_dir);

        Self {
            path,
            abs_path,
            name,
            version: None,
            description: None,
            worktree_name,
            is_workspace: false,
            types: Vec::new(),
            examples: Vec::new(),
            benches: Vec::new(),
            test_count: 0,
            is_rust: false,
        }
    }

    pub const fn is_workspace(&self) -> bool { self.is_workspace }
}

fn detect_types(table: &Table, project_dir: &Path) -> Vec<ProjectType> {
    let mut types = Vec::new();

    let is_proc_macro = table
        .get("lib")
        .and_then(|lib| lib.get("proc-macro"))
        .and_then(Value::as_bool)
        == Some(true);

    if is_proc_macro {
        types.push(ProjectType::ProcMacro);
    } else {
        let has_lib_section = table.get("lib").is_some();
        let has_lib_rs = project_dir.join("src/lib.rs").exists();
        if has_lib_section || has_lib_rs {
            types.push(ProjectType::Library);
        }
    }

    let has_bin_section = table.get("bin").is_some();
    let has_main_rs = project_dir.join("src/main.rs").exists();
    if has_bin_section || has_main_rs {
        types.push(ProjectType::Binary);
    }

    if project_dir.join("build.rs").exists() {
        types.push(ProjectType::BuildScript);
    }

    types
}

/// Collect examples grouped by category. Prefers `[[example]]` declarations, falls back to
/// file discovery.
fn collect_examples(table: &Table, project_dir: &Path) -> Vec<ExampleGroup> {
    // Collect from [[example]] entries in Cargo.toml
    if let Some(arr) = table.get("example").and_then(|v| v.as_array())
        && !arr.is_empty()
    {
        let mut groups: HashMap<String, Vec<String>> = HashMap::new();
        for entry in arr {
            let name = entry
                .get("name")
                .and_then(|n| n.as_str())
                .unwrap_or_default()
                .to_string();
            if name.is_empty() {
                continue;
            }
            // Derive category from path: "examples/2d/foo.rs" -> "2d"
            let category = entry
                .get("path")
                .and_then(|p| p.as_str())
                .and_then(|p| {
                    let parts: Vec<&str> = p.split('/').collect();
                    // "examples/category/file.rs" -> category
                    if parts.len() >= 3 {
                        Some(parts[1].to_string())
                    } else {
                        None
                    }
                })
                .unwrap_or_default();
            groups.entry(category).or_default().push(name);
        }
        return build_sorted_groups(groups);
    }

    // Auto-discover from examples/ directory
    let examples_dir = project_dir.join("examples");
    if !examples_dir.is_dir() {
        return Vec::new();
    }

    discover_examples_grouped(&examples_dir)
}

fn build_sorted_groups(
    mut groups: std::collections::HashMap<String, Vec<String>>,
) -> Vec<ExampleGroup> {
    let mut result: Vec<ExampleGroup> = groups
        .drain()
        .map(|(category, mut names)| {
            names.sort();
            ExampleGroup { category, names }
        })
        .collect();
    // Root-level first, then alphabetically by category
    result.sort_by(|a, b| {
        let a_root = a.category.is_empty();
        let b_root = b.category.is_empty();
        match (a_root, b_root) {
            (true, false) => std::cmp::Ordering::Less,
            (false, true) => std::cmp::Ordering::Greater,
            _ => a.category.cmp(&b.category),
        }
    });
    result
}

/// Auto-discover examples from a directory, grouping by subdirectory.
fn discover_examples_grouped(examples_dir: &Path) -> Vec<ExampleGroup> {
    let Ok(entries) = std::fs::read_dir(examples_dir) else {
        return Vec::new();
    };

    let mut groups: HashMap<String, Vec<String>> = HashMap::new();

    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_file() && path.extension().is_some_and(|e| e == "rs") {
            if let Some(stem) = path.file_stem() {
                groups
                    .entry(String::new())
                    .or_default()
                    .push(stem.to_string_lossy().to_string());
            }
        } else if path.is_dir() {
            let dir_name = path
                .file_name()
                .map(|n| n.to_string_lossy().to_string())
                .unwrap_or_default();
            // Collect .rs files and main.rs subdirs within this category
            if let Ok(sub_entries) = std::fs::read_dir(&path) {
                for sub in sub_entries.flatten() {
                    let sub_path = sub.path();
                    if sub_path.is_file() && sub_path.extension().is_some_and(|e| e == "rs") {
                        if let Some(stem) = sub_path.file_stem() {
                            groups
                                .entry(dir_name.clone())
                                .or_default()
                                .push(stem.to_string_lossy().to_string());
                        }
                    } else if sub_path.is_dir()
                        && sub_path.join("main.rs").exists()
                        && let Some(name) = sub_path.file_name()
                    {
                        groups
                            .entry(dir_name.clone())
                            .or_default()
                            .push(name.to_string_lossy().to_string());
                    }
                }
            }
        }
    }

    build_sorted_groups(groups)
}

/// Collect target names (e.g. benches). Prefers `[[toml_key]]` declarations, falls back to
/// file discovery in `dir_name/`.
fn collect_target_names(
    table: &Table,
    project_dir: &Path,
    toml_key: &str,
    dir_name: &str,
) -> Vec<String> {
    if let Some(arr) = table.get(toml_key).and_then(|v| v.as_array())
        && !arr.is_empty()
    {
        let mut names: Vec<String> = arr
            .iter()
            .filter_map(|entry| {
                entry
                    .get("name")
                    .and_then(|n| n.as_str())
                    .map(std::string::ToString::to_string)
            })
            .collect();
        names.sort();
        return names;
    }

    let dir = project_dir.join(dir_name);
    if !dir.is_dir() {
        return Vec::new();
    }

    let Ok(entries) = std::fs::read_dir(&dir) else {
        return Vec::new();
    };

    let mut names = Vec::new();
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_file() && path.extension().is_some_and(|e| e == "rs") {
            if let Some(stem) = path.file_stem() {
                names.push(stem.to_string_lossy().to_string());
            }
        } else if path.is_dir()
            && path.join("main.rs").exists()
            && let Some(name) = path.file_name()
        {
            names.push(name.to_string_lossy().to_string());
        }
    }
    names.sort();
    names
}

fn count_targets(table: &Table, project_dir: &Path, toml_key: &str, dir_name: &str) -> usize {
    let declared = table
        .get(toml_key)
        .and_then(|v| v.as_array())
        .map_or(0, Vec::len);

    if declared > 0 {
        return declared;
    }

    let dir = project_dir.join(dir_name);
    if !dir.is_dir() {
        return 0;
    }

    count_rs_files_recursive(&dir)
}

/// Detect if a project directory is inside a git worktree.
/// Walks up the directory tree looking for a `.git` file (not directory).
/// Returns the worktree root directory name as the label.
/// Returns a `~/`-prefixed path if under the home directory, otherwise the absolute path.
/// Returns a `~/`-prefixed path if under the home directory, otherwise the absolute path.
pub fn home_relative_path(path: &Path) -> String {
    if let Some(home) = dirs::home_dir()
        && let Ok(rel) = path.strip_prefix(&home)
    {
        return format!("~/{}", rel.display());
    }
    path.display().to_string()
}

fn detect_worktree_name(project_dir: &Path) -> Option<String> {
    let mut dir = project_dir;
    loop {
        let git_path = dir.join(".git");
        if git_path.is_file() {
            return dir.file_name().map(|n| n.to_string_lossy().to_string());
        }
        if git_path.is_dir() {
            // Found a real .git directory — not a worktree
            return None;
        }
        dir = dir.parent()?;
    }
}

fn count_rs_files_recursive(dir: &Path) -> usize {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return 0;
    };

    let mut count = 0;
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_file() && path.extension().is_some_and(|e| e == "rs") {
            count += 1;
        } else if path.is_dir() {
            // Subdirectories can contain examples too (e.g., examples/foo/main.rs)
            // Count the directory as one example if it has a main.rs
            if path.join("main.rs").exists() {
                count += 1;
            }
        }
    }
    count
}