Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions desktop/src-tauri/src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ mod project_git_exec;
mod project_git_merge_error;
mod project_git_push;
mod project_git_workflow;
mod project_repo_discovery;
mod project_repo_paths;
mod project_terminal;
mod qr_download;
Expand Down
25 changes: 8 additions & 17 deletions desktop/src-tauri/src/commands/project_git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ use super::project_git_exec::{
GitAuthConfig,
};
use super::project_git_push::push_project_local_repository_blocking;
use super::project_repo_paths::{canonical_repos_roots, find_local_repo_dir};
use super::project_repo_paths::{
canonical_repos_roots, discover_local_repo_dirs, find_local_repo_dir,
};
use crate::app_state::AppState;
use serde::Serialize;
use std::time::UNIX_EPOCH;
Expand Down Expand Up @@ -830,26 +832,15 @@ pub async fn list_project_local_repositories(
let mut seen_paths = std::collections::HashSet::new();
let mut repos = Vec::new();
for repos_root in repos_roots {
let entries = std::fs::read_dir(&repos_root)
.map_err(|error| format!("read reposDir: {error}"))?;
for entry in entries.filter_map(Result::ok) {
let Some(file_type) = entry.file_type().ok() else {
continue;
};
if !file_type.is_dir() && !file_type.is_symlink() {
continue;
}
let Ok(path) = entry.path().canonicalize() else {
continue;
};
if !path.starts_with(&repos_root) || !path.is_dir() || !path.join(".git").exists() {
continue;
}
for path in discover_local_repo_dirs(&repos_root)? {
if !seen_paths.insert(path.clone()) {
continue;
}
repos.push(ProjectLocalRepoInfo {
name: entry.file_name().to_string_lossy().to_string(),
name: path
.file_name()
.map(|name| name.to_string_lossy().to_string())
.unwrap_or_default(),
path: path.display().to_string(),
});
}
Expand Down
160 changes: 160 additions & 0 deletions desktop/src-tauri/src/commands/project_repo_discovery.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
//! Bounded discovery of local Git working trees.

use std::collections::HashSet;

/// Maximum number of directory levels below a configured repositories root
/// that local project discovery will inspect.
const MAX_LOCAL_REPO_DISCOVERY_DEPTH: usize = 4;

/// Discover Git working trees below `repos_root` without following symlinks
/// outside the configured root or recursing indefinitely through cycles.
///
/// Repository roots are terminal: once a `.git` entry is found, discovery does
/// not descend into that checkout and accidentally surface its submodules.
pub(crate) fn discover_local_repo_dirs(
repos_root: &std::path::Path,
) -> Result<Vec<std::path::PathBuf>, String> {
let repos_root = repos_root
.canonicalize()
.map_err(|error| format!("reposDir is not accessible: {error}"))?;
if !repos_root.is_dir() {
return Err("reposDir is not a directory".to_string());
}

let mut repos = Vec::new();
let mut visited = HashSet::from([repos_root.clone()]);
let mut pending = vec![(repos_root.clone(), 0usize)];

while let Some((directory, depth)) = pending.pop() {
let entries = match std::fs::read_dir(&directory) {
Ok(entries) => entries,
Err(error) if depth == 0 => return Err(format!("read reposDir: {error}")),
Err(_) => continue,
};

for entry in entries.filter_map(Result::ok) {
let Some(file_type) = entry.file_type().ok() else {
continue;
};
if !file_type.is_dir() && !file_type.is_symlink() {
continue;
}

let Ok(path) = entry.path().canonicalize() else {
continue;
};
if !path.starts_with(&repos_root) || !path.is_dir() || !visited.insert(path.clone()) {
continue;
}

if path.join(".git").exists() {
repos.push(path);
continue;
}

let child_depth = depth + 1;
if child_depth < MAX_LOCAL_REPO_DISCOVERY_DEPTH {
pending.push((path, child_depth));
}
}
}

repos.sort();
Ok(repos)
}

#[cfg(test)]
mod tests {
use super::{discover_local_repo_dirs, MAX_LOCAL_REPO_DISCOVERY_DEPTH};
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};

static NEXT_TEST_DIR: AtomicU64 = AtomicU64::new(0);

struct TestDir(std::path::PathBuf);

impl TestDir {
fn new() -> Self {
let sequence = NEXT_TEST_DIR.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"buzz-project-repo-discovery-{}-{sequence}",
std::process::id()
));
std::fs::create_dir_all(&path).expect("create temp directory");
Self(path)
}

fn path(&self) -> &Path {
&self.0
}
}

impl Drop for TestDir {
fn drop(&mut self) {
std::fs::remove_dir_all(&self.0).expect("remove temp directory");
}
}

fn create_repo(path: &Path) {
std::fs::create_dir_all(path.join(".git")).expect("create test repository");
}

#[test]
fn bounds_nested_repository_discovery_depth() {
let temp = TestDir::new();
let repos_root = temp.path().join("code");
let within_bound = repos_root
.join("one")
.join("two")
.join("three")
.join("repo-within-bound");
let beyond_bound = repos_root
.join("one")
.join("two")
.join("three")
.join("four")
.join("repo-beyond-bound");
create_repo(&within_bound);
create_repo(&beyond_bound);

let discovered = discover_local_repo_dirs(&repos_root).expect("discover repositories");

assert!(discovered.contains(&within_bound.canonicalize().unwrap()));
assert!(!discovered.contains(&beyond_bound.canonicalize().unwrap()));
assert_eq!(MAX_LOCAL_REPO_DISCOVERY_DEPTH, 4);
}

#[cfg(unix)]
#[test]
fn ignores_symlinks_that_escape_the_configured_root() {
use std::os::unix::fs::symlink;

let temp = TestDir::new();
let repos_root = temp.path().join("code");
std::fs::create_dir_all(&repos_root).unwrap();
let external_repo = temp.path().join("external-repo");
create_repo(&external_repo);
symlink(&external_repo, repos_root.join("escaped")).expect("create test symlink");

let discovered = discover_local_repo_dirs(&repos_root).expect("discover repositories");

assert!(discovered.is_empty());
}

#[cfg(unix)]
#[test]
fn visits_in_root_symlink_targets_only_once() {
use std::os::unix::fs::symlink;

let temp = TestDir::new();
let repos_root = temp.path().join("code");
let nested_group = repos_root.join("client");
let nested_repo = nested_group.join("web-app");
create_repo(&nested_repo);
symlink(&nested_group, repos_root.join("client-alias")).expect("create test symlink");

let discovered = discover_local_repo_dirs(&repos_root).expect("discover repositories");

assert_eq!(discovered, vec![nested_repo.canonicalize().unwrap()]);
}
}
49 changes: 48 additions & 1 deletion desktop/src-tauri/src/commands/project_repo_paths.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
//! Shared by the project git commands (snapshots, sync status, push) and the
//! project terminal launcher.

