1use anyhow::{Context, Result};
2use clap::Subcommand;
3use colored::Colorize;
4use tabled::{Table, Tabled};
5
6use crate::api::BitbucketClient;
7use crate::models::CreateRepositoryRequest;
8
9#[derive(Subcommand)]
10pub enum RepoCommands {
11 List {
13 workspace: String,
15
16 #[arg(short, long, default_value = "25")]
18 limit: u32,
19 },
20
21 View {
23 repo: String,
25
26 #[arg(short, long)]
28 web: bool,
29 },
30
31 Clone {
33 repo: String,
35
36 #[arg(short, long)]
38 dir: Option<String>,
39 },
40
41 Create {
43 workspace: String,
45
46 name: String,
48
49 #[arg(short, long)]
51 description: Option<String>,
52
53 #[arg(long)]
55 public: bool,
56
57 #[arg(short, long)]
59 project: Option<String>,
60
61 #[arg(long)]
63 fork_policy: Option<String>,
64 },
65
66 Fork {
68 repo: String,
70
71 #[arg(short, long)]
73 workspace: Option<String>,
74
75 #[arg(short, long)]
77 name: Option<String>,
78 },
79
80 Delete {
82 repo: String,
84
85 #[arg(short, long)]
87 yes: bool,
88 },
89}
90
91#[derive(Tabled)]
92struct RepoRow {
93 #[tabled(rename = "NAME")]
94 name: String,
95 #[tabled(rename = "DESCRIPTION")]
96 description: String,
97 #[tabled(rename = "PRIVATE")]
98 private: String,
99 #[tabled(rename = "UPDATED")]
100 updated: String,
101}
102
103impl RepoCommands {
104 pub async fn run(self) -> Result<()> {
105 match self {
106 RepoCommands::List { workspace, limit } => {
107 let client = BitbucketClient::from_stored().await?;
108 let repos = client
109 .list_repositories(&workspace, None, Some(limit))
110 .await?;
111
112 if repos.values.is_empty() {
113 println!("No repositories found in workspace '{}'", workspace);
114 return Ok(());
115 }
116
117 let rows: Vec<RepoRow> = repos
118 .values
119 .iter()
120 .map(|r| RepoRow {
121 name: r.full_name.clone(),
122 description: r
123 .description
124 .clone()
125 .unwrap_or_default()
126 .chars()
127 .take(40)
128 .collect::<String>(),
129 private: if r.is_private.unwrap_or(false) {
130 "Yes"
131 } else {
132 "No"
133 }
134 .to_string(),
135 updated: r
136 .updated_on
137 .map(|d| d.format("%Y-%m-%d").to_string())
138 .unwrap_or_default(),
139 })
140 .collect();
141
142 let table = Table::new(rows).to_string();
143 println!("{}", table);
144
145 if repos.next.is_some() {
146 println!(
147 "\n{} More repositories available. Use --limit to see more.",
148 "ℹ".blue()
149 );
150 }
151
152 Ok(())
153 }
154
155 RepoCommands::View { repo, web } => {
156 let (workspace, repo_slug) = parse_repo(&repo)?;
157 let client = BitbucketClient::from_stored().await?;
158 let repository = client.get_repository(&workspace, &repo_slug).await?;
159
160 if web {
161 if let Some(links) = &repository.links {
162 if let Some(html) = &links.html {
163 open::that(&html.href)?;
164 println!("Opened {} in browser", html.href.cyan());
165 return Ok(());
166 }
167 }
168 anyhow::bail!("Could not find repository URL");
169 }
170
171 println!("{}", repository.full_name.bold());
172 println!("{}", "─".repeat(50));
173
174 if let Some(desc) = &repository.description {
175 if !desc.is_empty() {
176 println!("{}", desc);
177 println!();
178 }
179 }
180
181 println!(
182 "{} {}",
183 "Private:".dimmed(),
184 if repository.is_private.unwrap_or(false) {
185 "Yes"
186 } else {
187 "No"
188 }
189 );
190 println!(
191 "{} {}",
192 "SCM:".dimmed(),
193 repository.scm.as_deref().unwrap_or("unknown")
194 );
195
196 if let Some(lang) = &repository.language {
197 if !lang.is_empty() {
198 println!("{} {}", "Language:".dimmed(), lang);
199 }
200 }
201
202 if let Some(branch) = &repository.mainbranch {
203 println!("{} {}", "Main branch:".dimmed(), branch.name);
204 }
205
206 if let Some(size) = repository.size {
207 let size_mb = size as f64 / (1024.0 * 1024.0);
208 println!("{} {:.2} MB", "Size:".dimmed(), size_mb);
209 }
210
211 if let Some(created) = repository.created_on {
212 println!("{} {}", "Created:".dimmed(), created.format("%Y-%m-%d"));
213 }
214
215 if let Some(updated) = repository.updated_on {
216 println!("{} {}", "Updated:".dimmed(), updated.format("%Y-%m-%d"));
217 }
218
219 if let Some(links) = &repository.links {
220 println!();
221 if let Some(html) = &links.html {
222 println!("{} {}", "Web:".dimmed(), html.href.cyan());
223 }
224 if let Some(clone_links) = &links.clone {
225 for link in clone_links {
226 println!("{} {} ({})", "Clone:".dimmed(), link.href, link.name);
227 }
228 }
229 }
230
231 Ok(())
232 }
233
234 RepoCommands::Clone { repo, dir } => {
235 let (workspace, repo_slug) = parse_repo(&repo)?;
236 let client = BitbucketClient::from_stored().await?;
237 let repository = client.get_repository(&workspace, &repo_slug).await?;
238
239 let clone_url = repository
240 .links
241 .as_ref()
242 .and_then(|l| l.clone.as_ref())
243 .and_then(|links| links.iter().find(|l| l.name == "ssh" || l.name == "https"))
244 .map(|l| &l.href)
245 .context("Could not find clone URL")?;
246
247 let target_dir = dir.unwrap_or_else(|| repo_slug.clone());
248
249 println!("Cloning {} into {}...", repo.cyan(), target_dir);
250
251 let status = std::process::Command::new("git")
252 .args(["clone", clone_url, &target_dir])
253 .status()
254 .context("Failed to run git clone")?;
255
256 if status.success() {
257 println!("{} Successfully cloned repository", "✓".green());
258 } else {
259 anyhow::bail!("git clone failed");
260 }
261
262 Ok(())
263 }
264
265 RepoCommands::Create {
266 workspace,
267 name,
268 description,
269 public,
270 project,
271 fork_policy,
272 } => {
273 let client = BitbucketClient::from_stored().await?;
274
275 let slug = name.to_lowercase().replace(' ', "-");
276
277 let resolved_fork_policy = fork_policy.unwrap_or_else(|| {
278 if public {
279 "allow_forks".to_string()
280 } else {
281 "no_public_forks".to_string()
282 }
283 });
284
285 let request = CreateRepositoryRequest {
286 scm: "git".to_string(),
287 name: Some(name.clone()),
288 description,
289 is_private: Some(!public),
290 project: project.map(|key| crate::models::ProjectKey { key }),
291 fork_policy: Some(resolved_fork_policy),
292 ..Default::default()
293 };
294
295 let repository = client
296 .create_repository(&workspace, &slug, &request)
297 .await?;
298
299 println!(
300 "{} Created repository {}",
301 "✓".green(),
302 repository.full_name.cyan()
303 );
304
305 if let Some(links) = &repository.links {
306 if let Some(html) = &links.html {
307 println!("{} {}", "URL:".dimmed(), html.href);
308 }
309 }
310
311 Ok(())
312 }
313
314 RepoCommands::Fork {
315 repo,
316 workspace,
317 name,
318 } => {
319 let (src_workspace, src_repo) = parse_repo(&repo)?;
320 let client = BitbucketClient::from_stored().await?;
321
322 let forked = client
323 .fork_repository(
324 &src_workspace,
325 &src_repo,
326 workspace.as_deref(),
327 name.as_deref(),
328 )
329 .await?;
330
331 println!("{} Forked to {}", "✓".green(), forked.full_name.cyan());
332
333 Ok(())
334 }
335
336 RepoCommands::Delete { repo, yes } => {
337 let (workspace, repo_slug) = parse_repo(&repo)?;
338
339 if !yes {
340 use dialoguer::Confirm;
341 let confirmed = Confirm::new()
342 .with_prompt(format!(
343 "Are you sure you want to delete {}? This cannot be undone!",
344 repo.red()
345 ))
346 .default(false)
347 .interact()?;
348
349 if !confirmed {
350 println!("Aborted");
351 return Ok(());
352 }
353 }
354
355 let client = BitbucketClient::from_stored().await?;
356 client.delete_repository(&workspace, &repo_slug).await?;
357
358 println!("{} Deleted repository {}", "✓".green(), repo);
359
360 Ok(())
361 }
362 }
363 }
364}
365
366fn parse_repo(repo: &str) -> Result<(String, String)> {
367 let parts: Vec<&str> = repo.split('/').collect();
368 if parts.len() != 2 {
369 anyhow::bail!(
370 "Invalid repository format. Expected 'workspace/repo-slug', got '{}'",
371 repo
372 );
373 }
374 Ok((parts[0].to_string(), parts[1].to_string()))
375}