git-z 0.2.4

A Git extension to go beyond.
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
// git-z - A Git extension to go beyond.
// Copyright (C) 2023-2025 Jean-Philippe Cugnet <jean-philippe@cugnet.eu>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! The `commit` subcommand.

pub mod backend;

use std::{fs, path::PathBuf, process::Command};

use clap::{Parser, builder::NonEmptyStringValueParser};
use eyre::{Context as _, Result, eyre};
use indexmap::IndexMap;
use inquire::{Confirm, CustomUserError, Select, Text, validator::Validation};
use itertools::Itertools as _;
use regex::Regex;
use serde::Serialize;
use tera::{Context, Tera};
use thiserror::Error;

use crate::{
    command::helpers::{load_config, page_size},
    commit_cache::{CommitCache, WizardState},
    config::{Config, Scopes, Ticket},
    tracing::LogResult as _,
};

use self::backend::{
    Backend, BackendError, CustomCommandBackend, GitBackend, PrintBackend,
};
use super::helpers::ensure_in_git_worktree;

#[cfg(feature = "unstable-pre-commit")]
use std::{env, io};

#[cfg(feature = "unstable-pre-commit")]
use is_executable::IsExecutable as _;

#[cfg(feature = "unstable-pre-commit")]
use crate::warning;

/// The commit command.
#[derive(Debug, Parser)]
pub struct Commit {
    /// Set the topic to be used for the ticket number instead of the branch.
    #[arg(long)]
    topic: Option<String>,
    /// Use a custom command instead of `git commit -em "$message"`.
    #[arg(
        long,
        group = "backend",
        value_parser = NonEmptyStringValueParser::new(),
    )]
    command: Option<String>,
    /// Print the commit message instead of calling `git commit`.
    #[arg(long, group = "backend")]
    print_only: bool,
    /// Do not run the pre-commit hook.
    #[cfg(feature = "unstable-pre-commit")]
    #[arg(long, short = 'n')]
    no_verify: bool,
    /// Extra arguments to be passed to `git commit`.
    #[arg(last = true)]
    extra_args: Vec<String>,
}

