Skip to main content

bitbucket_cli/cli/
mod.rs

1pub mod auth;
2pub mod branch;
3pub mod branch_restriction;
4pub mod branching_model;
5pub mod commit;
6pub mod deploy;
7pub mod file;
8pub mod issue;
9pub mod pagination;
10pub mod permission;
11pub mod pipeline;
12pub mod pr;
13pub mod repo;
14pub mod reviewer;
15pub mod tag;
16pub mod user;
17pub mod webhook;
18pub mod workspace;
19
20use std::sync::OnceLock;
21
22use clap::{Parser, Subcommand};
23
24#[derive(Parser)]
25#[command(name = "bitbucket")]
26#[command(author = "quinnjr")]
27#[command(version)]
28#[command(about = "A command-line interface for Bitbucket Cloud", long_about = None)]
29#[command(propagate_version = true)]
30pub struct Cli {
31    #[command(subcommand)]
32    pub command: Commands,
33
34    /// Workspace to use when omitted from arguments (overrides config default)
35    #[arg(long, global = true)]
36    pub workspace: Option<String>,
37
38    /// Output format for command results
39    #[arg(long, global = true, value_enum, default_value_t = OutputFormat::Table)]
40    pub output: OutputFormat,
41}
42
43/// How command results are rendered.
44#[derive(Clone, Copy, PartialEq, Eq, Debug, clap::ValueEnum)]
45pub enum OutputFormat {
46    /// Human-readable tables and text
47    Table,
48    /// Raw JSON for scripting
49    Json,
50}
51
52#[derive(Subcommand)]
53pub enum Commands {
54    /// Manage authentication with Bitbucket
55    Auth {
56        #[command(subcommand)]
57        command: auth::AuthCommands,
58    },
59
60    /// Manage repositories
61    Repo {
62        #[command(subcommand)]
63        command: repo::RepoCommands,
64    },
65
66    /// Manage pull requests
67    Pr {
68        #[command(subcommand)]
69        command: pr::PrCommands,
70    },
71
72    /// Manage issues
73    Issue {
74        #[command(subcommand)]
75        command: issue::IssueCommands,
76    },
77
78    /// Manage pipelines
79    Pipeline {
80        #[command(subcommand)]
81        command: pipeline::PipelineCommands,
82    },
83
84    /// Manage workspaces
85    Workspace {
86        #[command(subcommand)]
87        command: workspace::WorkspaceCommands,
88    },
89
90    /// Inspect Bitbucket user accounts
91    User {
92        #[command(subcommand)]
93        command: user::UserCommands,
94    },
95
96    /// Launch interactive TUI
97    Tui,
98}
99
100static OUTPUT_FORMAT: OnceLock<OutputFormat> = OnceLock::new();
101
102/// Record the global `--output` choice for this process.
103///
104/// `main` must call this once before dispatching a command; later calls are
105/// no-ops (set-once cell).
106pub fn set_output_format(format: OutputFormat) {
107    let _ = OUTPUT_FORMAT.set(format);
108}
109
110/// True when `--output json` was passed; handlers should emit raw JSON.
111pub fn output_json() -> bool {
112    OUTPUT_FORMAT.get().copied() == Some(OutputFormat::Json)
113}
114
115/// Serialize a value as pretty JSON to stdout.
116pub(crate) fn print_json<T: serde::Serialize>(value: &T) -> anyhow::Result<()> {
117    println!("{}", serde_json::to_string_pretty(value)?);
118    Ok(())
119}
120
121static WORKSPACE_OVERRIDE: OnceLock<Option<String>> = OnceLock::new();
122
123/// Record the global `--workspace` override for this process.
124///
125/// `main` must call this once before dispatching a command; the value is
126/// stored in a set-once cell, so any later call is a no-op. Commands that
127/// run before it is set fall back to the config file alone.
128pub fn set_workspace_override(workspace: Option<String>) {
129    let _ = WORKSPACE_OVERRIDE.set(workspace);
130}
131
132fn workspace_override() -> Option<String> {
133    WORKSPACE_OVERRIDE.get().cloned().flatten()
134}
135
136fn fallback_workspace() -> Option<String> {
137    workspace_override().or_else(|| {
138        crate::config::Config::load()
139            .ok()
140            .and_then(|c| c.default_workspace().map(String::from))
141    })
142}
143
144/// Resolve a workspace given optionally on the command line, falling back to
145/// the `--workspace` override recorded by [`set_workspace_override`] and then
146/// to `default_workspace` from the config file (read from disk on each call).
147pub fn resolve_workspace(explicit: Option<String>) -> anyhow::Result<String> {
148    resolve_workspace_with(explicit, fallback_workspace())
149}
150
151fn resolve_workspace_with(
152    explicit: Option<String>,
153    fallback: Option<String>,
154) -> anyhow::Result<String> {
155    explicit
156        .filter(|w| !w.is_empty())
157        .or(fallback.filter(|w| !w.is_empty()))
158        .ok_or_else(|| {
159            anyhow::anyhow!(
160                "No workspace specified. Pass a workspace argument, use --workspace, or set a default workspace in the config."
161            )
162        })
163}
164
165/// Ask the user to confirm a destructive action; on decline, print "Aborted"
166/// and return Ok(false).
167pub(crate) fn confirm_or_abort(prompt: String) -> anyhow::Result<bool> {
168    use dialoguer::Confirm;
169    let confirmed = Confirm::new()
170        .with_prompt(prompt)
171        .default(false)
172        .interact()?;
173
174    if !confirmed {
175        // stderr so an aborted run never corrupts `--output json` on stdout
176        eprintln!("Aborted");
177    }
178
179    Ok(confirmed)
180}
181
182/// Parse `workspace/repo-slug`, or a bare `repo-slug` resolved against
183/// --workspace / the configured default workspace.
184///
185/// Resolution order for a bare slug: the process-wide override recorded by
186/// [`set_workspace_override`], then `default_workspace` from the config file
187/// (read from disk on each call).
188pub fn parse_repo(repo: &str) -> anyhow::Result<(String, String)> {
189    let fallback = fallback_workspace();
190    parse_repo_with(repo, fallback.as_deref())
191}
192
193/// Resolve `repo create`'s positional pair: an explicit second argument makes
194/// the first the workspace; otherwise the first is `workspace/name` or a bare
195/// name resolved like any repo argument.
196pub fn resolve_create_target(
197    first: String,
198    second: Option<String>,
199) -> anyhow::Result<(String, String)> {
200    let fallback = fallback_workspace();
201    resolve_create_target_with(first, second, fallback.as_deref())
202}
203
204fn resolve_create_target_with(
205    first: String,
206    second: Option<String>,
207    fallback_workspace: Option<&str>,
208) -> anyhow::Result<(String, String)> {
209    match second {
210        Some(name) => {
211            if first.contains('/') {
212                anyhow::bail!("Pass either 'workspace/name' or '<workspace> <name>', not both");
213            }
214            Ok((first, name))
215        }
216        None => parse_repo_with(&first, fallback_workspace),
217    }
218}
219
220fn parse_repo_with(
221    repo: &str,
222    fallback_workspace: Option<&str>,
223) -> anyhow::Result<(String, String)> {
224    if repo.contains('/') {
225        let parts: Vec<&str> = repo.split('/').collect();
226        if parts.len() == 2 && !parts[0].is_empty() && !parts[1].is_empty() {
227            return Ok((parts[0].to_string(), parts[1].to_string()));
228        }
229        anyhow::bail!(
230            "Invalid repository format. Expected 'workspace/repo-slug', got '{}'",
231            repo
232        );
233    }
234
235    if repo.is_empty() {
236        anyhow::bail!(
237            "Invalid repository format. Expected 'workspace/repo-slug', got '{}'",
238            repo
239        );
240    }
241
242    match fallback_workspace {
243        Some(workspace) if !workspace.is_empty() => Ok((workspace.to_string(), repo.to_string())),
244        _ => anyhow::bail!(
245            "No workspace specified. Use 'workspace/repo-slug', pass --workspace, or set a default workspace in the config."
246        ),
247    }
248}
249
250#[cfg(test)]
251mod tests {
252    use clap::CommandFactory;
253
254    #[test]
255    fn cli_parser_is_valid() {
256        super::Cli::command().debug_assert();
257    }
258
259    #[test]
260    fn parse_repo_with_accepts_workspace_and_slug() {
261        let (workspace, slug) = super::parse_repo_with("ws/slug", None).unwrap();
262        assert_eq!(workspace, "ws");
263        assert_eq!(slug, "slug");
264    }
265
266    #[test]
267    fn parse_repo_with_rejects_wrong_arity() {
268        assert!(super::parse_repo_with("a/b/c", None).is_err());
269    }
270
271    #[test]
272    fn parse_repo_with_rejects_empty_components() {
273        assert!(super::parse_repo_with("ws/", Some("fallback")).is_err());
274        assert!(super::parse_repo_with("/repo", Some("fallback")).is_err());
275        assert!(super::parse_repo_with("/", Some("fallback")).is_err());
276        assert!(super::parse_repo_with("", Some("fallback")).is_err());
277    }
278
279    #[test]
280    fn parse_repo_with_resolves_bare_slug_against_fallback() {
281        let (workspace, slug) = super::parse_repo_with("slug", Some("ws")).unwrap();
282        assert_eq!(workspace, "ws");
283        assert_eq!(slug, "slug");
284    }
285
286    #[test]
287    fn parse_repo_with_rejects_bare_slug_without_fallback() {
288        assert!(super::parse_repo_with("slug", None).is_err());
289        assert!(super::parse_repo_with("slug", Some("")).is_err());
290    }
291
292    #[test]
293    fn resolve_create_target_with_takes_explicit_workspace_and_name() {
294        let (workspace, name) =
295            super::resolve_create_target_with("ws".into(), Some("name".into()), None).unwrap();
296        assert_eq!(workspace, "ws");
297        assert_eq!(name, "name");
298    }
299
300    #[test]
301    fn resolve_create_target_with_splits_slashed_first_argument() {
302        let (workspace, name) =
303            super::resolve_create_target_with("ws/name".into(), None, None).unwrap();
304        assert_eq!(workspace, "ws");
305        assert_eq!(name, "name");
306    }
307
308    #[test]
309    fn resolve_create_target_with_resolves_bare_name_against_fallback() {
310        let (workspace, name) =
311            super::resolve_create_target_with("name".into(), None, Some("acme")).unwrap();
312        assert_eq!(workspace, "acme");
313        assert_eq!(name, "name");
314    }
315
316    #[test]
317    fn resolve_create_target_with_rejects_bare_name_without_fallback() {
318        assert!(super::resolve_create_target_with("name".into(), None, None).is_err());
319    }
320
321    #[test]
322    fn resolve_create_target_with_rejects_slashed_workspace_plus_explicit_name() {
323        assert!(
324            super::resolve_create_target_with("ws/x".into(), Some("name".into()), None).is_err()
325        );
326    }
327
328    #[test]
329    fn resolve_workspace_with_prefers_explicit_over_fallback() {
330        let ws = super::resolve_workspace_with(Some("cli-ws".into()), Some("cfg-ws".into()));
331        assert_eq!(ws.unwrap(), "cli-ws");
332    }
333
334    #[test]
335    fn resolve_workspace_with_uses_fallback_when_explicit_missing_or_empty() {
336        assert_eq!(
337            super::resolve_workspace_with(None, Some("cfg-ws".into())).unwrap(),
338            "cfg-ws"
339        );
340        assert_eq!(
341            super::resolve_workspace_with(Some(String::new()), Some("cfg-ws".into())).unwrap(),
342            "cfg-ws"
343        );
344    }
345
346    #[test]
347    fn resolve_workspace_with_errors_when_nothing_available() {
348        assert!(super::resolve_workspace_with(None, None).is_err());
349        assert!(super::resolve_workspace_with(None, Some(String::new())).is_err());
350    }
351
352    // The only test allowed to touch the process-wide override: OnceLock is
353    // set-once, so a second test setting a different value could not pass.
354    #[test]
355    fn parse_repo_resolves_bare_slug_via_workspace_override() {
356        super::set_workspace_override(Some("override-ws".to_string()));
357        let (workspace, slug) = super::parse_repo("slug").unwrap();
358        assert_eq!(workspace, "override-ws");
359        assert_eq!(slug, "slug");
360    }
361}