1use anyhow::Result;
2use clap::Subcommand;
3use colored::Colorize;
4use tabled::{Table, Tabled};
5
6use super::{confirm_or_abort, output_json, parse_repo, print_json};
7use crate::api::BitbucketClient;
8use crate::models::{CreateWebhookRequest, Webhook};
9
10#[derive(Subcommand)]
11pub enum WebhookCommands {
12 List {
14 repo: String,
16
17 #[arg(short, long, default_value = "25")]
19 limit: u32,
20 },
21
22 Create {
24 repo: String,
26
27 #[arg(long)]
29 url: String,
30
31 #[arg(long = "event", value_name = "EVENT", required = true)]
33 events: Vec<String>,
34
35 #[arg(short, long)]
37 description: Option<String>,
38
39 #[arg(long)]
41 inactive: bool,
42 },
43
44 View {
46 repo: String,
48
49 uid: String,
51 },
52
53 Update {
55 repo: String,
57
58 uid: String,
60
61 #[arg(long)]
63 url: Option<String>,
64
65 #[arg(long = "event", value_name = "EVENT")]
67 events: Vec<String>,
68
69 #[arg(short, long)]
71 description: Option<String>,
72
73 #[arg(long, value_name = "true|false")]
75 active: Option<bool>,
76 },
77
78 Delete {
80 repo: String,
82
83 uid: String,
85
86 #[arg(short, long)]
88 yes: bool,
89 },
90}
91
92#[derive(Tabled)]
93struct WebhookRow {
94 #[tabled(rename = "UUID")]
95 uid: String,
96 #[tabled(rename = "URL")]
97 url: String,
98 #[tabled(rename = "ACTIVE")]
99 active: String,
100 #[tabled(rename = "EVENTS")]
101 events: String,
102}
103
104impl WebhookCommands {
105 pub async fn run(self) -> Result<()> {
106 match self {
107 WebhookCommands::List { repo, limit } => {
108 let (workspace, repo_slug) = parse_repo(&repo)?;
109 let client = BitbucketClient::from_stored().await?;
110 let hooks = client
111 .list_webhooks(&workspace, &repo_slug, Some(limit.clamp(1, 100)))
112 .await?;
113
114 if output_json() {
115 return print_json(&hooks.values);
116 }
117
118 if hooks.values.is_empty() {
119 println!("No webhooks found in {}", repo);
120 return Ok(());
121 }
122
123 let rows: Vec<WebhookRow> = hooks
124 .values
125 .iter()
126 .map(|h| WebhookRow {
127 uid: h.uuid.clone().unwrap_or_default(),
128 url: h.url.clone(),
129 active: if h.active.unwrap_or(false) {
130 "Yes"
131 } else {
132 "No"
133 }
134 .to_string(),
135 events: h.events.join(", ").chars().take(60).collect(),
136 })
137 .collect();
138
139 println!("{}", Table::new(rows));
140
141 if hooks.next.is_some() {
142 println!(
143 "\n{} More webhooks available. Use --limit to see more.",
144 "ℹ".blue()
145 );
146 }
147
148 Ok(())
149 }
150
151 WebhookCommands::Create {
152 repo,
153 url,
154 events,
155 description,
156 inactive,
157 } => {
158 let (workspace, repo_slug) = parse_repo(&repo)?;
159 let client = BitbucketClient::from_stored().await?;
160
161 let request = CreateWebhookRequest {
162 description,
163 url,
164 active: !inactive,
165 events,
166 };
167
168 let hook = client
169 .create_webhook(&workspace, &repo_slug, &request)
170 .await?;
171
172 if output_json() {
173 return print_json(&hook);
174 }
175
176 println!(
177 "{} Created webhook {} for {}",
178 "✓".green(),
179 hook.uuid.as_deref().unwrap_or("(no uid)").cyan(),
180 hook.url
181 );
182
183 Ok(())
184 }
185
186 WebhookCommands::View { repo, uid } => {
187 let (workspace, repo_slug) = parse_repo(&repo)?;
188 let client = BitbucketClient::from_stored().await?;
189 let hook = client.get_webhook(&workspace, &repo_slug, &uid).await?;
190
191 if output_json() {
192 return print_json(&hook);
193 }
194
195 println!("{}", hook.uuid.as_deref().unwrap_or(&uid).bold());
196 println!("{}", "─".repeat(50));
197
198 if let Some(desc) = &hook.description {
199 if !desc.is_empty() {
200 println!("{}", desc);
201 println!();
202 }
203 }
204
205 println!("{} {}", "URL:".dimmed(), hook.url.cyan());
206 println!(
207 "{} {}",
208 "Active:".dimmed(),
209 if hook.active.unwrap_or(false) {
210 "Yes"
211 } else {
212 "No"
213 }
214 );
215
216 if hook.events.is_empty() {
217 println!("{} (none)", "Events:".dimmed());
218 } else {
219 println!("{}", "Events:".dimmed());
220 for event in &hook.events {
221 println!(" {}", event);
222 }
223 }
224
225 Ok(())
226 }
227
228 WebhookCommands::Update {
229 repo,
230 uid,
231 url,
232 events,
233 description,
234 active,
235 } => {
236 let (workspace, repo_slug) = parse_repo(&repo)?;
237
238 if url.is_none() && events.is_empty() && description.is_none() && active.is_none() {
239 anyhow::bail!(
240 "Nothing to update. Pass at least one option, e.g. --url or --active."
241 );
242 }
243
244 let client = BitbucketClient::from_stored().await?;
245
246 let current = client.get_webhook(&workspace, &repo_slug, &uid).await?;
249 let request = build_webhook_update(current, url, events, description, active);
250
251 let updated = client
252 .update_webhook(&workspace, &repo_slug, &uid, &request)
253 .await?;
254
255 if output_json() {
256 return print_json(&updated);
257 }
258
259 println!(
260 "{} Updated webhook {}",
261 "✓".green(),
262 updated.uuid.as_deref().unwrap_or(&uid).cyan()
263 );
264
265 Ok(())
266 }
267
268 WebhookCommands::Delete { repo, uid, yes } => {
269 let (workspace, repo_slug) = parse_repo(&repo)?;
270
271 if !yes
272 && !confirm_or_abort(format!("Delete webhook {} from {}?", uid.red(), repo))?
273 {
274 return Ok(());
275 }
276
277 let client = BitbucketClient::from_stored().await?;
278 client.delete_webhook(&workspace, &repo_slug, &uid).await?;
279
280 if output_json() {
281 return print_json(&serde_json::json!({ "ok": true }));
282 }
283
284 println!("{} Deleted webhook {}", "✓".green(), uid);
285
286 Ok(())
287 }
288 }
289 }
290}
291
292fn build_webhook_update(
296 current: Webhook,
297 url: Option<String>,
298 events: Vec<String>,
299 description: Option<String>,
300 active: Option<bool>,
301) -> CreateWebhookRequest {
302 CreateWebhookRequest {
303 description: description.or(current.description),
304 url: url.unwrap_or(current.url),
305 active: active.or(current.active).unwrap_or(true),
306 events: if events.is_empty() {
307 current.events
308 } else {
309 events
310 },
311 }
312}
313
314#[cfg(test)]
315mod tests {
316 use super::build_webhook_update;
317 use crate::models::Webhook;
318
319 fn current() -> Webhook {
320 Webhook {
321 uuid: Some("{uid}".to_string()),
322 url: "https://old.example.com/hook".to_string(),
323 description: Some("old description".to_string()),
324 active: Some(true),
325 events: vec!["repo:push".to_string()],
326 }
327 }
328
329 #[test]
330 fn build_webhook_update_keeps_current_values_when_flags_unset() {
331 let request = build_webhook_update(current(), None, Vec::new(), None, None);
332 assert_eq!(request.url, "https://old.example.com/hook");
333 assert_eq!(request.description.as_deref(), Some("old description"));
334 assert!(request.active);
335 assert_eq!(request.events, vec!["repo:push".to_string()]);
336 }
337
338 #[test]
339 fn build_webhook_update_applies_changed_fields() {
340 let request = build_webhook_update(
341 current(),
342 Some("https://new.example.com/hook".to_string()),
343 vec!["pullrequest:created".to_string()],
344 Some("new description".to_string()),
345 Some(false),
346 );
347 assert_eq!(request.url, "https://new.example.com/hook");
348 assert_eq!(request.description.as_deref(), Some("new description"));
349 assert!(!request.active);
350 assert_eq!(request.events, vec!["pullrequest:created".to_string()]);
351 }
352
353 #[test]
354 fn build_webhook_update_defaults_unknown_active_state_to_enabled() {
355 let mut hook = current();
356 hook.active = None;
357 let request = build_webhook_update(hook, None, Vec::new(), None, None);
358 assert!(request.active);
359 }
360}