/// Usage errors of `git z commit`.
#[derive(Debug, Error)]
pub enum CommitError {
    /// The pre-commit hook could not be run.
    #[cfg(feature = "unstable-pre-commit")]
    #[error("Failed to run the pre-commit hook")]
    CannotRunPreCommit(#[source] io::Error),
    /// The pre-commit hook has failed.
    #[cfg(feature = "unstable-pre-commit")]
    #[error("The pre-commit hook has failed")]
    PreCommitFailed,
    /// The commit template is invalid.
    #[error("Failed to parse the commit template")]
    Template(#[source] tera::Error),
    /// The backend has returned an error.
    #[error("Failed to run the backend")]
    Backend(#[from] BackendError),
}

/// Wizard options from the CLI.
struct WizardOptions<'a> {
    /// The topic to use for the commit.
    topic: Option<&'a str>,
}

/// A conventional commit message.
#[derive(Debug, Serialize)]
struct CommitMessage {
    /// The type of commit.
    r#type: String,
    /// The optional scope of the commit.
    scope: Option<String>,
    /// The short commit description.
    description: String,
    /// The optional breaking change description.
    breaking_change: Option<String>,
    /// The optional linked ticket.
    ticket: Option<String>,
}

impl super::Command for Commit {
    #[tracing::instrument(name = "commit", level = "trace", skip_all)]
    fn run(&self) -> Result<()> {
        tracing::info!(params = ?self, "running commit");

        ensure_in_git_worktree()?;

        let config = load_config()?;

        let backend: Box<dyn Backend> = if self.print_only {
            tracing::info!("selecting the Print backend");
            Box::new(PrintBackend)
        } else if let Some(command) = &self.command {
            tracing::info!("selecting the custom command backend");
            Box::new(CustomCommandBackend::new(command)?)
        } else {
            tracing::info!("selecting the Git backend");
            Box::new(GitBackend::new(&self.extra_args))
        };

        #[cfg(feature = "unstable-pre-commit")]
        if !self.no_verify {
            run_pre_commit_hook()?;
        }

        let commit_message = make_commit_message(
            &config,
            &WizardOptions {
                topic: self.topic.as_deref(),
            },
        )?;

        backend
            .call(&commit_message)
            .map_err(CommitError::Backend)?;

        tracing::info!("commit success!");
        CommitCache::discard()?;
        Ok(())
    }
}

impl CommitMessage {
    /// Runs the wizard to build a commit message from user input.
    #[tracing::instrument(level = "trace", skip_all)]
    fn run_wizard(
        config: &Config,
        options: &WizardOptions<'_>,
        cache: &mut CommitCache,
    ) -> Result<Self> {
        let commit_message = Self {
            r#type: ask_type(config, cache)?,
            scope: ask_scope(config, cache)?,
            description: ask_description(cache)?,
            breaking_change: ask_breaking_change(cache)?,
            ticket: ask_ticket(config, options.topic, cache)?,
        };

        // NOTE: Marking the wizard as completed allows to skip the wizard on
        // next run if `git commit` has failed and there is a valid
        // `COMMIT_EDITMSG` file. In order to ensure `git z commit` does not
        // reuse an outdated message, let’s delete any existing `COMMIT_EDITMSG`
        // before marking the wizard as completed.
        delete_last_commit_message()?;
        cache.mark_wizard_as_completed()?;

        tracing::debug!(?commit_message);
        Ok(commit_message)
    }

    /// Builds a dummy commit message.
    fn dummy() -> Self {
        Self {
            r#type: String::from("dummy"),
            scope: Some(String::from("dummy")),
            description: String::from("dummy commit"),
            breaking_change: Some(String::from("Dummy breaking change.")),
            ticket: Some(String::from("#0")),
        }
    }
}

/// Runs the pre-commit hook if it exists.
#[cfg(feature = "unstable-pre-commit")]
#[tracing::instrument(level = "trace")]
fn run_pre_commit_hook() -> Result<()> {
    let pre_commit = pre_commit()?;

    if pre_commit.exists() {
        if pre_commit.is_executable() {
            tracing::info!(path = ?pre_commit, "running the pre-commit hook");

            let status = Command::new(pre_commit)
                .status()
                .map_err(CommitError::CannotRunPreCommit)
                .log_err()?;

            if !status.success() {
                Err(CommitError::PreCommitFailed).log_err()?;
            }

            tracing::info!("the pre-commit hook has returned a success");
        } else {
            let path = pre_commit
                .strip_prefix(env::current_dir()?)
                .unwrap_or(&pre_commit)
                .display();

            warning!(
                "The `{path}` hook was ignored because it is not set as \
                executable."
            );
        }
    } else {
        tracing::debug!("no pre-commit hook to run");
    }

    Ok(())
}

/// Makes a commit message.
#[tracing::instrument(level = "trace", skip_all)]
fn make_commit_message(
    config: &Config,
    options: &WizardOptions<'_>,
) -> Result<String> {
    let mut cache = CommitCache::load()?;

    let message = match cache.wizard_state {
        WizardState::NotStarted | WizardState::Ongoing => {
            make_message_from_wizard(config, options, &mut cache)?
        }
        WizardState::Completed => {
            tracing::debug!(
                "completed wizard state present, checking whether a valid \
                commit message is present"
            );
            if let Some(message) = last_commit_message()? {
                tracing::debug!(
                    "valid commit message present, asking the user whether to \
                    use it"
                );
                let do_reuse_message = ask_reuse_message()?;

                if do_reuse_message {
                    tracing::debug!("reusing the commit message");
                    message
                } else {
                    tracing::debug!("not reusing the commit message");
                    cache.reset()?;
                    make_message_from_wizard(config, options, &mut cache)?
                }
            } else {
                tracing::debug!("no valid commit message, rerun the wizard");
                cache.mark_wizard_as_ongoing()?;
                make_message_from_wizard(config, options, &mut cache)?
            }
        }
    };

    Ok(format_message(&message))
}

/// Makes a commit message by running the wizard.
#[tracing::instrument(level = "trace", skip_all)]
fn make_message_from_wizard(
    config: &Config,
    options: &WizardOptions<'_>,
    cache: &mut CommitCache,
) -> Result<String> {
    let tera = build_and_check_template(config)?;

    if cache.wizard_state == WizardState::Ongoing {
        tracing::debug!(
            "ongoing wizard state present, asking the user whether to use it"
        );
        let do_reuse_answers = ask_reuse_answers()?;

        if do_reuse_answers {
            tracing::debug!("reusing answers");
        } else {
            tracing::debug!("not reusing answers");
            cache.reset()?;
        }
    }

    let commit_message = CommitMessage::run_wizard(config, options, cache)?;
    let context = Context::from_serialize(commit_message).log_err()?;
    let message = tera.render("templates.commit", &context).log_err()?;
    tracing::debug!(rendered_message = ?message,);

    Ok(message)
}

/// Loads the commit template and checks for errors.
#[tracing::instrument(level = "trace", skip_all)]
fn build_and_check_template(config: &Config) -> Result<Tera> {
    let mut tera = Tera::default();

    tera.add_raw_template("templates.commit", &config.templates.commit)
        .map_err(CommitError::Template)
        .log_err()?;

    // Render a dummy commit to catch early any variable error.
    tera.render(
        "templates.commit",
        &Context::from_serialize(CommitMessage::dummy()).log_err()?,
    )
    .map_err(CommitError::Template)
    .log_err()?;

    Ok(tera)
}

/// Asks the user whether to reuse the commit message from an aborted run.
fn ask_reuse_message() -> Result<bool> {
    Ok(Confirm::new(
        "A previous run has been aborted. Do you want to reuse your commit \
            message?",
    )
    .with_help_message(
        "This will use your last commit message without running the wizard.",
    )
    .with_default(true)
    .prompt()
    .log_err()?)
}

/// Asks the user whether to reuse answers from an aborted run.
fn ask_reuse_answers() -> Result<bool> {
    Ok(Confirm::new(
        "A previous run has been aborted. Do you want to reuse your answers?",
    )
    .with_help_message(
        "The wizard will be run as usual with your answers pre-selected.",
    )
    .with_default(true)
    .prompt()
    .log_err()?)
}

/// Asks the user which type of commit they wants.
fn ask_type(config: &Config, cache: &mut CommitCache) -> Result<String> {
    let cached = cache.r#type().unwrap_or_default();
    let cursor = config.types.get_index_of(cached).unwrap_or_default();

    let choice = Select::new("Commit type", format_types(&config.types))
        .with_starting_cursor(cursor)
        .with_page_size(page_size(1))
        .with_formatter(&|choice| remove_type_description(choice.value))
        .prompt()
        .log_err()?;
    let r#type = remove_type_description(&choice);

    tracing::debug!(?r#type);
    cache.set_type(&r#type)?;

    Ok(r#type)
}

/// Asks the user to which scope the changes are applicable.
fn ask_scope(
    config: &Config,
    cache: &mut CommitCache,
) -> Result<Option<String>> {
    let scope = match &config.scopes {
        None => None,

        Some(Scopes::Any) => Text::new("Scope")
            .with_initial_value(cache.scope().unwrap_or_default())
            .with_help_message("Press ESC or leave empty to omit the scope.")
            .prompt_skippable()
            .log_err()?
            .filter(|s| !s.is_empty()),

        Some(Scopes::List { list }) => {
            let cached = cache.scope().unwrap_or_default();
            let cursor =
                list.iter().position(|s| s == cached).unwrap_or_default();

            let help_message = "↑↓ to move, enter to select, type to \
                filter, ESC to leave empty, update `git-z.toml` to add new \
                scopes";

            Select::new("Scope", list.clone())
                .with_starting_cursor(cursor)
                .with_help_message(help_message)
                .with_page_size(page_size(2))
                .prompt_skippable()
                .log_err()?
        }
    };

    tracing::debug!(?scope);
    cache.set_scope(scope.as_deref())?;

    Ok(scope)
}

/// Asks the user for a commit description.
fn ask_description(cache: &mut CommitCache) -> Result<String> {
    let placeholder =
        "describe your change with a short description (5-60 characters)";
    let message = "You will be able to add a long description to your \
        commit in an editor later.";

    let description = Text::new("Short description")
        .with_placeholder(placeholder)
        .with_initial_value(cache.description().unwrap_or_default())
        .with_help_message(message)
        .with_validator(validate_description)
        .prompt()
        .log_err()?;

    tracing::debug!(?description);
    cache.set_description(&description)?;

    Ok(description)
}

/// Asks the user for an optional breaking change description.
fn ask_breaking_change(cache: &mut CommitCache) -> Result<Option<String>> {
    let breaking_change = Text::new("BREAKING CHANGE")
        .with_placeholder("Summary of the breaking change.")
        .with_initial_value(cache.breaking_change().unwrap_or_default())
        .with_help_message(
            "Press ESC or leave empty if there are no breaking changes.",
        )
        .prompt_skippable()
        .log_err()?
        .filter(|s| !s.is_empty());

    tracing::debug!(?breaking_change);
    cache.set_breaking_change(breaking_change.as_deref())?;

    Ok(breaking_change)
}

/// Optionally asks the user for a ticket reference.
fn ask_ticket(
    config: &Config,
    topic: Option<&str>,
    cache: &mut CommitCache,
) -> Result<Option<String>> {
    let ticket = match &config.ticket {
        None => None,
        Some(Ticket { required, prefixes }) => {
            let placeholder = ticket_placeholder(prefixes)?;
            let cached_answer = cache.ticket();

            let branch = get_current_branch()?;
            let topic = topic.unwrap_or(&branch);
            let ticket_from_topic = extract_ticket_from_topic(topic, prefixes)?;

            let initial_value = cached_answer.unwrap_or_else(|| {
                ticket_from_topic.as_deref().unwrap_or_default()
            });

            let prompt = Text::new("Issue / ticket number")
                .with_placeholder(&placeholder)
                .with_initial_value(initial_value)
                .with_validator(validate_ticket);

            if *required {
                Some(prompt.prompt().log_err()?)
            } else {
                prompt
                    .with_help_message(
                        "Press ESC to omit the ticket reference.",
                    )
                    .prompt_skippable()
                    .log_err()?
            }
        }
    };

    tracing::debug!(?ticket);
    cache.set_ticket(ticket.as_deref())?;

    Ok(ticket)
}

/// Tries to extract a ticket number from the given topic.
#[tracing::instrument(level = "trace")]
fn extract_ticket_from_topic(
    topic: &str,
    prefixes: &[String],
) -> Result<Option<String>> {
    // Replace `#` with an empty string in the regex, as we want to match
    // branches like `feature/23-name` when `#` is a valid prefix like for
    // GitHub or GitLab issues.
    let regex = ticket_regex(prefixes).replace('#', "");

    let ticket = Regex::new(&regex)
        .wrap_err("Impossible to build a regex from the list of prefixes")
        .log_err()?
        .captures(topic)
        .map(|captures| captures[0].to_owned())
        .map(|ticket| {
            #[expect(
                clippy::unwrap_used,
                reason = "This regex is known to be valid."
            )]
            let regex = &Regex::new(r"^\d+$").unwrap();

            // If one of the valid prefixes is `#` and the matched ticket ID is
            // only made of numbers, we are in the GitHub / GitLab style, so
            // let’s add a `#` as a prefix to the ticket ID.
            if prefixes.contains(&String::from("#")) && regex.is_match(&ticket)
            {
                format!("#{ticket}")
            } else {
                ticket
            }
        });

    tracing::trace!(?ticket);
    Ok(ticket)
}

/// Gets the name of the current Git branch.
#[tracing::instrument(level = "trace")]
fn get_current_branch() -> Result<String> {
    let git_branch = Command::new("git")
        .args(["branch", "--show-current"])
        .output()
        .log_err()?;

    if !git_branch.status.success() {
        return Err(eyre!("Failed to run `git branch --show-current`"))
            .log_err();
    }

    let current_branch = String::from_utf8(git_branch.stdout).log_err()?;
    tracing::trace!(?current_branch);
    Ok(current_branch)
}

/// Formats the list of types and their description.
fn format_types(types: &IndexMap<String, String>) -> Vec<String> {
    let Some(max_type_len) = types.keys().map(String::len).max() else {
        return vec![];
    };

    types
        .iter()
        .map(|(ty, doc)| {
            let padding = " ".repeat(max_type_len - ty.len());
            format!("{ty}{padding}  {doc}")
        })
        .collect()
}

/// Removes the type description from the choice.
#[expect(
    clippy::missing_panics_doc,
    reason = "The unwrap in the function cannot actually panic."
)]
fn remove_type_description(choice: &str) -> String {
    #[expect(
        clippy::unwrap_used,
        reason = "Even an empty string will contain at least one split, so the \
            only call to next will always return Some(value)."
    )]
    choice.split(' ').next().unwrap().to_owned()
}

