Skip to main content

bitbucket_cli/cli/
branch.rs

1use anyhow::{Context, Result};
2use clap::Subcommand;
3use colored::Colorize;
4use tabled::{Table, Tabled};
5
6use super::commit::{author_label, first_line_truncated, short_hash};
7use super::{confirm_or_abort, output_json, parse_repo, print_json};
8use crate::api::BitbucketClient;
9use crate::cli::pagination::effective_limit;
10use crate::models::BranchDetail;
11
12/// Width of the truncated commit-message column in list tables.
13const MSG_WIDTH: usize = 50;
14
15#[derive(Subcommand)]
16pub enum BranchCommands {
17    /// List branches in a repository
18    List {
19        /// Repository in format workspace/repo-slug
20        repo: String,
21
22        /// Filter expression, e.g. 'name ~ "feat"'
23        #[arg(short = 'q', long)]
24        query: Option<String>,
25
26        /// Sort field, prefix with '-' for descending, e.g. -target.date
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        /// Page number to fetch
35        #[arg(long)]
36        page: Option<u32>,
37    },
38
39    /// Create a branch
40    Create {
41        /// Repository in format workspace/repo-slug
42        repo: String,
43
44        /// Name of the branch to create
45        name: String,
46
47        /// Commit hash or existing branch name to branch from (a 7-40 char hex value is treated as a commit hash)
48        #[arg(long, value_name = "HASH_OR_BRANCH")]
49        from: String,
50    },
51
52    /// View a single branch
53    View {
54        /// Repository in format workspace/repo-slug
55        repo: String,
56
57        /// Branch name
58        name: String,
59    },
60
61    /// Delete a branch
62    Delete {
63        /// Repository in format workspace/repo-slug
64        repo: String,
65
66        /// Branch name
67        name: String,
68
69        /// Skip confirmation prompt
70        #[arg(short, long)]
71        yes: bool,
72    },
73}
74
75#[derive(Tabled)]
76struct BranchRow {
77    #[tabled(rename = "NAME")]
78    name: String,
79    #[tabled(rename = "COMMIT")]
80    commit: String,
81    #[tabled(rename = "AUTHOR")]
82    author: String,
83    #[tabled(rename = "DATE")]
84    date: String,
85    #[tabled(rename = "MESSAGE")]
86    message: String,
87}
88
89impl From<&BranchDetail> for BranchRow {
90    fn from(branch: &BranchDetail) -> Self {
91        let target = branch.target.as_ref();
92        BranchRow {
93            name: branch.name.clone(),
94            commit: target.map(|t| short_hash(&t.hash)).unwrap_or_default(),
95            author: target
96                .map(|t| author_label(t.author.as_ref()))
97                .unwrap_or_else(|| "-".to_string()),
98            date: target
99                .and_then(|t| t.date)
100                .map(|d| d.format("%Y-%m-%d").to_string())
101                .unwrap_or_default(),
102            message: target
103                .and_then(|t| t.message.as_deref())
104                .map(|m| first_line_truncated(m, MSG_WIDTH))
105                .unwrap_or_default(),
106        }
107    }
108}
109
110impl BranchCommands {
111    pub async fn run(self) -> Result<()> {
112        match self {
113            BranchCommands::List {
114                repo,
115                query,
116                sort,
117                limit,
118                page,
119            } => {
120                let (workspace, repo_slug) = parse_repo(&repo)?;
121                let client = BitbucketClient::from_stored().await?;
122                let branches = client
123                    .list_branches_filtered(
124                        &workspace,
125                        &repo_slug,
126                        query.as_deref(),
127                        sort.as_deref(),
128                        page,
129                        Some(effective_limit(limit)),
130                    )
131                    .await?;
132
133                if output_json() {
134                    return print_json(&branches.values);
135                }
136
137                if branches.values.is_empty() {
138                    println!("No branches found in {}", repo);
139                    return Ok(());
140                }
141
142                let rows: Vec<BranchRow> = branches.values.iter().map(BranchRow::from).collect();
143                println!("{}", Table::new(rows));
144
145                if branches.next.is_some() {
146                    println!(
147                        "\n{} More branches available. Use --limit or --page to see more.",
148                        "ℹ".blue()
149                    );
150                }
151
152                Ok(())
153            }
154
155            BranchCommands::Create { repo, name, from } => {
156                let (workspace, repo_slug) = parse_repo(&repo)?;
157                let client = BitbucketClient::from_stored().await?;
158
159                // --from accepts either a commit hash or a branch name; the
160                // API only takes a hash, so resolve branch names first.
161                let target_hash = if looks_like_hash(&from) {
162                    from
163                } else {
164                    let source = client
165                        .get_branch(&workspace, &repo_slug, &from)
166                        .await
167                        .with_context(|| format!("Failed to resolve source branch '{}'", from))?;
168                    source
169                        .target
170                        .map(|t| t.hash)
171                        .with_context(|| format!("Branch '{}' has no target commit", from))?
172                };
173
174                let branch = client
175                    .create_branch(&workspace, &repo_slug, &name, &target_hash)
176                    .await?;
177
178                if output_json() {
179                    return print_json(&branch);
180                }
181
182                println!(
183                    "{} Created branch {} at {}",
184                    "✓".green(),
185                    branch.name.cyan(),
186                    short_hash(&target_hash)
187                );
188
189                Ok(())
190            }
191
192            BranchCommands::View { repo, name } => {
193                let (workspace, repo_slug) = parse_repo(&repo)?;
194                let client = BitbucketClient::from_stored().await?;
195                let branch = client.get_branch(&workspace, &repo_slug, &name).await?;
196
197                if output_json() {
198                    return print_json(&branch);
199                }
200
201                println!("{}", branch.name.bold());
202                println!("{}", "─".repeat(50));
203
204                if let Some(target) = &branch.target {
205                    println!("{} {}", "Commit:".dimmed(), target.hash);
206                    println!(
207                        "{} {}",
208                        "Author:".dimmed(),
209                        author_label(target.author.as_ref())
210                    );
211
212                    if let Some(date) = target.date {
213                        println!("{} {}", "Date:".dimmed(), date.format("%Y-%m-%d %H:%M:%S"));
214                    }
215
216                    if let Some(message) = &target.message {
217                        println!();
218                        println!("{}", message.trim_end());
219                    }
220                }
221
222                Ok(())
223            }
224
225            BranchCommands::Delete { repo, name, yes } => {
226                let (workspace, repo_slug) = parse_repo(&repo)?;
227
228                if !yes
229                    && !confirm_or_abort(format!("Delete branch {} from {}?", name.red(), repo))?
230                {
231                    return Ok(());
232                }
233
234                let client = BitbucketClient::from_stored().await?;
235                client.delete_branch(&workspace, &repo_slug, &name).await?;
236
237                if output_json() {
238                    return print_json(&serde_json::json!({ "ok": true }));
239                }
240
241                println!("{} Deleted branch {}", "✓".green(), name);
242
243                Ok(())
244            }
245        }
246    }
247}
248
249/// Whether `s` is plausibly an abbreviated or full commit hash:
250/// 7 to 40 hexadecimal characters.
251fn looks_like_hash(s: &str) -> bool {
252    (7..=40).contains(&s.len()) && s.chars().all(|c| c.is_ascii_hexdigit())
253}
254
255#[cfg(test)]
256mod tests {
257    use super::looks_like_hash;
258
259    #[test]
260    fn looks_like_hash_accepts_abbreviated_and_full_hashes() {
261        assert!(looks_like_hash("deadbee"));
262        assert!(looks_like_hash("DEADBEE1"));
263        assert!(looks_like_hash(&"a".repeat(40)));
264    }
265
266    #[test]
267    fn looks_like_hash_rejects_wrong_lengths() {
268        assert!(!looks_like_hash("abc123")); // 6 chars: too short
269        assert!(!looks_like_hash(&"a".repeat(41))); // too long
270        assert!(!looks_like_hash(""));
271    }
272
273    #[test]
274    fn looks_like_hash_rejects_non_hex_names() {
275        assert!(!looks_like_hash("develop"));
276        assert!(!looks_like_hash("feature/x"));
277        assert!(!looks_like_hash("release-1.0"));
278    }
279}