cucco 4.1.0

An interactive CLI for creating conventional commits, with git hooks support.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
//! Interactive prompts and scope autocompletion.

use anyhow::{Context, Result};
use conventional_commit_parser::parse_summary;
use gix::bstr::ByteSlice;
use indexmap::IndexMap;
use inquire::autocompletion::{Autocomplete, Replacement};
use inquire::error::InquireError;
use inquire::ui::{Attributes, Color, RenderConfig, StyleSheet};
use inquire::validator::Validation;
use inquire::{Confirm, CustomUserError, Select, Text};
use thiserror::Error;

use crate::config::{CommitType, Config};
use crate::multiline::{MultilineText, SuggestedText};
use crate::scope::ScopeMatches;

#[derive(Debug, Error)]
enum PromptError {
    #[error("{0} cancelled")]
    Cancelled(&'static str),
    #[error(transparent)]
    Inquire(InquireError),
}

#[derive(Debug)]
struct KeyboardEnhancement;

impl KeyboardEnhancement {
    fn enable() -> Result<Self> {
        #[cfg(unix)]
        {
            use crossterm::event::{KeyboardEnhancementFlags, PushKeyboardEnhancementFlags};

            crossterm::execute!(
                std::io::stderr(),
                PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
            )?;
        }

        Ok(Self)
    }
}

impl Drop for KeyboardEnhancement {
    fn drop(&mut self) {
        #[cfg(unix)]
        {
            use crossterm::event::PopKeyboardEnhancementFlags;

            _ = crossterm::execute!(std::io::stderr(), PopKeyboardEnhancementFlags);
        }
    }
}

impl PromptError {
    fn from_inquire(e: InquireError, prompt_name: &'static str) -> Self {
        match e {
            InquireError::OperationCanceled | InquireError::OperationInterrupted => {
                PromptError::Cancelled(prompt_name)
            }
            other => PromptError::Inquire(other),
        }
    }
}

fn get_skip_hint() -> &'static str {
    "<esc> or <return> to skip"
}

fn multiline_help() -> String {
    format!(
        "Use <alt+enter> for newlines, {skip_hint}",
        skip_hint = get_skip_hint()
    )
}

/// Print a prompt line as if the user had already answered it, so a
/// pre-assigned scope from ast-grep/pattern matching is still visible
/// instead of silently skipping the prompt.
fn print_answered_scope_prompt(scope: &str) {
    println!("\x1b[1mWhat's the scope of this change?\x1b[0m \x1b[90m{scope}\x1b[0m");
}

fn get_render_config() -> RenderConfig<'static> {
    RenderConfig {
        prompt: StyleSheet::new().with_attr(Attributes::BOLD),
        default_value: StyleSheet::new().with_fg(Color::Grey),
        ..RenderConfig::default()
    }
}

/// Transform commit type choice
fn transform_commit_type_choice(choice: &str) -> String {
    choice.split(':').next().unwrap().into()
}

/// Format the commit type choices
fn format_commit_type_choice(
    use_emoji: bool,
    commit_type: &CommitType,
    commit_types: &IndexMap<String, CommitType>,
) -> String {
    let name = &commit_type.name;
    let description = &commit_type.description;
    let use_emoji = use_emoji && commit_type.emoji.is_some();

    let emoji = if use_emoji {
        format!("{} ", commit_type.emoji.as_ref().unwrap())
    } else {
        String::new()
    };

    let width = commit_types
        .iter()
        .map(|(key, _)| key.chars().count())
        .max()
        .unwrap()
        - commit_type.name.chars().count()
        + if use_emoji { 5 } else { 3 };

    format!("{name}:{emoji:>width$}{description}")
}

fn validate_summary(input: &str) -> Result<Validation, CustomUserError> {
    if input.trim().is_empty() {
        Ok(Validation::Invalid("A summary is required".into()))
    } else {
        Ok(Validation::Valid)
    }
}

fn validate_issue_reference(input: &str) -> Result<Validation, CustomUserError> {
    if input.trim().is_empty() {
        Ok(Validation::Invalid("An issue reference is required".into()))
    } else {
        Ok(Validation::Valid)
    }
}

fn prompt_type(config: &Config) -> Result<String> {
    let type_values = config
        .commit_types
        .iter()
        .map(|(_, choice)| format_commit_type_choice(config.emoji, choice, &config.commit_types))
        .collect();

    let selected_type = Select::new("What type of change are you committing?", type_values)
        .with_render_config(get_render_config())
        .with_formatter(&|v| transform_commit_type_choice(v.value))
        .prompt()
        .map_err(|e| PromptError::from_inquire(e, "Commit type selection"))?;

    Ok(transform_commit_type_choice(&selected_type))
}