/// Validates the commit description.
#[expect(
    clippy::missing_panics_doc,
    reason = "The unwrap in the function cannot actually panic."
)]
#[expect(
    clippy::unnecessary_wraps,
    reason = "The signature of the function is imposed by Inquire."
)]
fn validate_description(
    description: &str,
) -> Result<Validation, CustomUserError> {
    #[expect(
        clippy::unwrap_used,
        reason = "We know from the first condition that description.len() > 0, \
            so there is at least one character in the string. Hence, \
            description.chars().next() in the third condition will always \
            return Some(value)."
    )]
    if description.len() < 5 {
        Ok(Validation::Invalid(
            "The description must be longer than 5 characters".into(),
        ))
    } else if description.len() > 60 {
        Ok(Validation::Invalid(
            "The description must not be longer than 60 characters".into(),
        ))
    } else if description.chars().next().unwrap().is_uppercase() {
        Ok(Validation::Invalid(
            "The description must start in lowercase".into(),
        ))
    } else {
        Ok(Validation::Valid)
    }
}

/// Validates the ticket reference.
fn validate_ticket(ticket: &str) -> Result<Validation, CustomUserError> {
    let config = Config::load()?;
    let prefixes = &config
        .ticket
        .ok_or(eyre!("no ticket prefix list"))
        .log_err()?
        .prefixes;

    let regex = ticket_regex(prefixes);
    let placeholder = ticket_placeholder(prefixes)?;

    if Regex::new(&format!("^{regex}$"))?.is_match(ticket) {
        Ok(Validation::Valid)
    } else {
        Ok(Validation::Invalid(
            format!(
                "The issue / ticket number must be in the form {placeholder}"
            )
            .into(),
        ))
    }
}

