rona 2.2.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
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
//! Command Line Interface (CLI) Module for Rona
//!
//! This module handles all command-line interface functionality for Rona, including
//! - Command parsing and execution
//! - Subcommand implementations
//! - CLI argument handling
//!
//! # Commands
//!
//! The CLI supports several commands:
//! - `add-with-exclude`: Add files to git while excluding specified patterns
//! - `commit`: Commit changes using the commit message from `commit_message.md`
//! - `generate`: Generate a new commit message file
//! - `init`: Initialize Rona configuration
//! - `list-status`: List git status files (for shell completion)
//! - `push`: Push changes to remote repository
//! - `set-editor`: Configure the editor for commit messages
//!
//! # Features
//!
//! - Supports verbose mode for detailed operation logging
//! - Integrates with git commands
//! - Provides shell completion capabilities
//! - Handles configuration management
//!

use crate::{
    config::Config,
    git_related::{
        COMMIT_MESSAGE_FILE_PATH, COMMIT_TYPES, create_needed_files, generate_commit_message,
        get_status_files, git_add_with_exclude_patterns, git_commit, git_push,
    },
    my_clap_theme,
};
use clap::{Parser, Subcommand, command};
use dialoguer::Select;
use glob::Pattern;
use std::process::Command;

/// CLI's commands
#[derive(Subcommand)]
enum Commands {
    /// Add all files to the `git add` command and exclude the patterns passed as positional arguments.
    #[command(short_flag = 'a', name = "add-with-exclude")]
    AddWithExclude {
        /// Patterns of files to exclude (supports glob patterns like `"node_modules/*"`)
        #[arg(value_name = "PATTERNS")]
        exclude: Vec<String>,
    },

    /// Directly commit the file with the text in `commit_message.md`.
    #[command(short_flag = 'c')]
    Commit {
        /// Whether to push the commit after committing
        #[arg(short = 'p', long = "push", default_value_t = false)]
        push: bool,

        /// Additionnal arguments to pass to the commit command
        #[arg(allow_hyphen_values = true)]
        args: Vec<String>,
    },

    /// Directly generate the `commit_message.md` file.
    #[command(short_flag = 'g')]
    Generate,

    /// Initialize the rona configuration file.
    #[command(short_flag = 'i', name = "init")]
    Initialize {
        /// Editor to use for the commit message.
        #[arg(default_value_t = String::from("nano"))]
        editor: String,
    },

    /// List files from git status (for shell completion on the -a)
    #[command(short_flag = 'l')]
    ListStatus,

    /// Push to a git repository.
    #[command(short_flag = 'p')]
    Push {
        /// Additionnal arguments to pass to the push command
        #[arg(allow_hyphen_values = true)]
        args: Vec<String>,
    },

    /// Set the editor to use for editing the commit message.
    #[command(short_flag = 's', name = "set-editor")]
    Set {
        /// The editor to use for the commit message
        #[arg(value_name = "EDITOR")]
        editor: String,
    },
}

#[derive(Parser)]
#[command(about = "Simple program that can:\n\
\t- Commit with the current 'commit_message.md' file text.\n\
\t- Generate the 'commit_message.md' file.\n\
\t- Push to git repository.\n\
\t- Push to git repository.")]
#[command(author = "Tom Planche <tomplanche@proton.me>")]
#[command(help_template = "{about}\nMade by: {author}\n\nUSAGE:\n{usage}\n\n{all-args}\n")]
#[command(name = "rona")]
pub struct Cli {
    /// Commands
    #[command(subcommand)]
    command: Commands,

    /// Verbose
    /// Optional 'verbose' argument. Only works if a subcommand is passed.
    /// If passed, it will print more information about the operation.
    #[arg(short, long, default_value = "false")]
    verbose: bool,
}