/// Autocompletes scopes from the configuration and the commit history.
#[derive(Debug, Clone)]
pub struct ScopeAutocompleter {
    /// Configuration providing the configured scopes and the repository path.
    pub config: Config,
}

impl ScopeAutocompleter {
    fn get_existing_scopes(&self) -> Result<Vec<String>> {
        let repo = gix::discover(&self.config.workdir).context("could not find git repository")?;

        let head_id = repo.head_id().context("could not get HEAD")?;

        let walk =
            repo.rev_walk([head_id.detach()])
                .sorting(gix::revision::walk::Sorting::ByCommitTime(
                    gix::traverse::commit::simple::CommitTimeOrder::NewestFirst,
                ));

        let mut scopes: Vec<String> = Vec::new();

        for info in walk.all()? {
            let info = info?;

            let commit = repo.find_commit(info.id)?;

            let message = commit
                .message()
                .map_err(|error| anyhow::Error::from(error.into_error()))?;

            let summary = message.summary();

            // Parse the summary - ignore errors for invalid commit messages
            if let Ok(parsed) = parse_summary(summary.to_str()?)
                && let Some(scope) = parsed.scope
                && !scopes.contains(&scope)
            {
                scopes.push(scope);
            }
        }

        Ok(scopes)
    }

    /// Configured scopes (formatted with descriptions) followed by any scopes
    /// seen in commit history that aren't already configured (plain names).
    fn get_suggestions_with_descriptions(&self) -> Vec<String> {
        let mut suggestions: Vec<String> = self
            .config
            .commit_scopes
            .values()
            .map(format_scope_display)
            .collect();

        for scope in self.get_existing_scopes().unwrap_or_default() {
            if !self.config.commit_scopes.contains_key(&scope) {
                suggestions.push(scope);
            }
        }

        suggestions
    }

    /// Returns every known scope name from config and history, without descriptions.
    pub fn get_all_scopes(&self) -> Vec<String> {
        self.get_suggestions_with_descriptions()
            .iter()
            .map(|s| scope_name(s).to_string())
            .collect()
    }
}

impl Autocomplete for ScopeAutocompleter {
    fn get_suggestions(&mut self, input: &str) -> Result<Vec<String>, CustomUserError> {
        Ok(self
            .get_suggestions_with_descriptions()
            .into_iter()
            .filter(|s| scope_name(s).contains(input) || s.contains(input))
            .collect())
    }

    fn get_completion(
        &mut self,
        _input: &str,
        highlighted_suggestion: Option<String>,
    ) -> Result<Replacement, CustomUserError> {
        // Strip description so the input receives only the scope name.
        Ok(highlighted_suggestion.map(|s| scope_name(&s).to_string()))
    }
}

/// Render a scope as `name: description`, or just `name` when it has no description.
fn format_scope_display(scope: &crate::config::CommitScope) -> String {
    match &scope.description {
        Some(description) => format!("{name}: {description}", name = scope.name),
        None => scope.name.clone(),
    }
}

/// The scope name is everything before the first `:` in a display string.
fn scope_name(display: &str) -> &str {
    display.split(':').next().unwrap_or(display).trim()
}

impl Config {
    fn scope_values_ordered(&self, scope_matches: &ScopeMatches) -> Vec<String> {
        let matched: Vec<_> = scope_matches
            .matches
            .iter()
            .filter_map(|name| self.commit_scopes.get(name))
            .map(format_scope_display)
            .collect();

        let rest = self
            .commit_scopes
            .values()
            .filter(|s| !scope_matches.matches.contains(&s.name))
            .map(format_scope_display);

        matched.into_iter().chain(rest).collect()
    }

    fn prompt_scope(&self, scope_matches: &ScopeMatches) -> Result<Option<String>> {
        if self.force_config_scopes && !self.commit_scopes.is_empty() {
            return self.prompt_scope_select(scope_matches);
        }
        self.prompt_scope_text(scope_matches)
    }

    fn prompt_scope_select(&self, scope_matches: &ScopeMatches) -> Result<Option<String>> {
        // A single unambiguous match is pre-assigned; print it so it stays visible.
        if let Some(scope) = scope_matches.suggested() {
            print_answered_scope_prompt(scope);
            return Ok(Some(scope.to_string()));
        }

        // Otherwise fall back to user selection, matched scopes listed first.
        let scope_values = self.scope_values_ordered(scope_matches);
        let prompt = Select::new("What's the scope of this change?", scope_values)
            .with_render_config(get_render_config())
            .with_formatter(&|v| scope_name(v.value).to_string());

        let result = if self.allow_empty_scope {
            prompt
                .prompt_skippable()
                .map_err(|e| PromptError::from_inquire(e, "Scope selection"))?
        } else {
            Some(
                prompt
                    .prompt()
                    .map_err(|e| PromptError::from_inquire(e, "Scope selection"))?,
            )
        };

        Ok(result.map(|s| scope_name(&s).to_string()))
    }

