Skip to content
Clone

feat: add function to strip trailing port from URL authority and corresponding tests

ZhenYi committed
parent 53a6f08 commit 4557313 Browse files

1 file changed

+43 −7

Modified lib/git/src/service/repos.rs View lib/git/src/service/repos.rs
@@ -179,6 +179,19 @@
179179 pub default_branch: Option<String>,
180180}
181181
182/// Strip a trailing `:<port>` from a URL authority (`localhost:3000` -> `localhost`).
183/// Bracketed IPv6 literals and non-numeric suffixes are left untouched.
184fn strip_authority_port(authority: &str) -> &str {
185 match authority.rsplit_once(':') {
186 Some((host, port))
187 if !host.is_empty() && port.chars().all(|c| c.is_ascii_digit()) && !port.is_empty() =>
188 {
189 host
190 }
191 _ => authority,
192 }
193}
194
182195impl GitService {
183196 pub fn http_clone_url(&self, space: &str, repo: &str) -> Option<String> {
184197 let cfg = &self.state.config.git;
@@ -199,13 +212,16 @@
199212 pub fn ssh_clone_url(&self, space: &str, repo: &str) -> Option<String> {
200213 let cfg = &self.state.config.git;
201214 let host = if cfg.ssh_clone_host.is_empty() {
202 cfg.base_url
203 .trim_start_matches("https://")
204 .trim_start_matches("http://")
205 .split('/')
206 .next()
207 .unwrap_or("")
208 .to_string()
215 // Derive from base_url; the HTTP port is not the SSH port, so drop it.
216 strip_authority_port(
217 cfg.base_url
218 .trim_start_matches("https://")
219 .trim_start_matches("http://")
220 .split('/')
221 .next()
222 .unwrap_or(""),
223 )
224 .to_string()
209225 } else {
210226 cfg.ssh_clone_host.clone()
211227 };
@@ -718,3 +734,23 @@
718734 }
719735 Ok(total)
720736}
737
738#[cfg(test)]
739mod tests {
740 use super::strip_authority_port;
741
742 #[test]
743 fn strips_http_port_but_keeps_host() {
744 assert_eq!(strip_authority_port("localhost:3000"), "localhost");
745 assert_eq!(strip_authority_port("git.example.com:8443"), "git.example.com");
746 assert_eq!(strip_authority_port("[::1]:3000"), "[::1]");
747 }
748
749 #[test]
750 fn leaves_host_without_numeric_port_intact() {
751 assert_eq!(strip_authority_port("localhost"), "localhost");
752 assert_eq!(strip_authority_port("localhost:"), "localhost:");
753 assert_eq!(strip_authority_port("[::1]"), "[::1]");
754 assert_eq!(strip_authority_port(""), "");
755 }
756}