diff --git a/crates/agentdeckd/src/suggestions/mod.rs b/crates/agentdeckd/src/suggestions/mod.rs index 655cabd..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,8 +259,10 @@ impl Suggestions { /// The Repository a git repo's remote names, by the name in lower case, for each of `folders` /// that is in one. fn worked_in(folders: &[String]) -> BTreeMap { - (folders.iter()) - .filter_map(|folder| remotes::repository_of(&PathBuf::from(folder))) + let git = remotes::Git::default(); + let folders: BTreeSet<&String> = folders.iter().collect(); + (folders.into_iter()) + .filter_map(|folder| remotes::repository_of(&PathBuf::from(folder), &git)) .map(|name| (name.to_string().to_lowercase(), name)) .collect() } diff --git a/crates/agentdeckd/src/suggestions/remotes.rs b/crates/agentdeckd/src/suggestions/remotes/file.rs similarity index 75% rename from crates/agentdeckd/src/suggestions/remotes.rs rename to crates/agentdeckd/src/suggestions/remotes/file.rs index 61ec0dc..00ad8be 100644 --- a/crates/agentdeckd/src/suggestions/remotes.rs +++ b/crates/agentdeckd/src/suggestions/remotes/file.rs @@ -1,31 +1,19 @@ -//! Which Repository a folder's git repo works in (spec §3 Suggestions): its `upstream` remote -//! when that is on GitHub, else its `origin`; any other remote is ignored. -//! -//! The remotes are read straight from the repo's `config` file, with no `git` process: the -//! folder or the nearest folder above it holding `.git`, a directory, or a file naming the -//! git dir (`gitdir: …`, as a worktree or a submodule has), whose `commondir` leads a worktree -//! to the main repo's config. `include` and `includeIf` files, and `url..insteadOf` -//! rewrites, aren't followed: a remote that only they make a GitHub URL suggests nothing. +//! The fallback for when `git` can't answer (spec §3 Suggestions): the remotes read straight +//! from the repo's `config` file. The repo is the folder or the nearest folder above it holding +//! `.git`, a directory, or a file naming the git dir (`gitdir: …`, as a worktree or a submodule +//! has), whose `commondir` leads a worktree to the main repo's config. Only that file is read: +//! `include` and `includeIf` files, the user's global config and `url..insteadOf` +//! rewrites aren't, so a remote that only they make a GitHub URL suggests nothing here. use std::collections::HashMap; use std::path::{Path, PathBuf}; -use agentdeck_core::RepositoryName; - -/// The Repository the git repo holding `folder` works in: its `upstream` remote when that is on -/// GitHub, else its `origin` when that is. `None` outside a git repo, or when neither is. -pub fn repository_of(folder: &Path) -> Option { +/// 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()?; - 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)?)) + 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| { @@ -146,10 +134,6 @@ mod tests { urls } - fn picked(text: &str) -> Option { - pick(&remote_urls(text)).map(|name| name.to_string()) - } - mod remote_urls { use super::*; @@ -234,35 +218,7 @@ mod tests { } } - mod pick { - use super::*; - - #[test] - fn should_prefer_upstream_on_github() { - let config = "[remote \"origin\"]\nurl = git@github.com:me/widgets.git\n\ - [remote \"upstream\"]\nurl = https://github.com/acme/widgets.git\n"; - - assert_eq!(picked(config).as_deref(), Some("acme/widgets")); - } - - #[test] - fn should_take_origin_when_upstream_is_not_on_github() { - let config = "[remote \"origin\"]\nurl = git@github.com:me/widgets.git\n\ - [remote \"upstream\"]\nurl = https://gitlab.com/acme/widgets.git\n"; - - assert_eq!(picked(config).as_deref(), Some("me/widgets")); - } - - #[test] - fn should_ignore_every_other_remote() { - let config = "[remote \"fork\"]\nurl = https://github.com/me/widgets\n\ - [remote \"origin\"]\nurl = https://gitlab.com/acme/widgets\n"; - - assert_eq!(picked(config), None); - } - } - - mod repository_of { + mod remote_urls_of { use super::*; fn write(path: &Path, text: &str) { @@ -270,6 +226,10 @@ mod tests { 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] @@ -280,8 +240,8 @@ mod tests { std::fs::create_dir_all(&deep).unwrap(); assert_eq!( - repository_of(&deep).map(|n| n.to_string()).as_deref(), - Some("acme/widgets") + origin(&deep).as_deref(), + Some("https://github.com/acme/widgets") ); } @@ -302,10 +262,8 @@ mod tests { ); assert_eq!( - repository_of(&dir.path().join("wt")) - .map(|n| n.to_string()) - .as_deref(), - Some("acme/widgets") + origin(&dir.path().join("wt")).as_deref(), + Some("https://github.com/acme/widgets") ); } @@ -319,10 +277,8 @@ mod tests { ); assert_eq!( - repository_of(&dir.path().join("lib")) - .map(|n| n.to_string()) - .as_deref(), - Some("acme/widgets") + origin(&dir.path().join("lib")).as_deref(), + Some("https://github.com/acme/widgets") ); } @@ -330,7 +286,7 @@ mod tests { fn should_find_none_outside_a_repo() { let dir = tempfile::tempdir().unwrap(); - assert_eq!(repository_of(dir.path()), None); + assert_eq!(remote_urls_of(dir.path()), None); } } } 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 new file mode 100644 index 0000000..1ea35f3 --- /dev/null +++ b/crates/agentdeckd/src/suggestions/remotes/mod.rs @@ -0,0 +1,134 @@ +//! 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. +//! +//! `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 file; +mod git; + +use std::collections::HashMap; +use std::ffi::OsString; +use std::path::Path; +use std::time::Duration; + +use agentdeck_core::RepositoryName; + +/// 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 `git` a folder's remotes are asked of: `git` on the daemon's `PATH`. +pub struct Git { + program: OsString, + timeout: Duration, +} + +impl Default for Git { + fn default() -> Git { + Git { + program: "git".into(), + timeout: GIT_TIMEOUT, + } + } +} + +/// 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, 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)? + } + }; + pick(&remotes) +} + +/// `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)?)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn picked(text: &str) -> Option { + pick(&file::remote_urls(text)).map(|name| name.to_string()) + } + + 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::*; + + /// 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_the_repos_config_when_git_cannot_start() { + let dir = tempfile::tempdir().unwrap(); + 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!( + repository_of(&dir.path().join("repo"), &no_git(dir.path())) + .map(|n| n.to_string()) + .as_deref(), + Some("acme/widgets") + ); + } + + #[test] + fn should_find_none_outside_a_repo_when_git_cannot_start() { + let dir = tempfile::tempdir().unwrap(); + + assert_eq!(repository_of(dir.path(), &no_git(dir.path())), None); + } + } +} diff --git a/crates/agentdeckd/tests/integration/suggestions.rs b/crates/agentdeckd/tests/integration/suggestions.rs index 05be0d6..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"; @@ -252,6 +252,243 @@ 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. Without a `git` that answers, the repo's + /// own `config` file still 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() + } + + /// [`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; + 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::*; diff --git a/docs/spec.md b/docs/spec.md index 54631f6..bb41588 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 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.