Skip to content
Merged
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
8 changes: 5 additions & 3 deletions crates/agentdeckd/src/suggestions/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

pub mod remotes;

use std::collections::{BTreeMap, HashMap, HashSet};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::path::PathBuf;
use std::sync::Arc;

Expand Down Expand Up @@ -259,8 +259,10 @@ impl Suggestions {
/// The Repository a git repo's remote names, by the name in lower case, for each of `folders`
/// that is in one.
fn worked_in(folders: &[String]) -> BTreeMap<String, RepositoryName> {
(folders.iter())
.filter_map(|folder| remotes::repository_of(&PathBuf::from(folder)))
let git = remotes::Git::default();
let folders: BTreeSet<&String> = folders.iter().collect();
(folders.into_iter())
.filter_map(|folder| remotes::repository_of(&PathBuf::from(folder), &git))
.map(|name| (name.to_string().to_lowercase(), name))
.collect()
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,31 +1,19 @@
//! Which Repository a folder's git repo works in (spec §3 Suggestions): its `upstream` remote
//! when that is on GitHub, else its `origin`; any other remote is ignored.
//!
//! The remotes are read straight from the repo's `config` file, with no `git` process: the
//! folder or the nearest folder above it holding `.git`, a directory, or a file naming the
//! git dir (`gitdir: …`, as a worktree or a submodule has), whose `commondir` leads a worktree
//! to the main repo's config. `include` and `includeIf` files, and `url.<base>.insteadOf`
//! rewrites, aren't followed: a remote that only they make a GitHub URL suggests nothing.
//! The fallback for when `git` can't answer (spec §3 Suggestions): the remotes read straight
//! from the repo's `config` file. The repo is the folder or the nearest folder above it holding
//! `.git`, a directory, or a file naming the git dir (`gitdir: …`, as a worktree or a submodule
//! has), whose `commondir` leads a worktree to the main repo's config. Only that file is read:
//! `include` and `includeIf` files, the user's global config and `url.<base>.insteadOf`
//! rewrites aren't, so a remote that only they make a GitHub URL suggests nothing here.

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use agentdeck_core::RepositoryName;

/// The Repository the git repo holding `folder` works in: its `upstream` remote when that is on
/// GitHub, else its `origin` when that is. `None` outside a git repo, or when neither is.
pub fn repository_of(folder: &Path) -> Option<RepositoryName> {
/// Each remote's URL by its name, from the `config` file of the git repo holding `folder`.
/// `None` outside a git repo, or when the file can't be read.
pub fn remote_urls_of(folder: &Path) -> Option<HashMap<String, String>> {
let config = std::fs::read_to_string(config_file(folder)?).ok()?;
pick(&remote_urls(&config))
}

/// `upstream` when it is on GitHub, else `origin` when it is.
fn pick(remotes: &HashMap<String, String>) -> Option<RepositoryName> {
["upstream", "origin"]
.into_iter()
.find_map(|remote| RepositoryName::from_remote_url(remotes.get(remote)?))
Some(remote_urls(&config))
}

/// The `config` file of the git repo holding `folder`, looking up from it.
fn config_file(folder: &Path) -> Option<PathBuf> {
folder.ancestors().find_map(|dir| {
Expand Down Expand Up @@ -146,10 +134,6 @@ mod tests {
urls
}

fn picked(text: &str) -> Option<String> {
pick(&remote_urls(text)).map(|name| name.to_string())
}

mod remote_urls {
use super::*;

Expand Down Expand Up @@ -234,42 +218,18 @@ mod tests {
}
}

mod pick {
use super::*;

#[test]
fn should_prefer_upstream_on_github() {
let config = "[remote \"origin\"]\nurl = git@github.com:me/widgets.git\n\
[remote \"upstream\"]\nurl = https://github.com/acme/widgets.git\n";

assert_eq!(picked(config).as_deref(), Some("acme/widgets"));
}

#[test]
fn should_take_origin_when_upstream_is_not_on_github() {
let config = "[remote \"origin\"]\nurl = git@github.com:me/widgets.git\n\
[remote \"upstream\"]\nurl = https://gitlab.com/acme/widgets.git\n";

assert_eq!(picked(config).as_deref(), Some("me/widgets"));
}

#[test]
fn should_ignore_every_other_remote() {
let config = "[remote \"fork\"]\nurl = https://github.com/me/widgets\n\
[remote \"origin\"]\nurl = https://gitlab.com/acme/widgets\n";

assert_eq!(picked(config), None);
}
}

mod repository_of {
mod remote_urls_of {
use super::*;

fn write(path: &Path, text: &str) {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}

fn origin(folder: &Path) -> Option<String> {
remote_urls_of(folder)?.remove("origin")
}

const ORIGIN: &str = "[remote \"origin\"]\n\turl = https://github.com/acme/widgets\n";

#[test]
Expand All @@ -280,8 +240,8 @@ mod tests {
std::fs::create_dir_all(&deep).unwrap();

assert_eq!(
repository_of(&deep).map(|n| n.to_string()).as_deref(),
Some("acme/widgets")
origin(&deep).as_deref(),
Some("https://github.com/acme/widgets")
);
}

Expand All @@ -302,10 +262,8 @@ mod tests {
);

assert_eq!(
repository_of(&dir.path().join("wt"))
.map(|n| n.to_string())
.as_deref(),
Some("acme/widgets")
origin(&dir.path().join("wt")).as_deref(),
Some("https://github.com/acme/widgets")
);
}

Expand All @@ -319,18 +277,16 @@ mod tests {
);

assert_eq!(
repository_of(&dir.path().join("lib"))
.map(|n| n.to_string())
.as_deref(),
Some("acme/widgets")
origin(&dir.path().join("lib")).as_deref(),
Some("https://github.com/acme/widgets")
);
}

#[test]
fn should_find_none_outside_a_repo() {
let dir = tempfile::tempdir().unwrap();

assert_eq!(repository_of(dir.path()), None);
assert_eq!(remote_urls_of(dir.path()), None);
}
}
}
152 changes: 152 additions & 0 deletions crates/agentdeckd/src/suggestions/remotes/git.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
//! Asking `git` for a folder's remotes (spec §3 Suggestions): one `git -C <folder> remote -v`,
//! which prints each remote's URL as git uses it, after `include`, `includeIf` and
//! `url.<base>.insteadOf` from every config file git reads. No shell runs it, and it gets the
//! daemon's own environment, so the user's git config applies, less the variables that would
//! point git at another repo than the folder's.

use std::collections::HashMap;
use std::ffi::OsStr;
use std::io::Read;
use std::path::Path;
use std::process::{Command, ExitStatus, Stdio};
use std::sync::mpsc;
use std::time::Duration;

/// The variables that would point git at another repo than `-C`'s folder.
const REPO_VARS: [&str; 3] = ["GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR"];

/// Why `git` gave no remotes.
#[derive(Debug, thiserror::Error)]
pub enum GitError {
#[error("starting {0:?}: {1}")]
Start(std::ffi::OsString, std::io::Error),
#[error("`git remote -v` took longer than {0:?}")]
TimedOut(Duration),
#[error("`git remote -v` exited with {0}")]
Failed(ExitStatus),
#[error("reading `git remote -v`: {0}")]
Read(std::io::Error),
}

/// Each remote's fetch URL by its name, as `<program> -C <folder> remote -v` prints them. A
/// `git` still running after `timeout` is killed.
pub fn remote_urls(
program: &OsStr,
folder: &Path,
timeout: Duration,
) -> Result<HashMap<String, String>, GitError> {
let mut command = Command::new(program);
command
.arg("-C")
.arg(folder)
.args(["remote", "-v"])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null());
for var in REPO_VARS {
command.env_remove(var);
}
let mut child = command
.spawn()
.map_err(|err| GitError::Start(program.to_owned(), err))?;
let mut stdout = child.stdout.take().expect("stdout is piped");
// The output is read on its own thread, so a `git` that hangs is waited for no longer than
// `timeout`. The thread ends when git's stdout closes, which killing it does.
let (sent, output) = mpsc::channel();
std::thread::spawn(move || {
let mut out = Vec::new();
let read = stdout.read_to_end(&mut out).map(|_| out);
let _ = sent.send(read);
});
let out = match output.recv_timeout(timeout) {
Ok(read) => read.map_err(GitError::Read)?,
Err(_) => {
let _ = child.kill();
let _ = child.wait();
return Err(GitError::TimedOut(timeout));
}
};
let status = child.wait().map_err(GitError::Read)?;
if !status.success() {
return Err(GitError::Failed(status));
}
Ok(parse(&String::from_utf8_lossy(&out)))
}

/// Each remote's fetch URL in `git remote -v`'s `output`, from its `<name>\t<url> (fetch)`
/// line (which a partial clone's ` [<filter>]` follows).
fn parse(output: &str) -> HashMap<String, String> {
(output.lines())
.filter_map(|line| {
let (name, rest) = line.split_once('\t')?;
let (url, _) = rest.split_once(" (fetch)")?;
let url = url.trim();
(!url.is_empty()).then(|| (name.to_owned(), url.to_owned()))
})
.collect()
}

#[cfg(test)]
mod tests {
use super::*;

mod parse {
use super::*;

fn parsed(output: &str) -> Vec<(String, String)> {
let mut urls: Vec<_> = parse(output).into_iter().collect();
urls.sort();
urls
}

#[test]
fn should_read_each_remotes_fetch_url_by_its_name() {
let output = "origin\thttps://github.com/me/widgets (fetch)\n\
origin\thttps://github.com/me/widgets (push)\n\
upstream\tgit@github.com:acme/widgets.git (fetch)\n\
upstream\tno-pushing (push)\n";

assert_eq!(
parsed(output),
[
("origin".into(), "https://github.com/me/widgets".into()),
("upstream".into(), "git@github.com:acme/widgets.git".into()),
]
);
}

#[test]
fn should_read_a_partial_clones_url_without_its_filter() {
let output = "origin\thttps://github.com/a/b (fetch) [blob:none]\n";

assert_eq!(
parsed(output),
[("origin".into(), "https://github.com/a/b".into())]
);
}

#[test]
fn should_skip_a_remote_without_a_url() {
assert_eq!(parsed("origin\t (fetch)\norigin\t (push)\n"), []);
}

#[test]
fn should_read_nothing_from_a_repo_without_remotes() {
assert_eq!(parsed(""), []);
}
}

mod remote_urls {
use super::*;

#[test]
fn should_fail_to_start_a_git_that_is_not_there() {
let dir = tempfile::tempdir().unwrap();
let missing = dir.path().join("no-git-here");

let err = remote_urls(missing.as_os_str(), dir.path(), Duration::from_secs(2));

assert!(matches!(err, Err(GitError::Start(..))), "{err:?}");
}
}
}
Loading