From 682f83bbd2a3307f69b0ef2a446b1c1fdb87fb09 Mon Sep 17 00:00:00 2001 From: bRRRITSCOLD Date: Mon, 23 Nov 2026 19:21:23 -0700 Subject: [PATCH 1/3] fix(daemon): follow git config includes and insteadOf for Suggestions Read the system and global git config files with the repo's, follow include.path and includeIf (gitdir:, gitdir/i:, onbranch:), and rewrite a remote's URL by the longest url..insteadOf, as git does, still without a git process. Co-Authored-By: Claude Opus 5.5 --- crates/agentdeckd/src/suggestions/mod.rs | 3 +- crates/agentdeckd/src/suggestions/remotes.rs | 336 --------- .../src/suggestions/remotes/config.rs | 646 ++++++++++++++++++ .../agentdeckd/src/suggestions/remotes/mod.rs | 523 ++++++++++++++ .../src/suggestions/remotes/wildmatch.rs | 182 +++++ .../tests/integration/suggestions.rs | 156 +++++ 6 files changed, 1509 insertions(+), 337 deletions(-) delete mode 100644 crates/agentdeckd/src/suggestions/remotes.rs create mode 100644 crates/agentdeckd/src/suggestions/remotes/config.rs create mode 100644 crates/agentdeckd/src/suggestions/remotes/mod.rs create mode 100644 crates/agentdeckd/src/suggestions/remotes/wildmatch.rs diff --git a/crates/agentdeckd/src/suggestions/mod.rs b/crates/agentdeckd/src/suggestions/mod.rs index 655cabd..4848e45 100644 --- a/crates/agentdeckd/src/suggestions/mod.rs +++ b/crates/agentdeckd/src/suggestions/mod.rs @@ -259,8 +259,9 @@ 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 { + let env = remotes::GitEnv::from_env(); (folders.iter()) - .filter_map(|folder| remotes::repository_of(&PathBuf::from(folder))) + .filter_map(|folder| remotes::repository_of(&PathBuf::from(folder), &env)) .map(|name| (name.to_string().to_lowercase(), name)) .collect() } diff --git a/crates/agentdeckd/src/suggestions/remotes.rs b/crates/agentdeckd/src/suggestions/remotes.rs deleted file mode 100644 index 61ec0dc..0000000 --- a/crates/agentdeckd/src/suggestions/remotes.rs +++ /dev/null @@ -1,336 +0,0 @@ -//! 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..insteadOf` -//! rewrites, aren't followed: a remote that only they make a GitHub URL suggests nothing. - -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 { - 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) -> Option { - ["upstream", "origin"] - .into_iter() - .find_map(|remote| RepositoryName::from_remote_url(remotes.get(remote)?)) -} - -/// The `config` file of the git repo holding `folder`, looking up from it. -fn config_file(folder: &Path) -> Option { - folder.ancestors().find_map(|dir| { - let dot_git = dir.join(".git"); - let git_dir = if dot_git.is_dir() { - dot_git - } else if dot_git.is_file() { - linked_git_dir(dir, &std::fs::read_to_string(&dot_git).ok()?)? - } else { - return None; - }; - // A worktree's git dir names the main repo's, which holds the config, in `commondir`. - let common = match std::fs::read_to_string(git_dir.join("commondir")) { - Ok(common) => git_dir.join(common.trim()), - Err(_) => git_dir, - }; - Some(common.join("config")) - }) -} - -/// The git dir a `.git` file in `dir` names (`gitdir: `, relative to `dir` or absolute). -fn linked_git_dir(dir: &Path, dot_git: &str) -> Option { - let path = dot_git - .lines() - .find_map(|line| line.strip_prefix("gitdir:"))?; - Some(dir.join(path.trim())) -} - -/// Each remote's URL in git config `text`, by the remote's name: its first `url`. -pub fn remote_urls(text: &str) -> HashMap { - let mut urls = HashMap::new(); - let mut remote: Option = None; - for line in text.lines() { - let line = line.trim(); - if line.is_empty() || line.starts_with(['#', ';']) { - continue; - } - if let Some(header) = line.strip_prefix('[') { - remote = remote_section(header); - // `[remote "origin"] url = …`: a key may follow its header on the line. - let Some((_, rest)) = header.split_once(']') else { - continue; - }; - if rest.trim().is_empty() { - continue; - } - if let (Some(name), Some(url)) = (&remote, url_value(rest.trim())) { - urls.entry(name.clone()).or_insert(url); - } - continue; - } - if let (Some(name), Some(url)) = (&remote, url_value(line)) { - urls.entry(name.clone()).or_insert(url); - } - } - urls -} - -/// The remote a section header names (the text after its `[`): `remote "origin"]`, or the old -/// `remote.origin]`, whose name git reads in lower case. `None` for any other section. -fn remote_section(header: &str) -> Option { - let (header, _) = header.split_once(']')?; - let header = header.trim(); - if let Some((section, sub)) = header.split_once(char::is_whitespace) { - let sub = sub.trim().strip_prefix('"')?.strip_suffix('"')?; - return section - .eq_ignore_ascii_case("remote") - .then(|| unescape(sub)); - } - let (section, sub) = header.split_once('.')?; - section - .eq_ignore_ascii_case("remote") - .then(|| sub.to_lowercase()) -} - -/// The value of a `url = …` line; `None` for another key. Quotes are taken off and an -/// unquoted `#` or `;` starts a comment. -fn url_value(line: &str) -> Option { - let (key, value) = line.split_once('=')?; - if !key.trim().eq_ignore_ascii_case("url") { - return None; - } - let mut out = String::new(); - let mut quoted = false; - let mut chars = value.trim().chars(); - while let Some(c) = chars.next() { - match c { - '"' => quoted = !quoted, - '\\' => out.extend(chars.next()), - '#' | ';' if !quoted => break, - c => out.push(c), - } - } - let url = out.trim().to_owned(); - (!url.is_empty()).then_some(url) -} - -/// A subsection name with git's `\"` and `\\` escapes undone. -fn unescape(sub: &str) -> String { - let mut out = String::new(); - let mut chars = sub.chars(); - while let Some(c) = chars.next() { - match c { - '\\' => out.extend(chars.next()), - c => out.push(c), - } - } - out -} - -#[cfg(test)] -mod tests { - use super::*; - - fn names(text: &str) -> Vec<(String, String)> { - let mut urls: Vec<_> = remote_urls(text).into_iter().collect(); - urls.sort(); - urls - } - - fn picked(text: &str) -> Option { - pick(&remote_urls(text)).map(|name| name.to_string()) - } - - mod remote_urls { - use super::*; - - #[test] - fn should_read_each_remotes_url_by_its_name() { - let config = "[core]\n\trepositoryformatversion = 0\n\ - [remote \"origin\"]\n\turl = git@github.com:me/widgets.git\n\ - \tfetch = +refs/heads/*:refs/remotes/origin/*\n\ - [remote \"upstream\"]\n\turl = https://github.com/acme/widgets.git\n\ - [branch \"main\"]\n\tremote = origin\n"; - - assert_eq!( - names(config), - [ - ("origin".into(), "git@github.com:me/widgets.git".into()), - ( - "upstream".into(), - "https://github.com/acme/widgets.git".into() - ), - ] - ); - } - - #[test] - fn should_keep_a_remotes_first_url() { - let config = "[remote \"origin\"]\nurl = https://github.com/a/one\n\ - url = https://github.com/a/two\n"; - - assert_eq!( - names(config), - [("origin".into(), "https://github.com/a/one".into())] - ); - } - - #[test] - fn should_ignore_case_in_section_and_key_but_not_in_the_remotes_name() { - let config = "[Remote \"Origin\"]\n URL = https://github.com/a/b\n"; - - assert_eq!( - names(config), - [("Origin".into(), "https://github.com/a/b".into())] - ); - } - - #[test] - fn should_read_the_old_dotted_header_in_lower_case() { - let config = "[remote.Upstream]\nurl = https://github.com/a/b\n"; - - assert_eq!( - names(config), - [("upstream".into(), "https://github.com/a/b".into())] - ); - } - - #[test] - fn should_skip_comments_and_take_off_quotes() { - let config = "# a comment\n; another\n[remote \"origin\"]\n\ - url = \"https://github.com/a/b\" # trailing\n"; - - assert_eq!( - names(config), - [("origin".into(), "https://github.com/a/b".into())] - ); - } - - #[test] - fn should_read_a_url_on_its_headers_line() { - let config = "[remote \"origin\"] url = https://github.com/a/b\n"; - - assert_eq!( - names(config), - [("origin".into(), "https://github.com/a/b".into())] - ); - } - - #[test] - fn should_not_take_a_url_from_another_section() { - let config = "[submodule \"lib\"]\nurl = https://github.com/a/lib\n\ - [url \"git@github.com:\"]\ninsteadOf = https://github.com/\n"; - - assert_eq!(names(config), []); - } - } - - 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 { - use super::*; - - fn write(path: &Path, text: &str) { - std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - std::fs::write(path, text).unwrap(); - } - - const ORIGIN: &str = "[remote \"origin\"]\n\turl = https://github.com/acme/widgets\n"; - - #[test] - fn should_read_the_repo_holding_a_folder_deep_inside_it() { - let dir = tempfile::tempdir().unwrap(); - write(&dir.path().join("repo/.git/config"), ORIGIN); - let deep = dir.path().join("repo/src/bin"); - std::fs::create_dir_all(&deep).unwrap(); - - assert_eq!( - repository_of(&deep).map(|n| n.to_string()).as_deref(), - Some("acme/widgets") - ); - } - - #[test] - fn should_follow_a_worktrees_git_file_to_the_main_repos_config() { - let dir = tempfile::tempdir().unwrap(); - write(&dir.path().join("main/.git/config"), ORIGIN); - write( - &dir.path().join("main/.git/worktrees/wt/commondir"), - "../..\n", - ); - write( - &dir.path().join("wt/.git"), - &format!( - "gitdir: {}\n", - dir.path().join("main/.git/worktrees/wt").display() - ), - ); - - assert_eq!( - repository_of(&dir.path().join("wt")) - .map(|n| n.to_string()) - .as_deref(), - Some("acme/widgets") - ); - } - - #[test] - fn should_follow_a_relative_git_file() { - let dir = tempfile::tempdir().unwrap(); - write(&dir.path().join("store/modules/lib/config"), ORIGIN); - write( - &dir.path().join("lib/.git"), - "gitdir: ../store/modules/lib\n", - ); - - assert_eq!( - repository_of(&dir.path().join("lib")) - .map(|n| n.to_string()) - .as_deref(), - Some("acme/widgets") - ); - } - - #[test] - fn should_find_none_outside_a_repo() { - let dir = tempfile::tempdir().unwrap(); - - assert_eq!(repository_of(dir.path()), None); - } - } -} diff --git a/crates/agentdeckd/src/suggestions/remotes/config.rs b/crates/agentdeckd/src/suggestions/remotes/config.rs new file mode 100644 index 0000000..abe4d4d --- /dev/null +++ b/crates/agentdeckd/src/suggestions/remotes/config.rs @@ -0,0 +1,646 @@ +//! git config files read as git reads them (spec §3 Suggestions): the syntax, and the files an +//! `include.path` or a matching `includeIf "".path` names, read where the include +//! stands. + +use std::path::{Path, PathBuf}; + +use super::wildmatch::wildmatch; + +/// One `key = value` of a config file. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Entry { + /// In lower case, as git compares it. + pub section: String, + /// As written, but in lower case under the old `[section.sub]` header. + pub subsection: Option, + /// In lower case, as git compares it. + pub key: String, + /// `None` for a key with no `=`, which git reads as true. + pub value: Option, +} + +impl Entry { + /// Whether this is `
..` or `
.`; both in lower case. + pub fn is(&self, section: &str, key: &str) -> bool { + self.section == section && self.key == key + } +} + +/// What an `includeIf` condition is tested against. +pub struct Context<'a> { + /// The repo's git dir (a worktree's own, not the main repo's), for `gitdir:` and `onbranch:`. + pub git_dir: &'a Path, + /// What `~/` stands for. + pub home: Option<&'a Path>, +} + +/// How deep includes nest before git gives up; deeper ones are left unread. +const MAX_INCLUDE_DEPTH: usize = 10; + +type Chars<'a> = std::iter::Peekable>; + +/// The entries of config `text`, in order; a line git can't read is skipped. +pub fn parse(text: &str) -> Vec { + let mut entries = Vec::new(); + let mut section: Option<(String, Option)> = None; + let mut chars = text.chars().peekable(); + while let Some(&c) = chars.peek() { + match c { + c if c.is_whitespace() => { + chars.next(); + } + '[' => { + chars.next(); + section = header(&mut chars); + if section.is_none() { + skip_line(&mut chars); + } + } + c if c.is_ascii_alphabetic() => { + let mut key = String::new(); + while let Some(&c) = chars.peek().filter(|c| c.is_ascii_alphanumeric() || **c == '-') + { + key.push(c.to_ascii_lowercase()); + chars.next(); + } + skip_blanks(&mut chars); + let value = match chars.peek() { + Some('=') => { + chars.next(); + Some(value(&mut chars)) + } + None | Some('\n' | '#' | ';') => None, + Some(_) => { + skip_line(&mut chars); + continue; + } + }; + if let Some((name, sub)) = §ion { + entries.push(Entry { + section: name.clone(), + subsection: sub.clone(), + key, + value, + }); + } + } + // A comment, or a line git would refuse. + _ => skip_line(&mut chars), + } + } + entries +} + +/// The section a header names, read up to its `]` from just after its `[`: `section`, +/// `section "sub"` or the old `section.sub`. `None` for one git can't read. +fn header(chars: &mut Chars) -> Option<(String, Option)> { + // A line break is never taken here, so the caller's skip to the next line keeps the next. + let mut name = String::new(); + loop { + match chars.next_if(|&c| c != '\n')? { + ']' => { + let name = name.to_ascii_lowercase(); + if name.is_empty() { + return None; + } + return Some(match name.split_once('.') { + Some((section, sub)) => (section.to_owned(), Some(sub.to_owned())), + None => (name, None), + }); + } + c if c.is_ascii_alphanumeric() || c == '-' || c == '.' => name.push(c), + ' ' | '\t' if !name.is_empty() && !name.contains('.') => break, + _ => return None, + } + } + skip_blanks(chars); + chars.next_if_eq(&'"')?; + let mut sub = String::new(); + loop { + match chars.next_if(|&c| c != '\n')? { + '"' => break, + '\\' => sub.push(chars.next_if(|&c| c != '\n')?), + c => sub.push(c), + } + } + chars.next_if_eq(&']')?; + Some((name.to_ascii_lowercase(), Some(sub))) +} + +/// A value read from after its `=` to the end of its line, as git reads it: trimmed, quotes +/// taken off, an unquoted `#` or `;` starting a comment, `\` escapes undone and a `\` at the end +/// of a line joining the next. +fn value(chars: &mut Chars) -> String { + let mut out = String::new(); + let mut quoted = false; + let mut spaces = 0; + while let Some(c) = chars.next() { + match c { + '\n' => break, + c if c.is_whitespace() && !quoted => { + if !out.is_empty() { + spaces += 1; + } + } + '#' | ';' if !quoted => { + skip_line(chars); + break; + } + c => { + out.extend(std::iter::repeat_n(' ', spaces)); + spaces = 0; + match c { + '"' => quoted = !quoted, + '\\' => match chars.next() { + Some('\n') | None => {} + Some('\r') if chars.peek() == Some(&'\n') => { + chars.next(); + } + Some('n') => out.push('\n'), + Some('t') => out.push('\t'), + Some('b') => out.push('\u{8}'), + Some(c) => out.push(c), + }, + c => out.push(c), + } + } + } + } + out +} + +fn skip_blanks(chars: &mut Chars) { + while chars.next_if(|c| matches!(c, ' ' | '\t' | '\r')).is_some() {} +} + +fn skip_line(chars: &mut Chars) { + for c in chars.by_ref() { + if c == '\n' { + return; + } + } +} + +/// The entries of the config `file`, each file it includes read in where the include stands; +/// none when it can't be read. +pub fn read(file: &Path, context: &Context) -> Vec { + let mut entries = Vec::new(); + read_into(file, context, 0, &mut entries); + entries +} + +fn read_into(file: &Path, context: &Context, depth: usize, entries: &mut Vec) { + let Ok(text) = std::fs::read_to_string(file) else { + return; + }; + for entry in parse(&text) { + let included = entry.key == "path" + && match (entry.section.as_str(), entry.subsection.as_deref()) { + ("include", None) => true, + ("includeif", Some(condition)) => context.holds(condition, file), + _ => false, + }; + let target = (entry.value.as_deref()) + .filter(|_| included && depth < MAX_INCLUDE_DEPTH) + .and_then(|path| context.include_path(path, file)); + entries.push(entry); + if let Some(target) = target { + read_into(&target, context, depth + 1, entries); + } + } +} + +impl Context<'_> { + /// The file an include in `file` names by `path`: under home for `~/`, beside `file` when + /// relative. + fn include_path(&self, path: &str, file: &Path) -> Option { + if let Some(rest) = path.strip_prefix("~/") { + return Some(self.home?.join(rest)); + } + let path = Path::new(path); + if path.is_absolute() { + return Some(path.to_owned()); + } + Some(file.parent()?.join(path)) + } + + /// Whether the `includeIf` `condition` in `file` holds for the repo. + fn holds(&self, condition: &str, file: &Path) -> bool { + if let Some(pattern) = condition.strip_prefix("gitdir:") { + self.in_git_dir(pattern, file, false) + } else if let Some(pattern) = condition.strip_prefix("gitdir/i:") { + self.in_git_dir(pattern, file, true) + } else if let Some(pattern) = condition.strip_prefix("onbranch:") { + self.on_branch(pattern) + } else { + false + } + } + + /// `gitdir:`: whether the git dir, its real path or as found, matches `pattern`, where + /// `~/` is home, `./` the dir of `file`, a pattern not starting with `/` may match at any + /// depth and one ending in `/` matches everything under it. + fn in_git_dir(&self, pattern: &str, file: &Path, fold: bool) -> bool { + // `./`'s dir is matched as it is written, not as a pattern. + let (literal, mut glob) = if let Some(rest) = pattern.strip_prefix("~/") { + let Some(home) = self.home else { + return false; + }; + (String::new(), format!("{}/{rest}", home.display())) + } else if let Some(rest) = pattern.strip_prefix("./") { + let real = std::fs::canonicalize(file).ok(); + let Some(dir) = real.as_deref().and_then(Path::parent) else { + return false; + }; + (format!("{}/", dir.display()), rest.to_owned()) + } else if pattern.starts_with('/') { + (String::new(), pattern.to_owned()) + } else { + (String::new(), format!("**/{pattern}")) + }; + if format!("{literal}{glob}").ends_with('/') { + glob.push_str("**"); + } + let found = std::path::absolute(self.git_dir).ok(); + let real = std::fs::canonicalize(self.git_dir).ok(); + [real, found].into_iter().flatten().any(|dir| { + let dir = dir.to_string_lossy(); + dir.get(..literal.len()).is_some_and(|head| { + if fold { + head.eq_ignore_ascii_case(&literal) + } else { + head == literal + } + }) && wildmatch(&glob, &dir[literal.len()..], fold) + }) + } + + /// `onbranch:`: whether the branch checked out matches `pattern`, where one ending in `/` + /// matches every branch under it. A detached HEAD is on none. + fn on_branch(&self, pattern: &str) -> bool { + let Ok(head) = std::fs::read_to_string(self.git_dir.join("HEAD")) else { + return false; + }; + let Some(branch) = head.trim().strip_prefix("ref: refs/heads/") else { + return false; + }; + let mut pattern = pattern.to_owned(); + if pattern.ends_with('/') { + pattern.push_str("**"); + } + wildmatch(&pattern, branch, false) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn entry(section: &str, subsection: Option<&str>, key: &str, value: Option<&str>) -> Entry { + Entry { + section: section.into(), + subsection: subsection.map(Into::into), + key: key.into(), + value: value.map(Into::into), + } + } + + /// Each entry's `key` and value, the way `git config --list` shows them. + fn listed(entries: &[Entry]) -> Vec { + (entries.iter()) + .map(|e| { + let name = match &e.subsection { + Some(sub) => format!("{}.{sub}.{}", e.section, e.key), + None => format!("{}.{}", e.section, e.key), + }; + match &e.value { + Some(value) => format!("{name}={value}"), + None => name, + } + }) + .collect() + } + + mod parse { + use super::*; + + #[test] + fn should_read_sections_and_keys_in_lower_case_and_subsections_as_written() { + let config = "[Core]\n\tBare = false\n[Remote \"Origin\"]\n\tURL = https://x/y\n"; + + assert_eq!( + parse(config), + [ + entry("core", None, "bare", Some("false")), + entry("remote", Some("Origin"), "url", Some("https://x/y")), + ] + ); + } + + #[test] + fn should_read_the_old_dotted_header_with_its_subsection_in_lower_case() { + assert_eq!( + listed(&parse("[remote.Upstream]\nurl = a\n")), + ["remote.upstream.url=a"] + ); + } + + #[test] + fn should_undo_a_quoted_subsections_escapes() { + assert_eq!( + listed(&parse("[url \"a\\\"b\\\\c\"]\ninsteadOf = d\n")), + ["url.a\"b\\c.insteadof=d"] + ); + } + + #[test] + fn should_read_a_key_without_a_value_as_none() { + assert_eq!( + parse("[core]\n\tbare\n"), + [entry("core", None, "bare", None)] + ); + } + + #[test] + fn should_read_a_key_on_its_headers_line() { + assert_eq!( + listed(&parse("[remote \"origin\"] url = a\n")), + ["remote.origin.url=a"] + ); + } + + #[test] + fn should_skip_comments_and_take_off_quotes() { + let config = "# a comment\n; another\n[remote \"origin\"] # here too\n\ + url = \"https://x/#y\" # trailing\n"; + + assert_eq!(listed(&parse(config)), ["remote.origin.url=https://x/#y"]); + } + + #[test] + fn should_trim_a_value_and_keep_its_inner_spaces() { + assert_eq!( + listed(&parse("[a]\nb = one two \r\n")), + ["a.b=one two"] + ); + } + + #[test] + fn should_undo_escapes_and_join_a_continued_line() { + assert_eq!( + listed(&parse("[a]\nb = one\\\n two\\t\\\"\\\\\n")), + ["a.b=one two\t\"\\"] + ); + } + + #[test] + fn should_skip_a_line_it_cannot_read() { + assert_eq!( + listed(&parse("orphan = 1\n[a]\n= 2\nb = 3\n[broken\n[c]\nd = 4\n")), + ["a.b=3", "c.d=4"] + ); + } + } + + mod read { + use std::path::PathBuf; + + use super::*; + + fn write(path: &Path, text: &str) { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } + + /// A temp dir with a git dir at `repo/.git` and a home at `home`. + struct Fixture { + dir: tempfile::TempDir, + } + + impl Fixture { + fn new() -> Fixture { + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(dir.path().join("work/repo/.git")).unwrap(); + std::fs::create_dir_all(dir.path().join("home")).unwrap(); + Fixture { dir } + } + + fn path(&self, rel: &str) -> PathBuf { + self.dir.path().join(rel) + } + + fn git_dir(&self) -> PathBuf { + self.path("work/repo/.git") + } + + /// Reads `file` for the repo at `work/repo`. + fn read(&self, file: &str) -> Vec { + let git_dir = self.git_dir(); + let home = self.path("home"); + let context = Context { + git_dir: &git_dir, + home: Some(&home), + }; + listed(&read(&self.path(file), &context)) + } + } + + #[test] + fn should_read_an_included_file_where_the_include_stands() { + let f = Fixture::new(); + write( + &f.path("config"), + "[a]\none = 1\n[include]\npath = more.inc\n[a]\nthree = 3\n", + ); + write(&f.path("more.inc"), "[a]\ntwo = 2\n"); + + assert_eq!( + f.read("config"), + ["a.one=1", "include.path=more.inc", "a.two=2", "a.three=3"] + ); + } + + #[test] + fn should_find_a_relative_include_beside_the_including_file() { + let f = Fixture::new(); + write(&f.path("config"), "[include]\npath = nested/one.inc\n"); + write(&f.path("nested/one.inc"), "[include]\npath = two.inc\n"); + write(&f.path("nested/two.inc"), "[a]\nb = 2\n"); + + assert_eq!(f.read("config").last().unwrap(), "a.b=2"); + } + + #[test] + fn should_find_an_include_under_home_or_at_an_absolute_path() { + let f = Fixture::new(); + let absolute = f.path("elsewhere/abs.inc"); + write( + &f.path("config"), + &format!( + "[include]\npath = ~/home.inc\npath = {}\n", + absolute.display() + ), + ); + write(&f.path("home/home.inc"), "[a]\nhome = 1\n"); + write(&absolute, "[a]\nabsolute = 1\n"); + + let read = f.read("config"); + + assert!(read.contains(&"a.home=1".to_owned()), "{read:?}"); + assert!(read.contains(&"a.absolute=1".to_owned()), "{read:?}"); + } + + #[test] + fn should_skip_an_include_that_cannot_be_read() { + let f = Fixture::new(); + write(&f.path("config"), "[include]\npath = missing.inc\n[a]\nb = 1\n"); + + assert_eq!(f.read("config"), ["include.path=missing.inc", "a.b=1"]); + } + + #[test] + fn should_stop_following_includes_ten_deep() { + let f = Fixture::new(); + write(&f.path("config"), "[a]\nb = 1\n[include]\npath = config\n"); + + assert_eq!( + (f.read("config").iter()) + .filter(|line| *line == "a.b=1") + .count(), + 11 + ); + } + + #[test] + fn should_read_nothing_from_a_file_that_cannot_be_read() { + let f = Fixture::new(); + + assert_eq!(f.read("missing"), Vec::::new()); + } + + mod include_if { + use super::*; + + /// Whether `config` with `[includeIf ""] path = cond.inc` reads it in. + fn follows(f: &Fixture, condition: &str) -> bool { + write( + &f.path("config"), + &format!("[includeIf \"{condition}\"]\npath = cond.inc\n"), + ); + write(&f.path("cond.inc"), "[a]\nb = 1\n"); + f.read("config").contains(&"a.b=1".to_owned()) + } + + #[test] + fn should_follow_gitdir_when_the_repos_git_dir_is_under_it() { + let f = Fixture::new(); + + assert!(follows( + &f, + &format!("gitdir:{}/", f.path("work").display()) + )); + assert!(follows( + &f, + &format!("gitdir:{}", f.git_dir().display()) + )); + } + + #[test] + fn should_not_follow_gitdir_when_the_repo_is_elsewhere() { + let f = Fixture::new(); + + assert!(!follows( + &f, + &format!("gitdir:{}/", f.path("play").display()) + )); + assert!(!follows( + &f, + &format!("gitdir:{}", f.path("work").display()) + )); + } + + #[test] + fn should_match_a_relative_gitdir_pattern_at_any_depth() { + let f = Fixture::new(); + + assert!(follows(&f, "gitdir:work/")); + assert!(follows(&f, "gitdir:repo/.git")); + assert!(!follows(&f, "gitdir:play/")); + } + + #[test] + fn should_expand_a_path_beside_the_config_file() { + let f = Fixture::new(); + + assert!(follows(&f, "gitdir:./work/")); + assert!(!follows(&f, "gitdir:./play/")); + } + + #[test] + fn should_expand_home_and_match_the_git_dir_before_or_after_links() { + let f = Fixture::new(); + let home = f.path("home"); + std::fs::create_dir_all(home.join("code")).unwrap(); + std::os::unix::fs::symlink(f.path("work"), home.join("code/work")).unwrap(); + let linked = home.join("code/work/repo/.git"); + write(&f.path("cond.inc"), "[a]\nb = 1\n"); + let follows_from = |condition: &str, git_dir: &Path| { + write( + &f.path("config"), + &format!("[includeIf \"{condition}\"]\npath = cond.inc\n"), + ); + let context = Context { + git_dir, + home: Some(&home), + }; + listed(&read(&f.path("config"), &context)).contains(&"a.b=1".to_owned()) + }; + + assert!(follows_from("gitdir:~/code/work/", &linked)); + assert!(follows_from( + &format!("gitdir:{}/", f.path("work").display()), + &linked + )); + assert!(!follows_from("gitdir:~/code/work/", &f.git_dir())); + } + + #[test] + fn should_ignore_case_only_under_gitdir_i() { + let f = Fixture::new(); + let upper = format!("{}/", f.path("WORK").display()); + + assert!(follows(&f, &format!("gitdir/i:{upper}"))); + assert!(!follows(&f, &format!("gitdir:{upper}"))); + } + + #[test] + fn should_follow_onbranch_when_the_checked_out_branch_matches() { + let f = Fixture::new(); + write( + &f.git_dir().join("HEAD"), + "ref: refs/heads/feature/widgets\n", + ); + + assert!(follows(&f, "onbranch:feature/")); + assert!(follows(&f, "onbranch:feature/w*")); + assert!(follows(&f, "onbranch:feature/widgets")); + assert!(!follows(&f, "onbranch:main")); + } + + #[test] + fn should_not_follow_onbranch_on_a_detached_head() { + let f = Fixture::new(); + write(&f.git_dir().join("HEAD"), "0123456789abcdef\n"); + + assert!(!follows(&f, "onbranch:**")); + } + + #[test] + fn should_not_follow_a_condition_it_does_not_know() { + let f = Fixture::new(); + + assert!(!follows(&f, "hasconfig:remote.*.url:https://github.com/**")); + } + } + } +} diff --git a/crates/agentdeckd/src/suggestions/remotes/mod.rs b/crates/agentdeckd/src/suggestions/remotes/mod.rs new file mode 100644 index 0000000..c24417b --- /dev/null +++ b/crates/agentdeckd/src/suggestions/remotes/mod.rs @@ -0,0 +1,523 @@ +//! 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 from git's config files as git reads them, with no `git` process: the +//! system file, the user's global files, then the repo's `config`, each with the files its +//! `include.path` and matching `includeIf` (`gitdir:`, `gitdir/i:`, `onbranch:`) name, read in +//! where they stand ([`config`]). A remote's first `url` is rewritten by the longest matching +//! `url..insteadOf` among them all, as `git remote get-url` gives it. 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. +//! +//! Reading a few small files costs less than a `git` process, works without `git` installed and +//! is never stale, so nothing is cached: each read of a Workspace's Suggestions reads them again. + +mod config; +mod wildmatch; + +use std::collections::HashMap; +use std::ffi::OsString; +use std::path::{Path, PathBuf}; + +use agentdeck_core::RepositoryName; + +use self::config::{Context, Entry}; + +/// The config files git reads before the repo's own, in order, and the home `~/` stands for, +/// from the environment the daemon runs in. +#[derive(Debug, PartialEq, Eq)] +pub struct GitEnv { + home: Option, + files: Vec, +} + +impl GitEnv { + /// The daemon's own environment's. + pub fn from_env() -> GitEnv { + GitEnv::from_vars(|name| std::env::var_os(name)) + } + + /// As git finds them from the variables `var` gives: the system file (`$GIT_CONFIG_SYSTEM`, + /// else `/etc/gitconfig`; none under a true `$GIT_CONFIG_NOSYSTEM`), then the global ones + /// (`$GIT_CONFIG_GLOBAL`, else `$XDG_CONFIG_HOME/git/config` or `~/.config/git/config`, and + /// `~/.gitconfig`). + fn from_vars(var: impl Fn(&str) -> Option) -> GitEnv { + let set = |name: &str| var(name).filter(|value| !value.is_empty()); + let home = set("HOME").map(PathBuf::from); + let mut files = Vec::new(); + if !set("GIT_CONFIG_NOSYSTEM").is_some_and(|value| is_true(&value)) { + let system = var("GIT_CONFIG_SYSTEM").unwrap_or_else(|| "/etc/gitconfig".into()); + files.push(PathBuf::from(system)); + } + if let Some(global) = var("GIT_CONFIG_GLOBAL") { + files.push(PathBuf::from(global)); + } else { + match (set("XDG_CONFIG_HOME"), &home) { + (Some(xdg), _) => files.push(PathBuf::from(xdg).join("git/config")), + (None, Some(home)) => files.push(home.join(".config/git/config")), + (None, None) => {} + } + files.extend(home.iter().map(|home| home.join(".gitconfig"))); + } + GitEnv { home, files } + } +} + +/// A boolean variable as git reads one: `true`, `yes`, `on` or a number other than 0. +fn is_true(value: &OsString) -> bool { + let value = value.to_string_lossy().to_ascii_lowercase(); + matches!(value.as_str(), "true" | "yes" | "on") || value.parse::().is_ok_and(|n| n != 0) +} + +/// 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, env: &GitEnv) -> Option { + let (git_dir, common_dir) = git_dirs(folder)?; + let context = Context { + git_dir: &git_dir, + home: env.home.as_deref(), + }; + let local = common_dir.join("config"); + let entries: Vec = (env.files.iter().chain([&local])) + .flat_map(|file| config::read(file, &context)) + .collect(); + pick(&entries) +} + +/// The git dir of the repo holding `folder`, looking up from it (a worktree's own), and the +/// one holding its config (a worktree's main repo's). +fn git_dirs(folder: &Path) -> Option<(PathBuf, PathBuf)> { + folder.ancestors().find_map(|dir| { + let dot_git = dir.join(".git"); + let git_dir = if dot_git.is_dir() { + dot_git + } else if dot_git.is_file() { + linked_git_dir(dir, &std::fs::read_to_string(&dot_git).ok()?)? + } else { + return None; + }; + // A worktree's git dir names the main repo's, which holds the config, in `commondir`. + let common = match std::fs::read_to_string(git_dir.join("commondir")) { + Ok(common) => git_dir.join(common.trim()), + Err(_) => git_dir.clone(), + }; + Some((git_dir, common)) + }) +} + +/// The git dir a `.git` file in `dir` names (`gitdir: `, relative to `dir` or absolute). +fn linked_git_dir(dir: &Path, dot_git: &str) -> Option { + let path = dot_git + .lines() + .find_map(|line| line.strip_prefix("gitdir:"))?; + Some(dir.join(path.trim())) +} + +/// `upstream` when it is on GitHub, else `origin` when it is, each as `insteadOf` rewrites it. +fn pick(entries: &[Entry]) -> Option { + let remotes = remote_urls(entries); + ["upstream", "origin"].into_iter().find_map(|remote| { + RepositoryName::from_remote_url(&rewrite(remotes.get(remote)?, entries)) + }) +} + +/// Each remote's URL by the remote's name: its first `url`, where an empty one clears those +/// before it. +fn remote_urls(entries: &[Entry]) -> HashMap { + let mut urls = HashMap::new(); + for entry in entries.iter().filter(|e| e.is("remote", "url")) { + let (Some(name), Some(url)) = (&entry.subsection, &entry.value) else { + continue; + }; + if url.is_empty() { + urls.remove(name); + } else { + urls.entry(name.clone()).or_insert_with(|| url.clone()); + } + } + urls +} + +/// `url` with the longest prefix a `url..insteadOf` names replaced by its base; the +/// first of those as long when several are. +fn rewrite(url: &str, entries: &[Entry]) -> String { + let rules = (entries.iter()) + .filter(|e| e.is("url", "insteadof")) + .filter_map(|e| Some((e.subsection.as_deref()?, e.value.as_deref()?))); + let mut best: Option<(&str, &str)> = None; + for (base, prefix) in rules { + if url.starts_with(prefix) && prefix.len() > best.map_or(0, |(_, p)| p.len()) { + best = Some((base, prefix)); + } + } + match best { + Some((base, prefix)) => format!("{base}{}", &url[prefix.len()..]), + None => url.to_owned(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn names(text: &str) -> Vec<(String, String)> { + let mut urls: Vec<_> = remote_urls(&config::parse(text)).into_iter().collect(); + urls.sort(); + urls + } + + fn picked(text: &str) -> Option { + pick(&config::parse(text)).map(|name| name.to_string()) + } + + mod remote_urls { + use super::*; + + #[test] + fn should_read_each_remotes_url_by_its_name() { + let config = "[core]\n\trepositoryformatversion = 0\n\ + [remote \"origin\"]\n\turl = git@github.com:me/widgets.git\n\ + \tfetch = +refs/heads/*:refs/remotes/origin/*\n\ + [remote \"upstream\"]\n\turl = https://github.com/acme/widgets.git\n\ + [branch \"main\"]\n\tremote = origin\n"; + + assert_eq!( + names(config), + [ + ("origin".into(), "git@github.com:me/widgets.git".into()), + ( + "upstream".into(), + "https://github.com/acme/widgets.git".into() + ), + ] + ); + } + + #[test] + fn should_keep_a_remotes_first_url() { + let config = "[remote \"origin\"]\nurl = https://github.com/a/one\n\ + url = https://github.com/a/two\n"; + + assert_eq!( + names(config), + [("origin".into(), "https://github.com/a/one".into())] + ); + } + + #[test] + fn should_start_over_after_an_empty_url() { + let config = "[remote \"origin\"]\nurl = https://github.com/a/one\n\ + url =\nurl = https://github.com/a/two\n"; + + assert_eq!( + names(config), + [("origin".into(), "https://github.com/a/two".into())] + ); + } + + #[test] + fn should_ignore_case_in_section_and_key_but_not_in_the_remotes_name() { + let config = "[Remote \"Origin\"]\n URL = https://github.com/a/b\n"; + + assert_eq!( + names(config), + [("Origin".into(), "https://github.com/a/b".into())] + ); + } + + #[test] + fn should_read_the_old_dotted_header_in_lower_case() { + let config = "[remote.Upstream]\nurl = https://github.com/a/b\n"; + + assert_eq!( + names(config), + [("upstream".into(), "https://github.com/a/b".into())] + ); + } + + #[test] + fn should_not_take_a_url_from_another_section() { + let config = "[submodule \"lib\"]\nurl = https://github.com/a/lib\n\ + [url \"git@github.com:\"]\ninsteadOf = https://github.com/\n"; + + assert_eq!(names(config), []); + } + } + + 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 instead_of { + use super::*; + + #[test] + fn should_rewrite_a_url_starting_with_an_insteadof_prefix() { + let config = "[remote \"origin\"]\nurl = gh:acme/widgets\n\ + [url \"https://github.com/\"]\ninsteadOf = gh:\n"; + + assert_eq!(picked(config).as_deref(), Some("acme/widgets")); + } + + #[test] + fn should_rewrite_by_the_longest_matching_prefix() { + let config = "[url \"https://gitlab.com/\"]\ninsteadOf = co:\n\ + [url \"https://github.com/acme/\"]\ninsteadOf = co:acme/\n\ + [remote \"origin\"]\nurl = co:acme/widgets\n"; + + assert_eq!(picked(config).as_deref(), Some("acme/widgets")); + } + + #[test] + fn should_rewrite_upstream_before_choosing_it() { + let config = "[remote \"origin\"]\nurl = https://github.com/me/widgets\n\ + [remote \"upstream\"]\nurl = base:widgets\n\ + [url \"git@github.com:acme/\"]\ninsteadOf = base:\n"; + + assert_eq!(picked(config).as_deref(), Some("acme/widgets")); + } + + #[test] + fn should_not_rewrite_by_push_instead_of() { + let config = "[remote \"origin\"]\nurl = gh:acme/widgets\n\ + [url \"https://github.com/\"]\npushInsteadOf = gh:\n"; + + assert_eq!(picked(config), None); + } + } + } + + mod git_env { + use super::*; + + fn from(vars: &[(&str, &str)]) -> GitEnv { + GitEnv::from_vars(|name| { + (vars.iter()) + .find(|(key, _)| *key == name) + .map(|(_, value)| OsString::from(value)) + }) + } + + fn files(env: &GitEnv) -> Vec<&str> { + env.files.iter().map(|f| f.to_str().unwrap()).collect() + } + + #[test] + fn should_read_the_system_file_then_xdg_then_home() { + let env = from(&[("HOME", "/h"), ("XDG_CONFIG_HOME", "/x")]); + + assert_eq!( + files(&env), + ["/etc/gitconfig", "/x/git/config", "/h/.gitconfig"] + ); + assert_eq!(env.home.as_deref(), Some(Path::new("/h"))); + } + + #[test] + fn should_look_in_home_dot_config_without_xdg_config_home() { + let env = from(&[("HOME", "/h"), ("XDG_CONFIG_HOME", "")]); + + assert_eq!( + files(&env), + ["/etc/gitconfig", "/h/.config/git/config", "/h/.gitconfig"] + ); + } + + #[test] + fn should_read_git_config_global_and_system_in_their_place() { + let env = from(&[ + ("HOME", "/h"), + ("GIT_CONFIG_SYSTEM", "/s"), + ("GIT_CONFIG_GLOBAL", "/g"), + ]); + + assert_eq!(files(&env), ["/s", "/g"]); + } + + #[test] + fn should_skip_the_system_file_only_when_git_config_nosystem_is_true() { + for (value, skipped) in [("1", true), ("yes", true), ("0", false), ("false", false)] { + let env = from(&[("GIT_CONFIG_NOSYSTEM", value), ("GIT_CONFIG_GLOBAL", "/g")]); + + assert_eq!( + files(&env) == ["/g"], + skipped, + "GIT_CONFIG_NOSYSTEM={value}" + ); + } + } + + #[test] + fn should_read_no_global_file_without_a_home() { + assert_eq!( + files(&from(&[("GIT_CONFIG_NOSYSTEM", "1")])), + Vec::<&str>::new() + ); + } + } + + mod repository_of { + use super::*; + + fn write(path: &Path, text: &str) { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } + + /// The env of a user whose home is `/home`, with no system file. + fn env(dir: &Path) -> GitEnv { + let home = dir.join("home"); + GitEnv::from_vars(|name| match name { + "HOME" => Some(home.clone().into()), + "GIT_CONFIG_NOSYSTEM" => Some("1".into()), + _ => None, + }) + } + + fn found(folder: &Path, dir: &Path) -> Option { + repository_of(folder, &env(dir)).map(|n| n.to_string()) + } + + const ORIGIN: &str = "[remote \"origin\"]\n\turl = https://github.com/acme/widgets\n"; + const SHORT: &str = "[remote \"origin\"]\n\turl = gh:acme/widgets\n"; + const GH: &str = "[url \"https://github.com/\"]\n\tinsteadOf = gh:\n"; + + #[test] + fn should_read_the_repo_holding_a_folder_deep_inside_it() { + let dir = tempfile::tempdir().unwrap(); + write(&dir.path().join("repo/.git/config"), ORIGIN); + let deep = dir.path().join("repo/src/bin"); + std::fs::create_dir_all(&deep).unwrap(); + + assert_eq!(found(&deep, dir.path()).as_deref(), Some("acme/widgets")); + } + + #[test] + fn should_follow_a_worktrees_git_file_to_the_main_repos_config() { + let dir = tempfile::tempdir().unwrap(); + write(&dir.path().join("main/.git/config"), SHORT); + write(&dir.path().join("home/.gitconfig"), GH); + write( + &dir.path().join("main/.git/worktrees/wt/commondir"), + "../..\n", + ); + write( + &dir.path().join("wt/.git"), + &format!( + "gitdir: {}\n", + dir.path().join("main/.git/worktrees/wt").display() + ), + ); + + assert_eq!( + found(&dir.path().join("wt"), dir.path()).as_deref(), + Some("acme/widgets") + ); + } + + #[test] + fn should_follow_a_relative_git_file() { + let dir = tempfile::tempdir().unwrap(); + write(&dir.path().join("store/modules/lib/config"), ORIGIN); + write( + &dir.path().join("lib/.git"), + "gitdir: ../store/modules/lib\n", + ); + + assert_eq!( + found(&dir.path().join("lib"), dir.path()).as_deref(), + Some("acme/widgets") + ); + } + + #[test] + fn should_find_none_outside_a_repo() { + let dir = tempfile::tempdir().unwrap(); + + assert_eq!(found(dir.path(), dir.path()), None); + } + + #[test] + fn should_rewrite_by_an_insteadof_in_the_repos_config() { + let dir = tempfile::tempdir().unwrap(); + write( + &dir.path().join("repo/.git/config"), + &format!("{SHORT}{GH}"), + ); + + assert_eq!( + found(&dir.path().join("repo"), dir.path()).as_deref(), + Some("acme/widgets") + ); + } + + #[test] + fn should_rewrite_by_an_insteadof_in_the_global_config() { + let dir = tempfile::tempdir().unwrap(); + write(&dir.path().join("repo/.git/config"), SHORT); + write(&dir.path().join("home/.config/git/config"), GH); + + assert_eq!( + found(&dir.path().join("repo"), dir.path()).as_deref(), + Some("acme/widgets") + ); + } + + #[test] + fn should_read_a_remote_from_an_included_file() { + let dir = tempfile::tempdir().unwrap(); + write( + &dir.path().join("repo/.git/config"), + "[include]\n\tpath = ../../shared/remotes.inc\n", + ); + write(&dir.path().join("shared/remotes.inc"), ORIGIN); + + assert_eq!( + found(&dir.path().join("repo"), dir.path()).as_deref(), + Some("acme/widgets") + ); + } + + #[test] + fn should_follow_a_global_include_if_only_for_a_repo_its_gitdir_matches() { + let dir = tempfile::tempdir().unwrap(); + write( + &dir.path().join("home/.gitconfig"), + "[includeIf \"gitdir:~/work/\"]\n\tpath = work.inc\n", + ); + write(&dir.path().join("home/work.inc"), GH); + write(&dir.path().join("home/work/repo/.git/config"), SHORT); + write(&dir.path().join("home/play/repo/.git/config"), SHORT); + + assert_eq!( + found(&dir.path().join("home/work/repo"), dir.path()).as_deref(), + Some("acme/widgets") + ); + assert_eq!(found(&dir.path().join("home/play/repo"), dir.path()), None); + } + } +} diff --git a/crates/agentdeckd/src/suggestions/remotes/wildmatch.rs b/crates/agentdeckd/src/suggestions/remotes/wildmatch.rs new file mode 100644 index 0000000..c7c8eac --- /dev/null +++ b/crates/agentdeckd/src/suggestions/remotes/wildmatch.rs @@ -0,0 +1,182 @@ +//! git's `wildmatch` with `WM_PATHNAME`, which `includeIf` conditions match with (spec §3 +//! Suggestions): `*`, `?` and `[…]` never match a `/`; `**` does as `**/` at the start, `/**/` +//! or a trailing `/**`, and is a `*` anywhere else. `\` takes the next character literally. + +/// Whether the whole of `text` matches `pattern`, ignoring ASCII case when `fold`. +pub fn wildmatch(pattern: &str, text: &str, fold: bool) -> bool { + let pattern: Vec = pattern.chars().collect(); + let text: Vec = text.chars().collect(); + matches(&pattern, 0, &text, 0, fold) +} + +/// Whether `text[t..]` matches `pattern[p..]`. +fn matches(pattern: &[char], mut p: usize, text: &[char], mut t: usize, fold: bool) -> bool { + while let Some(&c) = pattern.get(p) { + match c { + '*' => { + let mut end = p; + while pattern.get(end) == Some(&'*') { + end += 1; + } + let after_slash = p == 0 || pattern[p - 1] == '/'; + if end - p >= 2 && after_slash { + match pattern.get(end) { + // A trailing `/**` (or a lone `**`) takes everything left. + None => return true, + // `**/` takes no folders, or any number of whole ones. + Some('/') => { + return matches(pattern, end + 1, text, t, fold) + || (t..text.len()).any(|i| { + text[i] == '/' && matches(pattern, end + 1, text, i + 1, fold) + }); + } + Some(_) => {} + } + } + // Anything else is a `*`: any run of characters but `/`. + let mut i = t; + loop { + if matches(pattern, end, text, i, fold) { + return true; + } + if i == text.len() || text[i] == '/' { + return false; + } + i += 1; + } + } + '?' => { + if text.get(t).is_none_or(|&c| c == '/') { + return false; + } + p += 1; + t += 1; + } + '[' => { + let Some(&got) = text.get(t) else { + return false; + }; + match class(pattern, p + 1, got, fold) { + Some((true, next)) if got != '/' => { + p = next; + t += 1; + } + _ => return false, + } + } + c => { + let (want, next) = match c { + '\\' if p + 1 < pattern.len() => (pattern[p + 1], p + 2), + c => (c, p + 1), + }; + if !text.get(t).is_some_and(|&got| same(want, got, fold)) { + return false; + } + p = next; + t += 1; + } + } + } + t == text.len() +} + +/// Whether the class starting at `pattern[p..]` (just after its `[`) holds `got`, and where the +/// pattern goes on after its `]`; `None` for a class with no `]`. +fn class(pattern: &[char], mut p: usize, got: char, fold: bool) -> Option<(bool, usize)> { + let negated = matches!(pattern.get(p), Some('!' | '^')); + if negated { + p += 1; + } + let mut held = false; + let mut first = true; + loop { + let mut c = *pattern.get(p)?; + if c == ']' && !first { + return Some((held != negated, p + 1)); + } + first = false; + if c == '\\' { + p += 1; + c = *pattern.get(p)?; + } + if pattern.get(p + 1) == Some(&'-') && pattern.get(p + 2).is_some_and(|&e| e != ']') { + let mut end = pattern[p + 2]; + p += 3; + if end == '\\' { + end = *pattern.get(p)?; + p += 1; + } + let within = |g: char| c <= g && g <= end; + held |= within(got) + || (fold && (within(got.to_ascii_lowercase()) || within(got.to_ascii_uppercase()))); + } else { + held |= same(c, got, fold); + p += 1; + } + } +} + +fn same(want: char, got: char, fold: bool) -> bool { + want == got || (fold && want.eq_ignore_ascii_case(&got)) +} + +#[cfg(test)] +mod tests { + use super::*; + + mod wildmatch { + use super::*; + + #[test] + fn should_match_literal_text_whole() { + assert!(wildmatch("a/b", "a/b", false)); + assert!(!wildmatch("a/b", "a/bc", false)); + assert!(!wildmatch("a/bc", "a/b", false)); + } + + #[test] + fn should_not_let_a_star_or_question_mark_cross_a_slash() { + assert!(wildmatch("a/*.git", "a/repo.git", false)); + assert!(!wildmatch("a/*", "a/b/c", false)); + assert!(wildmatch("a/?", "a/b", false)); + assert!(!wildmatch("a?b", "a/b", false)); + } + + #[test] + fn should_let_a_double_star_between_slashes_cross_them() { + assert!(wildmatch("**/work/**", "/home/me/work/repo/.git", false)); + assert!(wildmatch("/home/**/.git", "/home/me/work/repo/.git", false)); + assert!(wildmatch("a/**/b", "a/b", false)); + assert!(!wildmatch("/home/me/work/**", "/home/me/workshop/.git", false)); + } + + #[test] + fn should_read_a_double_star_inside_a_name_as_a_star() { + assert!(wildmatch("a/b**", "a/bcd", false)); + assert!(!wildmatch("a/b**", "a/b/c", false)); + } + + #[test] + fn should_match_a_bracket_class_with_ranges_and_negation() { + assert!(wildmatch("v[0-9]", "v7", false)); + assert!(!wildmatch("v[!0-9]", "v7", false)); + assert!(wildmatch("v[^0-9]", "vx", false)); + assert!(wildmatch("[]x]", "]", false)); + assert!(!wildmatch("a[/]b", "a/b", false)); + } + + #[test] + fn should_take_an_escaped_character_literally() { + assert!(wildmatch(r"a\*", "a*", false)); + assert!(!wildmatch(r"a\*", "ab", false)); + } + + #[test] + fn should_ignore_case_only_when_folding() { + assert!(wildmatch("/Home/*", "/home/x", true)); + assert!(!wildmatch("/Home/*", "/home/x", false)); + assert!(wildmatch("[A-Z]", "q", true)); + assert!(!wildmatch("[A-Z]", "q", false)); + } + } +} diff --git a/crates/agentdeckd/tests/integration/suggestions.rs b/crates/agentdeckd/tests/integration/suggestions.rs index 05be0d6..6a0ed93 100644 --- a/crates/agentdeckd/tests/integration/suggestions.rs +++ b/crates/agentdeckd/tests/integration/suggestions.rs @@ -252,6 +252,162 @@ mod get_v1_workspaces_suggestions { } } + /// Remotes git sees only through its config files beyond the repo's own: includes, + /// `includeIf` and `insteadOf`. Each fixture is checked with `git remote get-url` too, so + /// it means to git what the test says it does. + mod git_config { + use super::*; + + fn write(path: &Path, text: &str) { + std::fs::create_dir_all(path.parent().expect("a parent")).expect("making its dir"); + std::fs::write(path, text).expect("writing a config file"); + } + + /// The daemon's global git config, `$XDG_CONFIG_HOME/git/config`. + fn global_config(daemon: &TestDaemon) -> PathBuf { + daemon.root().join("config/git/config") + } + + /// The URL git gives `remote` of the repo at `dir`, with the daemon's home and config. + fn git_url(daemon: &TestDaemon, dir: &Path, remote: &str) -> String { + let output = std::process::Command::new("git") + .args(["remote", "get-url", remote]) + .current_dir(dir) + .env_clear() + .env("PATH", std::env::var_os("PATH").unwrap_or_default()) + .env("HOME", daemon.home()) + .env("XDG_CONFIG_HOME", daemon.root().join("config")) + .env("GIT_CONFIG_NOSYSTEM", "1") + .output() + .expect("running git"); + String::from_utf8(output.stdout) + .expect("a UTF-8 URL") + .trim() + .to_owned() + } + + #[tokio::test] + async fn should_follow_an_insteadof_rewrite_in_the_global_config_200() { + let github = MockServer::start_async().await; + mock_rest_repo(&github, TOKEN, WIDGETS, RestRepo::new(WIDGETS)); + let daemon = signed_in(&github).await; + write( + &global_config(&daemon), + "[url \"https://github.com/\"]\n\tinsteadOf = gh:\n", + ); + let dir = repo(&daemon, "widgets", &[("origin", "gh:acme/widgets")]); + assert_eq!( + git_url(&daemon, &dir, "origin"), + "https://github.com/acme/widgets" + ); + let (web, tab) = workspace(&daemon.client, "web").await; + + working_in(&daemon.client, tab, &dir).await; + + assert_eq!(names(&daemon.client, web.id).await, [WIDGETS]); + } + + #[tokio::test] + async fn should_follow_an_insteadof_rewrite_in_the_repos_config_200() { + let github = MockServer::start_async().await; + mock_rest_repo(&github, TOKEN, WIDGETS, RestRepo::new(WIDGETS)); + let daemon = signed_in(&github).await; + let dir = repo(&daemon, "widgets", &[("upstream", "work:acme/widgets")]); + git(&dir, &["config", "url.git@github.com:.insteadOf", "work:"]); + assert_eq!( + git_url(&daemon, &dir, "upstream"), + "git@github.com:acme/widgets" + ); + let (web, tab) = workspace(&daemon.client, "web").await; + + working_in(&daemon.client, tab, &dir).await; + + assert_eq!(names(&daemon.client, web.id).await, [WIDGETS]); + } + + #[tokio::test] + async fn should_read_a_remote_from_an_included_file_200() { + let github = MockServer::start_async().await; + mock_rest_repo(&github, TOKEN, WIDGETS, RestRepo::new(WIDGETS)); + let daemon = signed_in(&github).await; + let dir = repo(&daemon, "widgets", &[]); + write( + &dir.join(".git/remotes.inc"), + "[remote \"origin\"]\n\turl = https://github.com/acme/widgets\n", + ); + git(&dir, &["config", "include.path", "remotes.inc"]); + assert_eq!( + git_url(&daemon, &dir, "origin"), + "https://github.com/acme/widgets" + ); + let (web, tab) = workspace(&daemon.client, "web").await; + + working_in(&daemon.client, tab, &dir).await; + + assert_eq!(names(&daemon.client, web.id).await, [WIDGETS]); + } + + #[tokio::test] + async fn should_follow_an_include_if_only_for_a_repo_its_gitdir_matches_200() { + let github = MockServer::start_async().await; + mock_rest_repo(&github, TOKEN, WIDGETS, RestRepo::new(WIDGETS)); + let daemon = signed_in(&github).await; + let work = daemon.root().join("dirs/work"); + write( + &global_config(&daemon), + &format!( + "[includeIf \"gitdir:{}/\"]\n\tpath = work.inc\n", + work.display() + ), + ); + write( + &daemon.root().join("config/git/work.inc"), + "[url \"https://github.com/acme/\"]\n\tinsteadOf = acme:\n", + ); + let inside = repo(&daemon, "work/widgets", &[("origin", "acme:widgets")]); + let outside = repo(&daemon, "play/widgets", &[("origin", "acme:widgets")]); + assert_eq!( + git_url(&daemon, &inside, "origin"), + "https://github.com/acme/widgets" + ); + assert_eq!(git_url(&daemon, &outside, "origin"), "acme:widgets"); + let (web, web_tab) = workspace(&daemon.client, "web").await; + let (play, play_tab) = workspace(&daemon.client, "play").await; + + working_in(&daemon.client, web_tab, &inside).await; + working_in(&daemon.client, play_tab, &outside).await; + + assert_eq!(names(&daemon.client, web.id).await, [WIDGETS]); + assert_eq!(names(&daemon.client, play.id).await, Vec::::new()); + } + + #[tokio::test] + async fn should_follow_a_worktree_to_the_main_repos_rewritten_remote_200() { + let github = MockServer::start_async().await; + mock_rest_repo(&github, TOKEN, WIDGETS, RestRepo::new(WIDGETS)); + let daemon = signed_in(&github).await; + write( + &global_config(&daemon), + "[url \"https://github.com/\"]\n\tinsteadOf = gh:\n", + ); + let main = daemon.new_dir("main"); + crate::support::git::init_with_commit(&main); + git(&main, &["remote", "add", "origin", "gh:acme/widgets"]); + let tree = daemon.root().join("dirs/tree"); + let tree_arg = tree.to_str().expect("a UTF-8 path"); + git(&main, &["worktree", "add", "--quiet", "-b", "wt", tree_arg]); + assert_eq!( + git_url(&daemon, &tree, "origin"), + "https://github.com/acme/widgets" + ); + let (web, tab) = workspace(&daemon.client, "web").await; + + working_in(&daemon.client, tab, &tree).await; + + assert_eq!(names(&daemon.client, web.id).await, [WIDGETS]); + } + } + mod folders { use super::*; From 28443a2a53271ab2ba577011e929a232acb87f6e Mon Sep 17 00:00:00 2001 From: bRRRITSCOLD Date: Mon, 23 Nov 2026 19:22:55 -0700 Subject: [PATCH 2/3] docs(spec): Suggestions read git config as git does MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Spec §3: the config files read, includes and includeIf conditions, insteadOf rewrites, and why the daemon reads them itself instead of running git. Co-Authored-By: Claude Opus 5.5 --- .../src/suggestions/remotes/config.rs | 19 +++++++++---------- .../agentdeckd/src/suggestions/remotes/mod.rs | 6 +++--- .../src/suggestions/remotes/wildmatch.rs | 6 +++++- docs/spec.md | 3 ++- 4 files changed, 19 insertions(+), 15 deletions(-) diff --git a/crates/agentdeckd/src/suggestions/remotes/config.rs b/crates/agentdeckd/src/suggestions/remotes/config.rs index abe4d4d..13774c2 100644 --- a/crates/agentdeckd/src/suggestions/remotes/config.rs +++ b/crates/agentdeckd/src/suggestions/remotes/config.rs @@ -58,7 +58,9 @@ pub fn parse(text: &str) -> Vec { } c if c.is_ascii_alphabetic() => { let mut key = String::new(); - while let Some(&c) = chars.peek().filter(|c| c.is_ascii_alphanumeric() || **c == '-') + while let Some(&c) = chars + .peek() + .filter(|c| c.is_ascii_alphanumeric() || **c == '-') { key.push(c.to_ascii_lowercase()); chars.next(); @@ -379,10 +381,7 @@ mod tests { #[test] fn should_trim_a_value_and_keep_its_inner_spaces() { - assert_eq!( - listed(&parse("[a]\nb = one two \r\n")), - ["a.b=one two"] - ); + assert_eq!(listed(&parse("[a]\nb = one two \r\n")), ["a.b=one two"]); } #[test] @@ -493,7 +492,10 @@ mod tests { #[test] fn should_skip_an_include_that_cannot_be_read() { let f = Fixture::new(); - write(&f.path("config"), "[include]\npath = missing.inc\n[a]\nb = 1\n"); + write( + &f.path("config"), + "[include]\npath = missing.inc\n[a]\nb = 1\n", + ); assert_eq!(f.read("config"), ["include.path=missing.inc", "a.b=1"]); } @@ -539,10 +541,7 @@ mod tests { &f, &format!("gitdir:{}/", f.path("work").display()) )); - assert!(follows( - &f, - &format!("gitdir:{}", f.git_dir().display()) - )); + assert!(follows(&f, &format!("gitdir:{}", f.git_dir().display()))); } #[test] diff --git a/crates/agentdeckd/src/suggestions/remotes/mod.rs b/crates/agentdeckd/src/suggestions/remotes/mod.rs index c24417b..4a4f3f2 100644 --- a/crates/agentdeckd/src/suggestions/remotes/mod.rs +++ b/crates/agentdeckd/src/suggestions/remotes/mod.rs @@ -117,9 +117,9 @@ fn linked_git_dir(dir: &Path, dot_git: &str) -> Option { /// `upstream` when it is on GitHub, else `origin` when it is, each as `insteadOf` rewrites it. fn pick(entries: &[Entry]) -> Option { let remotes = remote_urls(entries); - ["upstream", "origin"].into_iter().find_map(|remote| { - RepositoryName::from_remote_url(&rewrite(remotes.get(remote)?, entries)) - }) + ["upstream", "origin"] + .into_iter() + .find_map(|remote| RepositoryName::from_remote_url(&rewrite(remotes.get(remote)?, entries))) } /// Each remote's URL by the remote's name: its first `url`, where an empty one clears those diff --git a/crates/agentdeckd/src/suggestions/remotes/wildmatch.rs b/crates/agentdeckd/src/suggestions/remotes/wildmatch.rs index c7c8eac..264a8dd 100644 --- a/crates/agentdeckd/src/suggestions/remotes/wildmatch.rs +++ b/crates/agentdeckd/src/suggestions/remotes/wildmatch.rs @@ -147,7 +147,11 @@ mod tests { assert!(wildmatch("**/work/**", "/home/me/work/repo/.git", false)); assert!(wildmatch("/home/**/.git", "/home/me/work/repo/.git", false)); assert!(wildmatch("a/**/b", "a/b", false)); - assert!(!wildmatch("/home/me/work/**", "/home/me/workshop/.git", false)); + assert!(!wildmatch( + "/home/me/work/**", + "/home/me/workshop/.git", + false + )); } #[test] diff --git a/docs/spec.md b/docs/spec.md index 54631f6..fe307a9 100644 --- a/docs/spec.md +++ b/docs/spec.md @@ -125,7 +125,8 @@ A PR is **Finished** (`finished_at` set) while it is merged or closed, open but A **Suggestion** is a Repository one of a Workspace's Panes works in that the Workspace doesn't link (§4 `GET /v1/workspaces/{id}/suggestions`, §11). The daemon works them out from what it already knows, and stores nothing: - **Which folders count:** every Pane in the Workspace's tabs at its current folder (§6), an exited one at its last known folder. Nothing else on disk is looked at: no root such as `~/Code` is scanned. -- **Which remote counts:** the git repo holding the folder (the folder or the nearest one above it with `.git`) gives its `upstream` remote when that is a GitHub URL (`RepositoryName::from_remote_url`: https, ssh and scp-like), else its `origin` when that is; any other remote is ignored. In a fork setup that gives the base repo, where your PRs live. The remotes are read from the repo's own `config` file, with no `git` process: `.git` is a directory, or a file naming the git dir (`gitdir: …`, as a worktree or submodule has), whose `commondir` leads a worktree to the main repo's config. `include`, `includeIf` and `url..insteadOf` aren't followed. +- **Which remote counts:** the git repo holding the folder (the folder or the nearest one above it with `.git`) gives its `upstream` remote when that is a GitHub URL (`RepositoryName::from_remote_url`: https, ssh and scp-like), else its `origin` when that is; any other remote is ignored. In a fork setup that gives the base repo, where your PRs live. A remote's URL is the one `git remote get-url` gives: its first `url` (an empty `url` clears those before it), rewritten by the longest matching `url..insteadOf` from any of the files below, so a short form such as `gh:owner/name` counts once it expands to GitHub. `pushInsteadOf` is never applied, since only pushes use it. +- **How git's config is read:** the daemon reads the files itself, as git does, with no `git` process: the system file (`$GIT_CONFIG_SYSTEM`, else `/etc/gitconfig`; none while `$GIT_CONFIG_NOSYSTEM` is true), the global ones (`$GIT_CONFIG_GLOBAL`, else `$XDG_CONFIG_HOME/git/config` or `~/.config/git/config`, then `~/.gitconfig`), all found from the daemon's environment, then the repo's `config`. `.git` is a directory, or a file naming the git dir (`gitdir: …`, as a worktree or submodule has), whose `commondir` leads a worktree to the main repo's config. In each file, an `include.path`, and an `includeIf "".path` whose condition holds, is read in where it stands (relative to the including file, `~/` for home), up to 10 includes deep. `gitdir:` (and `gitdir/i:`, ignoring case) matches the repo's git dir, a worktree's own, before or after following links, with git's wildcards: `~/` is home, `./` the including file's dir, a pattern not starting with `/` matches at any depth and one ending in `/` everything under it. `onbranch:` matches the checked-out branch. `hasconfig:` and any other condition never hold, and a worktree's `config.worktree` and settings given by `git -c` or `$GIT_CONFIG_COUNT` aren't read. **Why not run `git`:** `git config` would follow every rule for free, but a process per folder change needs `git` installed, a timeout and a per-folder cache that a later edit to any of those files leaves stale; reading a few small files costs less than starting one, so nothing is cached and every working-out of a Workspace's Suggestions reads them again. - **Which Repositories count:** each `owner/name` is confirmed with GitHub once per run (REST `GET /repos/{owner}/{repo}`, as a lookup, §8), which gives its id and its name now; the answer, the Repository or that GitHub can't see one, is kept in memory for the run, so a name is asked about once however many Panes and Workspaces work in it. One GitHub can't see is never suggested. A failed call keeps nothing and is tried again on the next read. Signed out (no token, or one GitHub rejects), only a Repository agentdeck keeps by that name (§3), ignoring case, and that isn't Unreachable is suggested. Then the Repositories the Workspace links go; one other Workspaces link stays. An archived Workspace has none. - **Dismissals** (Not now, and unlinks made in the GUI) are GUI state (§11), never the daemon's: the daemon's Suggestions aren't filtered by them. From e3ac330b9c4e1a8b4b000f5665c77068db9ebd8b Mon Sep 17 00:00:00 2001 From: bRRRITSCOLD Date: Tue, 24 Nov 2026 04:11:23 -0700 Subject: [PATCH 3/3] fix(daemon): ask git for a folder's remotes, file reader as fallback MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the hand-written git config parser with one `git -C remote -v` per Pane folder, which applies includes, includeIf and insteadOf itself. No shell, the daemon's environment less GIT_DIR/GIT_WORK_TREE/GIT_COMMON_DIR, killed after 2 s. When git is missing, fails or times out, the repo's own config file is read as before. Spec §3 says why and why nothing is cached. Co-Authored-By: Claude Opus 5.5 --- crates/agentdeckd/src/suggestions/mod.rs | 9 +- .../src/suggestions/remotes/config.rs | 645 ------------------ .../src/suggestions/remotes/file.rs | 292 ++++++++ .../agentdeckd/src/suggestions/remotes/git.rs | 152 +++++ .../agentdeckd/src/suggestions/remotes/mod.rs | 497 ++------------ .../src/suggestions/remotes/wildmatch.rs | 186 ----- .../tests/integration/suggestions.rs | 85 ++- docs/spec.md | 4 +- 8 files changed, 588 insertions(+), 1282 deletions(-) delete mode 100644 crates/agentdeckd/src/suggestions/remotes/config.rs create mode 100644 crates/agentdeckd/src/suggestions/remotes/file.rs create mode 100644 crates/agentdeckd/src/suggestions/remotes/git.rs delete mode 100644 crates/agentdeckd/src/suggestions/remotes/wildmatch.rs diff --git a/crates/agentdeckd/src/suggestions/mod.rs b/crates/agentdeckd/src/suggestions/mod.rs index 4848e45..687d9d0 100644 --- a/crates/agentdeckd/src/suggestions/mod.rs +++ b/crates/agentdeckd/src/suggestions/mod.rs @@ -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; @@ -259,9 +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 { - let env = remotes::GitEnv::from_env(); - (folders.iter()) - .filter_map(|folder| remotes::repository_of(&PathBuf::from(folder), &env)) + 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() } diff --git a/crates/agentdeckd/src/suggestions/remotes/config.rs b/crates/agentdeckd/src/suggestions/remotes/config.rs deleted file mode 100644 index 13774c2..0000000 --- a/crates/agentdeckd/src/suggestions/remotes/config.rs +++ /dev/null @@ -1,645 +0,0 @@ -//! git config files read as git reads them (spec §3 Suggestions): the syntax, and the files an -//! `include.path` or a matching `includeIf "".path` names, read where the include -//! stands. - -use std::path::{Path, PathBuf}; - -use super::wildmatch::wildmatch; - -/// One `key = value` of a config file. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Entry { - /// In lower case, as git compares it. - pub section: String, - /// As written, but in lower case under the old `[section.sub]` header. - pub subsection: Option, - /// In lower case, as git compares it. - pub key: String, - /// `None` for a key with no `=`, which git reads as true. - pub value: Option, -} - -impl Entry { - /// Whether this is `
..` or `
.`; both in lower case. - pub fn is(&self, section: &str, key: &str) -> bool { - self.section == section && self.key == key - } -} - -/// What an `includeIf` condition is tested against. -pub struct Context<'a> { - /// The repo's git dir (a worktree's own, not the main repo's), for `gitdir:` and `onbranch:`. - pub git_dir: &'a Path, - /// What `~/` stands for. - pub home: Option<&'a Path>, -} - -/// How deep includes nest before git gives up; deeper ones are left unread. -const MAX_INCLUDE_DEPTH: usize = 10; - -type Chars<'a> = std::iter::Peekable>; - -/// The entries of config `text`, in order; a line git can't read is skipped. -pub fn parse(text: &str) -> Vec { - let mut entries = Vec::new(); - let mut section: Option<(String, Option)> = None; - let mut chars = text.chars().peekable(); - while let Some(&c) = chars.peek() { - match c { - c if c.is_whitespace() => { - chars.next(); - } - '[' => { - chars.next(); - section = header(&mut chars); - if section.is_none() { - skip_line(&mut chars); - } - } - c if c.is_ascii_alphabetic() => { - let mut key = String::new(); - while let Some(&c) = chars - .peek() - .filter(|c| c.is_ascii_alphanumeric() || **c == '-') - { - key.push(c.to_ascii_lowercase()); - chars.next(); - } - skip_blanks(&mut chars); - let value = match chars.peek() { - Some('=') => { - chars.next(); - Some(value(&mut chars)) - } - None | Some('\n' | '#' | ';') => None, - Some(_) => { - skip_line(&mut chars); - continue; - } - }; - if let Some((name, sub)) = §ion { - entries.push(Entry { - section: name.clone(), - subsection: sub.clone(), - key, - value, - }); - } - } - // A comment, or a line git would refuse. - _ => skip_line(&mut chars), - } - } - entries -} - -/// The section a header names, read up to its `]` from just after its `[`: `section`, -/// `section "sub"` or the old `section.sub`. `None` for one git can't read. -fn header(chars: &mut Chars) -> Option<(String, Option)> { - // A line break is never taken here, so the caller's skip to the next line keeps the next. - let mut name = String::new(); - loop { - match chars.next_if(|&c| c != '\n')? { - ']' => { - let name = name.to_ascii_lowercase(); - if name.is_empty() { - return None; - } - return Some(match name.split_once('.') { - Some((section, sub)) => (section.to_owned(), Some(sub.to_owned())), - None => (name, None), - }); - } - c if c.is_ascii_alphanumeric() || c == '-' || c == '.' => name.push(c), - ' ' | '\t' if !name.is_empty() && !name.contains('.') => break, - _ => return None, - } - } - skip_blanks(chars); - chars.next_if_eq(&'"')?; - let mut sub = String::new(); - loop { - match chars.next_if(|&c| c != '\n')? { - '"' => break, - '\\' => sub.push(chars.next_if(|&c| c != '\n')?), - c => sub.push(c), - } - } - chars.next_if_eq(&']')?; - Some((name.to_ascii_lowercase(), Some(sub))) -} - -/// A value read from after its `=` to the end of its line, as git reads it: trimmed, quotes -/// taken off, an unquoted `#` or `;` starting a comment, `\` escapes undone and a `\` at the end -/// of a line joining the next. -fn value(chars: &mut Chars) -> String { - let mut out = String::new(); - let mut quoted = false; - let mut spaces = 0; - while let Some(c) = chars.next() { - match c { - '\n' => break, - c if c.is_whitespace() && !quoted => { - if !out.is_empty() { - spaces += 1; - } - } - '#' | ';' if !quoted => { - skip_line(chars); - break; - } - c => { - out.extend(std::iter::repeat_n(' ', spaces)); - spaces = 0; - match c { - '"' => quoted = !quoted, - '\\' => match chars.next() { - Some('\n') | None => {} - Some('\r') if chars.peek() == Some(&'\n') => { - chars.next(); - } - Some('n') => out.push('\n'), - Some('t') => out.push('\t'), - Some('b') => out.push('\u{8}'), - Some(c) => out.push(c), - }, - c => out.push(c), - } - } - } - } - out -} - -fn skip_blanks(chars: &mut Chars) { - while chars.next_if(|c| matches!(c, ' ' | '\t' | '\r')).is_some() {} -} - -fn skip_line(chars: &mut Chars) { - for c in chars.by_ref() { - if c == '\n' { - return; - } - } -} - -/// The entries of the config `file`, each file it includes read in where the include stands; -/// none when it can't be read. -pub fn read(file: &Path, context: &Context) -> Vec { - let mut entries = Vec::new(); - read_into(file, context, 0, &mut entries); - entries -} - -fn read_into(file: &Path, context: &Context, depth: usize, entries: &mut Vec) { - let Ok(text) = std::fs::read_to_string(file) else { - return; - }; - for entry in parse(&text) { - let included = entry.key == "path" - && match (entry.section.as_str(), entry.subsection.as_deref()) { - ("include", None) => true, - ("includeif", Some(condition)) => context.holds(condition, file), - _ => false, - }; - let target = (entry.value.as_deref()) - .filter(|_| included && depth < MAX_INCLUDE_DEPTH) - .and_then(|path| context.include_path(path, file)); - entries.push(entry); - if let Some(target) = target { - read_into(&target, context, depth + 1, entries); - } - } -} - -impl Context<'_> { - /// The file an include in `file` names by `path`: under home for `~/`, beside `file` when - /// relative. - fn include_path(&self, path: &str, file: &Path) -> Option { - if let Some(rest) = path.strip_prefix("~/") { - return Some(self.home?.join(rest)); - } - let path = Path::new(path); - if path.is_absolute() { - return Some(path.to_owned()); - } - Some(file.parent()?.join(path)) - } - - /// Whether the `includeIf` `condition` in `file` holds for the repo. - fn holds(&self, condition: &str, file: &Path) -> bool { - if let Some(pattern) = condition.strip_prefix("gitdir:") { - self.in_git_dir(pattern, file, false) - } else if let Some(pattern) = condition.strip_prefix("gitdir/i:") { - self.in_git_dir(pattern, file, true) - } else if let Some(pattern) = condition.strip_prefix("onbranch:") { - self.on_branch(pattern) - } else { - false - } - } - - /// `gitdir:`: whether the git dir, its real path or as found, matches `pattern`, where - /// `~/` is home, `./` the dir of `file`, a pattern not starting with `/` may match at any - /// depth and one ending in `/` matches everything under it. - fn in_git_dir(&self, pattern: &str, file: &Path, fold: bool) -> bool { - // `./`'s dir is matched as it is written, not as a pattern. - let (literal, mut glob) = if let Some(rest) = pattern.strip_prefix("~/") { - let Some(home) = self.home else { - return false; - }; - (String::new(), format!("{}/{rest}", home.display())) - } else if let Some(rest) = pattern.strip_prefix("./") { - let real = std::fs::canonicalize(file).ok(); - let Some(dir) = real.as_deref().and_then(Path::parent) else { - return false; - }; - (format!("{}/", dir.display()), rest.to_owned()) - } else if pattern.starts_with('/') { - (String::new(), pattern.to_owned()) - } else { - (String::new(), format!("**/{pattern}")) - }; - if format!("{literal}{glob}").ends_with('/') { - glob.push_str("**"); - } - let found = std::path::absolute(self.git_dir).ok(); - let real = std::fs::canonicalize(self.git_dir).ok(); - [real, found].into_iter().flatten().any(|dir| { - let dir = dir.to_string_lossy(); - dir.get(..literal.len()).is_some_and(|head| { - if fold { - head.eq_ignore_ascii_case(&literal) - } else { - head == literal - } - }) && wildmatch(&glob, &dir[literal.len()..], fold) - }) - } - - /// `onbranch:`: whether the branch checked out matches `pattern`, where one ending in `/` - /// matches every branch under it. A detached HEAD is on none. - fn on_branch(&self, pattern: &str) -> bool { - let Ok(head) = std::fs::read_to_string(self.git_dir.join("HEAD")) else { - return false; - }; - let Some(branch) = head.trim().strip_prefix("ref: refs/heads/") else { - return false; - }; - let mut pattern = pattern.to_owned(); - if pattern.ends_with('/') { - pattern.push_str("**"); - } - wildmatch(&pattern, branch, false) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn entry(section: &str, subsection: Option<&str>, key: &str, value: Option<&str>) -> Entry { - Entry { - section: section.into(), - subsection: subsection.map(Into::into), - key: key.into(), - value: value.map(Into::into), - } - } - - /// Each entry's `key` and value, the way `git config --list` shows them. - fn listed(entries: &[Entry]) -> Vec { - (entries.iter()) - .map(|e| { - let name = match &e.subsection { - Some(sub) => format!("{}.{sub}.{}", e.section, e.key), - None => format!("{}.{}", e.section, e.key), - }; - match &e.value { - Some(value) => format!("{name}={value}"), - None => name, - } - }) - .collect() - } - - mod parse { - use super::*; - - #[test] - fn should_read_sections_and_keys_in_lower_case_and_subsections_as_written() { - let config = "[Core]\n\tBare = false\n[Remote \"Origin\"]\n\tURL = https://x/y\n"; - - assert_eq!( - parse(config), - [ - entry("core", None, "bare", Some("false")), - entry("remote", Some("Origin"), "url", Some("https://x/y")), - ] - ); - } - - #[test] - fn should_read_the_old_dotted_header_with_its_subsection_in_lower_case() { - assert_eq!( - listed(&parse("[remote.Upstream]\nurl = a\n")), - ["remote.upstream.url=a"] - ); - } - - #[test] - fn should_undo_a_quoted_subsections_escapes() { - assert_eq!( - listed(&parse("[url \"a\\\"b\\\\c\"]\ninsteadOf = d\n")), - ["url.a\"b\\c.insteadof=d"] - ); - } - - #[test] - fn should_read_a_key_without_a_value_as_none() { - assert_eq!( - parse("[core]\n\tbare\n"), - [entry("core", None, "bare", None)] - ); - } - - #[test] - fn should_read_a_key_on_its_headers_line() { - assert_eq!( - listed(&parse("[remote \"origin\"] url = a\n")), - ["remote.origin.url=a"] - ); - } - - #[test] - fn should_skip_comments_and_take_off_quotes() { - let config = "# a comment\n; another\n[remote \"origin\"] # here too\n\ - url = \"https://x/#y\" # trailing\n"; - - assert_eq!(listed(&parse(config)), ["remote.origin.url=https://x/#y"]); - } - - #[test] - fn should_trim_a_value_and_keep_its_inner_spaces() { - assert_eq!(listed(&parse("[a]\nb = one two \r\n")), ["a.b=one two"]); - } - - #[test] - fn should_undo_escapes_and_join_a_continued_line() { - assert_eq!( - listed(&parse("[a]\nb = one\\\n two\\t\\\"\\\\\n")), - ["a.b=one two\t\"\\"] - ); - } - - #[test] - fn should_skip_a_line_it_cannot_read() { - assert_eq!( - listed(&parse("orphan = 1\n[a]\n= 2\nb = 3\n[broken\n[c]\nd = 4\n")), - ["a.b=3", "c.d=4"] - ); - } - } - - mod read { - use std::path::PathBuf; - - use super::*; - - fn write(path: &Path, text: &str) { - std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - std::fs::write(path, text).unwrap(); - } - - /// A temp dir with a git dir at `repo/.git` and a home at `home`. - struct Fixture { - dir: tempfile::TempDir, - } - - impl Fixture { - fn new() -> Fixture { - let dir = tempfile::tempdir().unwrap(); - std::fs::create_dir_all(dir.path().join("work/repo/.git")).unwrap(); - std::fs::create_dir_all(dir.path().join("home")).unwrap(); - Fixture { dir } - } - - fn path(&self, rel: &str) -> PathBuf { - self.dir.path().join(rel) - } - - fn git_dir(&self) -> PathBuf { - self.path("work/repo/.git") - } - - /// Reads `file` for the repo at `work/repo`. - fn read(&self, file: &str) -> Vec { - let git_dir = self.git_dir(); - let home = self.path("home"); - let context = Context { - git_dir: &git_dir, - home: Some(&home), - }; - listed(&read(&self.path(file), &context)) - } - } - - #[test] - fn should_read_an_included_file_where_the_include_stands() { - let f = Fixture::new(); - write( - &f.path("config"), - "[a]\none = 1\n[include]\npath = more.inc\n[a]\nthree = 3\n", - ); - write(&f.path("more.inc"), "[a]\ntwo = 2\n"); - - assert_eq!( - f.read("config"), - ["a.one=1", "include.path=more.inc", "a.two=2", "a.three=3"] - ); - } - - #[test] - fn should_find_a_relative_include_beside_the_including_file() { - let f = Fixture::new(); - write(&f.path("config"), "[include]\npath = nested/one.inc\n"); - write(&f.path("nested/one.inc"), "[include]\npath = two.inc\n"); - write(&f.path("nested/two.inc"), "[a]\nb = 2\n"); - - assert_eq!(f.read("config").last().unwrap(), "a.b=2"); - } - - #[test] - fn should_find_an_include_under_home_or_at_an_absolute_path() { - let f = Fixture::new(); - let absolute = f.path("elsewhere/abs.inc"); - write( - &f.path("config"), - &format!( - "[include]\npath = ~/home.inc\npath = {}\n", - absolute.display() - ), - ); - write(&f.path("home/home.inc"), "[a]\nhome = 1\n"); - write(&absolute, "[a]\nabsolute = 1\n"); - - let read = f.read("config"); - - assert!(read.contains(&"a.home=1".to_owned()), "{read:?}"); - assert!(read.contains(&"a.absolute=1".to_owned()), "{read:?}"); - } - - #[test] - fn should_skip_an_include_that_cannot_be_read() { - let f = Fixture::new(); - write( - &f.path("config"), - "[include]\npath = missing.inc\n[a]\nb = 1\n", - ); - - assert_eq!(f.read("config"), ["include.path=missing.inc", "a.b=1"]); - } - - #[test] - fn should_stop_following_includes_ten_deep() { - let f = Fixture::new(); - write(&f.path("config"), "[a]\nb = 1\n[include]\npath = config\n"); - - assert_eq!( - (f.read("config").iter()) - .filter(|line| *line == "a.b=1") - .count(), - 11 - ); - } - - #[test] - fn should_read_nothing_from_a_file_that_cannot_be_read() { - let f = Fixture::new(); - - assert_eq!(f.read("missing"), Vec::::new()); - } - - mod include_if { - use super::*; - - /// Whether `config` with `[includeIf ""] path = cond.inc` reads it in. - fn follows(f: &Fixture, condition: &str) -> bool { - write( - &f.path("config"), - &format!("[includeIf \"{condition}\"]\npath = cond.inc\n"), - ); - write(&f.path("cond.inc"), "[a]\nb = 1\n"); - f.read("config").contains(&"a.b=1".to_owned()) - } - - #[test] - fn should_follow_gitdir_when_the_repos_git_dir_is_under_it() { - let f = Fixture::new(); - - assert!(follows( - &f, - &format!("gitdir:{}/", f.path("work").display()) - )); - assert!(follows(&f, &format!("gitdir:{}", f.git_dir().display()))); - } - - #[test] - fn should_not_follow_gitdir_when_the_repo_is_elsewhere() { - let f = Fixture::new(); - - assert!(!follows( - &f, - &format!("gitdir:{}/", f.path("play").display()) - )); - assert!(!follows( - &f, - &format!("gitdir:{}", f.path("work").display()) - )); - } - - #[test] - fn should_match_a_relative_gitdir_pattern_at_any_depth() { - let f = Fixture::new(); - - assert!(follows(&f, "gitdir:work/")); - assert!(follows(&f, "gitdir:repo/.git")); - assert!(!follows(&f, "gitdir:play/")); - } - - #[test] - fn should_expand_a_path_beside_the_config_file() { - let f = Fixture::new(); - - assert!(follows(&f, "gitdir:./work/")); - assert!(!follows(&f, "gitdir:./play/")); - } - - #[test] - fn should_expand_home_and_match_the_git_dir_before_or_after_links() { - let f = Fixture::new(); - let home = f.path("home"); - std::fs::create_dir_all(home.join("code")).unwrap(); - std::os::unix::fs::symlink(f.path("work"), home.join("code/work")).unwrap(); - let linked = home.join("code/work/repo/.git"); - write(&f.path("cond.inc"), "[a]\nb = 1\n"); - let follows_from = |condition: &str, git_dir: &Path| { - write( - &f.path("config"), - &format!("[includeIf \"{condition}\"]\npath = cond.inc\n"), - ); - let context = Context { - git_dir, - home: Some(&home), - }; - listed(&read(&f.path("config"), &context)).contains(&"a.b=1".to_owned()) - }; - - assert!(follows_from("gitdir:~/code/work/", &linked)); - assert!(follows_from( - &format!("gitdir:{}/", f.path("work").display()), - &linked - )); - assert!(!follows_from("gitdir:~/code/work/", &f.git_dir())); - } - - #[test] - fn should_ignore_case_only_under_gitdir_i() { - let f = Fixture::new(); - let upper = format!("{}/", f.path("WORK").display()); - - assert!(follows(&f, &format!("gitdir/i:{upper}"))); - assert!(!follows(&f, &format!("gitdir:{upper}"))); - } - - #[test] - fn should_follow_onbranch_when_the_checked_out_branch_matches() { - let f = Fixture::new(); - write( - &f.git_dir().join("HEAD"), - "ref: refs/heads/feature/widgets\n", - ); - - assert!(follows(&f, "onbranch:feature/")); - assert!(follows(&f, "onbranch:feature/w*")); - assert!(follows(&f, "onbranch:feature/widgets")); - assert!(!follows(&f, "onbranch:main")); - } - - #[test] - fn should_not_follow_onbranch_on_a_detached_head() { - let f = Fixture::new(); - write(&f.git_dir().join("HEAD"), "0123456789abcdef\n"); - - assert!(!follows(&f, "onbranch:**")); - } - - #[test] - fn should_not_follow_a_condition_it_does_not_know() { - let f = Fixture::new(); - - assert!(!follows(&f, "hasconfig:remote.*.url:https://github.com/**")); - } - } - } -} diff --git a/crates/agentdeckd/src/suggestions/remotes/file.rs b/crates/agentdeckd/src/suggestions/remotes/file.rs new file mode 100644 index 0000000..00ad8be --- /dev/null +++ b/crates/agentdeckd/src/suggestions/remotes/file.rs @@ -0,0 +1,292 @@ +//! 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..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}; + +/// 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> { + let config = std::fs::read_to_string(config_file(folder)?).ok()?; + Some(remote_urls(&config)) +} +/// The `config` file of the git repo holding `folder`, looking up from it. +fn config_file(folder: &Path) -> Option { + folder.ancestors().find_map(|dir| { + let dot_git = dir.join(".git"); + let git_dir = if dot_git.is_dir() { + dot_git + } else if dot_git.is_file() { + linked_git_dir(dir, &std::fs::read_to_string(&dot_git).ok()?)? + } else { + return None; + }; + // A worktree's git dir names the main repo's, which holds the config, in `commondir`. + let common = match std::fs::read_to_string(git_dir.join("commondir")) { + Ok(common) => git_dir.join(common.trim()), + Err(_) => git_dir, + }; + Some(common.join("config")) + }) +} + +/// The git dir a `.git` file in `dir` names (`gitdir: `, relative to `dir` or absolute). +fn linked_git_dir(dir: &Path, dot_git: &str) -> Option { + let path = dot_git + .lines() + .find_map(|line| line.strip_prefix("gitdir:"))?; + Some(dir.join(path.trim())) +} + +/// Each remote's URL in git config `text`, by the remote's name: its first `url`. +pub fn remote_urls(text: &str) -> HashMap { + let mut urls = HashMap::new(); + let mut remote: Option = None; + for line in text.lines() { + let line = line.trim(); + if line.is_empty() || line.starts_with(['#', ';']) { + continue; + } + if let Some(header) = line.strip_prefix('[') { + remote = remote_section(header); + // `[remote "origin"] url = …`: a key may follow its header on the line. + let Some((_, rest)) = header.split_once(']') else { + continue; + }; + if rest.trim().is_empty() { + continue; + } + if let (Some(name), Some(url)) = (&remote, url_value(rest.trim())) { + urls.entry(name.clone()).or_insert(url); + } + continue; + } + if let (Some(name), Some(url)) = (&remote, url_value(line)) { + urls.entry(name.clone()).or_insert(url); + } + } + urls +} + +/// The remote a section header names (the text after its `[`): `remote "origin"]`, or the old +/// `remote.origin]`, whose name git reads in lower case. `None` for any other section. +fn remote_section(header: &str) -> Option { + let (header, _) = header.split_once(']')?; + let header = header.trim(); + if let Some((section, sub)) = header.split_once(char::is_whitespace) { + let sub = sub.trim().strip_prefix('"')?.strip_suffix('"')?; + return section + .eq_ignore_ascii_case("remote") + .then(|| unescape(sub)); + } + let (section, sub) = header.split_once('.')?; + section + .eq_ignore_ascii_case("remote") + .then(|| sub.to_lowercase()) +} + +/// The value of a `url = …` line; `None` for another key. Quotes are taken off and an +/// unquoted `#` or `;` starts a comment. +fn url_value(line: &str) -> Option { + let (key, value) = line.split_once('=')?; + if !key.trim().eq_ignore_ascii_case("url") { + return None; + } + let mut out = String::new(); + let mut quoted = false; + let mut chars = value.trim().chars(); + while let Some(c) = chars.next() { + match c { + '"' => quoted = !quoted, + '\\' => out.extend(chars.next()), + '#' | ';' if !quoted => break, + c => out.push(c), + } + } + let url = out.trim().to_owned(); + (!url.is_empty()).then_some(url) +} + +/// A subsection name with git's `\"` and `\\` escapes undone. +fn unescape(sub: &str) -> String { + let mut out = String::new(); + let mut chars = sub.chars(); + while let Some(c) = chars.next() { + match c { + '\\' => out.extend(chars.next()), + c => out.push(c), + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn names(text: &str) -> Vec<(String, String)> { + let mut urls: Vec<_> = remote_urls(text).into_iter().collect(); + urls.sort(); + urls + } + + mod remote_urls { + use super::*; + + #[test] + fn should_read_each_remotes_url_by_its_name() { + let config = "[core]\n\trepositoryformatversion = 0\n\ + [remote \"origin\"]\n\turl = git@github.com:me/widgets.git\n\ + \tfetch = +refs/heads/*:refs/remotes/origin/*\n\ + [remote \"upstream\"]\n\turl = https://github.com/acme/widgets.git\n\ + [branch \"main\"]\n\tremote = origin\n"; + + assert_eq!( + names(config), + [ + ("origin".into(), "git@github.com:me/widgets.git".into()), + ( + "upstream".into(), + "https://github.com/acme/widgets.git".into() + ), + ] + ); + } + + #[test] + fn should_keep_a_remotes_first_url() { + let config = "[remote \"origin\"]\nurl = https://github.com/a/one\n\ + url = https://github.com/a/two\n"; + + assert_eq!( + names(config), + [("origin".into(), "https://github.com/a/one".into())] + ); + } + + #[test] + fn should_ignore_case_in_section_and_key_but_not_in_the_remotes_name() { + let config = "[Remote \"Origin\"]\n URL = https://github.com/a/b\n"; + + assert_eq!( + names(config), + [("Origin".into(), "https://github.com/a/b".into())] + ); + } + + #[test] + fn should_read_the_old_dotted_header_in_lower_case() { + let config = "[remote.Upstream]\nurl = https://github.com/a/b\n"; + + assert_eq!( + names(config), + [("upstream".into(), "https://github.com/a/b".into())] + ); + } + + #[test] + fn should_skip_comments_and_take_off_quotes() { + let config = "# a comment\n; another\n[remote \"origin\"]\n\ + url = \"https://github.com/a/b\" # trailing\n"; + + assert_eq!( + names(config), + [("origin".into(), "https://github.com/a/b".into())] + ); + } + + #[test] + fn should_read_a_url_on_its_headers_line() { + let config = "[remote \"origin\"] url = https://github.com/a/b\n"; + + assert_eq!( + names(config), + [("origin".into(), "https://github.com/a/b".into())] + ); + } + + #[test] + fn should_not_take_a_url_from_another_section() { + let config = "[submodule \"lib\"]\nurl = https://github.com/a/lib\n\ + [url \"git@github.com:\"]\ninsteadOf = https://github.com/\n"; + + assert_eq!(names(config), []); + } + } + + 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 { + remote_urls_of(folder)?.remove("origin") + } + + const ORIGIN: &str = "[remote \"origin\"]\n\turl = https://github.com/acme/widgets\n"; + + #[test] + fn should_read_the_repo_holding_a_folder_deep_inside_it() { + let dir = tempfile::tempdir().unwrap(); + write(&dir.path().join("repo/.git/config"), ORIGIN); + let deep = dir.path().join("repo/src/bin"); + std::fs::create_dir_all(&deep).unwrap(); + + assert_eq!( + origin(&deep).as_deref(), + Some("https://github.com/acme/widgets") + ); + } + + #[test] + fn should_follow_a_worktrees_git_file_to_the_main_repos_config() { + let dir = tempfile::tempdir().unwrap(); + write(&dir.path().join("main/.git/config"), ORIGIN); + write( + &dir.path().join("main/.git/worktrees/wt/commondir"), + "../..\n", + ); + write( + &dir.path().join("wt/.git"), + &format!( + "gitdir: {}\n", + dir.path().join("main/.git/worktrees/wt").display() + ), + ); + + assert_eq!( + origin(&dir.path().join("wt")).as_deref(), + Some("https://github.com/acme/widgets") + ); + } + + #[test] + fn should_follow_a_relative_git_file() { + let dir = tempfile::tempdir().unwrap(); + write(&dir.path().join("store/modules/lib/config"), ORIGIN); + write( + &dir.path().join("lib/.git"), + "gitdir: ../store/modules/lib\n", + ); + + assert_eq!( + 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!(remote_urls_of(dir.path()), None); + } + } +} diff --git a/crates/agentdeckd/src/suggestions/remotes/git.rs b/crates/agentdeckd/src/suggestions/remotes/git.rs new file mode 100644 index 0000000..451df7b --- /dev/null +++ b/crates/agentdeckd/src/suggestions/remotes/git.rs @@ -0,0 +1,152 @@ +//! Asking `git` for a folder's remotes (spec §3 Suggestions): one `git -C remote -v`, +//! which prints each remote's URL as git uses it, after `include`, `includeIf` and +//! `url..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 ` -C remote -v` prints them. A +/// `git` still running after `timeout` is killed. +pub fn remote_urls( + program: &OsStr, + folder: &Path, + timeout: Duration, +) -> Result, 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 `\t (fetch)` +/// line (which a partial clone's ` []` follows). +fn parse(output: &str) -> HashMap { + (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:?}"); + } + } +} diff --git a/crates/agentdeckd/src/suggestions/remotes/mod.rs b/crates/agentdeckd/src/suggestions/remotes/mod.rs index 4a4f3f2..1ea35f3 100644 --- a/crates/agentdeckd/src/suggestions/remotes/mod.rs +++ b/crates/agentdeckd/src/suggestions/remotes/mod.rs @@ -1,248 +1,70 @@ //! 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 from git's config files as git reads them, with no `git` process: the -//! system file, the user's global files, then the repo's `config`, each with the files its -//! `include.path` and matching `includeIf` (`gitdir:`, `gitdir/i:`, `onbranch:`) name, read in -//! where they stand ([`config`]). A remote's first `url` is rewritten by the longest matching -//! `url..insteadOf` among them all, as `git remote get-url` gives it. 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. -//! -//! Reading a few small files costs less than a `git` process, works without `git` installed and -//! is never stale, so nothing is cached: each read of a Workspace's Suggestions reads them again. +//! `git` itself is asked for the remotes ([`git`]), so each URL is the one git uses, after every +//! config file, include and `insteadOf` rewrite it applies. When `git` is missing, fails or +//! takes longer than [`GIT_TIMEOUT`], the repo's own `config` file is read instead +//! ([`file`](mod@file)). +//! Nothing is cached: Suggestions are worked out only when something they depend on changes, +//! and on a read, so a `git` per Pane folder each time costs little and never goes stale. -mod config; -mod wildmatch; +mod file; +mod git; use std::collections::HashMap; use std::ffi::OsString; -use std::path::{Path, PathBuf}; +use std::path::Path; +use std::time::Duration; use agentdeck_core::RepositoryName; -use self::config::{Context, Entry}; +/// How long `git remote -v` may take before the repo's `config` file is read instead. +pub const GIT_TIMEOUT: Duration = Duration::from_secs(2); -/// The config files git reads before the repo's own, in order, and the home `~/` stands for, -/// from the environment the daemon runs in. -#[derive(Debug, PartialEq, Eq)] -pub struct GitEnv { - home: Option, - files: Vec, +/// The `git` a folder's remotes are asked of: `git` on the daemon's `PATH`. +pub struct Git { + program: OsString, + timeout: Duration, } -impl GitEnv { - /// The daemon's own environment's. - pub fn from_env() -> GitEnv { - GitEnv::from_vars(|name| std::env::var_os(name)) - } - - /// As git finds them from the variables `var` gives: the system file (`$GIT_CONFIG_SYSTEM`, - /// else `/etc/gitconfig`; none under a true `$GIT_CONFIG_NOSYSTEM`), then the global ones - /// (`$GIT_CONFIG_GLOBAL`, else `$XDG_CONFIG_HOME/git/config` or `~/.config/git/config`, and - /// `~/.gitconfig`). - fn from_vars(var: impl Fn(&str) -> Option) -> GitEnv { - let set = |name: &str| var(name).filter(|value| !value.is_empty()); - let home = set("HOME").map(PathBuf::from); - let mut files = Vec::new(); - if !set("GIT_CONFIG_NOSYSTEM").is_some_and(|value| is_true(&value)) { - let system = var("GIT_CONFIG_SYSTEM").unwrap_or_else(|| "/etc/gitconfig".into()); - files.push(PathBuf::from(system)); +impl Default for Git { + fn default() -> Git { + Git { + program: "git".into(), + timeout: GIT_TIMEOUT, } - if let Some(global) = var("GIT_CONFIG_GLOBAL") { - files.push(PathBuf::from(global)); - } else { - match (set("XDG_CONFIG_HOME"), &home) { - (Some(xdg), _) => files.push(PathBuf::from(xdg).join("git/config")), - (None, Some(home)) => files.push(home.join(".config/git/config")), - (None, None) => {} - } - files.extend(home.iter().map(|home| home.join(".gitconfig"))); - } - GitEnv { home, files } } } -/// A boolean variable as git reads one: `true`, `yes`, `on` or a number other than 0. -fn is_true(value: &OsString) -> bool { - let value = value.to_string_lossy().to_ascii_lowercase(); - matches!(value.as_str(), "true" | "yes" | "on") || value.parse::().is_ok_and(|n| n != 0) -} - /// 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, env: &GitEnv) -> Option { - let (git_dir, common_dir) = git_dirs(folder)?; - let context = Context { - git_dir: &git_dir, - home: env.home.as_deref(), +pub fn repository_of(folder: &Path, git: &Git) -> Option { + let remotes = match git::remote_urls(&git.program, folder, git.timeout) { + Ok(remotes) => remotes, + Err(err) => { + tracing::debug!( + "asking git for {}'s remotes: {err}; reading its config file instead", + folder.display() + ); + file::remote_urls_of(folder)? + } }; - let local = common_dir.join("config"); - let entries: Vec = (env.files.iter().chain([&local])) - .flat_map(|file| config::read(file, &context)) - .collect(); - pick(&entries) -} - -/// The git dir of the repo holding `folder`, looking up from it (a worktree's own), and the -/// one holding its config (a worktree's main repo's). -fn git_dirs(folder: &Path) -> Option<(PathBuf, PathBuf)> { - folder.ancestors().find_map(|dir| { - let dot_git = dir.join(".git"); - let git_dir = if dot_git.is_dir() { - dot_git - } else if dot_git.is_file() { - linked_git_dir(dir, &std::fs::read_to_string(&dot_git).ok()?)? - } else { - return None; - }; - // A worktree's git dir names the main repo's, which holds the config, in `commondir`. - let common = match std::fs::read_to_string(git_dir.join("commondir")) { - Ok(common) => git_dir.join(common.trim()), - Err(_) => git_dir.clone(), - }; - Some((git_dir, common)) - }) + pick(&remotes) } -/// The git dir a `.git` file in `dir` names (`gitdir: `, relative to `dir` or absolute). -fn linked_git_dir(dir: &Path, dot_git: &str) -> Option { - let path = dot_git - .lines() - .find_map(|line| line.strip_prefix("gitdir:"))?; - Some(dir.join(path.trim())) -} - -/// `upstream` when it is on GitHub, else `origin` when it is, each as `insteadOf` rewrites it. -fn pick(entries: &[Entry]) -> Option { - let remotes = remote_urls(entries); +/// `upstream` when it is on GitHub, else `origin` when it is. +fn pick(remotes: &HashMap) -> Option { ["upstream", "origin"] .into_iter() - .find_map(|remote| RepositoryName::from_remote_url(&rewrite(remotes.get(remote)?, entries))) -} - -/// Each remote's URL by the remote's name: its first `url`, where an empty one clears those -/// before it. -fn remote_urls(entries: &[Entry]) -> HashMap { - let mut urls = HashMap::new(); - for entry in entries.iter().filter(|e| e.is("remote", "url")) { - let (Some(name), Some(url)) = (&entry.subsection, &entry.value) else { - continue; - }; - if url.is_empty() { - urls.remove(name); - } else { - urls.entry(name.clone()).or_insert_with(|| url.clone()); - } - } - urls -} - -/// `url` with the longest prefix a `url..insteadOf` names replaced by its base; the -/// first of those as long when several are. -fn rewrite(url: &str, entries: &[Entry]) -> String { - let rules = (entries.iter()) - .filter(|e| e.is("url", "insteadof")) - .filter_map(|e| Some((e.subsection.as_deref()?, e.value.as_deref()?))); - let mut best: Option<(&str, &str)> = None; - for (base, prefix) in rules { - if url.starts_with(prefix) && prefix.len() > best.map_or(0, |(_, p)| p.len()) { - best = Some((base, prefix)); - } - } - match best { - Some((base, prefix)) => format!("{base}{}", &url[prefix.len()..]), - None => url.to_owned(), - } + .find_map(|remote| RepositoryName::from_remote_url(remotes.get(remote)?)) } #[cfg(test)] mod tests { use super::*; - fn names(text: &str) -> Vec<(String, String)> { - let mut urls: Vec<_> = remote_urls(&config::parse(text)).into_iter().collect(); - urls.sort(); - urls - } - fn picked(text: &str) -> Option { - pick(&config::parse(text)).map(|name| name.to_string()) - } - - mod remote_urls { - use super::*; - - #[test] - fn should_read_each_remotes_url_by_its_name() { - let config = "[core]\n\trepositoryformatversion = 0\n\ - [remote \"origin\"]\n\turl = git@github.com:me/widgets.git\n\ - \tfetch = +refs/heads/*:refs/remotes/origin/*\n\ - [remote \"upstream\"]\n\turl = https://github.com/acme/widgets.git\n\ - [branch \"main\"]\n\tremote = origin\n"; - - assert_eq!( - names(config), - [ - ("origin".into(), "git@github.com:me/widgets.git".into()), - ( - "upstream".into(), - "https://github.com/acme/widgets.git".into() - ), - ] - ); - } - - #[test] - fn should_keep_a_remotes_first_url() { - let config = "[remote \"origin\"]\nurl = https://github.com/a/one\n\ - url = https://github.com/a/two\n"; - - assert_eq!( - names(config), - [("origin".into(), "https://github.com/a/one".into())] - ); - } - - #[test] - fn should_start_over_after_an_empty_url() { - let config = "[remote \"origin\"]\nurl = https://github.com/a/one\n\ - url =\nurl = https://github.com/a/two\n"; - - assert_eq!( - names(config), - [("origin".into(), "https://github.com/a/two".into())] - ); - } - - #[test] - fn should_ignore_case_in_section_and_key_but_not_in_the_remotes_name() { - let config = "[Remote \"Origin\"]\n URL = https://github.com/a/b\n"; - - assert_eq!( - names(config), - [("Origin".into(), "https://github.com/a/b".into())] - ); - } - - #[test] - fn should_read_the_old_dotted_header_in_lower_case() { - let config = "[remote.Upstream]\nurl = https://github.com/a/b\n"; - - assert_eq!( - names(config), - [("upstream".into(), "https://github.com/a/b".into())] - ); - } - - #[test] - fn should_not_take_a_url_from_another_section() { - let config = "[submodule \"lib\"]\nurl = https://github.com/a/lib\n\ - [url \"git@github.com:\"]\ninsteadOf = https://github.com/\n"; - - assert_eq!(names(config), []); - } + pick(&file::remote_urls(text)).map(|name| name.to_string()) } mod pick { @@ -271,253 +93,42 @@ mod tests { assert_eq!(picked(config), None); } - - mod instead_of { - use super::*; - - #[test] - fn should_rewrite_a_url_starting_with_an_insteadof_prefix() { - let config = "[remote \"origin\"]\nurl = gh:acme/widgets\n\ - [url \"https://github.com/\"]\ninsteadOf = gh:\n"; - - assert_eq!(picked(config).as_deref(), Some("acme/widgets")); - } - - #[test] - fn should_rewrite_by_the_longest_matching_prefix() { - let config = "[url \"https://gitlab.com/\"]\ninsteadOf = co:\n\ - [url \"https://github.com/acme/\"]\ninsteadOf = co:acme/\n\ - [remote \"origin\"]\nurl = co:acme/widgets\n"; - - assert_eq!(picked(config).as_deref(), Some("acme/widgets")); - } - - #[test] - fn should_rewrite_upstream_before_choosing_it() { - let config = "[remote \"origin\"]\nurl = https://github.com/me/widgets\n\ - [remote \"upstream\"]\nurl = base:widgets\n\ - [url \"git@github.com:acme/\"]\ninsteadOf = base:\n"; - - assert_eq!(picked(config).as_deref(), Some("acme/widgets")); - } - - #[test] - fn should_not_rewrite_by_push_instead_of() { - let config = "[remote \"origin\"]\nurl = gh:acme/widgets\n\ - [url \"https://github.com/\"]\npushInsteadOf = gh:\n"; - - assert_eq!(picked(config), None); - } - } - } - - mod git_env { - use super::*; - - fn from(vars: &[(&str, &str)]) -> GitEnv { - GitEnv::from_vars(|name| { - (vars.iter()) - .find(|(key, _)| *key == name) - .map(|(_, value)| OsString::from(value)) - }) - } - - fn files(env: &GitEnv) -> Vec<&str> { - env.files.iter().map(|f| f.to_str().unwrap()).collect() - } - - #[test] - fn should_read_the_system_file_then_xdg_then_home() { - let env = from(&[("HOME", "/h"), ("XDG_CONFIG_HOME", "/x")]); - - assert_eq!( - files(&env), - ["/etc/gitconfig", "/x/git/config", "/h/.gitconfig"] - ); - assert_eq!(env.home.as_deref(), Some(Path::new("/h"))); - } - - #[test] - fn should_look_in_home_dot_config_without_xdg_config_home() { - let env = from(&[("HOME", "/h"), ("XDG_CONFIG_HOME", "")]); - - assert_eq!( - files(&env), - ["/etc/gitconfig", "/h/.config/git/config", "/h/.gitconfig"] - ); - } - - #[test] - fn should_read_git_config_global_and_system_in_their_place() { - let env = from(&[ - ("HOME", "/h"), - ("GIT_CONFIG_SYSTEM", "/s"), - ("GIT_CONFIG_GLOBAL", "/g"), - ]); - - assert_eq!(files(&env), ["/s", "/g"]); - } - - #[test] - fn should_skip_the_system_file_only_when_git_config_nosystem_is_true() { - for (value, skipped) in [("1", true), ("yes", true), ("0", false), ("false", false)] { - let env = from(&[("GIT_CONFIG_NOSYSTEM", value), ("GIT_CONFIG_GLOBAL", "/g")]); - - assert_eq!( - files(&env) == ["/g"], - skipped, - "GIT_CONFIG_NOSYSTEM={value}" - ); - } - } - - #[test] - fn should_read_no_global_file_without_a_home() { - assert_eq!( - files(&from(&[("GIT_CONFIG_NOSYSTEM", "1")])), - Vec::<&str>::new() - ); - } } mod repository_of { use super::*; - fn write(path: &Path, text: &str) { - std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - std::fs::write(path, text).unwrap(); - } - - /// The env of a user whose home is `/home`, with no system file. - fn env(dir: &Path) -> GitEnv { - let home = dir.join("home"); - GitEnv::from_vars(|name| match name { - "HOME" => Some(home.clone().into()), - "GIT_CONFIG_NOSYSTEM" => Some("1".into()), - _ => None, - }) - } - - fn found(folder: &Path, dir: &Path) -> Option { - repository_of(folder, &env(dir)).map(|n| n.to_string()) - } - - const ORIGIN: &str = "[remote \"origin\"]\n\turl = https://github.com/acme/widgets\n"; - const SHORT: &str = "[remote \"origin\"]\n\turl = gh:acme/widgets\n"; - const GH: &str = "[url \"https://github.com/\"]\n\tinsteadOf = gh:\n"; - - #[test] - fn should_read_the_repo_holding_a_folder_deep_inside_it() { - let dir = tempfile::tempdir().unwrap(); - write(&dir.path().join("repo/.git/config"), ORIGIN); - let deep = dir.path().join("repo/src/bin"); - std::fs::create_dir_all(&deep).unwrap(); - - assert_eq!(found(&deep, dir.path()).as_deref(), Some("acme/widgets")); - } - - #[test] - fn should_follow_a_worktrees_git_file_to_the_main_repos_config() { - let dir = tempfile::tempdir().unwrap(); - write(&dir.path().join("main/.git/config"), SHORT); - write(&dir.path().join("home/.gitconfig"), GH); - write( - &dir.path().join("main/.git/worktrees/wt/commondir"), - "../..\n", - ); - write( - &dir.path().join("wt/.git"), - &format!( - "gitdir: {}\n", - dir.path().join("main/.git/worktrees/wt").display() - ), - ); - - assert_eq!( - found(&dir.path().join("wt"), dir.path()).as_deref(), - Some("acme/widgets") - ); - } - - #[test] - fn should_follow_a_relative_git_file() { - let dir = tempfile::tempdir().unwrap(); - write(&dir.path().join("store/modules/lib/config"), ORIGIN); - write( - &dir.path().join("lib/.git"), - "gitdir: ../store/modules/lib\n", - ); - - assert_eq!( - found(&dir.path().join("lib"), dir.path()).as_deref(), - Some("acme/widgets") - ); - } - - #[test] - fn should_find_none_outside_a_repo() { - let dir = tempfile::tempdir().unwrap(); - - assert_eq!(found(dir.path(), dir.path()), None); - } - - #[test] - fn should_rewrite_by_an_insteadof_in_the_repos_config() { - let dir = tempfile::tempdir().unwrap(); - write( - &dir.path().join("repo/.git/config"), - &format!("{SHORT}{GH}"), - ); - - assert_eq!( - found(&dir.path().join("repo"), dir.path()).as_deref(), - Some("acme/widgets") - ); - } - - #[test] - fn should_rewrite_by_an_insteadof_in_the_global_config() { - let dir = tempfile::tempdir().unwrap(); - write(&dir.path().join("repo/.git/config"), SHORT); - write(&dir.path().join("home/.config/git/config"), GH); - - assert_eq!( - found(&dir.path().join("repo"), dir.path()).as_deref(), - Some("acme/widgets") - ); + /// A `git` that can't start, so the repo's `config` file answers. + fn no_git(dir: &Path) -> Git { + Git { + program: dir.join("no-git-here").into(), + timeout: GIT_TIMEOUT, + } } #[test] - fn should_read_a_remote_from_an_included_file() { + fn should_read_the_repos_config_when_git_cannot_start() { let dir = tempfile::tempdir().unwrap(); - write( - &dir.path().join("repo/.git/config"), - "[include]\n\tpath = ../../shared/remotes.inc\n", - ); - write(&dir.path().join("shared/remotes.inc"), ORIGIN); + std::fs::create_dir_all(dir.path().join("repo/.git")).unwrap(); + std::fs::write( + dir.path().join("repo/.git/config"), + "[remote \"origin\"]\n\turl = https://github.com/acme/widgets\n", + ) + .unwrap(); assert_eq!( - found(&dir.path().join("repo"), dir.path()).as_deref(), + repository_of(&dir.path().join("repo"), &no_git(dir.path())) + .map(|n| n.to_string()) + .as_deref(), Some("acme/widgets") ); } #[test] - fn should_follow_a_global_include_if_only_for_a_repo_its_gitdir_matches() { + fn should_find_none_outside_a_repo_when_git_cannot_start() { let dir = tempfile::tempdir().unwrap(); - write( - &dir.path().join("home/.gitconfig"), - "[includeIf \"gitdir:~/work/\"]\n\tpath = work.inc\n", - ); - write(&dir.path().join("home/work.inc"), GH); - write(&dir.path().join("home/work/repo/.git/config"), SHORT); - write(&dir.path().join("home/play/repo/.git/config"), SHORT); - assert_eq!( - found(&dir.path().join("home/work/repo"), dir.path()).as_deref(), - Some("acme/widgets") - ); - assert_eq!(found(&dir.path().join("home/play/repo"), dir.path()), None); + assert_eq!(repository_of(dir.path(), &no_git(dir.path())), None); } } } diff --git a/crates/agentdeckd/src/suggestions/remotes/wildmatch.rs b/crates/agentdeckd/src/suggestions/remotes/wildmatch.rs deleted file mode 100644 index 264a8dd..0000000 --- a/crates/agentdeckd/src/suggestions/remotes/wildmatch.rs +++ /dev/null @@ -1,186 +0,0 @@ -//! git's `wildmatch` with `WM_PATHNAME`, which `includeIf` conditions match with (spec §3 -//! Suggestions): `*`, `?` and `[…]` never match a `/`; `**` does as `**/` at the start, `/**/` -//! or a trailing `/**`, and is a `*` anywhere else. `\` takes the next character literally. - -/// Whether the whole of `text` matches `pattern`, ignoring ASCII case when `fold`. -pub fn wildmatch(pattern: &str, text: &str, fold: bool) -> bool { - let pattern: Vec = pattern.chars().collect(); - let text: Vec = text.chars().collect(); - matches(&pattern, 0, &text, 0, fold) -} - -/// Whether `text[t..]` matches `pattern[p..]`. -fn matches(pattern: &[char], mut p: usize, text: &[char], mut t: usize, fold: bool) -> bool { - while let Some(&c) = pattern.get(p) { - match c { - '*' => { - let mut end = p; - while pattern.get(end) == Some(&'*') { - end += 1; - } - let after_slash = p == 0 || pattern[p - 1] == '/'; - if end - p >= 2 && after_slash { - match pattern.get(end) { - // A trailing `/**` (or a lone `**`) takes everything left. - None => return true, - // `**/` takes no folders, or any number of whole ones. - Some('/') => { - return matches(pattern, end + 1, text, t, fold) - || (t..text.len()).any(|i| { - text[i] == '/' && matches(pattern, end + 1, text, i + 1, fold) - }); - } - Some(_) => {} - } - } - // Anything else is a `*`: any run of characters but `/`. - let mut i = t; - loop { - if matches(pattern, end, text, i, fold) { - return true; - } - if i == text.len() || text[i] == '/' { - return false; - } - i += 1; - } - } - '?' => { - if text.get(t).is_none_or(|&c| c == '/') { - return false; - } - p += 1; - t += 1; - } - '[' => { - let Some(&got) = text.get(t) else { - return false; - }; - match class(pattern, p + 1, got, fold) { - Some((true, next)) if got != '/' => { - p = next; - t += 1; - } - _ => return false, - } - } - c => { - let (want, next) = match c { - '\\' if p + 1 < pattern.len() => (pattern[p + 1], p + 2), - c => (c, p + 1), - }; - if !text.get(t).is_some_and(|&got| same(want, got, fold)) { - return false; - } - p = next; - t += 1; - } - } - } - t == text.len() -} - -/// Whether the class starting at `pattern[p..]` (just after its `[`) holds `got`, and where the -/// pattern goes on after its `]`; `None` for a class with no `]`. -fn class(pattern: &[char], mut p: usize, got: char, fold: bool) -> Option<(bool, usize)> { - let negated = matches!(pattern.get(p), Some('!' | '^')); - if negated { - p += 1; - } - let mut held = false; - let mut first = true; - loop { - let mut c = *pattern.get(p)?; - if c == ']' && !first { - return Some((held != negated, p + 1)); - } - first = false; - if c == '\\' { - p += 1; - c = *pattern.get(p)?; - } - if pattern.get(p + 1) == Some(&'-') && pattern.get(p + 2).is_some_and(|&e| e != ']') { - let mut end = pattern[p + 2]; - p += 3; - if end == '\\' { - end = *pattern.get(p)?; - p += 1; - } - let within = |g: char| c <= g && g <= end; - held |= within(got) - || (fold && (within(got.to_ascii_lowercase()) || within(got.to_ascii_uppercase()))); - } else { - held |= same(c, got, fold); - p += 1; - } - } -} - -fn same(want: char, got: char, fold: bool) -> bool { - want == got || (fold && want.eq_ignore_ascii_case(&got)) -} - -#[cfg(test)] -mod tests { - use super::*; - - mod wildmatch { - use super::*; - - #[test] - fn should_match_literal_text_whole() { - assert!(wildmatch("a/b", "a/b", false)); - assert!(!wildmatch("a/b", "a/bc", false)); - assert!(!wildmatch("a/bc", "a/b", false)); - } - - #[test] - fn should_not_let_a_star_or_question_mark_cross_a_slash() { - assert!(wildmatch("a/*.git", "a/repo.git", false)); - assert!(!wildmatch("a/*", "a/b/c", false)); - assert!(wildmatch("a/?", "a/b", false)); - assert!(!wildmatch("a?b", "a/b", false)); - } - - #[test] - fn should_let_a_double_star_between_slashes_cross_them() { - assert!(wildmatch("**/work/**", "/home/me/work/repo/.git", false)); - assert!(wildmatch("/home/**/.git", "/home/me/work/repo/.git", false)); - assert!(wildmatch("a/**/b", "a/b", false)); - assert!(!wildmatch( - "/home/me/work/**", - "/home/me/workshop/.git", - false - )); - } - - #[test] - fn should_read_a_double_star_inside_a_name_as_a_star() { - assert!(wildmatch("a/b**", "a/bcd", false)); - assert!(!wildmatch("a/b**", "a/b/c", false)); - } - - #[test] - fn should_match_a_bracket_class_with_ranges_and_negation() { - assert!(wildmatch("v[0-9]", "v7", false)); - assert!(!wildmatch("v[!0-9]", "v7", false)); - assert!(wildmatch("v[^0-9]", "vx", false)); - assert!(wildmatch("[]x]", "]", false)); - assert!(!wildmatch("a[/]b", "a/b", false)); - } - - #[test] - fn should_take_an_escaped_character_literally() { - assert!(wildmatch(r"a\*", "a*", false)); - assert!(!wildmatch(r"a\*", "ab", false)); - } - - #[test] - fn should_ignore_case_only_when_folding() { - assert!(wildmatch("/Home/*", "/home/x", true)); - assert!(!wildmatch("/Home/*", "/home/x", false)); - assert!(wildmatch("[A-Z]", "q", true)); - assert!(!wildmatch("[A-Z]", "q", false)); - } - } -} diff --git a/crates/agentdeckd/tests/integration/suggestions.rs b/crates/agentdeckd/tests/integration/suggestions.rs index 6a0ed93..0e11e92 100644 --- a/crates/agentdeckd/tests/integration/suggestions.rs +++ b/crates/agentdeckd/tests/integration/suggestions.rs @@ -18,7 +18,7 @@ use crate::support::github::{ }; use crate::support::terminal::{eventually, in_state, sh}; use crate::support::ws::{Frame, Ws}; -use crate::support::{TestDaemon, error_response}; +use crate::support::{TestDaemon, error_response, set_daemon_env}; const TOKEN: &str = "gho_test"; const WIDGETS: &str = "acme/widgets"; @@ -254,7 +254,8 @@ mod get_v1_workspaces_suggestions { /// Remotes git sees only through its config files beyond the repo's own: includes, /// `includeIf` and `insteadOf`. Each fixture is checked with `git remote get-url` too, so - /// it means to git what the test says it does. + /// it means to git what the test says it does. Without a `git` that answers, the repo's + /// own `config` file still does. mod git_config { use super::*; @@ -286,6 +287,86 @@ mod get_v1_workspaces_suggestions { .to_owned() } + /// [`signed_in`], with the `PATH` that `path` makes from the daemon's temp root. + async fn signed_in_on_path( + github: &MockServer, + path: impl FnOnce(&Path) -> String, + ) -> TestDaemon { + mock_viewer(github, TOKEN, "octocat", None); + let dirs = tempfile::tempdir().expect("a temp dir"); + set_gh_token(dirs.path(), Some(TOKEN)); + let path = path(dirs.path()); + set_daemon_env(dirs.path(), &[("PATH", &path)]); + TestDaemon::start_with_github(dirs, &github.url("/graphql")).await + } + + /// `dir` holding links to the programs a Pane and the stub `gh` run, and no `git`. + fn without_git(dir: &Path) -> PathBuf { + std::fs::create_dir_all(dir).expect("making the dir"); + for program in ["sh", "sleep", "cat", "dirname"] { + let found = std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()) + .map(|entry| entry.join(program)) + .find(|path| path.is_file()) + .unwrap_or_else(|| panic!("{program} on PATH")); + std::os::unix::fs::symlink(found, dir.join(program)).expect("linking it"); + } + dir.to_owned() + } + + #[tokio::test] + async fn should_read_the_repos_own_config_without_git_200() { + let github = MockServer::start_async().await; + mock_rest_repo(&github, TOKEN, WIDGETS, RestRepo::new(WIDGETS)); + let daemon = signed_in_on_path(&github, |root| { + let no_git = without_git(&root.join("no-git")); + format!("{}:{}", root.join("bin").display(), no_git.display()) + }) + .await; + assert!(!daemon.root().join("no-git/git").exists()); + let dir = repo( + &daemon, + "widgets", + &[("origin", "https://github.com/acme/widgets")], + ); + let (web, tab) = workspace(&daemon.client, "web").await; + + working_in(&daemon.client, tab, &dir).await; + + assert_eq!(names(&daemon.client, web.id).await, [WIDGETS]); + } + + #[tokio::test] + async fn should_read_the_repos_own_config_when_git_hangs_200() { + let github = MockServer::start_async().await; + mock_rest_repo(&github, TOKEN, WIDGETS, RestRepo::new(WIDGETS)); + let daemon = signed_in_on_path(&github, |root| { + let hang = root.join("hang"); + write(&hang.join("git"), "#!/bin/sh\nexec sleep 30\n"); + std::fs::set_permissions( + hang.join("git"), + std::os::unix::fs::PermissionsExt::from_mode(0o755), + ) + .expect("making the stub git executable"); + format!( + "{}:{}:{}", + root.join("bin").display(), + hang.display(), + std::env::var("PATH").unwrap_or_default() + ) + }) + .await; + let dir = repo( + &daemon, + "widgets", + &[("origin", "https://github.com/acme/widgets")], + ); + let (web, tab) = workspace(&daemon.client, "web").await; + + working_in(&daemon.client, tab, &dir).await; + + assert_eq!(names(&daemon.client, web.id).await, [WIDGETS]); + } + #[tokio::test] async fn should_follow_an_insteadof_rewrite_in_the_global_config_200() { let github = MockServer::start_async().await; diff --git a/docs/spec.md b/docs/spec.md index fe307a9..bb41588 100644 --- a/docs/spec.md +++ b/docs/spec.md @@ -125,8 +125,8 @@ A PR is **Finished** (`finished_at` set) while it is merged or closed, open but A **Suggestion** is a Repository one of a Workspace's Panes works in that the Workspace doesn't link (§4 `GET /v1/workspaces/{id}/suggestions`, §11). The daemon works them out from what it already knows, and stores nothing: - **Which folders count:** every Pane in the Workspace's tabs at its current folder (§6), an exited one at its last known folder. Nothing else on disk is looked at: no root such as `~/Code` is scanned. -- **Which remote counts:** the git repo holding the folder (the folder or the nearest one above it with `.git`) gives its `upstream` remote when that is a GitHub URL (`RepositoryName::from_remote_url`: https, ssh and scp-like), else its `origin` when that is; any other remote is ignored. In a fork setup that gives the base repo, where your PRs live. A remote's URL is the one `git remote get-url` gives: its first `url` (an empty `url` clears those before it), rewritten by the longest matching `url..insteadOf` from any of the files below, so a short form such as `gh:owner/name` counts once it expands to GitHub. `pushInsteadOf` is never applied, since only pushes use it. -- **How git's config is read:** the daemon reads the files itself, as git does, with no `git` process: the system file (`$GIT_CONFIG_SYSTEM`, else `/etc/gitconfig`; none while `$GIT_CONFIG_NOSYSTEM` is true), the global ones (`$GIT_CONFIG_GLOBAL`, else `$XDG_CONFIG_HOME/git/config` or `~/.config/git/config`, then `~/.gitconfig`), all found from the daemon's environment, then the repo's `config`. `.git` is a directory, or a file naming the git dir (`gitdir: …`, as a worktree or submodule has), whose `commondir` leads a worktree to the main repo's config. In each file, an `include.path`, and an `includeIf "".path` whose condition holds, is read in where it stands (relative to the including file, `~/` for home), up to 10 includes deep. `gitdir:` (and `gitdir/i:`, ignoring case) matches the repo's git dir, a worktree's own, before or after following links, with git's wildcards: `~/` is home, `./` the including file's dir, a pattern not starting with `/` matches at any depth and one ending in `/` everything under it. `onbranch:` matches the checked-out branch. `hasconfig:` and any other condition never hold, and a worktree's `config.worktree` and settings given by `git -c` or `$GIT_CONFIG_COUNT` aren't read. **Why not run `git`:** `git config` would follow every rule for free, but a process per folder change needs `git` installed, a timeout and a per-folder cache that a later edit to any of those files leaves stale; reading a few small files costs less than starting one, so nothing is cached and every working-out of a Workspace's Suggestions reads them again. +- **Which remote counts:** the git repo holding the folder (the folder or the nearest one above it with `.git`) gives its `upstream` remote when that is a GitHub URL (`RepositoryName::from_remote_url`: https, ssh and scp-like), else its `origin` when that is; any other remote is ignored. In a fork setup that gives the base repo, where your PRs live. A remote's URL is its fetch URL as git uses it, so one written as a short form such as `gh:owner/name` counts once a `url..insteadOf` expands it to GitHub, and one defined in an included file counts too. +- **How the remotes are read:** `git` itself is asked: one `git -C remote -v` per Pane folder (each folder once per working-out), run without a shell, with the daemon's own environment (so the user's system, global, included and `includeIf` config all apply) less `GIT_DIR`, `GIT_WORK_TREE` and `GIT_COMMON_DIR`, and killed after 2 s. Its fetch lines give each remote's URL after git's own includes and `insteadOf` rewrites. When `git` is missing, exits with an error or times out, the daemon reads the repo's own `config` file instead: `.git` is a directory, or a file naming the git dir (`gitdir: …`, as a worktree or submodule has), whose `commondir` leads a worktree to the main repo's config. That fallback follows no `include`, `includeIf`, global config or `insteadOf`. **Why `git` and not a parser of our own:** git's config rules (include conditions, path patterns, rewrite precedence) are many and keep growing, and asking git is right by definition. **Nothing is cached:** Suggestions are worked out only when something they depend on changes (below: a Pane opening, exiting or moving, a Link, a Repository or the sign-in changing) and on each read of the route, never per keystroke, so a `git` per Pane folder each time costs little and never goes stale after a config edit. - **Which Repositories count:** each `owner/name` is confirmed with GitHub once per run (REST `GET /repos/{owner}/{repo}`, as a lookup, §8), which gives its id and its name now; the answer, the Repository or that GitHub can't see one, is kept in memory for the run, so a name is asked about once however many Panes and Workspaces work in it. One GitHub can't see is never suggested. A failed call keeps nothing and is tried again on the next read. Signed out (no token, or one GitHub rejects), only a Repository agentdeck keeps by that name (§3), ignoring case, and that isn't Unreachable is suggested. Then the Repositories the Workspace links go; one other Workspaces link stays. An archived Workspace has none. - **Dismissals** (Not now, and unlinks made in the GUI) are GUI state (§11), never the daemon's: the daemon's Suggestions aren't filtered by them.