/// Builds a regex to match valid tickets from the list of valid prefixes.
fn ticket_regex(prefixes: &[String]) -> String {
    let prefixes = prefixes.join("|");
    format!("(?:{prefixes})\\d+")
}

/// Builds the ticket placeholder from the list of valid prefixes.
fn ticket_placeholder(prefixes: &[String]) -> Result<String> {
    prefixes
        .iter()
        .map(|prefix| format!("{prefix}XXX"))
        .reduce(|acc, prefix| format!("{acc} or {prefix}"))
        .ok_or(eyre!("empty ticket prefix list"))
}

/// Returns the last commit message if it exists.
#[tracing::instrument(level = "trace")]
fn last_commit_message() -> Result<Option<String>> {
    let commit_editmsg = commit_editmsg()?;

    let remove_commented_lines =
        |s: &str| s.lines().filter(|line| !line.starts_with('#')).join("\n");

    let maybe_message = commit_editmsg
        .exists()
        .then(|| fs::read_to_string(&commit_editmsg))
        .transpose()
        .wrap_err_with(|| {
            format!("failed to read {}", commit_editmsg.display())
        })
        .log_err()?
        .as_deref()
        .map(remove_commented_lines)
        .map(|last_message| {
            tracing::trace!(?last_message);
            last_message
        })
        .filter(|s| !s.trim().is_empty());

    Ok(maybe_message)
}

