1use 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::models::{BranchingModelBranchSettings, ModelBranch, UpdateBranchingModelRequest};
9
10#[derive(Subcommand)]
12pub enum BranchingModelCommands {
13 View {
15 repo: String,
17 },
18
19 Set {
21 repo: String,
23
24 #[arg(long, value_name = "BRANCH")]
26 development: Option<String>,
27
28 #[arg(long, value_name = "BRANCH")]
30 production: Option<String>,
31 },
32}
33
34#[derive(Tabled)]
35struct BranchTypeRow {
36 #[tabled(rename = "KIND")]
37 kind: String,
38 #[tabled(rename = "PREFIX")]
39 prefix: String,
40}
41
42impl BranchingModelCommands {
43 pub async fn run(self) -> Result<()> {
45 match self {
46 BranchingModelCommands::View { repo } => {
47 let (workspace, repo_slug) = parse_repo(&repo)?;
48 let client = BitbucketClient::from_stored().await?;
49 let model = client.get_branching_model(&workspace, &repo_slug).await?;
50
51 if output_json() {
52 return print_json(&model);
53 }
54
55 println!("{}", format!("Branching model for {}", repo).bold());
56 println!("{}", "─".repeat(50));
57
58 println!(
59 "{} {}",
60 "Development:".dimmed(),
61 describe_model_branch(model.development.as_ref())
62 );
63 println!(
64 "{} {}",
65 "Production:".dimmed(),
66 describe_model_branch(model.production.as_ref())
67 );
68
69 match model.branch_types.as_deref() {
70 Some(branch_types) if !branch_types.is_empty() => {
71 println!();
72 println!("{}", "Branch types:".bold());
73
74 let rows: Vec<BranchTypeRow> = branch_types
75 .iter()
76 .map(|t| BranchTypeRow {
77 kind: t.kind.clone().unwrap_or_else(|| "-".into()),
78 prefix: t.prefix.clone().unwrap_or_else(|| "-".into()),
79 })
80 .collect();
81
82 println!("{}", Table::new(rows));
83 }
84 _ => {
85 println!();
86 println!("No branch types configured");
87 }
88 }
89
90 Ok(())
91 }
92
93 BranchingModelCommands::Set {
94 repo,
95 development,
96 production,
97 } => {
98 let (workspace, repo_slug) = parse_repo(&repo)?;
99
100 let request = build_branching_model_update(development, production);
101 if request.is_empty() {
102 anyhow::bail!("Nothing to update. Pass --development and/or --production.");
103 }
104
105 let client = BitbucketClient::from_stored().await?;
106 let updated = client
107 .update_branching_model_settings(&workspace, &repo_slug, &request)
108 .await?;
109
110 if output_json() {
111 return print_json(&updated);
112 }
113
114 println!(
115 "{} Updated branching model for {}",
116 "✓".green(),
117 repo.cyan()
118 );
119 println!(
120 "{} {}",
121 "Development:".dimmed(),
122 describe_model_branch(updated.development.as_ref())
123 );
124 println!(
125 "{} {}",
126 "Production:".dimmed(),
127 describe_model_branch(updated.production.as_ref())
128 );
129
130 Ok(())
131 }
132 }
133 }
134}
135
136fn build_branching_model_update(
140 development: Option<String>,
141 production: Option<String>,
142) -> UpdateBranchingModelRequest {
143 UpdateBranchingModelRequest {
144 development: development.map(|name| BranchingModelBranchSettings {
145 name: Some(name),
146 use_mainbranch: Some(false),
147 enabled: None,
148 }),
149 production: production.map(|name| BranchingModelBranchSettings {
150 name: Some(name),
151 use_mainbranch: Some(false),
152 enabled: Some(true),
153 }),
154 }
155}
156
157fn describe_model_branch(branch: Option<&ModelBranch>) -> String {
161 let Some(branch) = branch else {
162 return "(not set)".to_string();
163 };
164
165 let name = branch
166 .branch
167 .as_ref()
168 .map(|b| b.name.as_str())
169 .or(branch.name.as_deref());
170
171 match (name, branch.use_mainbranch.unwrap_or(false)) {
172 (Some(name), true) => format!("{} (main branch)", name),
173 (Some(name), false) => name.to_string(),
174 (None, true) => "(main branch)".to_string(),
175 (None, false) => "-".to_string(),
176 }
177}
178
179#[cfg(test)]
180mod tests {
181 use super::*;
182 use crate::models::Branch;
183
184 #[test]
185 fn build_update_with_no_flags_is_empty() {
186 assert!(build_branching_model_update(None, None).is_empty());
187 }
188
189 #[test]
190 fn build_update_sets_development_branch_by_name() {
191 let request = build_branching_model_update(Some("develop".into()), None);
192
193 let development = request.development.expect("development should be set");
194 assert_eq!(development.name.as_deref(), Some("develop"));
195 assert_eq!(development.use_mainbranch, Some(false));
196 assert_eq!(development.enabled, None);
197 assert!(request.production.is_none());
198 }
199
200 #[test]
201 fn build_update_enables_production_branch() {
202 let request = build_branching_model_update(None, Some("release".into()));
203
204 let production = request.production.expect("production should be set");
205 assert_eq!(production.name.as_deref(), Some("release"));
206 assert_eq!(production.use_mainbranch, Some(false));
207 assert_eq!(production.enabled, Some(true));
208 assert!(request.development.is_none());
209 }
210
211 fn model_branch(
212 name: Option<&str>,
213 resolved: Option<&str>,
214 use_mainbranch: Option<bool>,
215 ) -> ModelBranch {
216 ModelBranch {
217 name: name.map(String::from),
218 branch: resolved.map(|n| Branch {
219 name: n.to_string(),
220 branch_type: None,
221 }),
222 use_mainbranch,
223 }
224 }
225
226 #[test]
227 fn describe_model_branch_prefers_resolved_branch_name() {
228 let branch = model_branch(Some("development"), Some("main"), Some(true));
229 assert_eq!(describe_model_branch(Some(&branch)), "main (main branch)");
230 }
231
232 #[test]
233 fn describe_model_branch_uses_configured_name_without_resolution() {
234 let branch = model_branch(Some("develop"), None, Some(false));
235 assert_eq!(describe_model_branch(Some(&branch)), "develop");
236 }
237
238 #[test]
239 fn describe_model_branch_handles_unnamed_mainbranch_tracking() {
240 let branch = model_branch(None, None, Some(true));
241 assert_eq!(describe_model_branch(Some(&branch)), "(main branch)");
242 }
243
244 #[test]
245 fn describe_model_branch_handles_missing_branch() {
246 assert_eq!(describe_model_branch(None), "(not set)");
247 let empty = model_branch(None, None, None);
248 assert_eq!(describe_model_branch(Some(&empty)), "-");
249 }
250}