Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

Extract git URL parsing into dedicated module

Maximilian Roos2b1361cf2444
diff --git a/src/commands/list/ci_status.rs b/src/commands/list/ci_status.rs
index 89c675ab8..cca9461f8 100644
--- a/src/commands/list/ci_status.rs
+++ b/src/commands/list/ci_status.rs
@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize, de::DeserializeOwned};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
-use worktrunk::git::Repository;
+use worktrunk::git::{GitRemoteUrl, Repository};
use worktrunk::shell_exec::run;
use worktrunk::utils::get_now;
@@ -55,7 +55,7 @@ pub fn get_gitlab_host_for_repo(repo_root: &str) -> Option<String> {
let url = get_remote_url_for_repo(repo_root)?;
// Only return host if this looks like a GitLab URL
if detect_platform_from_url(&url) == Some(CiPlatform::GitLab) {
- parse_remote_host(&url).map(|s| s.to_string())
+ parse_remote_host(&url)
} else {
None
}
@@ -80,86 +80,20 @@ pub fn get_gitlab_host_for_repo(repo_root: &str) -> Option<String> {
/// Neither `gh` nor `glab` CLI support server-side filtering by source repository.
/// The `gh pr list --head` flag only accepts branch name, not `owner:branch` format.
/// So we fetch PRs matching the branch name, then filter by `headRepositoryOwner`.
-///
-/// # Supported URL formats
-///
-/// - `https://<host>/<owner>/<repo>.git` → `owner`
-/// - `git@<host>:<owner>/<repo>.git` → `owner`
-/// - `ssh://git@<host>/<owner>/<repo>.git` → `owner`
-fn parse_remote_owner(url: &str) -> Option<&str> {
- parse_owner_repo(url).map(|(owner, _)| owner)
+fn parse_remote_owner(url: &str) -> Option<String> {
+ GitRemoteUrl::parse(url).map(|u| u.owner().to_string())
}
/// Extract owner and repository name from a git remote URL.
-///
-/// # Supported URL formats
-///
-/// - `https://<host>/<owner>/<repo>.git` → `(owner, repo)`
-/// - `git@<host>:<owner>/<repo>.git` → `(owner, repo)`
-/// - `ssh://git@<host>/<owner>/<repo>.git` → `(owner, repo)`
-fn parse_owner_repo(url: &str) -> Option<(&str, &str)> {
- let url = url.trim();
-
- let (owner, repo_with_suffix) = if let Some(rest) = url.strip_prefix("https://") {
- // https://github.com/owner/repo.git -> (owner, repo.git)
- let mut parts = rest.split('/').skip(1); // skip host
- (parts.next()?, parts.next()?)
- } else if let Some(rest) = url.strip_prefix("ssh://") {
- // ssh://[email protected]/owner/repo.git -> (owner, repo.git)
- let without_user = rest.split('@').next_back()?;
- let mut parts = without_user.split('/').skip(1); // skip host
- (parts.next()?, parts.next()?)
- } else if let Some(rest) = url.strip_prefix("git@") {
- // [email protected]:owner/repo.git -> (owner, repo.git)
- let path = rest.split(':').nth(1)?;
- let mut parts = path.split('/');
- (parts.next()?, parts.next()?)
- } else {
- return None;
- };
-
- // Strip .git suffix from repo if present
- let repo = repo_with_suffix
- .strip_suffix(".git")
- .unwrap_or(repo_with_suffix);
-
- if owner.is_empty() || repo.is_empty() {
- None
- } else {
- Some((owner, repo))
- }
+fn parse_owner_repo(url: &str) -> Option<(String, String)> {
+ GitRemoteUrl::parse(url).map(|u| (u.owner().to_string(), u.repo().to_string()))
}
/// Extract hostname from a git remote URL.
///
/// Used to check auth status against a specific GitLab host instead of the default.
-///
-/// # Supported URL formats
-///
-/// - `https://<host>/<owner>/<repo>.git` → `host`
-/// - `git@<host>:<owner>/<repo>.git` → `host`
-/// - `ssh://git@<host>/<owner>/<repo>.git` → `host`
-fn parse_remote_host(url: &str) -> Option<&str> {
- let url = url.trim();
-
- let host = if let Some(rest) = url.strip_prefix("https://") {
- // https://gitlab.example.com/owner/repo.git -> gitlab.example.com
- rest.split('/').next()
- } else if let Some(rest) = url.strip_prefix("http://") {
- // http://gitlab.example.com/owner/repo.git -> gitlab.example.com
- rest.split('/').next()
- } else if let Some(rest) = url.strip_prefix("ssh://") {
- // ssh://[email protected]/owner/repo.git -> gitlab.example.com
- let without_user = rest.split('@').next_back()?;
- without_user.split('/').next()
- } else if let Some(rest) = url.strip_prefix("git@") {
- // [email protected]:owner/repo.git -> gitlab.example.com
- rest.split(':').next()
- } else {
- None
- }?;
-
- if host.is_empty() { None } else { Some(host) }
+fn parse_remote_host(url: &str) -> Option<String> {
+ GitRemoteUrl::parse(url).map(|u| u.host().to_string())
}
#[cfg(test)]
@@ -242,68 +176,71 @@ mod tests {
// GitHub HTTPS
assert_eq!(
parse_remote_owner("https://github.com/max-sixty/worktrunk.git"),
- Some("max-sixty")
+ Some("max-sixty".to_string())
);
assert_eq!(
parse_remote_owner(" https://github.com/owner/repo\n"),
- Some("owner")
+ Some("owner".to_string())
);
// GitHub SSH (git@ form) - most common for developers
assert_eq!(
parse_remote_owner("[email protected]:max-sixty/worktrunk.git"),
- Some("max-sixty")
+ Some("max-sixty".to_string())
);
// GitHub SSH (ssh:// form)
assert_eq!(
parse_remote_owner("ssh://[email protected]/owner/repo.git"),
- Some("owner")
+ Some("owner".to_string())
);
assert_eq!(
parse_remote_owner("ssh://github.com/owner/repo.git"),
- Some("owner")
+ Some("owner".to_string())
);
// GitLab HTTPS
assert_eq!(
parse_remote_owner("https://gitlab.com/owner/repo.git"),
- Some("owner")
+ Some("owner".to_string())
);
assert_eq!(
parse_remote_owner("https://gitlab.example.com/owner/repo.git"),
- Some("owner")
+ Some("owner".to_string())
);
// GitLab SSH
assert_eq!(
parse_remote_owner("[email protected]:owner/repo.git"),
- Some("owner")
+ Some("owner".to_string())
);
// Bitbucket
assert_eq!(
parse_remote_owner("https://bitbucket.org/owner/repo.git"),
- Some("owner")
+ Some("owner".to_string())
);
assert_eq!(
parse_remote_owner("[email protected]:owner/repo.git"),
- Some("owner")
+ Some("owner".to_string())
);
// Organization repos - owner is the org, not the user
assert_eq!(
parse_remote_owner("https://github.com/company-org/project.git"),
- Some("company-org")
+ Some("company-org".to_string())
+ );
+
+ // HTTP (legacy, common on self-hosted)
+ assert_eq!(
+ parse_remote_owner("http://github.com/owner/repo.git"),
+ Some("owner".to_string())
);
// Malformed URLs
assert_eq!(parse_remote_owner("https://github.com/"), None);
assert_eq!(parse_remote_owner("[email protected]:"), None);
assert_eq!(parse_remote_owner(""), None);
-
- // Unsupported protocols
- assert_eq!(parse_remote_owner("http://github.com/owner/repo.git"), None);
}
#[test]
@@ -311,41 +248,41 @@ mod tests {
// HTTPS
assert_eq!(
parse_remote_host("https://gitlab.com/owner/repo.git"),
- Some("gitlab.com")
+ Some("gitlab.com".to_string())
);
assert_eq!(
parse_remote_host("https://gitlab.example.com/owner/repo.git"),
- Some("gitlab.example.com")
+ Some("gitlab.example.com".to_string())
);
assert_eq!(
parse_remote_host(" https://github.com/owner/repo\n"),
- Some("github.com")
+ Some("github.com".to_string())
);
// HTTP (legacy, common on self-hosted)
assert_eq!(
parse_remote_host("http://gitlab.internal.company.com/owner/repo.git"),
- Some("gitlab.internal.company.com")
+ Some("gitlab.internal.company.com".to_string())
);
// SSH (git@ form)
assert_eq!(
parse_remote_host("[email protected]:owner/repo.git"),
- Some("gitlab.com")
+ Some("gitlab.com".to_string())
);
assert_eq!(
parse_remote_host("[email protected]:owner/repo.git"),
- Some("gitlab.example.com")
+ Some("gitlab.example.com".to_string())
);
// SSH (ssh:// form)
assert_eq!(
parse_remote_host("ssh://[email protected]/owner/repo.git"),
- Some("gitlab.example.com")
+ Some("gitlab.example.com".to_string())
);
assert_eq!(
parse_remote_host("ssh://gitlab.example.com/owner/repo.git"),
- Some("gitlab.example.com")
+ Some("gitlab.example.com".to_string())
);
// Malformed URLs
@@ -654,37 +591,37 @@ mod tests {
// GitHub HTTPS
assert_eq!(
parse_owner_repo("https://github.com/owner/repo.git"),
- Some(("owner", "repo"))
+ Some(("owner".to_string(), "repo".to_string()))
);
assert_eq!(
parse_owner_repo("https://github.com/owner/repo"),
- Some(("owner", "repo"))
+ Some(("owner".to_string(), "repo".to_string()))
);
assert_eq!(
parse_owner_repo(" https://github.com/owner/repo.git\n"),
- Some(("owner", "repo"))
+ Some(("owner".to_string(), "repo".to_string()))
);
// GitHub SSH (git@ form)
assert_eq!(
parse_owner_repo("[email protected]:owner/repo.git"),
- Some(("owner", "repo"))
+ Some(("owner".to_string(), "repo".to_string()))
);
assert_eq!(
parse_owner_repo("[email protected]:owner/repo"),
- Some(("owner", "repo"))
+ Some(("owner".to_string(), "repo".to_string()))
);
// GitHub SSH (ssh:// form)
assert_eq!(
parse_owner_repo("ssh://[email protected]/owner/repo.git"),
- Some(("owner", "repo"))
+ Some(("owner".to_string(), "repo".to_string()))
);
// GitLab
assert_eq!(
parse_owner_repo("https://gitlab.com/owner/repo.git"),
- Some(("owner", "repo"))
+ Some(("owner".to_string(), "repo".to_string()))
);
// Malformed URLs
@@ -818,7 +755,7 @@ const MAX_PRS_TO_FETCH: u8 = 20;
/// See [`parse_remote_owner`] for details on why this is necessary.
fn get_origin_owner(repo_root: &str) -> Option<String> {
let url = get_remote_url_for_repo(repo_root)?;
- parse_remote_owner(&url).map(|s| s.to_string())
+ parse_remote_owner(&url)
}
/// Get the owner and repo name from the origin remote.
@@ -826,8 +763,7 @@ fn get_origin_owner(repo_root: &str) -> Option<String> {
/// Used for GitHub API calls that require `repos/{owner}/{repo}/...` paths.
fn get_owner_repo(repo_root: &str) -> Option<(String, String)> {
let url = get_remote_url_for_repo(repo_root)?;
- let (owner, repo) = parse_owner_repo(&url)?;
- Some((owner.to_string(), repo.to_string()))
+ parse_owner_repo(&url)
}
/// Get the GitLab project ID for the current repository.
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 74398f4e7..5ed71894b 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -7,6 +7,7 @@ mod diff;
mod error;
mod parse;
mod repository;
+mod url;
#[cfg(test)]
mod test;
@@ -41,6 +42,7 @@ pub use error::{
is_command_not_approved,
};
pub use repository::{Repository, ResolvedWorktree, set_base_path};
+pub use url::GitRemoteUrl;
/// Why branch content is considered integrated into the target branch.
///
/// Used by both `wt list` (for status symbols) and `wt remove` (for messages).
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index df981e1e2..83e2ce78a 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -11,8 +11,8 @@ use dunce::canonicalize;
// Import types and functions from parent module (mod.rs)
use super::{
- BranchCategory, CompletionBranch, DefaultBranchName, DiffStats, GitError, LineDiff, Worktree,
- WorktreeList,
+ BranchCategory, CompletionBranch, DefaultBranchName, DiffStats, GitError, GitRemoteUrl,
+ LineDiff, Worktree, WorktreeList,
};
/// Result of resolving a worktree name.
@@ -1502,44 +1502,20 @@ impl Repository {
let remote = self.primary_remote()?;
if let Ok(url) = self.run_command(&["remote", "get-url", remote]) {
- let url = url.trim();
-
- // Parse common git URL formats:
- // - https://github.com/user/repo.git
- // - [email protected]:user/repo.git
- // - ssh://[email protected]/user/repo.git
-
- // Remove .git suffix if present
- let url = url.strip_suffix(".git").unwrap_or(url);
-
- // Handle SSH format (git@host:path)
- if let Some(ssh_part) = url.strip_prefix("git@")
- && let Some((host, path)) = ssh_part.split_once(':')
- {
- return Ok(format!("{}/{}", host, path));
+ if let Some(parsed) = GitRemoteUrl::parse(url.trim()) {
+ return Ok(parsed.project_identifier());
}
-
- // Handle HTTPS/HTTP format
- if let Some(https_part) = url
- .strip_prefix("https://")
- .or_else(|| url.strip_prefix("http://"))
- {
- return Ok(https_part.to_string());
- }
-
- // Handle ssh:// format
+ // Fallback for URLs that don't fit host/owner/repo model (e.g., with ports)
+ let url = url.trim().strip_suffix(".git").unwrap_or(url.trim());
+ // Handle ssh:// format with port: ssh://git@host:port/path -> host/port/path
if let Some(ssh_part) = url.strip_prefix("ssh://") {
- // Remove git@ prefix if present
let ssh_part = ssh_part.strip_prefix("git@").unwrap_or(ssh_part);
- // Replace first : with /
if let Some(colon_pos) = ssh_part.find(':') {
- let (host, path) = ssh_part.split_at(colon_pos);
- return Ok(format!("{}{}", host, path.replacen(':', "/", 1)));
+ let (host, rest) = ssh_part.split_at(colon_pos);
+ return Ok(format!("{}{}", host, rest.replacen(':', "/", 1)));
}
return Ok(ssh_part.to_string());
}
-
- // If we can't parse it, use the URL as-is
return Ok(url.to_string());
}
diff --git a/src/git/url.rs b/src/git/url.rs
new file mode 100644
index 000000000..686c9b0ad
--- /dev/null
+++ b/src/git/url.rs
@@ -0,0 +1,220 @@
+//! Git remote URL parsing.
+//!
+//! Parses git remote URLs into structured components (host, owner, repo).
+//! Supports HTTPS, SSH, and git@ URL formats.
+
+/// Parsed git remote URL with host, owner, and repository components.
+///
+/// # Supported URL formats
+///
+/// - `https://<host>/<owner>/<repo>.git`
+/// - `http://<host>/<owner>/<repo>.git`
+/// - `git@<host>:<owner>/<repo>.git`
+/// - `ssh://git@<host>/<owner>/<repo>.git`
+/// - `ssh://<host>/<owner>/<repo>.git`
+///
+/// # Example
+///
+/// ```
+/// use worktrunk::git::GitRemoteUrl;
+///
+/// let url = GitRemoteUrl::parse("[email protected]:owner/repo.git").unwrap();
+/// assert_eq!(url.host(), "github.com");
+/// assert_eq!(url.owner(), "owner");
+/// assert_eq!(url.repo(), "repo");
+/// assert_eq!(url.project_identifier(), "github.com/owner/repo");
+/// ```
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct GitRemoteUrl {
+ host: String,
+ owner: String,
+ repo: String,
+}
+
+impl GitRemoteUrl {
+ /// Parse a git remote URL into structured components.
+ ///
+ /// Returns `None` for malformed URLs or unsupported formats.
+ pub fn parse(url: &str) -> Option<Self> {
+ let url = url.trim();
+
+ let (host, owner, repo_with_suffix) = if let Some(rest) = url.strip_prefix("https://") {
+ // https://github.com/owner/repo.git
+ let mut parts = rest.split('/');
+ let host = parts.next()?;
+ let owner = parts.next()?;
+ let repo = parts.next()?;
+ (host, owner, repo)
+ } else if let Some(rest) = url.strip_prefix("http://") {
+ // http://github.com/owner/repo.git
+ let mut parts = rest.split('/');
+ let host = parts.next()?;
+ let owner = parts.next()?;
+ let repo = parts.next()?;
+ (host, owner, repo)
+ } else if let Some(rest) = url.strip_prefix("ssh://") {
+ // ssh://[email protected]/owner/repo.git or ssh://github.com/owner/repo.git
+ // Note: URLs with ports (ssh://host:2222/...) are not supported here
+ // as they don't fit the host/owner/repo model. They should be handled
+ // as raw strings (project_identifier fallback).
+ let without_user = rest.split('@').next_back()?;
+ let mut parts = without_user.split('/');
+ let host = parts.next()?;
+ // If host contains a colon (port), this URL doesn't fit our model
+ if host.contains(':') {
+ return None;
+ }
+ let owner = parts.next()?;
+ let repo = parts.next()?;
+ (host, owner, repo)
+ } else if let Some(rest) = url.strip_prefix("git@") {
+ // [email protected]:owner/repo.git
+ let (host, path) = rest.split_once(':')?;
+ let mut parts = path.split('/');
+ let owner = parts.next()?;
+ let repo = parts.next()?;
+ (host, owner, repo)
+ } else {
+ return None;
+ };
+
+ // Strip .git suffix from repo if present
+ let repo = repo_with_suffix
+ .strip_suffix(".git")
+ .unwrap_or(repo_with_suffix);
+
+ // Validate non-empty
+ if host.is_empty() || owner.is_empty() || repo.is_empty() {
+ return None;
+ }
+
+ Some(Self {
+ host: host.to_string(),
+ owner: owner.to_string(),
+ repo: repo.to_string(),
+ })
+ }
+
+ /// The hostname (e.g., "github.com", "gitlab.example.com").
+ pub fn host(&self) -> &str {
+ &self.host
+ }
+
+ /// The repository owner or organization (e.g., "owner", "company-org").
+ pub fn owner(&self) -> &str {
+ &self.owner
+ }
+
+ /// The repository name without .git suffix (e.g., "repo").
+ pub fn repo(&self) -> &str {
+ &self.repo
+ }
+
+ /// Project identifier in "host/owner/repo" format.
+ ///
+ /// Used for tracking approved commands per project.
+ pub fn project_identifier(&self) -> String {
+ format!("{}/{}/{}", self.host, self.owner, self.repo)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_https_urls() {
+ let url = GitRemoteUrl::parse("https://github.com/owner/repo.git").unwrap();
+ assert_eq!(url.host(), "github.com");
+ assert_eq!(url.owner(), "owner");
+ assert_eq!(url.repo(), "repo");
+ assert_eq!(url.project_identifier(), "github.com/owner/repo");
+
+ // Without .git suffix
+ let url = GitRemoteUrl::parse("https://github.com/owner/repo").unwrap();
+ assert_eq!(url.repo(), "repo");
+
+ // With whitespace
+ let url = GitRemoteUrl::parse(" https://github.com/owner/repo.git\n").unwrap();
+ assert_eq!(url.owner(), "owner");
+ }
+
+ #[test]
+ fn test_http_urls() {
+ let url = GitRemoteUrl::parse("http://gitlab.internal.company.com/owner/repo.git").unwrap();
+ assert_eq!(url.host(), "gitlab.internal.company.com");
+ assert_eq!(url.owner(), "owner");
+ assert_eq!(url.repo(), "repo");
+ }
+
+ #[test]
+ fn test_git_at_urls() {
+ let url = GitRemoteUrl::parse("[email protected]:owner/repo.git").unwrap();
+ assert_eq!(url.host(), "github.com");
+ assert_eq!(url.owner(), "owner");
+ assert_eq!(url.repo(), "repo");
+
+ // Without .git suffix
+ let url = GitRemoteUrl::parse("[email protected]:owner/repo").unwrap();
+ assert_eq!(url.repo(), "repo");
+
+ // GitLab
+ let url = GitRemoteUrl::parse("[email protected]:owner/repo.git").unwrap();
+ assert_eq!(url.host(), "gitlab.example.com");
+
+ // Bitbucket
+ let url = GitRemoteUrl::parse("[email protected]:owner/repo.git").unwrap();
+ assert_eq!(url.host(), "bitbucket.org");
+ }
+
+ #[test]
+ fn test_ssh_urls() {
+ // With git@ user
+ let url = GitRemoteUrl::parse("ssh://[email protected]/owner/repo.git").unwrap();
+ assert_eq!(url.host(), "github.com");
+ assert_eq!(url.owner(), "owner");
+ assert_eq!(url.repo(), "repo");
+
+ // Without user
+ let url = GitRemoteUrl::parse("ssh://github.com/owner/repo.git").unwrap();
+ assert_eq!(url.host(), "github.com");
+ assert_eq!(url.owner(), "owner");
+ }
+
+ #[test]
+ fn test_malformed_urls() {
+ assert!(GitRemoteUrl::parse("").is_none());
+ assert!(GitRemoteUrl::parse("https://github.com/").is_none());
+ assert!(GitRemoteUrl::parse("https://github.com/owner/").is_none());
+ assert!(GitRemoteUrl::parse("[email protected]:").is_none());
+ assert!(GitRemoteUrl::parse("[email protected]:owner/").is_none());
+ assert!(GitRemoteUrl::parse("ftp://github.com/owner/repo.git").is_none());
+ }
+
+ #[test]
+ fn test_org_repos() {
+ let url = GitRemoteUrl::parse("https://github.com/company-org/project.git").unwrap();
+ assert_eq!(url.owner(), "company-org");
+ assert_eq!(url.repo(), "project");
+ }
+
+ #[test]
+ fn test_project_identifier() {
+ let cases = [
+ (
+ "https://github.com/max-sixty/worktrunk.git",
+ "github.com/max-sixty/worktrunk",
+ ),
+ ("[email protected]:owner/repo.git", "github.com/owner/repo"),
+ (
+ "ssh://[email protected]/org/project.git",
+ "gitlab.example.com/org/project",
+ ),
+ ];
+
+ for (input, expected) in cases {
+ let url = GitRemoteUrl::parse(input).unwrap();
+ assert_eq!(url.project_identifier(), expected, "input: {input}");
+ }
+ }
+}