/// Runs the program.
///
/// # Panics
/// * If the given glob patterns are invalid.
///
/// # Errors
/// * Return an error if the command fails.
pub fn run() -> Result<(), Box<dyn std::error::Error>> {
    let cli = Cli::parse();

    let config = Config::new()?;

    match cli.command {
        Commands::AddWithExclude { exclude } => {
            let patterns: Vec<Pattern> = exclude
                .iter()
                .map(|p| Pattern::new(p).expect("Invalid glob pattern"))
                .collect();

            git_add_with_exclude_patterns(&patterns, cli.verbose)?;
        }
        Commands::Commit { args, push } => {
            git_commit(&args, cli.verbose)?;

            if push {
                git_push(&Vec::new(), cli.verbose)?;
            }
        }
        Commands::ListStatus => {
            let files = get_status_files()?;

            // Print each file on a new line for fish shell completion
            for file in files {
                println!("{file}");
            }
        }
        Commands::Generate => {
            create_needed_files()?;

            let commit_type =
                COMMIT_TYPES[Select::with_theme(&my_clap_theme::ColorfulTheme::default())
                    .default(0)
                    .items(&COMMIT_TYPES)
                    .interact()
                    .unwrap()];

            generate_commit_message(commit_type, cli.verbose)?;

            let editor = config.get_editor()?;

            Command::new(editor)
                .arg(COMMIT_MESSAGE_FILE_PATH)
                .spawn()
                .expect("Failed to spawn editor")
                .wait()
                .expect("Failed to wait for editor");
        }
        Commands::Initialize { editor } => {
            config.create_config_file(&editor)?;
        }
        Commands::Push { args } => {
            git_push(&args, cli.verbose)?;
        }
        Commands::Set { editor } => {
            config.set_editor(&editor)?;
        }
    }

    Ok(())
}

#[cfg(test)]
mod cli_tests {
    use super::*;
    use clap::Parser;

    // === ADD COMMAND TESTS ===

    #[test]
    fn test_add_basic() {
        let args = vec!["rona", "-a"];
        let cli = Cli::try_parse_from(args).unwrap();

        match cli.command {
            Commands::AddWithExclude { exclude } => {
                assert!(exclude.is_empty());
            }
            _ => panic!("Wrong command parsed"),
        }
    }

    #[test]
    fn test_add_single_pattern() {
        let args = vec!["rona", "-a", "*.txt"];
        let cli = Cli::try_parse_from(args).unwrap();

        match cli.command {
            Commands::AddWithExclude { exclude } => {
                assert_eq!(exclude, vec!["*.txt"]);
            }
            _ => panic!("Wrong command parsed"),
        }
    }

    #[test]
    fn test_add_multiple_patterns() {
        let args = vec!["rona", "-a", "*.txt", "*.log", "target/*"];
        let cli = Cli::try_parse_from(args).unwrap();

        match cli.command {
            Commands::AddWithExclude { exclude } => {
                assert_eq!(exclude, vec!["*.txt", "*.log", "target/*"]);
            }
            _ => panic!("Wrong command parsed"),
        }
    }

    #[test]
    fn test_add_with_long_name() {
        let args = vec!["rona", "add-with-exclude", "*.txt"];
        let cli = Cli::try_parse_from(args).unwrap();

        match cli.command {
            Commands::AddWithExclude { exclude } => {
                assert_eq!(exclude, vec!["*.txt"]);
            }
            _ => panic!("Wrong command parsed"),
        }
    }

    // === COMMIT COMMAND TESTS ===

    #[test]
    fn test_commit_basic() {
        let args = vec!["rona", "-c"];
        let cli = Cli::try_parse_from(args).unwrap();

        match cli.command {
            Commands::Commit { args, push } => {
                assert!(!push);
                assert!(args.is_empty());
            }
            _ => panic!("Wrong command parsed"),
        }
    }

    #[test]
    fn test_commit_with_push_flag() {
        let args = vec!["rona", "-c", "--push"];
        let cli = Cli::try_parse_from(args).unwrap();

        match cli.command {
            Commands::Commit { args, push } => {
                assert!(push);
                assert!(args.is_empty());
            }
            _ => panic!("Wrong command parsed"),
        }
    }

    #[test]
    fn test_commit_with_message() {
        let args = vec!["rona", "-c", "Regular commit message"];
        let cli = Cli::try_parse_from(args).unwrap();

        match cli.command {
            Commands::Commit { args, push } => {
                assert!(!push);
                assert_eq!(args, vec!["Regular commit message"]);
            }
            _ => panic!("Wrong command parsed"),
        }
    }