    fn prompt_scope_text(&self, scope_matches: &ScopeMatches) -> Result<Option<String>> {
        let mut autocompleter = ScopeAutocompleter {
            config: self.clone(),
        };
        let detected = scope_matches.suggested();
        let has_completions = self.autocomplete
            && !autocompleter
                .get_suggestions("")
                .unwrap_or_default()
                .is_empty();

        // Build the help line from the parts that actually apply.
        let mut hints: Vec<String> = Vec::new();
        if has_completions {
            hints.push("↑↓ to move, tab to autocomplete".into());
        }
        if let Some(scope) = detected {
            hints.push(format!("enter to use `{scope}`"));
        } else if scope_matches.matches.len() > 1 {
            hints.push(format!("matched: {}", scope_matches.matches.join(", ")));
        }
        hints.push(get_skip_hint().into());
        let help = hints.join(", ");

        let mut text = Text::new("What's the scope of this change?")
            .with_render_config(RenderConfig {
                option: StyleSheet::new().with_fg(Color::Grey),
                ..get_render_config()
            })
            .with_help_message(&help);

        if let Some(scope) = detected {
            text = text.with_initial_value(scope);
        }

        if self.autocomplete {
            text = text.with_autocomplete(autocompleter);
        }

        // A scope is only strictly required when none was detected for us.
        if !self.allow_empty_scope && detected.is_none() {
            text = text.with_validator(|input: &str| {
                if input.trim().is_empty() {
                    Ok(Validation::Invalid("A scope is required".into()))
                } else {
                    Ok(Validation::Valid)
                }
            });
            return Ok(Some(
                text.prompt()
                    .map_err(|e| PromptError::from_inquire(e, "Scope selection"))?,
            ));
        }

        match text
            .prompt_skippable()
            .map_err(|e| PromptError::from_inquire(e, "Scope selection"))?
        {
            Some(s) if s.is_empty() => Ok(None),
            result => Ok(result),
        }
    }
}

fn prompt_summary(msg: String) -> Result<String> {
    let previous_summary = match parse_summary(&msg) {
        Ok(parsed) => parsed.summary,
        Err(_) => "".into(),
    };

    let summary = SuggestedText::new(
        "Write a short, imperative tense description of the change:",
        &previous_summary,
        validate_summary,
    )
    .prompt()
    .map_err(|e| PromptError::from_inquire(e, "Commit summary input"))?;

    Ok(summary)
}

fn prompt_body() -> Result<Option<String>> {
    let help_message = multiline_help();
    let _keyboard_enhancement = KeyboardEnhancement::enable()?;

    match MultilineText::new(
        "Provide a longer description of the change:",
        help_message.as_str(),
    )
    .prompt_skippable()
    .map_err(|e| PromptError::from_inquire(e, "Body input"))?
    {
        Some(summary) if summary.is_empty() => Ok(None),
        Some(summary) => Ok(Some(summary)),
        None => Ok(None),
    }
}

fn prompt_breaking() -> Result<bool> {
    let answer = Confirm::new("Are there any breaking changes?")
        .with_render_config(get_render_config())
        .with_default(false)
        .prompt()
        .map_err(|e| PromptError::from_inquire(e, "Breaking changes prompt"))?;

    Ok(answer)
}

fn prompt_breaking_text() -> Result<Option<String>> {
    let help_message = multiline_help();
    let _keyboard_enhancement = KeyboardEnhancement::enable()?;

    match MultilineText::new(
        "Describe the breaking changes in detail:",
        help_message.as_str(),
    )
    .prompt_skippable()
    .map_err(|e| PromptError::from_inquire(e, "Breaking changes description"))?
    {
        Some(text) if text.is_empty() => Ok(None),
        Some(text) => Ok(Some(text)),
        None => Ok(None),
    }
}

fn prompt_issues() -> Result<bool> {
    let answer = Confirm::new("Does this change affect any open issues?")
        .with_render_config(get_render_config())
        .with_default(false)
        .prompt()
        .map_err(|e| PromptError::from_inquire(e, "Issues prompt"))?;

    Ok(answer)
}

