rona 2.22.2

A simple CLI tool to help you with your git workflow.
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
//! Commit Operations
//!
//! Git commit-related functionality including commit counting, commit message generation,
//! and commit execution operations.

use std::{
    fs::{File, OpenOptions, read_to_string, write},
    io::Write,
    path::Path,
    process::Command,
};

use colored::Colorize;

use crate::{
    errors::{GitError, Result, RonaError},
    git::branch::{format_branch_name, get_current_branch},
};

use super::{
    files::get_ignore_patterns,
    get_top_level_path,
    status::{process_deleted_files_for_commit_message, process_git_status},
};

pub const COMMIT_MESSAGE_FILE_PATH: &str = "commit_message.md";
pub const COMMIT_TYPES: [&str; 4] = ["chore", "feat", "fix", "test"];

/// Gets the total number of commits in the current branch.
///
/// This function counts all commits reachable from the current HEAD.
/// Returns 0 for a fresh repository with no commits.
///
/// # Errors
///
/// Returns an error if:
/// - Not currently in a git repository
/// - The commit count output cannot be parsed
///
/// # Returns
///
/// The total number of commits as a `u32`
///
/// # Examples
///
/// ```no_run
/// use rona::git::commit::get_current_commit_nb;
///
/// let commit_count = get_current_commit_nb()?;
/// println!("This repository has {} commits", commit_count);
///
/// // Use for commit numbering
/// let next_commit_number = commit_count + 1;
/// println!("Next commit will be #{}", next_commit_number);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn get_current_commit_nb() -> Result<u32> {
    let output = Command::new("git")
        .args(["rev-list", "--count", "HEAD"])
        .output()
        .map_err(RonaError::Io)?;

    if !output.status.success() {
        // Likely a fresh repository with no commits
        return Ok(0);
    }

    let count_str = String::from_utf8_lossy(&output.stdout).trim().to_string();

    count_str.parse::<u32>().map_err(|_| {
        RonaError::Git(GitError::InvalidStatus {
            output: format!("Failed to parse commit count: {count_str}"),
        })
    })
}

/// Detects if GPG signing is configured in git.
///
/// Checks whether a signing key is configured via `git config --get user.signingkey`.
/// When this returns `true`, git will attempt to sign commits automatically.
///
/// # Returns
/// * `true` if a signing key is configured
/// * `false` if no signing key is configured
///
/// # Examples
///
/// ```no_run
/// use rona::git::commit::is_gpg_signing_available;
///
/// if is_gpg_signing_available() {
///     println!("GPG signing is configured");
/// } else {
///     println!("GPG signing is not configured, will create unsigned commit");
/// }
/// ```
#[must_use]
pub fn is_gpg_signing_available() -> bool {
    let output = Command::new("git")
        .args(["config", "--get", "user.signingkey"])
        .output();

    match output {
        Ok(out) => out.status.success() && !String::from_utf8_lossy(&out.stdout).trim().is_empty(),
        Err(_) => false,
    }
}

/// Handles dry run output for commit operations.
///
/// # Arguments
/// * `file_content` - The commit message content
/// * `unsigned` - Whether the commit should be unsigned
/// * `filtered_args` - Additional git arguments
/// * `is_amend` - Whether this is an amend operation
fn handle_dry_run_output(
    file_content: &str,
    unsigned: bool,
    filtered_args: &[String],
    is_amend: bool,
) {
    println!("Would commit with message:");
    println!("---");
    println!("{}", file_content.trim());
    println!("---");

    if is_amend {
        println!("Would amend the previous commit");
    }

    let gpg_available = is_gpg_signing_available();
    let would_sign = !unsigned && gpg_available;

    if unsigned {
        println!("Would create unsigned commit");
    } else if would_sign {
        println!("Would sign commit with GPG");
    } else {
        println!("Would create unsigned commit (GPG signing not available)");
        if !gpg_available {
            println!(
                "{} GPG signing not available or not configured.",
                "WARNING:".yellow().bold()
            );
            println!("   To suppress this warning, use the --unsigned (-u) flag.");
        }
    }

    if !filtered_args.is_empty() {
        println!("With additional args: {filtered_args:?}");
    }
}

