Skip to main content

bitbucket_cli/cli/
workspace.rs

1use anyhow::Result;
2use clap::Subcommand;
3use colored::Colorize;
4use tabled::{Table, Tabled};
5
6use super::{confirm_or_abort, resolve_workspace};
7use crate::api::BitbucketClient;
8use crate::cli::pagination::{MAX_LIMIT, effective_limit};
9use crate::models::{
10    CreateProjectRequest, ProjectDetail, UpdateProjectRequest, Workspace, WorkspaceMembership,
11    WorkspacePermission,
12};
13
14#[derive(Subcommand)]
15pub enum WorkspaceCommands {
16    /// List workspaces you have access to
17    List {
18        /// Filter by your role in the workspace
19        #[arg(long, value_parser = ["member", "collaborator", "owner"])]
20        role: Option<String>,
21
22        /// Filter with a Bitbucket query (BBQL) expression, e.g. 'name~"acme"'
23        #[arg(short, long)]
24        query: Option<String>,
25
26        /// Sort by a field, e.g. 'name' or '-created_on' for descending
27        #[arg(long)]
28        sort: Option<String>,
29
30        /// Number of results per page (max 100)
31        #[arg(short, long, default_value = "25")]
32        limit: u32,
33
34        /// Fetch every page instead of a single page of results
35        #[arg(long, conflicts_with_all = ["role", "query", "sort", "limit"])]
36        all: bool,
37    },
38
39    /// View workspace details
40    View {
41        /// Workspace slug (defaults to --workspace or the configured default workspace)
42        workspace: Option<String>,
43    },
44
45    /// List members of a workspace
46    Members {
47        /// Workspace slug (defaults to --workspace or the configured default workspace)
48        workspace: Option<String>,
49
50        /// Number of results per page (max 100)
51        #[arg(short, long, default_value = "25")]
52        limit: u32,
53    },
54
55    /// List user permissions on a workspace or one of its repositories
56    Permissions {
57        /// Workspace slug (defaults to --workspace or the configured default workspace)
58        workspace: Option<String>,
59
60        /// Show permissions on this repository instead of the workspace
61        #[arg(long)]
62        repo: Option<String>,
63
64        /// Number of results per page (max 100)
65        #[arg(short, long, default_value = "25")]
66        limit: u32,
67    },
68
69    /// Manage projects in a workspace
70    Project {
71        #[command(subcommand)]
72        command: ProjectCommands,
73    },
74}
75
76#[derive(Subcommand)]
77pub enum ProjectCommands {
78    /// List projects in a workspace
79    List {
80        /// Workspace slug (defaults to --workspace or the configured default workspace)
81        workspace: Option<String>,
82
83        /// Filter with a Bitbucket query (BBQL) expression, e.g. 'name~"api"'
84        #[arg(short, long)]
85        query: Option<String>,
86
87        /// Sort by a field, e.g. 'name' or '-updated_on' for descending
88        #[arg(long)]
89        sort: Option<String>,
90
91        /// Number of results per page (max 100)
92        #[arg(short, long, default_value = "25")]
93        limit: u32,
94
95        /// Page number to fetch
96        #[arg(long)]
97        page: Option<u32>,
98    },
99
100    /// View project details
101    View {
102        /// Project key, e.g. PROJ
103        key: String,
104
105        /// Workspace slug (defaults to --workspace or the configured default workspace)
106        #[arg(long)]
107        workspace: Option<String>,
108    },
109
110    /// Create a new project
111    Create {
112        /// Project key, e.g. PROJ
113        key: String,
114
115        /// Project name
116        name: String,
117
118        /// Project description
119        #[arg(short, long)]
120        description: Option<String>,
121
122        /// Make the project private (default)
123        #[arg(long, conflicts_with = "public")]
124        private: bool,
125
126        /// Make the project public
127        #[arg(long)]
128        public: bool,
129
130        /// Workspace slug (defaults to --workspace or the configured default workspace)
131        #[arg(long)]
132        workspace: Option<String>,
133    },
134
135    /// Update project settings
136    Edit {
137        /// Project key, e.g. PROJ
138        key: String,
139
140        /// New project name
141        #[arg(long)]
142        name: Option<String>,
143
144        /// New description
145        #[arg(short, long)]
146        description: Option<String>,
147
148        /// Make the project private
149        #[arg(long, conflicts_with = "public")]
150        private: bool,
151
152        /// Make the project public
153        #[arg(long)]
154        public: bool,
155
156        /// Workspace slug (defaults to --workspace or the configured default workspace)
157        #[arg(long)]
158        workspace: Option<String>,
159    },
160
161    /// Delete a project
162    Delete {
163        /// Project key, e.g. PROJ
164        key: String,
165
166        /// Workspace slug (defaults to --workspace or the configured default workspace)
167        #[arg(long)]
168        workspace: Option<String>,
169
170        /// Skip confirmation prompt
171        #[arg(short, long)]
172        yes: bool,
173    },
174}
175
176#[derive(Tabled)]
177struct WorkspaceRow {
178    #[tabled(rename = "SLUG")]
179    slug: String,
180    #[tabled(rename = "NAME")]
181    name: String,
182    #[tabled(rename = "PRIVATE")]
183    private: String,
184    #[tabled(rename = "CREATED")]
185    created: String,
186}
187
188#[derive(Tabled)]
189struct MemberRow {
190    #[tabled(rename = "NAME")]
191    name: String,
192    #[tabled(rename = "USERNAME")]
193    username: String,
194    #[tabled(rename = "UUID")]
195    uuid: String,
196}
197
198#[derive(Tabled)]
199struct PermissionRow {
200    #[tabled(rename = "USER")]
201    user: String,
202    #[tabled(rename = "PERMISSION")]
203    permission: String,
204}
205
206#[derive(Tabled)]
207struct ProjectRow {
208    #[tabled(rename = "KEY")]
209    key: String,
210    #[tabled(rename = "NAME")]
211    name: String,
212    #[tabled(rename = "PRIVATE")]
213    private: String,
214    #[tabled(rename = "UPDATED")]
215    updated: String,
216}
217
218/// Render an optional privacy flag as Yes/No/-
219fn privacy_label(is_private: Option<bool>) -> String {
220    match is_private {
221        Some(true) => "Yes",
222        Some(false) => "No",
223        None => "-",
224    }
225    .to_string()
226}
227
228fn workspace_rows(workspaces: &[Workspace]) -> Vec<WorkspaceRow> {
229    workspaces
230        .iter()
231        .map(|w| WorkspaceRow {
232            slug: w.slug.clone(),
233            name: w.name.clone(),
234            private: privacy_label(w.is_private),
235            created: w
236                .created_on
237                .map(|d| d.format("%Y-%m-%d").to_string())
238                .unwrap_or_default(),
239        })
240        .collect()
241}
242
243fn member_rows(members: &[WorkspaceMembership]) -> Vec<MemberRow> {
244    members
245        .iter()
246        .map(|m| MemberRow {
247            name: m
248                .user
249                .as_ref()
250                .map(|u| u.display_name.clone())
251                .unwrap_or_else(|| "-".to_string()),
252            username: m
253                .user
254                .as_ref()
255                .and_then(|u| u.username.clone())
256                .unwrap_or_else(|| "-".to_string()),
257            uuid: m
258                .user
259                .as_ref()
260                .map(|u| u.uuid.clone())
261                .unwrap_or_else(|| "-".to_string()),
262        })
263        .collect()
264}
265
266fn permission_rows(permissions: &[WorkspacePermission]) -> Vec<PermissionRow> {
267    permissions
268        .iter()
269        .map(|p| PermissionRow {
270            user: p
271                .user
272                .as_ref()
273                .map(|u| u.display_name.clone())
274                .unwrap_or_else(|| "-".to_string()),
275            permission: p.permission.clone().unwrap_or_else(|| "-".to_string()),
276        })
277        .collect()
278}
279
280fn project_rows(projects: &[ProjectDetail]) -> Vec<ProjectRow> {
281    projects
282        .iter()
283        .map(|p| ProjectRow {
284            key: p.key.clone(),
285            name: p.name.clone(),
286            private: privacy_label(p.is_private),
287            updated: p
288                .updated_on
289                .map(|d| d.format("%Y-%m-%d").to_string())
290                .unwrap_or_default(),
291        })
292        .collect()
293}
294
295impl WorkspaceCommands {
296    pub async fn run(self) -> Result<()> {
297        match self {
298            WorkspaceCommands::List {
299                role,
300                query,
301                sort,
302                limit,
303                all,
304            } => {
305                let client = BitbucketClient::from_stored().await?;
306
307                if all {
308                    let workspaces = client.list_workspaces().await?;
309
310                    if super::output_json() {
311                        return super::print_json(&workspaces);
312                    }
313
314                    if workspaces.is_empty() {
315                        println!("No workspaces found");
316                        return Ok(());
317                    }
318
319                    let table = Table::new(workspace_rows(&workspaces)).to_string();
320                    println!("{}", table);
321
322                    return Ok(());
323                }
324
325                let limit = effective_limit(limit);
326                let page = client
327                    .list_workspaces_filtered(
328                        role.as_deref(),
329                        query.as_deref(),
330                        sort.as_deref(),
331                        None,
332                        Some(limit),
333                    )
334                    .await?;
335
336                if super::output_json() {
337                    return super::print_json(&page.values);
338                }
339
340                if page.values.is_empty() {
341                    println!("No workspaces found");
342                    return Ok(());
343                }
344
345                let table = Table::new(workspace_rows(&page.values)).to_string();
346                println!("{}", table);
347
348                if page.next.is_some() {
349                    println!(
350                        "\n{} More workspaces available. Use --all to fetch every workspace.",
351                        "ℹ".blue()
352                    );
353                }
354
355                Ok(())
356            }
357
358            WorkspaceCommands::View { workspace } => {
359                let workspace = resolve_workspace(workspace)?;
360                let client = BitbucketClient::from_stored().await?;
361                let workspace = client.get_workspace(&workspace).await?;
362
363                if super::output_json() {
364                    return super::print_json(&workspace);
365                }
366
367                println!("{}", workspace.name.bold());
368                println!("{}", "─".repeat(50));
369                println!("{} {}", "Slug:".bold(), workspace.slug);
370                println!("{} {}", "UUID:".bold(), workspace.uuid);
371                println!(
372                    "{} {}",
373                    "Private:".bold(),
374                    privacy_label(workspace.is_private)
375                );
376                println!(
377                    "{} {}",
378                    "Created:".bold(),
379                    workspace
380                        .created_on
381                        .map(|d| d.format("%Y-%m-%d").to_string())
382                        .unwrap_or_else(|| "-".to_string())
383                );
384
385                Ok(())
386            }
387
388            WorkspaceCommands::Members { workspace, limit } => {
389                let workspace = resolve_workspace(workspace)?;
390                let limit = effective_limit(limit);
391                let client = BitbucketClient::from_stored().await?;
392                let members = client
393                    .list_workspace_members(&workspace, Some(limit))
394                    .await?;
395
396                if super::output_json() {
397                    return super::print_json(&members.values);
398                }
399
400                if members.values.is_empty() {
401                    println!("No members found in workspace '{}'", workspace);
402                    return Ok(());
403                }
404
405                let table = Table::new(member_rows(&members.values)).to_string();
406                println!("{}", table);
407
408                if members.next.is_some() {
409                    println!(
410                        "\n{} More members available. Increase --limit (max {}) to see more.",
411                        "ℹ".blue(),
412                        MAX_LIMIT
413                    );
414                }
415
416                Ok(())
417            }
418
419            WorkspaceCommands::Permissions {
420                workspace,
421                repo,
422                limit,
423            } => {
424                let workspace = resolve_workspace(workspace)?;
425                let limit = effective_limit(limit);
426                let client = BitbucketClient::from_stored().await?;
427                let permissions = client
428                    .list_workspace_permissions(&workspace, repo.as_deref(), None, Some(limit))
429                    .await?;
430
431                if super::output_json() {
432                    return super::print_json(&permissions.values);
433                }
434
435                if permissions.values.is_empty() {
436                    match &repo {
437                        Some(repo) => {
438                            println!(
439                                "No permissions found on repository '{}/{}'",
440                                workspace, repo
441                            )
442                        }
443                        None => println!("No permissions found in workspace '{}'", workspace),
444                    }
445                    return Ok(());
446                }
447
448                let table = Table::new(permission_rows(&permissions.values)).to_string();
449                println!("{}", table);
450
451                if permissions.next.is_some() {
452                    println!(
453                        "\n{} More permissions available. Increase --limit (max {}) to see more.",
454                        "ℹ".blue(),
455                        MAX_LIMIT
456                    );
457                }
458
459                Ok(())
460            }
461
462            WorkspaceCommands::Project { command } => command.run().await,
463        }
464    }
465}
466
467impl ProjectCommands {
468    pub async fn run(self) -> Result<()> {
469        match self {
470            ProjectCommands::List {
471                workspace,
472                query,
473                sort,
474                limit,
475                page,
476            } => {
477                let workspace = resolve_workspace(workspace)?;
478                let limit = effective_limit(limit);
479                let client = BitbucketClient::from_stored().await?;
480                let projects = client
481                    .list_projects(
482                        &workspace,
483                        query.as_deref(),
484                        sort.as_deref(),
485                        page,
486                        Some(limit),
487                    )
488                    .await?;
489
490                if super::output_json() {
491                    return super::print_json(&projects.values);
492                }
493
494                if projects.values.is_empty() {
495                    println!("No projects found in workspace '{}'", workspace);
496                    return Ok(());
497                }
498
499                let table = Table::new(project_rows(&projects.values)).to_string();
500                println!("{}", table);
501
502                if projects.next.is_some() {
503                    println!(
504                        "\n{} More projects available. Use --page {} to see the next page.",
505                        "ℹ".blue(),
506                        page.unwrap_or(1) + 1
507                    );
508                }
509
510                Ok(())
511            }
512
513            ProjectCommands::View { key, workspace } => {
514                let workspace = resolve_workspace(workspace)?;
515                let client = BitbucketClient::from_stored().await?;
516                let project = client.get_project(&workspace, &key).await?;
517
518                if super::output_json() {
519                    return super::print_json(&project);
520                }
521
522                println!("{} {}", project.key.bold(), project.name);
523                println!("{}", "─".repeat(50));
524
525                if let Some(desc) = &project.description {
526                    if !desc.is_empty() {
527                        println!("{}", desc);
528                        println!();
529                    }
530                }
531
532                println!(
533                    "{} {}",
534                    "UUID:".bold(),
535                    project.uuid.as_deref().unwrap_or("-")
536                );
537                println!(
538                    "{} {}",
539                    "Private:".bold(),
540                    privacy_label(project.is_private)
541                );
542                println!(
543                    "{} {}",
544                    "Created:".bold(),
545                    project
546                        .created_on
547                        .map(|d| d.format("%Y-%m-%d").to_string())
548                        .unwrap_or_else(|| "-".to_string())
549                );
550                println!(
551                    "{} {}",
552                    "Updated:".bold(),
553                    project
554                        .updated_on
555                        .map(|d| d.format("%Y-%m-%d").to_string())
556                        .unwrap_or_else(|| "-".to_string())
557                );
558
559                Ok(())
560            }
561
562            ProjectCommands::Create {
563                key,
564                name,
565                description,
566                private: _,
567                public,
568                workspace,
569            } => {
570                let workspace = resolve_workspace(workspace)?;
571                let client = BitbucketClient::from_stored().await?;
572
573                let request = CreateProjectRequest {
574                    name,
575                    key,
576                    description,
577                    // Private unless --public was given (private is the default).
578                    is_private: Some(!public),
579                };
580
581                let project = client.create_project(&workspace, &request).await?;
582
583                if super::output_json() {
584                    return super::print_json(&project);
585                }
586
587                println!(
588                    "{} Created project {} in workspace {}",
589                    "✓".green(),
590                    project.key.cyan(),
591                    workspace
592                );
593
594                Ok(())
595            }
596
597            ProjectCommands::Edit {
598                key,
599                name,
600                description,
601                private,
602                public,
603                workspace,
604            } => {
605                let workspace = resolve_workspace(workspace)?;
606
607                let request = UpdateProjectRequest {
608                    name,
609                    description,
610                    is_private: if private {
611                        Some(true)
612                    } else if public {
613                        Some(false)
614                    } else {
615                        None
616                    },
617                };
618
619                if request.is_empty() {
620                    anyhow::bail!(
621                        "No changes specified. Pass at least one of --name, --description, --private, or --public."
622                    );
623                }
624
625                let client = BitbucketClient::from_stored().await?;
626                let project = client.update_project(&workspace, &key, &request).await?;
627
628                if super::output_json() {
629                    return super::print_json(&project);
630                }
631
632                println!("{} Updated project {}", "✓".green(), project.key.cyan());
633
634                Ok(())
635            }
636
637            ProjectCommands::Delete {
638                key,
639                workspace,
640                yes,
641            } => {
642                let workspace = resolve_workspace(workspace)?;
643
644                if !yes
645                    && !confirm_or_abort(format!(
646                        "Are you sure you want to delete project {} from workspace {}? This cannot be undone!",
647                        key.red(),
648                        workspace
649                    ))?
650                {
651                    return Ok(());
652                }
653
654                let client = BitbucketClient::from_stored().await?;
655                client.delete_project(&workspace, &key).await?;
656
657                if super::output_json() {
658                    return super::print_json(&serde_json::json!({"ok": true}));
659                }
660
661                println!("{} Deleted project {}", "✓".green(), key);
662
663                Ok(())
664            }
665        }
666    }
667}
668
669#[cfg(test)]
670mod tests {
671    use super::privacy_label;
672
673    #[test]
674    fn privacy_label_renders_all_states() {
675        assert_eq!(privacy_label(Some(true)), "Yes");
676        assert_eq!(privacy_label(Some(false)), "No");
677        assert_eq!(privacy_label(None), "-");
678    }
679}