fn prompt_issue_text() -> Result<String> {
    let summary = Text::new("Add the issue reference:")
        .with_render_config(get_render_config())
        .with_help_message("e.g. \"closes #123\"")
        .with_validator(validate_issue_reference)
        .prompt()
        .map_err(|e| PromptError::from_inquire(e, "Issue reference input"))?;

    Ok(summary)
}

/// Answers collected by the interactive prompts.
#[derive(Debug, PartialEq, Eq)]
pub struct Answers {
    /// Selected commit type name.
    pub commit_type: String,
    /// Chosen scope, if any.
    pub scope: Option<String>,
    /// Short description of the change.
    pub summary: String,
    /// Longer description of the change, if any.
    pub body: Option<String>,
    /// Issue reference to add as a footer, if any.
    pub issue_footer: Option<String>,
    /// Whether the change is breaking.
    pub is_breaking_change: bool,
    /// Description of the breaking change, if any.
    pub breaking_change_footer: Option<String>,
}

/// Runs the interactive prompts and collects the answers.
///
/// # Errors
///
/// Returns an error if the user cancels a prompt or the terminal fails.
pub fn create_prompt(
    last_message: String,
    config: &Config,
    scope_matches: &ScopeMatches,
) -> Result<Answers> {
    let commit_type = prompt_type(config)?;
    let scope = config.prompt_scope(scope_matches)?;
    let summary = prompt_summary(last_message)?;
    let body = prompt_body()?;

    let mut breaking = false;
    let mut breaking_footer: Option<String> = None;
    if config.breaking_changes {
        breaking = prompt_breaking()?;
        if breaking {
            breaking_footer = prompt_breaking_text()?;
        }
    }

    let mut issue_footer = None;
    if config.issues && prompt_issues()? {
        issue_footer = Some(prompt_issue_text()?);
    }

    Ok(Answers {
        commit_type,
        scope,
        summary,
        body,
        issue_footer,
        is_breaking_change: breaking,
        breaking_change_footer: breaking_footer,
    })
}

/// Asks the user to confirm the commit.
///
/// # Errors
///
/// Returns an error if the user cancels the prompt or the terminal fails.
pub fn prompt_confirm() -> Result<bool> {
    let answer = Confirm::new("Proceed with this commit?")
        .with_render_config(get_render_config())
        .with_default(true)
        .prompt()
        .map_err(|e| PromptError::from_inquire(e, "Confirmation"))?;

    Ok(answer)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_transform_commit_type_choice() {
        let transformed = transform_commit_type_choice(
            "feat:       A code change that neither fixes a bug nor adds a feature",
        );

        assert_eq!(transformed, "feat");
    }

    #[test]
    fn test_format_commit_type_choice() {
        let config = Config::new(None).unwrap();
        let commit_types = config.commit_types;

        let choice =
            format_commit_type_choice(false, commit_types.get("ci").unwrap(), &commit_types);

        assert_eq!(
            choice,
            "ci:         Changes to our CI configuration files and scripts"
        );
    }

    #[test]
    fn test_format_commit_type_choice_emoji() {
        let commit_type = CommitType {
            name: "123".into(),
            emoji: None,
            description: "Test".into(),
        };

        let commit_types = indexmap::indexmap! {
            "123".into() => commit_type.clone(),
        };

        let choice = format_commit_type_choice(true, &commit_type, &commit_types);

        assert_eq!(choice, "123:   Test");
    }

    #[test]
    fn test_render_commit_type_choice_with_emoji() {
        let config = Config::new(None).unwrap();
        let commit_types = config.commit_types;

        let choice =
            format_commit_type_choice(true, commit_types.get("ci").unwrap(), &commit_types);

        assert_eq!(
            choice,
            "ci:         🤖 Changes to our CI configuration files and scripts"
        );
    }

    #[test]
    fn test_validate_summary() {
        let validated = validate_summary("needed more badges :badger:");

        assert!(validated.is_ok());
        assert!(
            validated
                .expect("Summary should be OK")
                .eq(&Validation::Valid)
        );

        let validated = validate_summary("");

        assert!(validated.is_ok());
        assert!(
            validated
                .expect("Summary should be OK")
                .eq(&Validation::Invalid("A summary is required".into()))
        );
    }

    #[test]
    fn test_validate_issue_reference() {
        let validated = validate_issue_reference("closes #123");

        assert!(validated.is_ok());
        assert!(
            validated
                .expect("Issue reference should be OK")
                .eq(&Validation::Valid)
        );

        let validated = validate_issue_reference("");

        assert!(validated.is_ok());
        assert!(
            validated
                .expect("Summary should be OK")
                .eq(&Validation::Invalid(
                    "An issue reference is required".into()
                ))
        );
    }
}