Skip to main content

worktree_io/issue/parse/
detect.rs

1use anyhow::{bail, Context, Result};
2
3use crate::issue::IssueRef;
4
5impl IssueRef {
6    /// Detect the repository from the current working directory.
7    ///
8    /// Reads the `origin` remote URL and current branch, then creates
9    /// an [`Self::RemoteBranch`].
10    ///
11    /// # Errors
12    ///
13    /// Returns an error if the current directory is not inside a git
14    /// repository, has no `origin` remote, or the remote URL is not a
15    /// recognised GitHub or GitLab URL.
16    pub fn from_current_repo() -> Result<Self> {
17        // LLVM_COV_EXCL_START
18        let cwd = std::env::current_dir().context("Could not determine current directory")?;
19        let remote_url = crate::git::get_remote_url(&cwd, "origin").context(
20            "Not inside a git repository with an 'origin' remote.\n\
21                 Run `worktree open <REF>` with an explicit issue reference.",
22        )?;
23        let branch = crate::git::detect_local_default_branch(&cwd)
24            .context("Could not detect current branch")?;
25
26        if let Some((owner, repo)) = super::gh::parse_github_remote_url(&remote_url) {
27            return Ok(Self::RemoteBranch {
28                host: "github".into(),
29                owner,
30                repo,
31                branch,
32            });
33        }
34        if let Some((owner, repo)) = super::gitlab::parse_gitlab_remote_url(&remote_url) {
35            return Ok(Self::RemoteBranch {
36                host: "gitlab".into(),
37                owner,
38                repo,
39                branch,
40            });
41        }
42        bail!(
43            "Remote URL {remote_url:?} is not a supported GitHub or GitLab URL.\n\
44             Run `worktree open <REF>` with an explicit issue reference."
45        );
46        // LLVM_COV_EXCL_STOP
47    }
48}