Skip to main content

bitbucket_cli/cli/
repo.rs

1use std::collections::HashSet;
2use std::path::{Path, PathBuf};
3
4use anyhow::{Context, Result};
5use clap::Subcommand;
6use colored::Colorize;
7use tabled::{Table, Tabled};
8
9use super::parse_repo;
10use crate::api::{BitbucketClient, download_url};
11use crate::models::{CreateRepositoryRequest, UpdateRepositoryRequest};
12
13#[derive(Subcommand)]
14pub enum RepoCommands {
15    /// List repositories in a workspace
16    List {
17        /// Workspace slug (defaults to --workspace or the configured default workspace)
18        workspace: Option<String>,
19
20        /// Number of results per page
21        #[arg(short, long, default_value = "25")]
22        limit: u32,
23    },
24
25    /// View repository details
26    View {
27        /// Repository in format workspace/repo-slug
28        repo: String,
29
30        /// Open in browser
31        #[arg(short, long)]
32        web: bool,
33    },
34
35    /// Clone a repository
36    Clone {
37        /// Repository in format workspace/repo-slug
38        repo: String,
39
40        /// Directory to clone into
41        #[arg(short, long)]
42        dir: Option<String>,
43    },
44
45    /// Create a new repository
46    Create {
47        /// Workspace slug, `workspace/name`, or just the repository name
48        /// when --workspace or a default workspace supplies the workspace
49        #[arg(value_name = "WORKSPACE_OR_NAME")]
50        workspace: String,
51
52        /// Repository name (omit when the first argument already names the repository)
53        name: Option<String>,
54
55        /// Repository description
56        #[arg(short, long)]
57        description: Option<String>,
58
59        /// Make repository public
60        #[arg(long)]
61        public: bool,
62
63        /// Project key to add repository to
64        #[arg(short, long)]
65        project: Option<String>,
66
67        /// Fork policy: allow_forks, no_public_forks, no_forks (default: allow_forks when --public, no_public_forks otherwise)
68        #[arg(long)]
69        fork_policy: Option<String>,
70    },
71
72    /// Update repository settings
73    Update {
74        /// Repository in format workspace/repo-slug
75        repo: String,
76
77        /// New repository name (also changes the repository slug)
78        #[arg(long)]
79        name: Option<String>,
80
81        /// New description
82        #[arg(short, long)]
83        description: Option<String>,
84
85        /// Make repository private
86        #[arg(long, conflicts_with = "public")]
87        private: bool,
88
89        /// Make repository public
90        #[arg(long)]
91        public: bool,
92
93        /// Primary language
94        #[arg(short, long)]
95        language: Option<String>,
96
97        /// Fork policy: allow_forks, no_public_forks, no_forks
98        #[arg(long)]
99        fork_policy: Option<String>,
100
101        /// Enable or disable the issue tracker
102        #[arg(long, value_name = "true|false")]
103        issues: Option<bool>,
104
105        /// Enable or disable the wiki
106        #[arg(long, value_name = "true|false")]
107        wiki: Option<bool>,
108
109        /// Main branch name
110        #[arg(long)]
111        main_branch: Option<String>,
112    },
113
114    /// Move a repository to a different project in its workspace
115    Move {
116        /// Repository in format workspace/repo-slug
117        repo: String,
118
119        /// Destination project key
120        project: String,
121    },
122
123    /// Fork a repository
124    Fork {
125        /// Repository to fork in format workspace/repo-slug
126        repo: String,
127
128        /// Workspace to fork into
129        #[arg(short, long)]
130        workspace: Option<String>,
131
132        /// New repository name
133        #[arg(short, long)]
134        name: Option<String>,
135    },
136
137    /// Delete a repository
138    Delete {
139        /// Repository in format workspace/repo-slug
140        repo: String,
141
142        /// Skip confirmation prompt
143        #[arg(short, long)]
144        yes: bool,
145    },
146
147    /// Manage repository downloads (uploaded file artifacts)
148    Download {
149        #[command(subcommand)]
150        command: DownloadCommands,
151    },
152}
153
154#[derive(Subcommand)]
155pub enum DownloadCommands {
156    /// Upload one or more files to the repository's downloads area
157    Upload {
158        /// Repository in format workspace/repo-slug
159        repo: String,
160
161        /// File(s) to upload. Uploading a file whose name already exists replaces it.
162        #[arg(required = true)]
163        files: Vec<PathBuf>,
164    },
165
166    /// List artifacts in the repository's downloads area
167    List {
168        /// Repository in format workspace/repo-slug
169        repo: String,
170    },
171
172    /// Delete an artifact from the repository's downloads area
173    Delete {
174        /// Repository in format workspace/repo-slug
175        repo: String,
176
177        /// Name of the artifact to delete
178        name: String,
179
180        /// Skip confirmation prompt
181        #[arg(short, long)]
182        yes: bool,
183    },
184}
185
186#[derive(Tabled)]
187struct RepoRow {
188    #[tabled(rename = "NAME")]
189    name: String,
190    #[tabled(rename = "DESCRIPTION")]
191    description: String,
192    #[tabled(rename = "PRIVATE")]
193    private: String,
194    #[tabled(rename = "UPDATED")]
195    updated: String,
196}
197
198impl RepoCommands {
199    pub async fn run(self) -> Result<()> {
200        match self {
201            RepoCommands::List { workspace, limit } => {
202                let workspace = super::resolve_workspace(workspace)?;
203                let client = BitbucketClient::from_stored().await?;
204                let repos = client
205                    .list_repositories(&workspace, None, Some(limit))
206                    .await?;
207
208                if repos.values.is_empty() {
209                    println!("No repositories found in workspace '{}'", workspace);
210                    return Ok(());
211                }
212
213                let rows: Vec<RepoRow> = repos
214                    .values
215                    .iter()
216                    .map(|r| RepoRow {
217                        name: r.full_name.clone(),
218                        description: r
219                            .description
220                            .clone()
221                            .unwrap_or_default()
222                            .chars()
223                            .take(40)
224                            .collect::<String>(),
225                        private: if r.is_private.unwrap_or(false) {
226                            "Yes"
227                        } else {
228                            "No"
229                        }
230                        .to_string(),
231                        updated: r
232                            .updated_on
233                            .map(|d| d.format("%Y-%m-%d").to_string())
234                            .unwrap_or_default(),
235                    })
236                    .collect();
237
238                let table = Table::new(rows).to_string();
239                println!("{}", table);
240
241                if repos.next.is_some() {
242                    println!(
243                        "\n{} More repositories available. Use --limit to see more.",
244                        "ℹ".blue()
245                    );
246                }
247
248                Ok(())
249            }
250
251            RepoCommands::View { repo, web } => {
252                let (workspace, repo_slug) = parse_repo(&repo)?;
253                let client = BitbucketClient::from_stored().await?;
254                let repository = client.get_repository(&workspace, &repo_slug).await?;
255
256                if web {
257                    if let Some(links) = &repository.links {
258                        if let Some(html) = &links.html {
259                            open::that(&html.href)?;
260                            println!("Opened {} in browser", html.href.cyan());
261                            return Ok(());
262                        }
263                    }
264                    anyhow::bail!("Could not find repository URL");
265                }
266
267                println!("{}", repository.full_name.bold());
268                println!("{}", "─".repeat(50));
269
270                if let Some(desc) = &repository.description {
271                    if !desc.is_empty() {
272                        println!("{}", desc);
273                        println!();
274                    }
275                }
276
277                println!(
278                    "{} {}",
279                    "Private:".dimmed(),
280                    if repository.is_private.unwrap_or(false) {
281                        "Yes"
282                    } else {
283                        "No"
284                    }
285                );
286                println!(
287                    "{} {}",
288                    "SCM:".dimmed(),
289                    repository.scm.as_deref().unwrap_or("unknown")
290                );
291
292                if let Some(lang) = &repository.language {
293                    if !lang.is_empty() {
294                        println!("{} {}", "Language:".dimmed(), lang);
295                    }
296                }
297
298                if let Some(branch) = &repository.mainbranch {
299                    println!("{} {}", "Main branch:".dimmed(), branch.name);
300                }
301
302                if let Some(size) = repository.size {
303                    let size_mb = size as f64 / (1024.0 * 1024.0);
304                    println!("{} {:.2} MB", "Size:".dimmed(), size_mb);
305                }
306
307                if let Some(created) = repository.created_on {
308                    println!("{} {}", "Created:".dimmed(), created.format("%Y-%m-%d"));
309                }
310
311                if let Some(updated) = repository.updated_on {
312                    println!("{} {}", "Updated:".dimmed(), updated.format("%Y-%m-%d"));
313                }
314
315                if let Some(links) = &repository.links {
316                    println!();
317                    if let Some(html) = &links.html {
318                        println!("{} {}", "Web:".dimmed(), html.href.cyan());
319                    }
320                    if let Some(clone_links) = &links.clone {
321                        for link in clone_links {
322                            println!("{} {} ({})", "Clone:".dimmed(), link.href, link.name);
323                        }
324                    }
325                }
326
327                Ok(())
328            }
329
330            RepoCommands::Clone { repo, dir } => {
331                let (workspace, repo_slug) = parse_repo(&repo)?;
332                let client = BitbucketClient::from_stored().await?;
333                let repository = client.get_repository(&workspace, &repo_slug).await?;
334
335                let clone_url = repository
336                    .links
337                    .as_ref()
338                    .and_then(|l| l.clone.as_ref())
339                    .and_then(|links| links.iter().find(|l| l.name == "ssh" || l.name == "https"))
340                    .map(|l| &l.href)
341                    .context("Could not find clone URL")?;
342
343                let target_dir = dir.unwrap_or_else(|| repo_slug.clone());
344
345                println!("Cloning {} into {}...", repo.cyan(), target_dir);
346
347                let status = std::process::Command::new("git")
348                    .args(["clone", clone_url, &target_dir])
349                    .status()
350                    .context("Failed to run git clone")?;
351
352                if status.success() {
353                    println!("{} Successfully cloned repository", "✓".green());
354                } else {
355                    anyhow::bail!("git clone failed");
356                }
357
358                Ok(())
359            }
360
361            RepoCommands::Create {
362                workspace,
363                name,
364                description,
365                public,
366                project,
367                fork_policy,
368            } => {
369                let (workspace, name) = super::resolve_create_target(workspace, name)?;
370
371                let client = BitbucketClient::from_stored().await?;
372
373                let slug = name.to_lowercase().replace(' ', "-");
374
375                let resolved_fork_policy = fork_policy.unwrap_or_else(|| {
376                    if public {
377                        "allow_forks".to_string()
378                    } else {
379                        "no_public_forks".to_string()
380                    }
381                });
382
383                let request = CreateRepositoryRequest {
384                    scm: "git".to_string(),
385                    name: Some(name.clone()),
386                    description,
387                    is_private: Some(!public),
388                    project: project.map(|key| crate::models::ProjectKey { key }),
389                    fork_policy: Some(resolved_fork_policy),
390                    ..Default::default()
391                };
392
393                let repository = client
394                    .create_repository(&workspace, &slug, &request)
395                    .await?;
396
397                println!(
398                    "{} Created repository {}",
399                    "✓".green(),
400                    repository.full_name.cyan()
401                );
402
403                if let Some(links) = &repository.links {
404                    if let Some(html) = &links.html {
405                        println!("{} {}", "URL:".dimmed(), html.href);
406                    }
407                }
408
409                Ok(())
410            }
411
412            RepoCommands::Update {
413                repo,
414                name,
415                description,
416                private,
417                public,
418                language,
419                fork_policy,
420                issues,
421                wiki,
422                main_branch,
423            } => {
424                let (workspace, repo_slug) = parse_repo(&repo)?;
425
426                let request = build_update_request(UpdateFlags {
427                    name,
428                    description,
429                    private,
430                    public,
431                    language,
432                    fork_policy,
433                    issues,
434                    wiki,
435                    main_branch,
436                });
437
438                if request.is_empty() {
439                    anyhow::bail!(
440                        "Nothing to update. Pass at least one option, e.g. --description or --private."
441                    );
442                }
443
444                let client = BitbucketClient::from_stored().await?;
445                let updated = client
446                    .update_repository(&workspace, &repo_slug, &request)
447                    .await?;
448
449                println!(
450                    "{} Updated repository {}",
451                    "✓".green(),
452                    updated.full_name.cyan()
453                );
454
455                if let Some(new_slug) = &updated.slug {
456                    if new_slug != &repo_slug {
457                        println!(
458                            "{} Repository slug changed: {} → {}",
459                            "ℹ".blue(),
460                            repo_slug,
461                            new_slug.cyan()
462                        );
463                    }
464                }
465
466                Ok(())
467            }
468
469            RepoCommands::Move { repo, project } => {
470                let (workspace, repo_slug) = parse_repo(&repo)?;
471
472                let request = UpdateRepositoryRequest {
473                    project: Some(crate::models::ProjectKey {
474                        key: project.clone(),
475                    }),
476                    ..Default::default()
477                };
478
479                let client = BitbucketClient::from_stored().await?;
480                let updated = client
481                    .update_repository(&workspace, &repo_slug, &request)
482                    .await?;
483
484                let project_label = updated
485                    .project
486                    .as_ref()
487                    .map(|p| format!("{} ({})", p.name, p.key))
488                    .unwrap_or(project);
489
490                println!(
491                    "{} Moved {} to project {}",
492                    "✓".green(),
493                    updated.full_name.cyan(),
494                    project_label.cyan()
495                );
496
497                Ok(())
498            }
499
500            RepoCommands::Fork {
501                repo,
502                workspace,
503                name,
504            } => {
505                let (src_workspace, src_repo) = parse_repo(&repo)?;
506                let client = BitbucketClient::from_stored().await?;
507
508                let forked = client
509                    .fork_repository(
510                        &src_workspace,
511                        &src_repo,
512                        workspace.as_deref(),
513                        name.as_deref(),
514                    )
515                    .await?;
516
517                println!("{} Forked to {}", "✓".green(), forked.full_name.cyan());
518
519                Ok(())
520            }
521
522            RepoCommands::Delete { repo, yes } => {
523                let (workspace, repo_slug) = parse_repo(&repo)?;
524
525                if !yes
526                    && !confirm_or_abort(format!(
527                        "Are you sure you want to delete {}? This cannot be undone!",
528                        repo.red()
529                    ))?
530                {
531                    return Ok(());
532                }
533
534                let client = BitbucketClient::from_stored().await?;
535                client.delete_repository(&workspace, &repo_slug).await?;
536
537                println!("{} Deleted repository {}", "✓".green(), repo);
538
539                Ok(())
540            }
541
542            RepoCommands::Download { command } => command.run().await,
543        }
544    }
545}
546
547#[derive(Tabled)]
548struct DownloadRow {
549    #[tabled(rename = "NAME")]
550    name: String,
551    #[tabled(rename = "SIZE")]
552    size: String,
553    #[tabled(rename = "DOWNLOADS")]
554    downloads: String,
555}
556
557impl DownloadCommands {
558    pub async fn run(self) -> Result<()> {
559        match self {
560            DownloadCommands::Upload { repo, files } => {
561                let (workspace, repo_slug) = parse_repo(&repo)?;
562
563                // Resolve each path to (upload-name, path) up front so a bad path
564                // fails before we open a network connection.
565                let uploads: Vec<(String, PathBuf)> = files
566                    .iter()
567                    .map(|p| Ok((upload_name_for(p)?, p.clone())))
568                    .collect::<Result<_>>()?;
569
570                // Bitbucket keys downloads by filename, so two inputs with the
571                // same basename would silently overwrite each other server-side.
572                let mut seen = HashSet::new();
573                for (name, _) in &uploads {
574                    if !seen.insert(name.as_str()) {
575                        anyhow::bail!(
576                            "Duplicate upload name '{}': multiple input files share this filename; Bitbucket stores downloads by filename, so one would overwrite the other",
577                            name
578                        );
579                    }
580                }
581
582                let client = BitbucketClient::from_stored().await?;
583                client
584                    .upload_downloads(&workspace, &repo_slug, &uploads)
585                    .await?;
586
587                for (name, _) in &uploads {
588                    println!(
589                        "{} Uploaded {}",
590                        "✓".green(),
591                        download_url(&workspace, &repo_slug, name).cyan()
592                    );
593                }
594
595                Ok(())
596            }
597
598            DownloadCommands::List { repo } => {
599                let (workspace, repo_slug) = parse_repo(&repo)?;
600                let client = BitbucketClient::from_stored().await?;
601                let downloads = client.list_downloads(&workspace, &repo_slug).await?;
602
603                if downloads.is_empty() {
604                    println!("No downloads found in {}", repo);
605                    return Ok(());
606                }
607
608                let rows: Vec<DownloadRow> = downloads
609                    .iter()
610                    .map(|d| DownloadRow {
611                        name: d.name.clone(),
612                        size: d.size.map(format_size).unwrap_or_else(|| "-".to_string()),
613                        downloads: d
614                            .downloads
615                            .map(|n| n.to_string())
616                            .unwrap_or_else(|| "-".to_string()),
617                    })
618                    .collect();
619
620                println!("{}", Table::new(rows));
621
622                Ok(())
623            }
624
625            DownloadCommands::Delete { repo, name, yes } => {
626                let (workspace, repo_slug) = parse_repo(&repo)?;
627
628                if !yes
629                    && !confirm_or_abort(format!("Delete download {} from {}?", name.red(), repo))?
630                {
631                    return Ok(());
632                }
633
634                let client = BitbucketClient::from_stored().await?;
635                client
636                    .delete_download(&workspace, &repo_slug, &name)
637                    .await
638                    .with_context(|| {
639                        format!(
640                            "Failed to delete download '{}' from {}/{}",
641                            name, workspace, repo_slug
642                        )
643                    })?;
644
645                println!("{} Deleted download {}", "✓".green(), name);
646
647                Ok(())
648            }
649        }
650    }
651}
652
653/// The `repo update` command-line flags, grouped for translation into an
654/// `UpdateRepositoryRequest`.
655#[derive(Default)]
656struct UpdateFlags {
657    name: Option<String>,
658    description: Option<String>,
659    private: bool,
660    public: bool,
661    language: Option<String>,
662    fork_policy: Option<String>,
663    issues: Option<bool>,
664    wiki: Option<bool>,
665    main_branch: Option<String>,
666}
667
668/// Build the update request for `repo update` from its command-line flags.
669fn build_update_request(flags: UpdateFlags) -> UpdateRepositoryRequest {
670    UpdateRepositoryRequest {
671        name: flags.name,
672        description: flags.description,
673        is_private: if flags.private {
674            Some(true)
675        } else if flags.public {
676            Some(false)
677        } else {
678            None
679        },
680        language: flags.language,
681        fork_policy: flags.fork_policy,
682        has_issues: flags.issues,
683        has_wiki: flags.wiki,
684        project: None,
685        mainbranch: flags.main_branch.map(|name| crate::models::Branch {
686            name,
687            branch_type: None,
688        }),
689    }
690}
691
692/// Ask the user to confirm a destructive action; on decline, print "Aborted"
693/// and return Ok(false).
694fn confirm_or_abort(prompt: String) -> Result<bool> {
695    use dialoguer::Confirm;
696    let confirmed = Confirm::new()
697        .with_prompt(prompt)
698        .default(false)
699        .interact()?;
700
701    if !confirmed {
702        println!("Aborted");
703    }
704
705    Ok(confirmed)
706}
707
708/// Extract the file name (final path component) from a path, for use as the
709/// uploaded artifact name.
710fn upload_name_for(path: &Path) -> Result<String> {
711    path.file_name()
712        .and_then(|n| n.to_str())
713        .map(|s| s.to_string())
714        .with_context(|| format!("Could not determine a file name for '{}'", path.display()))
715}
716
717/// Format a byte count into a short human-readable string.
718fn format_size(bytes: u64) -> String {
719    const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
720    let mut size = bytes as f64;
721    let mut unit = 0;
722    while size >= 1024.0 && unit < UNITS.len() - 1 {
723        size /= 1024.0;
724        unit += 1;
725    }
726    if unit == 0 {
727        format!("{} {}", bytes, UNITS[unit])
728    } else {
729        format!("{:.1} {}", size, UNITS[unit])
730    }
731}
732
733#[cfg(test)]
734mod tests {
735    use super::*;
736
737    #[test]
738    fn format_size_uses_bytes_below_1k() {
739        assert_eq!(format_size(0), "0 B");
740        assert_eq!(format_size(512), "512 B");
741        assert_eq!(format_size(1023), "1023 B");
742    }
743
744    #[test]
745    fn format_size_scales_to_larger_units() {
746        assert_eq!(format_size(1024), "1.0 KB");
747        assert_eq!(format_size(1536), "1.5 KB");
748        assert_eq!(format_size(1024 * 1024), "1.0 MB");
749        assert_eq!(format_size(5 * 1024 * 1024 * 1024), "5.0 GB");
750    }
751
752    #[test]
753    fn upload_name_takes_final_component() {
754        let p = PathBuf::from("/tmp/screenshots/login.png");
755        assert_eq!(upload_name_for(&p).unwrap(), "login.png");
756    }
757
758    fn empty_update_request(private: bool, public: bool) -> UpdateRepositoryRequest {
759        build_update_request(UpdateFlags {
760            private,
761            public,
762            ..Default::default()
763        })
764    }
765
766    #[test]
767    fn build_update_request_maps_private_flag() {
768        assert_eq!(empty_update_request(true, false).is_private, Some(true));
769    }
770
771    #[test]
772    fn build_update_request_maps_public_flag() {
773        assert_eq!(empty_update_request(false, true).is_private, Some(false));
774    }
775
776    #[test]
777    fn build_update_request_leaves_privacy_unset_without_flags() {
778        assert_eq!(empty_update_request(false, false).is_private, None);
779    }
780
781    #[test]
782    fn build_update_request_maps_main_branch() {
783        let request = build_update_request(UpdateFlags {
784            main_branch: Some("develop".to_string()),
785            ..Default::default()
786        });
787        let branch = request.mainbranch.expect("mainbranch should be set");
788        assert_eq!(branch.name, "develop");
789        assert_eq!(branch.branch_type, None);
790    }
791}