bitbucket_cli/cli/
commit.rs1use anyhow::Result;
2use clap::Subcommand;
3use colored::Colorize;
4use tabled::{Table, Tabled};
5
6use super::{output_json, parse_repo, print_json};
7use crate::api::BitbucketClient;
8use crate::cli::pagination::effective_limit;
9use crate::models::CommitAuthor;
10
11const MSG_WIDTH: usize = 50;
13
14#[derive(Subcommand)]
15pub enum CommitCommands {
16 List {
18 repo: String,
20
21 #[arg(short = 'r', long = "ref", value_name = "REF")]
23 git_ref: Option<String>,
24
25 #[arg(short, long, default_value = "25")]
27 limit: u32,
28
29 #[arg(long)]
31 page: Option<u32>,
32 },
33
34 View {
36 repo: String,
38
39 hash: String,
41 },
42
43 Diff {
45 repo: String,
47
48 spec: String,
50 },
51}
52
53#[derive(Tabled)]
54struct CommitRow {
55 #[tabled(rename = "HASH")]
56 hash: String,
57 #[tabled(rename = "AUTHOR")]
58 author: String,
59 #[tabled(rename = "DATE")]
60 date: String,
61 #[tabled(rename = "MESSAGE")]
62 message: String,
63}
64
65impl CommitCommands {
66 pub async fn run(self) -> Result<()> {
67 match self {
68 CommitCommands::List {
69 repo,
70 git_ref,
71 limit,
72 page,
73 } => {
74 let (workspace, repo_slug) = parse_repo(&repo)?;
75 let client = BitbucketClient::from_stored().await?;
76 let commits = client
77 .list_commits(
78 &workspace,
79 &repo_slug,
80 git_ref.as_deref(),
81 page,
82 Some(effective_limit(limit)),
83 )
84 .await?;
85
86 if output_json() {
87 return print_json(&commits.values);
88 }
89
90 if commits.values.is_empty() {
91 println!("No commits found in {}", repo);
92 return Ok(());
93 }
94
95 let rows: Vec<CommitRow> = commits
96 .values
97 .iter()
98 .map(|c| CommitRow {
99 hash: short_hash(&c.hash),
100 author: author_label(c.author.as_ref()),
101 date: c
102 .date
103 .map(|d| d.format("%Y-%m-%d").to_string())
104 .unwrap_or_default(),
105 message: first_line_truncated(
106 c.message.as_deref().unwrap_or(""),
107 MSG_WIDTH,
108 ),
109 })
110 .collect();
111
112 println!("{}", Table::new(rows));
113
114 if commits.next.is_some() {
115 println!(
116 "\n{} More commits available. Use --limit or --page to see more.",
117 "ℹ".blue()
118 );
119 }
120
121 Ok(())
122 }
123
124 CommitCommands::View { repo, hash } => {
125 let (workspace, repo_slug) = parse_repo(&repo)?;
126 let client = BitbucketClient::from_stored().await?;
127 let commit = client.get_commit(&workspace, &repo_slug, &hash).await?;
128
129 if output_json() {
130 return print_json(&commit);
131 }
132
133 println!("{}", commit.hash.bold());
134 println!("{}", "─".repeat(50));
135 println!(
136 "{} {}",
137 "Author:".dimmed(),
138 author_label(commit.author.as_ref())
139 );
140
141 if let Some(date) = commit.date {
142 println!("{} {}", "Date:".dimmed(), date.format("%Y-%m-%d %H:%M:%S"));
143 }
144
145 if let Some(message) = &commit.message {
146 println!();
147 println!("{}", message.trim_end());
148 }
149
150 Ok(())
151 }
152
153 CommitCommands::Diff { repo, spec } => {
154 let (workspace, repo_slug) = parse_repo(&repo)?;
155 let client = BitbucketClient::from_stored().await?;
156 let diff = client.get_diff(&workspace, &repo_slug, &spec).await?;
157
158 print!("{}", diff);
159
160 Ok(())
161 }
162 }
163 }
164}
165
166pub(crate) fn short_hash(hash: &str) -> String {
168 hash.chars().take(7).collect()
169}
170
171pub(crate) fn first_line_truncated(message: &str, max: usize) -> String {
173 message
174 .lines()
175 .next()
176 .unwrap_or("")
177 .chars()
178 .take(max)
179 .collect()
180}
181
182pub(crate) fn author_label(author: Option<&CommitAuthor>) -> String {
185 author
186 .and_then(|a| {
187 a.user
188 .as_ref()
189 .map(|u| u.display_name.clone())
190 .or_else(|| a.raw.clone())
191 })
192 .unwrap_or_else(|| "-".to_string())
193}
194
195#[cfg(test)]
196mod tests {
197 use super::*;
198
199 #[test]
200 fn short_hash_abbreviates_to_seven_chars() {
201 assert_eq!(short_hash("deadbeefcafe1234"), "deadbee");
202 }
203
204 #[test]
205 fn short_hash_keeps_already_short_input() {
206 assert_eq!(short_hash("abc12"), "abc12");
207 }
208
209 #[test]
210 fn first_line_truncated_takes_first_line() {
211 assert_eq!(
212 first_line_truncated("feat: add login\n\nLong body here", 60),
213 "feat: add login"
214 );
215 }
216
217 #[test]
218 fn first_line_truncated_caps_length() {
219 assert_eq!(first_line_truncated("abcdefghij", 4), "abcd");
220 }
221
222 #[test]
223 fn first_line_truncated_handles_empty_message() {
224 assert_eq!(first_line_truncated("", 60), "");
225 }
226
227 #[test]
228 fn author_label_prefers_user_display_name_over_raw() {
229 let author = CommitAuthor {
230 raw: Some("Jo <jo@example.com>".to_string()),
231 user: Some(crate::models::User {
232 uuid: "{user-uuid}".to_string(),
233 username: None,
234 display_name: "Jo Bloggs".to_string(),
235 account_id: None,
236 user_type: "user".to_string(),
237 links: None,
238 }),
239 };
240 assert_eq!(author_label(Some(&author)), "Jo Bloggs");
241 }
242
243 #[test]
244 fn author_label_falls_back_to_raw_then_dash() {
245 let raw_only = CommitAuthor {
246 raw: Some("Jo <jo@example.com>".to_string()),
247 user: None,
248 };
249 assert_eq!(author_label(Some(&raw_only)), "Jo <jo@example.com>");
250
251 let empty = CommitAuthor {
252 raw: None,
253 user: None,
254 };
255 assert_eq!(author_label(Some(&empty)), "-");
256 assert_eq!(author_label(None), "-");
257 }
258}