commit_wizard/core/usecases/commit/
make.rs1use std::time::Instant;
2
3use scriba::{SelectOption, SelectRequest};
4
5use crate::{
6 core::{Context, CoreResult},
7 engine::{
8 ErrorCode, PromptTrait,
9 constants::emoji::{ERROR, PREVIEW, SUCCESS},
10 },
11};
12
13#[allow(clippy::too_many_arguments)]
14pub fn run(
15 ctx: &Context,
16 allow_empty: bool,
17 commit_type: Option<String>,
18 scope: Option<String>,
19 message: Option<String>,
20 breaking: bool,
21 breaking_message: Option<String>,
22 body: Option<String>,
23 footer: Vec<String>,
24) -> CoreResult<()> {
25 let ui = ctx.ui();
26 let start = Instant::now();
27 let policy = &ctx.policy().commit;
28
29 let non_interactive = !ctx.is_interactive() || (commit_type.is_some() && message.is_some());
30
31 if breaking
34 && policy.breaking_footer_required
35 && breaking_message
36 .as_ref()
37 .map(|s| s.trim().is_empty())
38 .unwrap_or(true)
39 {
40 return Err(ErrorCode::InvalidInput.error().with_context(
41 "reason",
42 "breaking change flag was provided but no breaking message was supplied",
43 ));
44 }
45
46 let commit_type = match commit_type {
48 Some(value) => {
49 if !policy.allows_type(&value) {
50 return Err(ErrorCode::InvalidInput
51 .error()
52 .with_context("field", "type")
53 .with_context("value", value));
54 }
55 value
56 }
57 None if non_interactive => {
58 return Err(ErrorCode::InvalidInput
59 .error()
60 .with_context("field", "type")
61 .with_context("reason", "type is required in non-interactive mode"));
62 }
63 None => {
64 let request = SelectRequest::new(
65 "What type of change are you committing?".to_string(),
66 policy
67 .types
68 .iter()
69 .map(|t| {
70 let label = if policy.use_emojis && t.emoji.is_some() {
71 format!("{} {}", t.emoji.as_deref().unwrap(), t.key)
72 } else {
73 t.key.clone()
74 };
75 SelectOption::new(t.key.clone(), label)
76 .description(t.description.as_deref().unwrap_or_default().to_string())
77 })
78 .collect(),
79 )
80 .with_page_size(10);
81
82 ui.select(&request).map_err(|_| {
83 ErrorCode::InvalidInput
84 .error()
85 .with_context("field", "type")
86 })?
87 }
88 };
89
90 let scope: Option<String> = match scope {
92 Some(value) => {
93 if policy.restrict_scopes_to_defined && !policy.allows_scope(&value) {
94 return Err(ErrorCode::InvalidInput
95 .error()
96 .with_context("field", "scope")
97 .with_context("value", value));
98 }
99 Some(value)
100 }
101 None if policy.header_format.require_scope && non_interactive => {
102 return Err(ErrorCode::InvalidInput
103 .error()
104 .with_context("field", "scope")
105 .with_context(
106 "reason",
107 "scope is required by policy in non-interactive mode",
108 ));
109 }
110 None if policy.header_format.require_scope => {
111 let value = ui.text("Scope", None, Some("Required by current commit policy"))?;
112 let trimmed: String = value.trim().to_string();
113
114 if trimmed.is_empty() {
115 return Err(ErrorCode::InvalidInput
116 .error()
117 .with_context("field", "scope")
118 .with_context("reason", "scope is required by policy"));
119 }
120
121 if policy.restrict_scopes_to_defined && !policy.allows_scope(&trimmed) {
122 return Err(ErrorCode::InvalidInput
123 .error()
124 .with_context("field", "scope")
125 .with_context("value", trimmed));
126 }
127
128 Some(trimmed)
129 }
130 None if non_interactive => None,
131 None => {
132 if ui.confirm("Add a scope?", false)? {
133 let value = ui.text("Scope", None, Some("Leave empty to omit"))?;
134 let trimmed: String = value.trim().to_string();
135
136 if trimmed.is_empty() {
137 None
138 } else {
139 if policy.restrict_scopes_to_defined && !policy.allows_scope(&trimmed) {
140 return Err(ErrorCode::InvalidInput
141 .error()
142 .with_context("field", "scope")
143 .with_context("value", trimmed));
144 }
145 Some(trimmed)
146 }
147 } else {
148 None
149 }
150 }
151 };
152
153 let summary = match message {
155 Some(value) if value.trim().is_empty() => {
156 return Err(ErrorCode::InvalidInput
157 .error()
158 .with_context("field", "message")
159 .with_context("reason", "commit summary cannot be empty"));
160 }
161 Some(value) => value.trim().to_string(),
162 None if non_interactive => {
163 return Err(ErrorCode::InvalidInput
164 .error()
165 .with_context("field", "message")
166 .with_context("reason", "message is required in non-interactive mode"));
167 }
168 None => loop {
169 let value = ui.text(
170 "Write a short summary",
171 None,
172 Some("Imperative tone, e.g. 'add parser'"),
173 )?;
174 let trimmed = value.trim().to_string();
175 if !trimmed.is_empty() {
176 break trimmed;
177 }
178 ui.logger().warn("Summary cannot be empty");
179 },
180 };
181
182 let subject_max_length = usize::try_from(policy.subject_max_length).unwrap();
183
184 if summary.len() > subject_max_length {
185 return Err(ErrorCode::InvalidInput
186 .error()
187 .with_context("field", "message")
188 .with_context("reason", "commit summary exceeds configured max length")
189 .with_context("length", summary.len().to_string())
190 .with_context("max", policy.subject_max_length.to_string()));
191 }
192
193 let (breaking, breaking_message) = if breaking {
195 (true, breaking_message.map(|s| s.trim().to_string()))
196 } else if non_interactive {
197 (false, None)
198 } else if ui.confirm("Does this commit include breaking changes?", false)? {
199 let msg = ui.text(
200 "Describe the breaking change",
201 None,
202 Some(if policy.breaking_footer_required {
203 "Required by current commit policy"
204 } else {
205 "Optional; leave empty to omit the BREAKING CHANGE footer"
206 }),
207 )?;
208 let trimmed = msg.trim().to_string();
209 if trimmed.is_empty() && policy.breaking_footer_required {
210 return Err(ErrorCode::InvalidInput
211 .error()
212 .with_context("field", "breaking_message")
213 .with_context("reason", "breaking change description cannot be empty"));
214 }
215 (true, (!trimmed.is_empty()).then_some(trimmed))
216 } else {
217 (false, None)
218 };
219
220 let body = match body {
221 Some(value) if value.trim().is_empty() => None,
222 Some(value) => Some(value.trim().to_string()),
223 None if non_interactive => None,
224 None => {
225 if ui.confirm("Add a longer description?", false)? {
226 let value = ui.text("Body", None, Some("Optional detailed description"))?;
227 let trimmed = value.trim().to_string();
228 if trimmed.is_empty() {
229 None
230 } else {
231 Some(trimmed)
232 }
233 } else {
234 None
235 }
236 }
237 };
238
239 let footers = if !footer.is_empty() || non_interactive {
240 footer
241 .into_iter()
242 .map(|v| v.trim().to_string())
243 .filter(|v| !v.is_empty())
244 .collect::<Vec<_>>()
245 } else {
246 let mut lines = Vec::new();
247 if ui.confirm("Add footer lines?", false)? {
248 loop {
249 let value = ui.text(
250 "Footer",
251 None,
252 Some("Examples: Closes #123, Co-authored-by: Name <email>"),
253 )?;
254 let trimmed = value.trim().to_string();
255 if trimmed.is_empty() {
256 break;
257 }
258 lines.push(trimmed);
259 }
260 }
261 lines
262 };
263
264 let type_emoji = policy
265 .find_type(&commit_type)
266 .and_then(|t| t.emoji.as_deref());
267
268 let header = build_header(
269 &commit_type,
270 scope.as_deref(),
271 &summary,
272 breaking,
273 type_emoji,
274 policy.use_emojis,
275 );
276 let commit_message = build_commit_message(
277 &header,
278 body.as_deref(),
279 if breaking {
280 breaking_message.as_deref()
281 } else {
282 None
283 },
284 &footers,
285 &policy.breaking_footer_key,
286 );
287
288 ui.logger().heading(&format!("{} Commit Preview", PREVIEW));
289 eprintln!("-------------------------");
290 for line in commit_message.lines() {
291 eprintln!("{}", line);
292 }
293 eprintln!("-------------------------");
294 eprintln!();
295
296 let duration_ms = start.elapsed().as_millis() as u64;
297
298 if ctx.dry_run() {
299 let meta = ui
300 .new_output_meta()
301 .with_duration_ms(duration_ms)
302 .with_timestamp(chrono::Utc::now().to_string())
303 .with_command("commit".to_string())
304 .with_dry_run(true);
305
306 let content = ui
307 .new_output_content()
308 .title(format!("{} Commit Preview", PREVIEW))
309 .subtitle("Dry run: no commit was created")
310 .data("type", commit_type)
311 .data("scope", scope.unwrap_or_default())
312 .data("breaking", breaking.to_string())
313 .data("message", commit_message);
314
315 return ui.print_with_meta(&content, Some(&meta), true);
316 }
317
318 if !non_interactive && !ui.confirm("Create this commit?", true)? {
319 ui.logger().warn(&format!("{} Commit cancelled", ERROR));
320 return Ok(());
321 }
322
323 ctx.git().commit(&commit_message, allow_empty)?;
324
325 let meta = ui
326 .new_output_meta()
327 .with_duration_ms(duration_ms)
328 .with_timestamp(chrono::Utc::now().to_string())
329 .with_command("commit".to_string())
330 .with_dry_run(false);
331
332 let content = ui
333 .new_output_content()
334 .title(format!("{} Commit Created", SUCCESS))
335 .subtitle("Git commit completed successfully")
336 .data("type", commit_type)
337 .data("scope", scope.unwrap_or_default())
338 .data("breaking", breaking.to_string())
339 .data("header", header);
340
341 ui.print_with_meta(&content, Some(&meta), true)
342}
343
344fn build_header(
345 commit_type: &str,
346 scope: Option<&str>,
347 summary: &str,
348 breaking: bool,
349 emoji: Option<&str>,
350 use_emojis: bool,
351) -> String {
352 let type_prefix = if let (true, Some(e)) = (use_emojis, emoji) {
353 format!("{e} {commit_type}")
354 } else {
355 commit_type.to_string()
356 };
357
358 match (scope, breaking) {
359 (Some(scope), true) => format!("{type_prefix}({scope})!: {summary}"),
360 (Some(scope), false) => format!("{type_prefix}({scope}): {summary}"),
361 (None, true) => format!("{type_prefix}!: {summary}"),
362 (None, false) => format!("{type_prefix}: {summary}"),
363 }
364}
365
366fn build_commit_message(
367 header: &str,
368 body: Option<&str>,
369 breaking_message: Option<&str>,
370 footers: &[String],
371 breaking_footer_key: &str,
372) -> String {
373 let mut out = String::from(header);
374
375 if let Some(body) = body {
376 let trimmed = body.trim();
377 if !trimmed.is_empty() {
378 out.push_str("\n\n");
379 out.push_str(trimmed);
380 }
381 }
382
383 if let Some(message) = breaking_message {
384 let trimmed = message.trim();
385 if !trimmed.is_empty() {
386 out.push_str("\n\n");
387 out.push_str(breaking_footer_key);
388 out.push_str(": ");
389 out.push_str(trimmed);
390 }
391 }
392
393 for footer in footers {
394 let trimmed = footer.trim();
395 if !trimmed.is_empty() {
396 out.push('\n');
397 out.push_str(trimmed);
398 }
399 }
400
401 out
402}