/// Commits files to the git repository using `git commit -F`.
///
/// This function reads the commit message from `commit_message.md` and creates
/// a git commit with that message. By using the git CLI directly, all git hooks
/// (pre-commit, commit-msg, post-commit, etc.) are triggered naturally.
///
/// GPG signing is handled by git's own configuration (`commit.gpgsign`,
/// `user.signingkey`). Pass `unsigned = true` to disable signing via
/// `--no-gpg-sign`.
///
/// # Arguments
/// * `args` - Additional arguments (supports `--amend` to amend the previous commit)
/// * `unsigned` - If true, creates an unsigned commit (passes `--no-gpg-sign`)
/// * `dry_run` - If true, only show what would be committed without actually committing
///
/// # Errors
/// * If the commit message file doesn't exist
/// * If reading the commit message file fails
/// * If the git commit command fails
/// * If not in a git repository
///
/// # Examples
///
/// ```no_run
/// use rona::git::commit::git_commit;
///
/// // Commit with automatic GPG detection (default)
/// git_commit(&[], false, false)?;
///
/// // Unsigned commit
/// git_commit(&[], true, false)?;
///
/// // Amend the previous commit
/// git_commit(&["--amend".to_string()], false, false)?;
///
/// // Dry run to preview the commit
/// git_commit(&[], false, true)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[tracing::instrument(skip_all)]
pub fn git_commit(args: &[String], unsigned: bool, dry_run: bool) -> Result<()> {
    tracing::debug!(unsigned, dry_run, "Committing files...");

    let project_root = get_top_level_path()?;
    let commit_file_path = project_root.join(COMMIT_MESSAGE_FILE_PATH);

    if !commit_file_path.exists() {
        return Err(RonaError::Git(GitError::CommitMessageNotFound));
    }

    let file_content = read_to_string(&commit_file_path)?;

    // Detect --amend and filter out flags that don't apply to git commit -F
    let is_amend = args.iter().any(|arg| arg == "--amend");
    let filtered_args: Vec<String> = args
        .iter()
        .filter(|arg| !arg.starts_with("-c") && !arg.starts_with("--commit") && *arg != "--amend")
        .cloned()
        .collect();

    if dry_run {
        handle_dry_run_output(&file_content, unsigned, &filtered_args, is_amend);
        return Ok(());
    }

    // Warn if user expects signing but no key is configured
    if !unsigned && !is_gpg_signing_available() {
        println!(
            "{} GPG signing not available or not configured. Creating unsigned commit.",
            "WARNING:".yellow().bold()
        );
        println!("   To suppress this warning, use the --unsigned (-u) flag.");
    }

    let commit_file_str = commit_file_path.to_str().ok_or_else(|| {
        RonaError::Git(GitError::CommandFailed {
            command: "commit".to_string(),
            output: "Invalid path to commit message file".to_string(),
        })
    })?;

    let mut cmd = Command::new("git");
    cmd.arg("commit");

    if is_amend {
        cmd.arg("--amend");
    }

    if unsigned {
        cmd.arg("--no-gpg-sign");
    }

    cmd.args(["-F", commit_file_str]);

    // Use .status() so git inherits stdin/stdout/stderr.
    // This allows hooks to run and interactive GPG prompts to work.
    let status = cmd.status().map_err(RonaError::Io)?;

    if !status.success() {
        return Err(RonaError::Git(GitError::CommandFailed {
            command: "commit".to_string(),
            output: "git commit failed".to_string(),
        }));
    }

    tracing::debug!("commit successful!");

    Ok(())
}

