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 creates an [`Self::Adhoc`] with
9    /// a randomly generated branch name.
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 name = crate::name_gen::generate_name();
24
25        if let Some((owner, repo)) = super::gh::parse_github_remote_url(&remote_url) {
26            return Ok(Self::Adhoc { owner, repo, name });
27        }
28        if let Some((owner, repo)) = super::gitlab::parse_gitlab_remote_url(&remote_url) {
29            return Ok(Self::Adhoc { owner, repo, name });
30        }
31        bail!(
32            "Remote URL {remote_url:?} is not a supported GitHub or GitLab URL.\n\
33             Run `worktree open <REF>` with an explicit issue reference."
34        );
35        // LLVM_COV_EXCL_STOP
36    }
37}