Skip to main content

bitbucket_cli/cli/
mod.rs

1pub mod auth;
2pub mod issue;
3pub mod pipeline;
4pub mod pr;
5pub mod repo;
6pub mod workspace;
7
8use std::sync::OnceLock;
9
10use clap::{Parser, Subcommand};
11
12#[derive(Parser)]
13#[command(name = "bitbucket")]
14#[command(author = "Pegasus Heavy Industries")]
15#[command(version)]
16#[command(about = "A command-line interface for Bitbucket Cloud", long_about = None)]
17#[command(propagate_version = true)]
18pub struct Cli {
19    #[command(subcommand)]
20    pub command: Commands,
21
22    /// Workspace to use when omitted from arguments (overrides config default)
23    #[arg(long, global = true)]
24    pub workspace: Option<String>,
25}
26
27#[derive(Subcommand)]
28pub enum Commands {
29    /// Manage authentication with Bitbucket
30    Auth {
31        #[command(subcommand)]
32        command: auth::AuthCommands,
33    },
34
35    /// Manage repositories
36    Repo {
37        #[command(subcommand)]
38        command: repo::RepoCommands,
39    },
40
41    /// Manage pull requests
42    Pr {
43        #[command(subcommand)]
44        command: pr::PrCommands,
45    },
46
47    /// Manage issues
48    Issue {
49        #[command(subcommand)]
50        command: issue::IssueCommands,
51    },
52
53    /// Manage pipelines
54    Pipeline {
55        #[command(subcommand)]
56        command: pipeline::PipelineCommands,
57    },
58
59    /// Manage workspaces
60    Workspace {
61        #[command(subcommand)]
62        command: workspace::WorkspaceCommands,
63    },
64
65    /// Launch interactive TUI
66    Tui,
67}
68
69static WORKSPACE_OVERRIDE: OnceLock<Option<String>> = OnceLock::new();
70
71/// Record the global `--workspace` override for this process.
72///
73/// `main` must call this once before dispatching a command; the value is
74/// stored in a set-once cell, so any later call is a no-op. Commands that
75/// run before it is set fall back to the config file alone.
76pub fn set_workspace_override(workspace: Option<String>) {
77    let _ = WORKSPACE_OVERRIDE.set(workspace);
78}
79
80fn workspace_override() -> Option<String> {
81    WORKSPACE_OVERRIDE.get().cloned().flatten()
82}
83
84fn fallback_workspace() -> Option<String> {
85    workspace_override().or_else(|| {
86        crate::config::Config::load()
87            .ok()
88            .and_then(|c| c.default_workspace().map(String::from))
89    })
90}
91
92/// Resolve a workspace given optionally on the command line, falling back to
93/// the `--workspace` override recorded by [`set_workspace_override`] and then
94/// to `default_workspace` from the config file (read from disk on each call).
95pub fn resolve_workspace(explicit: Option<String>) -> anyhow::Result<String> {
96    resolve_workspace_with(explicit, fallback_workspace())
97}
98
99fn resolve_workspace_with(
100    explicit: Option<String>,
101    fallback: Option<String>,
102) -> anyhow::Result<String> {
103    explicit
104        .filter(|w| !w.is_empty())
105        .or(fallback.filter(|w| !w.is_empty()))
106        .ok_or_else(|| {
107            anyhow::anyhow!(
108                "No workspace specified. Pass a workspace argument, use --workspace, or set a default workspace in the config."
109            )
110        })
111}
112
113/// Parse `workspace/repo-slug`, or a bare `repo-slug` resolved against
114/// --workspace / the configured default workspace.
115///
116/// Resolution order for a bare slug: the process-wide override recorded by
117/// [`set_workspace_override`], then `default_workspace` from the config file
118/// (read from disk on each call).
119pub fn parse_repo(repo: &str) -> anyhow::Result<(String, String)> {
120    let fallback = fallback_workspace();
121    parse_repo_with(repo, fallback.as_deref())
122}
123
124/// Resolve `repo create`'s positional pair: an explicit second argument makes
125/// the first the workspace; otherwise the first is `workspace/name` or a bare
126/// name resolved like any repo argument.
127pub fn resolve_create_target(
128    first: String,
129    second: Option<String>,
130) -> anyhow::Result<(String, String)> {
131    let fallback = fallback_workspace();
132    resolve_create_target_with(first, second, fallback.as_deref())
133}
134
135fn resolve_create_target_with(
136    first: String,
137    second: Option<String>,
138    fallback_workspace: Option<&str>,
139) -> anyhow::Result<(String, String)> {
140    match second {
141        Some(name) => {
142            if first.contains('/') {
143                anyhow::bail!("Pass either 'workspace/name' or '<workspace> <name>', not both");
144            }
145            Ok((first, name))
146        }
147        None => parse_repo_with(&first, fallback_workspace),
148    }
149}
150
151fn parse_repo_with(
152    repo: &str,
153    fallback_workspace: Option<&str>,
154) -> anyhow::Result<(String, String)> {
155    if repo.contains('/') {
156        let parts: Vec<&str> = repo.split('/').collect();
157        if parts.len() == 2 && !parts[0].is_empty() && !parts[1].is_empty() {
158            return Ok((parts[0].to_string(), parts[1].to_string()));
159        }
160        anyhow::bail!(
161            "Invalid repository format. Expected 'workspace/repo-slug', got '{}'",
162            repo
163        );
164    }
165
166    if repo.is_empty() {
167        anyhow::bail!(
168            "Invalid repository format. Expected 'workspace/repo-slug', got '{}'",
169            repo
170        );
171    }
172
173    match fallback_workspace {
174        Some(workspace) if !workspace.is_empty() => Ok((workspace.to_string(), repo.to_string())),
175        _ => anyhow::bail!(
176            "No workspace specified. Use 'workspace/repo-slug', pass --workspace, or set a default workspace in the config."
177        ),
178    }
179}
180
181#[cfg(test)]
182mod tests {
183    use clap::CommandFactory;
184
185    #[test]
186    fn cli_parser_is_valid() {
187        super::Cli::command().debug_assert();
188    }
189
190    #[test]
191    fn parse_repo_with_accepts_workspace_and_slug() {
192        let (workspace, slug) = super::parse_repo_with("ws/slug", None).unwrap();
193        assert_eq!(workspace, "ws");
194        assert_eq!(slug, "slug");
195    }
196
197    #[test]
198    fn parse_repo_with_rejects_wrong_arity() {
199        assert!(super::parse_repo_with("a/b/c", None).is_err());
200    }
201
202    #[test]
203    fn parse_repo_with_rejects_empty_components() {
204        assert!(super::parse_repo_with("ws/", Some("fallback")).is_err());
205        assert!(super::parse_repo_with("/repo", Some("fallback")).is_err());
206        assert!(super::parse_repo_with("/", Some("fallback")).is_err());
207        assert!(super::parse_repo_with("", Some("fallback")).is_err());
208    }
209
210    #[test]
211    fn parse_repo_with_resolves_bare_slug_against_fallback() {
212        let (workspace, slug) = super::parse_repo_with("slug", Some("ws")).unwrap();
213        assert_eq!(workspace, "ws");
214        assert_eq!(slug, "slug");
215    }
216
217    #[test]
218    fn parse_repo_with_rejects_bare_slug_without_fallback() {
219        assert!(super::parse_repo_with("slug", None).is_err());
220        assert!(super::parse_repo_with("slug", Some("")).is_err());
221    }
222
223    #[test]
224    fn resolve_create_target_with_takes_explicit_workspace_and_name() {
225        let (workspace, name) =
226            super::resolve_create_target_with("ws".into(), Some("name".into()), None).unwrap();
227        assert_eq!(workspace, "ws");
228        assert_eq!(name, "name");
229    }
230
231    #[test]
232    fn resolve_create_target_with_splits_slashed_first_argument() {
233        let (workspace, name) =
234            super::resolve_create_target_with("ws/name".into(), None, None).unwrap();
235        assert_eq!(workspace, "ws");
236        assert_eq!(name, "name");
237    }
238
239    #[test]
240    fn resolve_create_target_with_resolves_bare_name_against_fallback() {
241        let (workspace, name) =
242            super::resolve_create_target_with("name".into(), None, Some("acme")).unwrap();
243        assert_eq!(workspace, "acme");
244        assert_eq!(name, "name");
245    }
246
247    #[test]
248    fn resolve_create_target_with_rejects_bare_name_without_fallback() {
249        assert!(super::resolve_create_target_with("name".into(), None, None).is_err());
250    }
251
252    #[test]
253    fn resolve_create_target_with_rejects_slashed_workspace_plus_explicit_name() {
254        assert!(
255            super::resolve_create_target_with("ws/x".into(), Some("name".into()), None).is_err()
256        );
257    }
258
259    #[test]
260    fn resolve_workspace_with_prefers_explicit_over_fallback() {
261        let ws = super::resolve_workspace_with(Some("cli-ws".into()), Some("cfg-ws".into()));
262        assert_eq!(ws.unwrap(), "cli-ws");
263    }
264
265    #[test]
266    fn resolve_workspace_with_uses_fallback_when_explicit_missing_or_empty() {
267        assert_eq!(
268            super::resolve_workspace_with(None, Some("cfg-ws".into())).unwrap(),
269            "cfg-ws"
270        );
271        assert_eq!(
272            super::resolve_workspace_with(Some(String::new()), Some("cfg-ws".into())).unwrap(),
273            "cfg-ws"
274        );
275    }
276
277    #[test]
278    fn resolve_workspace_with_errors_when_nothing_available() {
279        assert!(super::resolve_workspace_with(None, None).is_err());
280        assert!(super::resolve_workspace_with(None, Some(String::new())).is_err());
281    }
282
283    // The only test allowed to touch the process-wide override: OnceLock is
284    // set-once, so a second test setting a different value could not pass.
285    #[test]
286    fn parse_repo_resolves_bare_slug_via_workspace_override() {
287        super::set_workspace_override(Some("override-ws".to_string()));
288        let (workspace, slug) = super::parse_repo("slug").unwrap();
289        assert_eq!(workspace, "override-ws");
290        assert_eq!(slug, "slug");
291    }
292}