/// Deletes the last commit message if it exists.
#[tracing::instrument(level = "trace")]
fn delete_last_commit_message() -> Result<()> {
    let commit_editmsg = commit_editmsg()?;

    commit_editmsg
        .exists()
        .then(|| {
            tracing::debug!("deleting the previous COMMIT_EDITMSG");
            fs::remove_file(&commit_editmsg)
        })
        .transpose()
        .map(|_| ())
        .wrap_err_with(|| {
            format!("failed to delete {}", commit_editmsg.display())
        })
        .log_err()
}

/// Returns the path to the `COMMIT_EDITMSG` file.
fn commit_editmsg() -> Result<PathBuf> {
    Ok(git_dir()?.join("COMMIT_EDITMSG"))
}

/// Returns the path to the pre-commit hook.
#[cfg(feature = "unstable-pre-commit")]
fn pre_commit() -> Result<PathBuf> {
    Ok(git_dir()?.join("hooks").join("pre-commit"))
}

/// Returns the path of the Git directory.
#[tracing::instrument(level = "trace")]
fn git_dir() -> Result<PathBuf> {
    let git_rev_parse = Command::new("git")
        .args(["rev-parse", "--git-dir"])
        .output()
        .log_err()?;

    if !git_rev_parse.status.success() {
        return Err(eyre!("Failed to run `git rev-parse --git-dir`")).log_err();
    }

    let git_dir = String::from_utf8(git_rev_parse.stdout).log_err()?;
    Ok(PathBuf::from(git_dir.trim()))
}

/// Formats the commit message.
#[expect(
    clippy::missing_panics_doc,
    reason = "The unwrap in the function cannot actually panic."
)]
fn format_message(message: &str) -> String {
    #[expect(clippy::unwrap_used, reason = "This regex is known to be valid.")]
    let regex = Regex::new(r"\n{3,}").unwrap();
    regex.replace_all(message, "\n\n").trim().to_owned()
}