/// Prepares the commit message.
/// It creates the commit message file and empties it if it already exists.
/// It also adds the modified / added files to the commit message file.
///
/// # Errors
/// * If we cannot write to the commit message file
/// * If we cannot read the git status
/// * If we cannot process either git status or deleted files from the git status
/// * If we cannot read the commitignore file
///
/// # Arguments
/// * `commit_type` - `&str` - The commit type
/// * `no_commit_number` - `bool` - Whether to include the commit number in the header
#[tracing::instrument(skip_all)]
pub fn generate_commit_message(commit_type: &str, no_commit_number: bool) -> Result<()> {
    let project_root = get_top_level_path()?;
    let commit_message_path = project_root.join(COMMIT_MESSAGE_FILE_PATH);

    // Empty the file if it exists
    if commit_message_path.exists() {
        write(&commit_message_path, "")?;
    }

    // Get git status info
    let modified_files = process_git_status()?;
    let deleted_files = process_deleted_files_for_commit_message()?;

    // Open the commit file for writing
    let mut commit_file = OpenOptions::new()
        .append(true)
        .create(true)
        .open(&commit_message_path)?;

    // Write header
    write_commit_header(&mut commit_file, commit_type, no_commit_number)?;

    // Get files to ignore
    let ignore_patterns = get_ignore_patterns()?;

    // Process modified files
    for file in modified_files {
        if !should_ignore_file(&file, &ignore_patterns)? {
            writeln!(commit_file, "- `{file}`:\n\n\t\n")?;
        }
    }

    // Process deleted files
    for file in deleted_files {
        writeln!(commit_file, "- `{file}`: deleted\n")?;
    }

    // Close the file
    commit_file.flush()?;

    tracing::debug!("{} created", commit_message_path.display());

    Ok(())
}

/// Writes the commit header to the commit file.
///
/// # Arguments
/// * `commit_file` - The file to write to
/// * `commit_type` - The type of commit
/// * `no_commit_number` - Whether to include the commit number in the header
///
/// # Errors
/// * If writing to the file fails
fn write_commit_header(
    commit_file: &mut File,
    commit_type: &str,
    no_commit_number: bool,
) -> Result<()> {
    let branch_name = format_branch_name(&COMMIT_TYPES, &get_current_branch()?);

    if no_commit_number {
        writeln!(commit_file, "({commit_type} on {branch_name})\n\n")?;
    } else {
        let commit_number = get_current_commit_nb()? + 1;
        writeln!(
            commit_file,
            "[{commit_number}] ({commit_type} on {branch_name})\n\n"
        )?;
    }

    Ok(())
}