pub(crate) use super::project_repo_discovery::discover_local_repo_dirs;
use crate::managed_agents::nest_dir;
use url::Url;

Expand Down Expand Up @@ -122,9 +123,12 @@ pub(crate) fn find_local_repo_dir(
clone_url: Option<&str>,
) -> Result<Option<std::path::PathBuf>, String> {
let repos_roots = canonical_repos_roots(repos_dir)?;
let candidates = local_repo_candidates(project_dtag, clone_url);

for repos_root in repos_roots {
for candidate in local_repo_candidates(project_dtag, clone_url) {
// Preserve the fast path for the conventional `<repos_root>/<repo>`
// layout before walking nested organization/group directories.
for candidate in &candidates {
let candidate_path = repos_root.join(candidate);
let Ok(candidate_path) = candidate_path.canonicalize() else {
continue;
Expand All @@ -140,6 +144,23 @@ pub(crate) fn find_local_repo_dir(
return Ok(Some(candidate_path));
}
}

let discovered = discover_local_repo_dirs(&repos_root)?;
for candidate in &candidates {
for candidate_path in &discovered {
if candidate_path.file_name().and_then(|name| name.to_str())
!= Some(candidate.as_str())
{
continue;
}
if clone_url
.map(|url| checkout_origin_matches(candidate_path, &repos_root, url))
.unwrap_or(true)
{
return Ok(Some(candidate_path.clone()));
}
}
}
}
Ok(None)
}
Expand Down Expand Up @@ -190,3 +211,29 @@ pub(crate) fn canonical_repos_roots(
}
Ok(roots)
}

#[cfg(test)]
mod tests {
use super::{discover_local_repo_dirs, find_local_repo_dir};
use std::path::Path;

fn create_repo(path: &Path) {
std::fs::create_dir_all(path.join(".git")).expect("create test repository");
}

#[test]
fn discovers_repositories_in_nested_group_directories() {
let temp = tempfile::tempdir().expect("create temp directory");
let repos_root = temp.path().join("code");
let nested_repo = repos_root.join("client").join("web-app");
create_repo(&nested_repo);

let discovered = discover_local_repo_dirs(&repos_root).expect("discover repositories");

assert_eq!(discovered, vec![nested_repo.canonicalize().unwrap()]);
assert_eq!(
find_local_repo_dir(Some(repos_root.to_str().unwrap()), "web-app", None,).unwrap(),
Some(nested_repo.canonicalize().unwrap())
);
}
}