Skip to content

The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.

feat(vcs,ssh): resolve ~/.ssh/config Host aliases for git remotes (#2399)

Deng Liu2841a5a406d8
diff --git a/crates/ide-github/src/model.rs b/crates/ide-github/src/model.rs
index d134abd3b..a1c849131 100644
--- a/crates/ide-github/src/model.rs
+++ b/crates/ide-github/src/model.rs
@@ -627,8 +627,8 @@ mod tests {
#[test]
fn finds_remote_by_repo() {
let remotes = vec![
- ide_vcs::Remote { name: "origin".into(), url: "[email protected]:me/App.git".into() },
- ide_vcs::Remote { name: "upstream".into(), url: "https://github.com/org/app/".into() },
+ ide_vcs::Remote { name: "origin".into(), url: "[email protected]:me/App.git".into(), resolved_url: None },
+ ide_vcs::Remote { name: "upstream".into(), url: "https://github.com/org/app/".into(), resolved_url: None },
];
assert_eq!(remote_for(&remotes, "me/app").map(|r| r.name.as_str()), Some("origin"));
assert_eq!(remote_for(&remotes, "org/app").map(|r| r.name.as_str()), Some("upstream"));
diff --git a/crates/ide-host/src/ops/vcs/commands.rs b/crates/ide-host/src/ops/vcs/commands.rs
index 96fb3ab7b..760afcb0f 100644
--- a/crates/ide-host/src/ops/vcs/commands.rs
+++ b/crates/ide-host/src/ops/vcs/commands.rs
@@ -996,7 +996,17 @@ pub async fn vcs_rebase_with(
pub async fn vcs_remotes(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<Vec<Remote>> {
let project = LogAccess::new(host, window, repo.as_deref());
- blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.remotes())).await
+ blocking(move || {
+ let mut remotes = project.with_log_repo_at(repo.as_deref(), |r| r.remotes())?;
+ for r in &mut remotes {
+ let resolved = ide_ssh::resolve_ssh_remote_url(&r.url);
+ if resolved != r.url {
+ r.resolved_url = Some(resolved);
+ }
+ }
+ Ok(remotes)
+ })
+ .await
}
pub async fn vcs_edit_remote(host: &Host, window: &str, repo: Option<PathBuf>, edit: RemoteEdit) -> IdeResult<()> {
diff --git a/crates/ide-ssh/src/lib.rs b/crates/ide-ssh/src/lib.rs
index c5790b281..ba28c1478 100644
--- a/crates/ide-ssh/src/lib.rs
+++ b/crates/ide-ssh/src/lib.rs
@@ -20,5 +20,5 @@ pub use manager::SshManager;
pub use russh::Sig;
pub use session::{ConnectError, ExecOutput, Output, RemoteProcess, Session, UnknownHostKey};
pub use sftp::RemoteEntry;
-pub use target::{SshFiles, SshTarget, expand, openssh_args};
+pub use target::{SshFiles, SshTarget, expand, openssh_args, resolve_ssh_remote_url, resolve_ssh_remote_url_with};
pub use tunnel::Tunnel;
diff --git a/crates/ide-ssh/src/target.rs b/crates/ide-ssh/src/target.rs
index bf6bdde9e..b9095b3f0 100644
--- a/crates/ide-ssh/src/target.rs
+++ b/crates/ide-ssh/src/target.rs
@@ -6,6 +6,9 @@ use ide_core::{IdeError, IdeResult};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
+mod remote_url;
+pub use remote_url::{resolve_ssh_remote_url, resolve_ssh_remote_url_with};
+
const MATCH_EXEC_TIMEOUT: Duration = Duration::from_secs(10);
/// An SSH host and how to authenticate to it.
@@ -262,6 +265,7 @@ fn eval_match(
port_override: Option<u16>,
user_override: Option<&str>,
out: &RawConfig,
+ allow_exec: bool,
) -> bool {
let tokens = split_args(value);
if tokens.is_empty() {
@@ -308,6 +312,9 @@ fn eval_match(
"user" => pattern_list_matches(arg.split(','), user),
"localuser" => pattern_list_matches(arg.split(','), &local),
"exec" => {
+ if !allow_exec {
+ return false;
+ }
let cmd = expand_tokens(arg, alias, host, port, user, &local);
eval_match_exec(&cmd)
}
@@ -383,7 +390,7 @@ fn parse_config_file(
active = pattern_list_matches(patterns.iter().map(String::as_str), alias);
}
"match" => {
- active = eval_match(value, alias, port_override, user_override, out);
+ active = eval_match(value, alias, port_override, user_override, out, true);
}
_ if !active => {}
"include" => {
@@ -685,4 +692,93 @@ mod tests {
SshTarget { host: "box".into(), auth: SshAuth::KeyPair, key_file: "/k/id".into(), ..Default::default() };
assert_eq!(openssh_args(&t), ["-i", "/k/id", "-o", "IdentitiesOnly=yes", "--", "box"]);
}
+
+ #[test]
+ fn resolves_ssh_remote_urls_from_ssh_config() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = tmp.path().join("config");
+ std::fs::write(
+ &config,
+ "Host github-personal\n HostName github.com\n User git\n IdentityFile ~/.ssh/id_ecdsa\n IdentitiesOnly yes\n\n\
+ Host gh-443\n HostName ssh.github.com\n Port 443\n\n\
+ Host gl-work\n HostName altssh.gitlab.com\n\n\
+ Host *\n HostName fallback.example.com\n",
+ )
+ .unwrap();
+
+ assert_eq!(
+ resolve_ssh_remote_url_with("git@github-personal:dengliu/openidea.git", Some(&config)),
+ "[email protected]:dengliu/openidea.git"
+ );
+ assert_eq!(
+ resolve_ssh_remote_url_with("git@github-personal:l0ng-ai/openidea.git", Some(&config)),
+ "[email protected]:l0ng-ai/openidea.git"
+ );
+ assert_eq!(
+ resolve_ssh_remote_url_with("ssh://git@github-personal:22/l0ng-ai/openidea.git", Some(&config)),
+ "ssh://[email protected]:22/l0ng-ai/openidea.git"
+ );
+ assert_eq!(
+ resolve_ssh_remote_url_with("git@gh-443:org/repo.git", Some(&config)),
+ "[email protected]:org/repo.git"
+ );
+ assert_eq!(
+ resolve_ssh_remote_url_with("git@gl-work:group/repo.git", Some(&config)),
+ "[email protected]:group/repo.git"
+ );
+ // Non-SSH URLs are untouched even with a `Host *` wildcard in ~/.ssh/config.
+ assert_eq!(
+ resolve_ssh_remote_url_with("https://github.com/l0ng-ai/openidea.git", Some(&config)),
+ "https://github.com/l0ng-ai/openidea.git"
+ );
+ }
+
+ #[test]
+ fn remote_urls_cover_scp_paths_and_leave_local_urls_unchanged() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = tmp.path().join("config");
+ std::fs::write(&config, "Host *\n HostName github.com\n").unwrap();
+ for (url, expected) in [
+ ("git@alias:/org/repo.git", "[email protected]:/org/repo.git"),
+ ("a:org/repo.git", "github.com:org/repo.git"),
+ ("ssh://alice@alias:443/org/repo.git", "ssh://[email protected]:443/org/repo.git"),
+ ("https://alias/org/repo.git", "https://alias/org/repo.git"),
+ ("file:///alias/org/repo.git", "file:///alias/org/repo.git"),
+ ("./alias:repo.git", "./alias:repo.git"),
+ ("/alias:repo.git", "/alias:repo.git"),
+ ("C:\\repo.git", "C:\\repo.git"),
+ ("C:/repo.git", "C:/repo.git"),
+ ("ssh://alias:bad/org/repo.git", "ssh://alias:bad/org/repo.git"),
+ ] {
+ assert_eq!(resolve_ssh_remote_url_with(url, Some(&config)), expected, "{url}");
+ }
+ }
+
+ #[test]
+ fn remote_config_include_keeps_host_context_and_first_option() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = tmp.path().join("config");
+ std::fs::create_dir(tmp.path().join("parts")).unwrap();
+ std::fs::write(tmp.path().join("parts/hosts"), "Include more\nHost other\n User other\n").unwrap();
+ std::fs::write(tmp.path().join("more"), "Host included\n HostName github.com\n").unwrap();
+ std::fs::write(&config, "Include parts/hosts\n HostName wrong.example\nHost g? !gl\n HostName github.com # forge\nHost *\n HostName fallback.example\n").unwrap();
+ for (alias, host) in [("gh", "github.com"), ("gl", "fallback.example"), ("included", "github.com")] {
+ assert_eq!(
+ resolve_ssh_remote_url_with(&format!("git@{alias}:o/r"), Some(&config)),
+ format!("git@{host}:o/r")
+ );
+ }
+ }
+
+ #[test]
+ fn remote_config_malformed_or_unreadable_hosts_fall_back() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = tmp.path().join("config");
+ let url = "git@alias:o/r";
+ assert_eq!(resolve_ssh_remote_url_with(url, Some(&config)), url);
+ for value in ["\"\"", "\"github.com", "github.com extra", "bad/host", ""] {
+ std::fs::write(&config, format!("Host alias\n HostName {value}\n")).unwrap();
+ assert_eq!(resolve_ssh_remote_url_with(url, Some(&config)), url, "{value:?}");
+ }
+ }
}
diff --git a/crates/ide-ssh/src/target/remote_url.rs b/crates/ide-ssh/src/target/remote_url.rs
new file mode 100644
index 000000000..23775899b
--- /dev/null
+++ b/crates/ide-ssh/src/target/remote_url.rs
@@ -0,0 +1,292 @@
+use super::{
+ RawConfig, SshFiles, eval_match, expand, expand_include_glob, pattern_list_matches, split_args, split_directive,
+};
+use parking_lot::Mutex;
+use std::collections::HashMap;
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, OnceLock};
+use std::time::{Duration, Instant};
+
+#[derive(Default)]
+struct ConfigCache {
+ loaded_at: Option<Instant>,
+ files: HashMap<PathBuf, Option<Arc<str>>>,
+ includes: HashMap<PathBuf, Vec<PathBuf>>,
+}
+
+impl ConfigCache {
+ fn read(&mut self, path: &Path) -> Option<Arc<str>> {
+ self.files.entry(path.to_owned()).or_insert_with(|| std::fs::read_to_string(path).ok().map(Arc::from)).clone()
+ }
+
+ fn includes(&mut self, pattern: &Path) -> Vec<PathBuf> {
+ self.includes.entry(pattern.to_owned()).or_insert_with(|| expand_include_glob(pattern)).clone()
+ }
+}
+
+struct RemoteConfig<'a> {
+ alias: &'a str,
+ port: Option<u16>,
+ user: Option<&'a str>,
+ directory: &'a Path,
+ active: bool,
+ raw: RawConfig,
+}
+
+impl RemoteConfig<'_> {
+ fn read(&mut self, path: &Path, cache: &mut ConfigCache, depth: usize) -> Option<()> {
+ if depth >= 8 {
+ return Some(());
+ }
+ let Some(contents) = cache.read(path) else { return Some(()) };
+ for line in contents.lines() {
+ let line = without_comment(line)?;
+ let Some((key, value)) = split_directive(line) else {
+ if !line.trim().is_empty() {
+ return None;
+ }
+ continue;
+ };
+ let args = split_args(value);
+ match key.to_ascii_lowercase().as_str() {
+ "host" => self.active = pattern_list_matches(args.iter().map(String::as_str), self.alias),
+ "match" => {
+ // Host detection has no canonical/final pass and never evaluates commands, even negated ones.
+ self.active =
+ !args.iter().any(|a| matches!(a.to_ascii_lowercase().as_str(), "canonical" | "final"))
+ && eval_match(value, self.alias, self.port, self.user, &self.raw, false);
+ }
+ _ if !self.active => {}
+ "include" => {
+ for arg in args {
+ let expanded = expand(&arg);
+ let pattern = if expanded.is_relative() { self.directory.join(expanded) } else { expanded };
+ for file in cache.includes(&pattern) {
+ self.read(&file, cache, depth + 1)?;
+ }
+ }
+ }
+ "hostname" if self.raw.hostname.is_none() => {
+ let [host] = args.as_slice() else { return None };
+ let host = expand_hostname(host, self.alias)?;
+ if !valid_host(&host) {
+ return None;
+ }
+ self.raw.hostname = Some(host);
+ }
+ "user" if self.raw.user.is_none() => {
+ let [user] = args.as_slice() else { return None };
+ self.raw.user = Some(user.clone());
+ }
+ "port" if self.raw.port.is_none() => {
+ let [port] = args.as_slice() else { return None };
+ self.raw.port = Some(port.parse().ok().filter(|p| *p != 0)?);
+ }
+ // Identity files, proxy commands and all other connection options are intentionally ignored.
+ _ => {}
+ }
+ }
+ Some(())
+ }
+}
+
+fn without_comment(line: &str) -> Option<&str> {
+ let mut quote = None;
+ for (i, ch) in line.char_indices() {
+ match quote {
+ Some(q) if ch == q => quote = None,
+ Some(_) => {}
+ None if ch == '"' || ch == '\'' => quote = Some(ch),
+ None if ch == '#' => return Some(&line[..i]),
+ None => {}
+ }
+ }
+ quote.is_none().then_some(line)
+}
+
+fn expand_hostname(template: &str, alias: &str) -> Option<String> {
+ let mut out = String::new();
+ let mut chars = template.chars();
+ while let Some(ch) = chars.next() {
+ if ch != '%' {
+ out.push(ch);
+ } else {
+ match chars.next()? {
+ 'h' => out.push_str(alias),
+ '%' => out.push('%'),
+ _ => return None,
+ }
+ }
+ }
+ Some(out)
+}
+
+fn valid_host(host: &str) -> bool {
+ !host.is_empty()
+ && !host.starts_with('-')
+ && (host.chars().all(|c| c.is_alphanumeric() || matches!(c, '.' | '-' | '_'))
+ || host.parse::<std::net::Ipv6Addr>().is_ok())
+}
+
+/// Resolves SSH git remote hosts for forge detection, never for making connections.
+/// Reads only `~/.ssh/config` and its Includes, without running commands. File contents and
+/// Include expansions are cached for one second, including missing files.
+/// `ssh.github.com` (normally port 443) and `altssh.gitlab.com` become their web hosts;
+/// explicit users, ports and paths remain unchanged. Non-SSH URLs are returned unchanged.
+pub fn resolve_ssh_remote_url(url: &str) -> String {
+ static CACHE: OnceLock<Mutex<ConfigCache>> = OnceLock::new();
+ let mut cache = CACHE.get_or_init(Mutex::default).lock();
+ if cache.loaded_at.is_none_or(|at| at.elapsed() >= Duration::from_secs(1))
+ || cache.files.len() > 128
+ || cache.includes.len() > 128
+ {
+ *cache = ConfigCache { loaded_at: Some(Instant::now()), ..Default::default() };
+ }
+ resolve(url, SshFiles::default().config.as_deref(), &mut cache)
+}
+
+/// Like [`resolve_ssh_remote_url`], using an explicit config file without the shared cache.
+pub fn resolve_ssh_remote_url_with(url: &str, config: Option<&Path>) -> String {
+ resolve(url, config, &mut ConfigCache::default())
+}
+
+fn resolve(url: &str, config: Option<&Path>, cache: &mut ConfigCache) -> String {
+ let trimmed = url.trim();
+ let (prefix, alias, suffix, port, user) = if let Some((scheme, rest)) = trimmed.split_once("://") {
+ if !scheme.eq_ignore_ascii_case("ssh") {
+ return url.to_owned();
+ }
+ let Some((authority, _)) = rest.split_once('/') else { return url.to_owned() };
+ let (user, host_port) = authority.rsplit_once('@').map_or((None, authority), |(u, h)| (Some(u), h));
+ // Bracketed IPv6 literals have no Host alias to resolve.
+ if host_port.starts_with('[') {
+ return url.to_owned();
+ }
+ let (alias, port) = match host_port.split_once(':') {
+ Some((host, port)) => {
+ let Ok(port) = port.parse::<u16>() else { return url.to_owned() };
+ if port == 0 {
+ return url.to_owned();
+ }
+ (host, Some(port))
+ }
+ None => (host_port, None),
+ };
+ let start = scheme.len() + 3 + user.map_or(0, |u| u.len() + 1);
+ (&trimmed[..start], alias, &trimmed[start + alias.len()..], port, user)
+ } else {
+ let Some((left, path)) = trimmed.split_once(':') else { return url.to_owned() };
+ if path.is_empty() || left.contains(['/', '\\']) || (left.len() == 1 && path.starts_with(['/', '\\'])) {
+ return url.to_owned();
+ }
+ let (user, alias) = left.rsplit_once('@').map_or((None, left), |(u, h)| (Some(u), h));
+ let start = user.map_or(0, |u| u.len() + 1);
+ (&trimmed[..start], alias, &trimmed[left.len()..], None, user)
+ };
+ if !valid_host(alias) || alias.contains(':') {
+ return url.to_owned();
+ }
+ let mut parsed = RemoteConfig {
+ alias,
+ port,
+ user,
+ directory: config.and_then(Path::parent).unwrap_or_else(|| Path::new(".")),
+ active: true,
+ raw: RawConfig::default(),
+ };
+ if let Some(path) = config
+ && parsed.read(path, cache, 0).is_none()
+ {
+ return url.to_owned();
+ }
+ let host = parsed.raw.hostname.as_deref().unwrap_or(alias);
+ let host = if host.eq_ignore_ascii_case("ssh.github.com") {
+ "github.com"
+ } else if host.eq_ignore_ascii_case("altssh.gitlab.com") {
+ "gitlab.com"
+ } else {
+ host
+ };
+ if host == alias {
+ return url.to_owned();
+ }
+ if host.contains(':') { format!("{prefix}[{host}]{suffix}") } else { format!("{prefix}{host}{suffix}") }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn remote_inspection_never_executes_commands_or_reads_connection_files() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = tmp.path().join("config");
+ let marker = tmp.path().join("executed");
+ let unrelated = tmp.path().join("not-config");
+ std::fs::write(&unrelated, "HostName wrong.example\n").unwrap();
+ std::fs::write(
+ &config,
+ format!(
+ "Match exec \"touch {}\"\n HostName wrong.example\n\
+ Match !exec \"touch {}\"\n HostName wrong.example\n\
+ Host *\n ProxyCommand touch {}\n LocalCommand touch {}\n\
+ IdentityFile {}\n UserKnownHostsFile {}\n HostName github.com\n",
+ marker.display(),
+ marker.display(),
+ marker.display(),
+ marker.display(),
+ unrelated.display(),
+ unrelated.display(),
+ ),
+ )
+ .unwrap();
+ let mut cache = ConfigCache::default();
+ assert_eq!(resolve("git@alias:o/r", Some(&config), &mut cache), "[email protected]:o/r");
+ assert!(!marker.exists());
+ assert_eq!(cache.files.keys().collect::<Vec<_>>(), [&config]);
+ }
+
+ #[test]
+ fn includes_are_ordered_conditional_and_bounded() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = tmp.path().join("config");
+ std::fs::write(tmp.path().join("b.conf"), "Host *\n HostName wrong.example\n").unwrap();
+ std::fs::write(tmp.path().join("a.conf"), "Host *\n HostName github.com\n").unwrap();
+ std::fs::write(&config, "Host !alias *\n Include b.conf\nHost alias\n Include *.conf\n").unwrap();
+ assert_eq!(resolve_ssh_remote_url_with("git@alias:o/r", Some(&config)), "[email protected]:o/r");
+ for i in 0..9 {
+ std::fs::write(tmp.path().join(format!("level{i}")), format!("Include level{}\n", i + 1)).unwrap();
+ }
+ std::fs::write(tmp.path().join("level9"), "HostName wrong.example\n").unwrap();
+ std::fs::write(&config, "Include level0\nInclude config\nHost alias\n HostName github.com\n").unwrap();
+ let mut cache = ConfigCache::default();
+ assert_eq!(resolve("git@alias:o/r", Some(&config), &mut cache), "[email protected]:o/r");
+ assert!(!cache.files.contains_key(&tmp.path().join("level7")));
+ // Reusing the cache does not reread a file for each remote.
+ std::fs::write(&config, "HostName wrong.example\n").unwrap();
+ assert_eq!(resolve("git@alias:o/r", Some(&config), &mut cache), "[email protected]:o/r");
+ }
+
+ #[test]
+ fn explicit_url_fields_and_ssh_host_normalization_are_preserved() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = tmp.path().join("config");
+ std::fs::write(&config, "Host alias\n User configured\n Port 2222\n HostName ssh.github.com\n").unwrap();
+ for (url, expected) in [
+ ("ssh://alice@alias:443/o/r.git", "ssh://[email protected]:443/o/r.git"),
+ ("ssh://alias/o/r.git", "ssh://github.com/o/r.git"),
+ ("git@alias:/o/r.git", "[email protected]:/o/r.git"),
+ ("[email protected]:o/r.git", "[email protected]:o/r.git"),
+ ("ssh://[email protected]:443/o/r.git", "ssh://[email protected]:443/o/r.git"),
+ ] {
+ assert_eq!(resolve_ssh_remote_url_with(url, Some(&config)), expected, "{url}");
+ }
+ std::fs::write(&config, "Host alias\n HostName 2001:db8::1\n").unwrap();
+ assert_eq!(
+ resolve_ssh_remote_url_with("ssh://git@alias:2222/o/r", Some(&config)),
+ "ssh://git@[2001:db8::1]:2222/o/r"
+ );
+ std::fs::write(&config, "Host alias\n HostName %h.example\n").unwrap();
+ assert_eq!(resolve_ssh_remote_url_with("git@alias:o/r", Some(&config)), "[email protected]:o/r");
+ }
+}
diff --git a/crates/ide-vcs/src/remotes.rs b/crates/ide-vcs/src/remotes.rs
index 0049a7777..b04d0740d 100644
--- a/crates/ide-vcs/src/remotes.rs
+++ b/crates/ide-vcs/src/remotes.rs
@@ -13,6 +13,9 @@ pub struct Remote {
pub name: String,
/// Fetch URL.
pub url: String,
+ /// Fetch URL with any `~/.ssh/config` host alias resolved, when different from `url`.
+ #[serde(default)]
+ pub resolved_url: Option<String>,
}
fn check_rev(rev: &str) -> IdeResult<()> {
@@ -32,7 +35,7 @@ pub(crate) fn parse_remotes(text: &str) -> Vec<Remote> {
if kind.is_some_and(|k| k != "(fetch)") || out.iter().any(|r| r.name == name) {
continue;
}
- out.push(Remote { name: name.to_owned(), url: url.to_owned() });
+ out.push(Remote { name: name.to_owned(), url: url.to_owned(), resolved_url: None });
}
out
}
@@ -106,8 +109,8 @@ mod tests {
assert_eq!(
parse_remotes(text),
[
- Remote { name: "origin".into(), url: "[email protected]:me/app.git".into() },
- Remote { name: "upstream".into(), url: "https://github.com/org/app".into() },
+ Remote { name: "origin".into(), url: "[email protected]:me/app.git".into(), resolved_url: None },
+ Remote { name: "upstream".into(), url: "https://github.com/org/app".into(), resolved_url: None },
]
);
}
diff --git a/crates/ide-vcs/tests/log_shape.rs b/crates/ide-vcs/tests/log_shape.rs
index 4414d6d51..9649c9848 100644
--- a/crates/ide-vcs/tests/log_shape.rs
+++ b/crates/ide-vcs/tests/log_shape.rs
@@ -171,7 +171,7 @@ fn remotes_and_worktrees_are_managed() {
.unwrap();
assert_eq!(
repo.remotes().unwrap(),
- vec![Remote { name: "upstream".into(), url: "https://example.com/b.git".into() }]
+ vec![Remote { name: "upstream".into(), url: "https://example.com/b.git".into(), resolved_url: None }]
);
assert!(repo.edit_remote(&RemoteEdit::Add { name: "--bad".into(), url: "x".into() }).is_err());
repo.edit_remote(&RemoteEdit::Remove { name: "upstream".into() }).unwrap();
diff --git a/src/bindings.ts b/src/bindings.ts
index f503dfdb9..296ded8d0 100644
--- a/src/bindings.ts
+++ b/src/bindings.ts
@@ -7282,6 +7282,8 @@ export type Remote = {
name: string,
/** Fetch URL. */
url: string,
+ /** Fetch URL with any `~/.ssh/config` host alias resolved, when different from `url`. */
+ resolvedUrl?: string | null,
};
/** Manage Remotes edits. */
diff --git a/src/features/github/data/data.test.ts b/src/features/github/data/data.test.ts
index 506a38a7a..703de25e2 100644
--- a/src/features/github/data/data.test.ts
+++ b/src/features/github/data/data.test.ts
@@ -405,14 +405,20 @@ describe("pull request helpers", () => {
expect(parseGitHubRemote(url), url).toEqual({ owner: "o", name: "r" });
expect(parseGitHubRemote("https://gitlab.com/o/r.git")).toBeNull();
expect(parseGitHubRemote("/local/repo")).toBeNull();
+ expect(parseGitHubRemote("https://ssh.github.com/o/r.git")).toBeNull();
expect(
githubRemotes([
{ name: "origin", url: "[email protected]:me/r.git" },
+ {
+ name: "fork",
+ url: "git@github-personal:dengliu/r.git",
+ resolvedUrl: "[email protected]:dengliu/r.git",
+ },
{ name: "upstream", url: "https://github.com/org/r.git" },
{ name: "dup", url: "https://github.com/ORG/r" },
{ name: "other", url: "https://example.com/x/y" },
]).map((r) => `${r.remote}=${r.owner}/${r.name}`),
- ).toEqual(["origin=me/r", "upstream=org/r"]);
+ ).toEqual(["origin=me/r", "fork=dengliu/r", "upstream=org/r"]);
});
});
diff --git a/src/features/github/data/repository.ts b/src/features/github/data/repository.ts
index 52a27f21d..5354088a0 100644
--- a/src/features/github/data/repository.ts
+++ b/src/features/github/data/repository.ts
@@ -106,12 +106,12 @@ export const nameWithOwner = (r: GHRepositoryCoordinates) => `${r.owner}/${r.nam
/** The GitHub remotes among `remotes` of the repository at `root`, one per GitHub repository. */
export function githubRemotes(
- remotes: ReadonlyArray<{ name: string; url: string }>,
+ remotes: ReadonlyArray<{ name: string; url: string; resolvedUrl?: string | null }>,
root: string | null = null,
): GHRemote[] {
const out: GHRemote[] = [];
for (const r of remotes) {
- const c = parseGitHubRemote(r.url);
+ const c = parseGitHubRemote(r.resolvedUrl ?? r.url);
if (c && !out.some((o) => sameRepository(o, c))) out.push({ ...c, remote: r.name, url: r.url, root });
}
return out;
diff --git a/src/features/github/reviewMode/model.ts b/src/features/github/reviewMode/model.ts
index 5d314eeef..91cf4a56f 100644
--- a/src/features/github/reviewMode/model.ts
+++ b/src/features/github/reviewMode/model.ts
@@ -40,13 +40,15 @@ export interface TrackedBranch {
export function trackedBranch(
remote: string | null,
merge: string | null,
- remotes: ReadonlyArray<{ name: string; url: string }>,
+ remotes: ReadonlyArray<{ name: string; url: string; resolvedUrl?: string | null }>,
connected?: GHRepositoryCoordinates,
): TrackedBranch | null {
if (!remote || !merge || remote === ".") return null;
- const url = remotes.find((r) => r.name === remote)?.url ?? remote;
+ const found = remotes.find((r) => r.name === remote);
+ const url = found?.url ?? remote;
const repository =
- parseGitHubRemote(url) ?? (connected && remoteOfRepository([{ name: remote, url }], connected) ? connected : null);
+ parseGitHubRemote(found?.resolvedUrl ?? url) ??
+ (connected && remoteOfRepository([{ name: remote, url }], connected) ? connected : null);
if (!repository) return null;
const pr = /^refs\/pull\/(\d+)\/head$/.exec(merge);
if (pr) return { repository, branch: null, pullRequest: Number(pr[1]) };
diff --git a/src/features/github/reviewMode/reviewMode.test.tsx b/src/features/github/reviewMode/reviewMode.test.tsx
index dbf2174bb..6048246d4 100644
--- a/src/features/github/reviewMode/reviewMode.test.tsx
+++ b/src/features/github/reviewMode/reviewMode.test.tsx
@@ -158,6 +158,12 @@ describe("model", () => {
expect(trackedBranch(".", "refs/heads/main", remotes)).toBeNull();
const alias = [{ name: "origin", url: "git@work-github:o/r.git" }];
expect(trackedBranch("origin", "refs/heads/x", alias)).toBeNull();
+ const resolved = [{ ...alias[0]!, resolvedUrl: "ssh://[email protected]:443/o/r.git" }];
+ expect(trackedBranch("origin", "refs/heads/x", resolved)).toEqual({
+ repository: { owner: "o", name: "r" },
+ branch: "x",
+ pullRequest: null,
+ });
expect(trackedBranch("origin", "refs/heads/x", alias, { owner: "o", name: "r" })?.repository).toEqual({
owner: "o",
name: "r",