    #[test]
    fn test_commit_with_git_flag() {
        let args = vec!["rona", "-c", "--amend"];
        let cli = Cli::try_parse_from(args).unwrap();

        match cli.command {
            Commands::Commit { args, push } => {
                assert!(!push);
                assert_eq!(args, vec!["--amend"]);
            }
            _ => panic!("Wrong command parsed"),
        }
    }

    #[test]
    fn test_commit_with_multiple_git_flags() {
        let args = vec!["rona", "-c", "--amend", "--no-edit"];
        let cli = Cli::try_parse_from(args).unwrap();

        match cli.command {
            Commands::Commit { args, push } => {
                assert!(!push);
                assert_eq!(args, vec!["--amend", "--no-edit"]);
            }
            _ => panic!("Wrong command parsed"),
        }
    }

    #[test]
    fn test_commit_with_push_and_git_flags() {
        let args = vec!["rona", "-c", "--push", "--amend", "--no-edit"];
        let cli = Cli::try_parse_from(args).unwrap();

        match cli.command {
            Commands::Commit { args, push } => {
                assert!(push);
                assert_eq!(args, vec!["--amend", "--no-edit"]);
            }
            _ => panic!("Wrong command parsed"),
        }
    }

    #[test]
    fn test_commit_with_message_and_push() {
        let args = vec!["rona", "-c", "--push", "Commit message"];
        let cli = Cli::try_parse_from(args).unwrap();

        match cli.command {
            Commands::Commit { args, push } => {
                assert!(push);
                assert_eq!(args, vec!["Commit message"]);
            }
            _ => panic!("Wrong command parsed"),
        }
    }

    // === PUSH COMMAND TESTS ===

    #[test]
    fn test_push_basic() {
        let args = vec!["rona", "-p"];
        let cli = Cli::try_parse_from(args).unwrap();

        match cli.command {
            Commands::Push { args } => {
                assert!(args.is_empty());
            }
            _ => panic!("Wrong command parsed"),
        }
    }

    #[test]
    fn test_push_with_force() {
        let args = vec!["rona", "-p", "--force"];
        let cli = Cli::try_parse_from(args).unwrap();

        match cli.command {
            Commands::Push { args } => {
                assert_eq!(args, vec!["--force"]);
            }
            _ => panic!("Wrong command parsed"),
        }
    }

    #[test]
    fn test_push_with_multiple_args() {
        let args = vec!["rona", "-p", "--force", "--set-upstream", "origin", "main"];
        let cli = Cli::try_parse_from(args).unwrap();

        match cli.command {
            Commands::Push { args } => {
                assert_eq!(args, vec!["--force", "--set-upstream", "origin", "main"]);
            }
            _ => panic!("Wrong command parsed"),
        }
    }

    #[test]
    fn test_push_with_remote_and_branch() {
        let args = vec!["rona", "-p", "origin", "feature/branch"];
        let cli = Cli::try_parse_from(args).unwrap();

        match cli.command {
            Commands::Push { args } => {
                assert_eq!(args, vec!["origin", "feature/branch"]);
            }
            _ => panic!("Wrong command parsed"),
        }
    }

    #[test]
    fn test_push_with_upstream_tracking() {
        let args = vec!["rona", "-p", "-u", "origin", "main"];
        let cli = Cli::try_parse_from(args).unwrap();

        match cli.command {
            Commands::Push { args } => {
                assert_eq!(args, vec!["-u", "origin", "main"]);
            }
            _ => panic!("Wrong command parsed"),
        }
    }

    // === GENERATE COMMAND TESTS ===

    #[test]
    fn test_generate_command() {
        let args = vec!["rona", "-g"];
        let cli = Cli::try_parse_from(args).unwrap();

        match cli.command {
            Commands::Generate => (),
            _ => panic!("Wrong command parsed"),
        }
    }

    // === LIST STATUS COMMAND TESTS ===

    #[test]
    fn test_list_status_command() {
        let args = vec!["rona", "-l"];
        let cli = Cli::try_parse_from(args).unwrap();

        match cli.command {
            Commands::ListStatus => (),
            _ => panic!("Wrong command parsed"),
        }
    }

    // === INITIALIZE COMMAND TESTS ===

