use std::path::Path;
use serde::Serialize;
use super::is_git_repo;
pub(super) const MAX_ENTRIES: usize = 200;
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct ProjectCandidate {
pub name: String,
pub path: String,
pub owner: Option<String>,
pub registered: bool,
}
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum RosterSource {
Registry,
#[default]
FsOnly,
}
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Default)]
pub struct ProjectRoster {
pub entries: Vec<ProjectCandidate>,
#[serde(default)]
pub source: RosterSource,
}
pub fn list_projects() -> ProjectRoster {
match dirs::home_dir() {
Some(home) => list_projects_in(&home, &trusty_common::workspace_layout::workspace_root()),
None => ProjectRoster::default(),
}
}
pub(super) fn list_projects_in(home: &Path, workspace_root: &Path) -> ProjectRoster {
let mut entries = if workspace_root.is_dir() {
scan_owner_layout(workspace_root)
} else {
scan_flat_layout(home)
};
entries.sort_by_key(|e| e.name.to_lowercase());
entries.truncate(MAX_ENTRIES);
ProjectRoster {
entries,
source: RosterSource::FsOnly,
}
}
fn scan_owner_layout(mpm_root: &Path) -> Vec<ProjectCandidate> {
let mut out = Vec::new();
let Ok(owners) = std::fs::read_dir(mpm_root) else {
return out;
};
for owner_entry in owners.flatten() {
let owner_path = owner_entry.path();
if !owner_path.is_dir() {
continue;
}
let owner_name = owner_entry.file_name().to_string_lossy().into_owned();
if owner_name.starts_with('.') {
continue;
}
let Ok(repos) = std::fs::read_dir(&owner_path) else {
continue;
};
for repo_entry in repos.flatten() {
let repo_path = repo_entry.path();
if !repo_path.is_dir() {
continue;
}
let repo_name = repo_entry.file_name().to_string_lossy().into_owned();
if repo_name.starts_with('.') || !is_git_repo(&repo_path) {
continue;
}
out.push(ProjectCandidate {
name: repo_name,
path: repo_path.display().to_string(),
owner: Some(owner_name.clone()),
registered: false,
});
}
}
out
}
fn scan_flat_layout(home: &Path) -> Vec<ProjectCandidate> {
let mut out = Vec::new();
let Ok(read) = std::fs::read_dir(home) else {
return out;
};
for entry in read.flatten() {
let path = entry.path();
if !path.is_dir() {
continue;
}
let name = entry.file_name().to_string_lossy().into_owned();
if name.starts_with('.') || !is_git_repo(&path) {
continue;
}
out.push(ProjectCandidate {
name,
path: path.display().to_string(),
owner: None,
registered: false,
});
}
out
}
#[cfg(test)]
mod tests {
use trusty_common::workspace_layout::DEFAULT_WORKSPACE_DIR;
use super::*;
fn mkdir(p: &Path) {
std::fs::create_dir_all(p).expect("mkdir");
}
fn mk_git_repo(p: &Path) {
mkdir(p);
mkdir(&p.join(".git"));
}
#[test]
fn trusty_mpm_projects_layout_is_scanned_two_levels_deep() {
let home = tempfile::tempdir().expect("tempdir");
let root = home.path().join(DEFAULT_WORKSPACE_DIR);
mk_git_repo(&root.join("bobmatnyc").join("trusty-tools"));
mkdir(&root.join("bobmatnyc").join("scratch")); mk_git_repo(&root.join("acme").join("widgets"));
let roster = list_projects_in(home.path(), &home.path().join(DEFAULT_WORKSPACE_DIR));
assert_eq!(roster.entries.len(), 2);
let names: Vec<&str> = roster.entries.iter().map(|e| e.name.as_str()).collect();
assert!(names.contains(&"trusty-tools"));
assert!(names.contains(&"widgets"));
let tt = roster
.entries
.iter()
.find(|e| e.name == "trusty-tools")
.expect("trusty-tools entry");
assert_eq!(tt.owner.as_deref(), Some("bobmatnyc"));
}
#[test]
fn falls_back_to_flat_home_scan_when_no_trusty_mpm_projects_dir() {
let home = tempfile::tempdir().expect("tempdir");
mk_git_repo(&home.path().join("acme-api"));
mkdir(&home.path().join("Downloads"));
let roster = list_projects_in(home.path(), &home.path().join(DEFAULT_WORKSPACE_DIR));
assert_eq!(roster.entries.len(), 1);
assert_eq!(roster.entries[0].name, "acme-api");
assert_eq!(roster.entries[0].owner, None);
}
#[test]
fn non_git_directories_are_excluded() {
let home = tempfile::tempdir().expect("tempdir");
let root = home.path().join(DEFAULT_WORKSPACE_DIR);
mkdir(&root.join("bobmatnyc").join("not-a-repo"));
let roster = list_projects_in(home.path(), &home.path().join(DEFAULT_WORKSPACE_DIR));
assert!(roster.entries.is_empty());
}
#[test]
fn unreadable_owner_dir_is_skipped_not_fatal() {
let home = tempfile::tempdir().expect("tempdir");
let root = home.path().join(DEFAULT_WORKSPACE_DIR);
mkdir(&root);
std::fs::write(root.join("not-a-dir-owner"), "x").expect("write");
mk_git_repo(&root.join("realowner").join("repo"));
let roster = list_projects_in(home.path(), &home.path().join(DEFAULT_WORKSPACE_DIR));
assert_eq!(roster.entries.len(), 1);
assert_eq!(roster.entries[0].owner.as_deref(), Some("realowner"));
}
#[test]
fn empty_home_returns_empty_roster() {
let home = tempfile::tempdir().expect("tempdir");
mkdir(&home.path().join("Documents"));
let roster = list_projects_in(home.path(), &home.path().join(DEFAULT_WORKSPACE_DIR));
assert!(roster.entries.is_empty());
}
#[test]
fn scan_is_capped_at_max_entries() {
let home = tempfile::tempdir().expect("tempdir");
let owner = home.path().join(DEFAULT_WORKSPACE_DIR).join("owner");
for i in 0..(MAX_ENTRIES + 25) {
mk_git_repo(&owner.join(format!("repo-{i:04}")));
}
let roster = list_projects_in(home.path(), &home.path().join(DEFAULT_WORKSPACE_DIR));
assert_eq!(roster.entries.len(), MAX_ENTRIES);
}
#[test]
fn results_are_sorted_case_insensitively_by_name() {
let home = tempfile::tempdir().expect("tempdir");
let root = home.path().join(DEFAULT_WORKSPACE_DIR);
mk_git_repo(&root.join("owner").join("Zebra"));
mk_git_repo(&root.join("owner").join("apple"));
mk_git_repo(&root.join("owner").join("Banana"));
let roster = list_projects_in(home.path(), &home.path().join(DEFAULT_WORKSPACE_DIR));
let names: Vec<&str> = roster.entries.iter().map(|e| e.name.as_str()).collect();
assert_eq!(names, vec!["apple", "Banana", "Zebra"]);
}
#[test]
fn configured_workspace_root_is_scanned_not_the_default() {
let _guard = env_lock();
let configured = tempfile::tempdir().expect("tempdir");
mk_git_repo(&configured.path().join("acme").join("widgets"));
unsafe {
std::env::set_var(
trusty_common::workspace_layout::WORKSPACE_ROOT_ENV,
configured.path(),
);
}
let roster = list_projects();
unsafe {
std::env::remove_var(trusty_common::workspace_layout::WORKSPACE_ROOT_ENV);
}
let found = roster
.entries
.iter()
.find(|e| e.name == "widgets")
.unwrap_or_else(|| {
panic!(
"the configured workspace root {} must be scanned; roster was {:?}",
configured.path().display(),
roster.entries
)
});
assert_eq!(found.owner.as_deref(), Some("acme"));
assert!(
Path::new(&found.path).starts_with(configured.path()),
"entry path {} must sit under the configured root {}",
found.path,
configured.path().display()
);
}
#[test]
fn default_workspace_root_is_unchanged_when_nothing_is_configured() {
let _guard = env_lock();
unsafe {
std::env::remove_var(trusty_common::workspace_layout::WORKSPACE_ROOT_ENV);
}
let root = trusty_common::workspace_layout::resolve_workspace_root(None);
let home = dirs::home_dir().expect("home");
assert_eq!(DEFAULT_WORKSPACE_DIR, "trusty-mpm-projects");
assert_eq!(root, home.join(DEFAULT_WORKSPACE_DIR));
}
fn env_lock() -> std::sync::MutexGuard<'static, ()> {
static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
LOCK.get_or_init(|| std::sync::Mutex::new(()))
.lock()
.unwrap_or_else(|e| e.into_inner())
}
}