Skip to main content

ag_forge/
remote.rs

1//! Forge remote detection helpers shared across provider adapters.
2
3use super::{
4    ForgeKind, ForgeRemote, GitHubReviewRequestAdapter, GitLabReviewRequestAdapter,
5    ReviewRequestError,
6};
7
8/// Detects one supported forge remote from `repo_url`.
9///
10/// # Errors
11/// Returns [`ReviewRequestError::UnsupportedRemote`] when the repository
12/// remote does not map to a supported forge.
13pub fn detect_remote(repo_url: &str) -> Result<ForgeRemote, ReviewRequestError> {
14    if let Some(remote) = GitHubReviewRequestAdapter::detect_remote(repo_url) {
15        return Ok(remote);
16    }
17
18    if let Some(remote) = GitLabReviewRequestAdapter::detect_remote(repo_url) {
19        return Ok(remote);
20    }
21
22    Err(ReviewRequestError::UnsupportedRemote {
23        repo_url: display_safe_remote_url(repo_url),
24    })
25}
26
27/// Parsed remote components extracted from one git remote URL.
28#[derive(Clone, Debug, Eq, PartialEq)]
29pub(crate) struct ParsedRemote {
30    /// Canonical forge host used for browser and API requests.
31    ///
32    /// SSH transport ports are stripped so review-request commands target the
33    /// authenticated HTTPS host instead of the SSH daemon port.
34    pub(crate) host: String,
35    /// Repository namespace or owner path.
36    pub(crate) namespace: String,
37    /// Repository name without a trailing `.git` suffix.
38    pub(crate) project: String,
39    /// Credential-free remote URL suitable for display and diagnostics.
40    pub(crate) repo_url: String,
41    /// Browser-openable repository URL derived from the remote.
42    pub(crate) web_url: String,
43}
44
45impl ParsedRemote {
46    /// Converts the parsed remote into one supported forge remote.
47    pub(crate) fn into_forge_remote(self, forge_kind: ForgeKind) -> ForgeRemote {
48        ForgeRemote {
49            command_working_directory: None,
50            forge_kind,
51            host: self.host,
52            namespace: self.namespace,
53            project: self.project,
54            repo_url: self.repo_url,
55            web_url: self.web_url,
56        }
57    }
58
59    /// Builds one parsed remote from extracted host and path components.
60    ///
61    /// When `strip_transport_port` is `true`, the parsed host is normalized for
62    /// browser and API access by dropping any SSH transport port.
63    fn from_parts(
64        repo_url: &str,
65        host: &str,
66        path: &str,
67        strip_transport_port: bool,
68    ) -> Option<ParsedRemote> {
69        let host = host.trim().trim_matches('/').to_ascii_lowercase();
70        let host = if strip_transport_port {
71            strip_port(&host).to_string()
72        } else {
73            host
74        };
75        let path = path.trim().trim_matches('/').trim_end_matches(".git");
76        if host.is_empty() || path.is_empty() {
77            return None;
78        }
79
80        let (namespace, project) = path.rsplit_once('/')?;
81        if namespace.is_empty() || project.is_empty() {
82            return None;
83        }
84
85        Some(Self {
86            host: host.clone(),
87            namespace: namespace.to_string(),
88            project: project.to_string(),
89            repo_url: display_safe_remote_url(repo_url),
90            web_url: format!("https://{host}/{path}"),
91        })
92    }
93}
94
95/// Parses a git remote URL into normalized hostname and repository components.
96///
97/// URL remotes may include `username[:password]@` userinfo, which is removed
98/// before the remote is retained or used for diagnostics.
99pub(crate) fn parse_remote_url(repo_url: &str) -> Option<ParsedRemote> {
100    let trimmed_url = repo_url.trim().trim_end_matches('/');
101    if trimmed_url.is_empty() {
102        return None;
103    }
104
105    if let Some((authority, path)) = trimmed_url.split_once(':')
106        && authority.contains('@')
107    {
108        let host = strip_userinfo(authority);
109
110        return ParsedRemote::from_parts(trimmed_url, host, path, true);
111    }
112
113    let (scheme, scheme_rest) = trimmed_url.split_once("://")?;
114    let scheme_rest = scheme_rest.strip_prefix("git@").unwrap_or(scheme_rest);
115    let (authority, path) = scheme_rest.split_once('/')?;
116    let host = strip_userinfo(authority);
117    let strip_transport_port = scheme.eq_ignore_ascii_case("ssh");
118
119    ParsedRemote::from_parts(trimmed_url, host, path, strip_transport_port)
120}
121
122/// Removes any `:port` suffix from `host`.
123pub(crate) fn strip_port(host: &str) -> &str {
124    host.split(':').next().unwrap_or(host)
125}
126
127/// Removes URL userinfo so repository remotes are safe to retain or display.
128fn display_safe_remote_url(repo_url: &str) -> String {
129    let trimmed_url = repo_url.trim();
130    let Some((scheme, scheme_rest)) = trimmed_url.split_once("://") else {
131        if let Some((authority, suffix)) = trimmed_url.split_once(':')
132            && authority.contains('@')
133        {
134            return format!("{}:{suffix}", strip_userinfo(authority));
135        }
136
137        return trimmed_url.to_string();
138    };
139    let (authority, suffix) = scheme_rest
140        .split_once('/')
141        .map_or((scheme_rest, ""), |(authority, path)| (authority, path));
142    let authority = strip_userinfo(authority);
143    if suffix.is_empty() {
144        return format!("{scheme}://{authority}");
145    }
146
147    format!("{scheme}://{authority}/{suffix}")
148}
149
150/// Removes any `username[:password]@` prefix from one URL authority segment.
151fn strip_userinfo(authority: &str) -> &str {
152    authority
153        .rsplit_once('@')
154        .map_or(authority, |(_, host)| host)
155}
156
157#[cfg(test)]
158#[path = "remote_test.rs"]
159mod tests;