    #[test]
    fn test_init_default_editor() {
        let args = vec!["rona", "-i"];
        let cli = Cli::try_parse_from(args).unwrap();

        match cli.command {
            Commands::Initialize { editor } => {
                assert_eq!(editor, "nano");
            }
            _ => panic!("Wrong command parsed"),
        }
    }

    #[test]
    fn test_init_custom_editor() {
        let args = vec!["rona", "-i", "zed"];
        let cli = Cli::try_parse_from(args).unwrap();

        match cli.command {
            Commands::Initialize { editor } => {
                assert_eq!(editor, "zed");
            }
            _ => panic!("Wrong command parsed"),
        }
    }

    // === SET EDITOR COMMAND TESTS ===

    #[test]
    fn test_set_editor() {
        let args = vec!["rona", "-s", "vim"];
        let cli = Cli::try_parse_from(args).unwrap();

        match cli.command {
            Commands::Set { editor } => {
                assert_eq!(editor, "vim");
            }
            _ => panic!("Wrong command parsed"),
        }
    }

    #[test]
    fn test_set_editor_with_spaces() {
        let args = vec!["rona", "-s", "\"Visual Studio Code\""];
        let cli = Cli::try_parse_from(args).unwrap();

        match cli.command {
            Commands::Set { editor } => {
                assert_eq!(editor, "\"Visual Studio Code\"");
            }
            _ => panic!("Wrong command parsed"),
        }
    }

    #[test]
    fn test_set_editor_with_path() {
        let args = vec!["rona", "-s", "/usr/bin/vim"];
        let cli = Cli::try_parse_from(args).unwrap();

        match cli.command {
            Commands::Set { editor } => {
                assert_eq!(editor, "/usr/bin/vim");
            }
            _ => panic!("Wrong command parsed"),
        }
    }

    // === VERBOSE FLAG TESTS ===

    #[test]
    fn test_verbose_with_commit() {
        let args = vec!["rona", "-v", "-c"];
        let cli = Cli::try_parse_from(args).unwrap();
        assert!(cli.verbose);
    }

    #[test]
    fn test_verbose_with_push() {
        let args = vec!["rona", "-v", "-p"];
        let cli = Cli::try_parse_from(args).unwrap();
        assert!(cli.verbose);
    }

    #[test]
    fn test_verbose_long_form() {
        let args = vec!["rona", "--verbose", "-c"];
        let cli = Cli::try_parse_from(args).unwrap();
        assert!(cli.verbose);
    }

    // === EDGE CASES AND ERROR TESTS ===

    #[test]
    fn test_commit_flag_order_sensitivity() {
        let args = vec!["rona", "-c", "--amend", "--push"];
        let cli = Cli::try_parse_from(args).unwrap();

        match cli.command {
            Commands::Commit { args, push } => {
                assert!(!push); // --push should be treated as git arg
                assert_eq!(args, vec!["--amend", "--push"]);
            }
            _ => panic!("Wrong command parsed"),
        }
    }

    #[test]
    fn test_commit_with_similar_looking_args() {
        let args = vec!["rona", "-c", "--push-to-upstream"];
        let cli = Cli::try_parse_from(args).unwrap();

        match cli.command {
            Commands::Commit { args, push } => {
                assert!(!push);
                assert_eq!(args, vec!["--push-to-upstream"]);
            }
            _ => panic!("Wrong command parsed"),
        }
    }

    #[test]
    fn test_invalid_command() {
        let args = vec!["rona", "--invalid"];
        assert!(Cli::try_parse_from(args).is_err());
    }

    #[test]
    fn test_missing_required_value() {
        let args = vec!["rona", "-s"]; // missing editor value
        assert!(Cli::try_parse_from(args).is_err());
    }

    #[test]
    fn test_complex_command_combination() {
        let args = vec!["rona", "-v", "-c", "--push", "--amend", "--no-edit"];
        let cli = Cli::try_parse_from(args).unwrap();

        assert!(cli.verbose);
        match cli.command {
            Commands::Commit { args, push } => {
                assert!(push);
                assert_eq!(args, vec!["--amend", "--no-edit"]);
            }
            _ => panic!("Wrong command parsed"),
        }
    }
}