/// Checks if a file should be ignored based on ignored patterns.
///
/// # Arguments
/// * `file` - The file to check
/// * `ignore_patterns` - Patterns to check against
///
/// # Errors
/// * If checking file paths fails
///
/// # Returns
/// * `true` if the file should be ignored, `false` otherwise
fn should_ignore_file(file: &str, ignore_patterns: &[String]) -> Result<bool> {
    use crate::utils::check_for_file_in_folder;

    // Check if the file is directly in the ignore list
    if ignore_patterns.contains(&file.to_string()) {
        return Ok(true);
    }

    // Check if the file is in a folder that's in the ignore list
    let file_path = Path::new(file);

    for item in ignore_patterns {
        let item_path = Path::new(item);

        if check_for_file_in_folder(file_path, item_path)? {
            return Ok(true);
        }
    }

    Ok(false)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Mutex;
    use tempfile::TempDir;

    // Tests that call set_current_dir must serialize — it is process-global state.
    static DIR_MUTEX: Mutex<()> = Mutex::new(());

    /// Initializes a minimal git repo in `path` suitable for making real commits.
    #[cfg(unix)]
    fn init_git_repo(
        path: &std::path::Path,
    ) -> std::result::Result<(), Box<dyn std::error::Error>> {
        for args in [
            vec!["init"],
            vec!["config", "user.email", "test@example.com"],
            vec!["config", "user.name", "Test"],
        ] {
            Command::new("git").current_dir(path).args(&args).output()?;
        }
        Ok(())
    }

    #[test]
    fn test_gpg_signing_available() {
        // Verifies the function does not panic; result depends on system config.
        let _result = is_gpg_signing_available();
    }

    #[test]
    fn test_git_commit_dry_run_with_unsigned() -> std::result::Result<(), Box<dyn std::error::Error>>
    {
        let _guard = DIR_MUTEX.lock().map_err(|e| e.to_string())?;

        let temp_dir = TempDir::new()?;
        let temp_path = temp_dir.path();

        Command::new("git")
            .current_dir(temp_path)
            .arg("init")
            .output()?;

        let commit_msg = "[1] (test on main)\n\n- `test.txt`:\n\n\t\n";
        write(temp_path.join("commit_message.md"), commit_msg)?;

        let original_dir = std::env::current_dir()?;
        std::env::set_current_dir(temp_path)?;

        let result = git_commit(&[], true, true);

        std::env::set_current_dir(original_dir)?;

        assert!(result.is_ok());
        Ok(())
    }

    /// Verifies that a `pre-commit` hook is triggered when `git_commit` runs.
    ///
    /// The hook writes a marker file. If it fires, the file exists after the commit.
    /// This test would have been impossible with git2 (which bypasses all hooks).
    #[test]
    #[cfg(unix)]
    fn test_pre_commit_hook_fires() -> std::result::Result<(), Box<dyn std::error::Error>> {
        use std::os::unix::fs::PermissionsExt;

        let _guard = DIR_MUTEX.lock().map_err(|e| e.to_string())?;

        let temp_dir = TempDir::new()?;
        let temp_path = temp_dir.path();

        init_git_repo(temp_path)?;

        // Stage a file so the commit has something to record.
        write(temp_path.join("test.txt"), "hello")?;
        Command::new("git")
            .current_dir(temp_path)
            .args(["add", "test.txt"])
            .output()?;

        // Install a pre-commit hook that writes a marker file.
        let hooks_dir = temp_path.join(".git/hooks");
        std::fs::create_dir_all(&hooks_dir)?;
        let hook_path = hooks_dir.join("pre-commit");
        write(&hook_path, "#!/bin/sh\ntouch HOOK_FIRED\n")?;
        let mut perms = std::fs::metadata(&hook_path)?.permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&hook_path, perms)?;

        write(
            temp_path.join("commit_message.md"),
            "(test on main)\n\n- `test.txt`:\n\n\t\n",
        )?;

        let original_dir = std::env::current_dir()?;
        std::env::set_current_dir(temp_path)?;

        let result = git_commit(&[], true, false);

        std::env::set_current_dir(&original_dir)?;

        assert!(result.is_ok(), "commit failed: {result:?}");
        assert!(
            temp_path.join("HOOK_FIRED").exists(),
            "pre-commit hook did not fire"
        );
        Ok(())
    }

    /// Verifies that a failing `pre-commit` hook prevents the commit.
    ///
    /// A hook that exits non-zero must cause `git_commit` to return an error.
    #[test]
    #[cfg(unix)]
    fn test_pre_commit_hook_blocks_commit() -> std::result::Result<(), Box<dyn std::error::Error>> {
        use std::os::unix::fs::PermissionsExt;

        let _guard = DIR_MUTEX.lock().map_err(|e| e.to_string())?;

        let temp_dir = TempDir::new()?;
        let temp_path = temp_dir.path();

        init_git_repo(temp_path)?;

        write(temp_path.join("test.txt"), "hello")?;
        Command::new("git")
            .current_dir(temp_path)
            .args(["add", "test.txt"])
            .output()?;

        // Install a pre-commit hook that always rejects the commit.
        let hooks_dir = temp_path.join(".git/hooks");
        std::fs::create_dir_all(&hooks_dir)?;
        let hook_path = hooks_dir.join("pre-commit");
        write(&hook_path, "#!/bin/sh\nexit 1\n")?;
        let mut perms = std::fs::metadata(&hook_path)?.permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&hook_path, perms)?;

        write(
            temp_path.join("commit_message.md"),
            "(test on main)\n\n- `test.txt`:\n\n\t\n",
        )?;

        let original_dir = std::env::current_dir()?;
        std::env::set_current_dir(temp_path)?;

        let result = git_commit(&[], true, false);

        std::env::set_current_dir(&original_dir)?;

        assert!(
            result.is_err(),
            "commit should have been blocked by the pre-commit hook"
        );
        Ok(())
    }
}