rona 2.23.1

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
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
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
//! Template Processing Module for Rona
//!
//! This module handles template parsing and variable substitution for commit messages.
//! It provides a flexible templating system that allows users to customize how their
//! commit messages are formatted using variables.

use chrono::Local;
use regex::Regex;
use std::{collections::HashMap, hash::BuildHasher};

use crate::errors::{Result, RonaError};

/// Template variables that can be used in commit message templates
#[derive(Debug, Clone)]
pub struct TemplateVariables {
    pub commit_number: Option<u32>,
    pub commit_type: String,
    pub branch_name: String,
    pub message: String,
    pub date: String,
    pub time: String,
    pub author: String,
    pub email: String,
}

impl TemplateVariables {
    /// Creates a new `TemplateVariables` instance with current date/time and git info
    ///
    /// # Errors
    /// * If git author information cannot be retrieved
    pub fn new(
        commit_number: Option<u32>,
        commit_type: String,
        branch_name: String,
        message: String,
    ) -> Result<Self> {
        let (date, time) = {
            let now = Local::now();

            (
                now.format("%Y-%m-%d").to_string(),
                now.format("%H:%M:%S").to_string(),
            )
        };

        let (author, email) = get_git_author_info()?;

        Ok(Self {
            commit_number,
            commit_type,
            branch_name,
            message,
            date,
            time,
            author,
            email,
        })
    }

    /// Converts the variables to a `HashMap` for template substitution
    #[must_use]
    pub fn to_map(&self) -> HashMap<String, String> {
        let mut map = HashMap::new();

        map.insert("commit_type".to_string(), self.commit_type.clone());
        map.insert("branch_name".to_string(), self.branch_name.clone());
        map.insert("message".to_string(), self.message.clone());
        map.insert("date".to_string(), self.date.clone());
        map.insert("time".to_string(), self.time.clone());
        map.insert("author".to_string(), self.author.clone());
        map.insert("email".to_string(), self.email.clone());

        if let Some(commit_number) = self.commit_number {
            map.insert("commit_number".to_string(), commit_number.to_string());
        } else {
            map.insert("commit_number".to_string(), String::new());
        }

        map
    }
}

/// Branch-specific template variables for branch name generation.
#[derive(Debug, Clone)]
pub struct BranchTemplateVariables {
    pub branch_type: String,
    pub description: String,
    pub date: String,
    pub time: String,
    pub author: String,
}

impl BranchTemplateVariables {
    /// Creates a new `BranchTemplateVariables` with current date/time and git author.
    ///
    /// # Errors
    /// * If git author information cannot be retrieved
    pub fn new(branch_type: String, description: String) -> Result<Self> {
        let now = chrono::Local::now();
        let date = now.format("%Y-%m-%d").to_string();
        let time = now.format("%H:%M:%S").to_string();
        let (author, _email) = get_git_author_info()?;
        Ok(Self {
            branch_type,
            description,
            date,
            time,
            author,
        })
    }

    /// Converts the variables to a `HashMap` for template substitution.
    #[must_use]
    pub fn to_map(&self) -> HashMap<String, String> {
        let mut map = HashMap::new();
        map.insert("branch_type".to_string(), self.branch_type.clone());
        map.insert("description".to_string(), self.description.clone());
        map.insert("date".to_string(), self.date.clone());
        map.insert("time".to_string(), self.time.clone());
        map.insert("author".to_string(), self.author.clone());
        map
    }
}

/// Processes conditional blocks in a template string using a pre-merged variable map.
fn process_conditional_blocks_from_map(
    template: &str,
    variable_map: &HashMap<String, String>,
) -> Result<String> {
    let mut result = template.to_string();

    // Regex to find opening conditional tags: {?variable_name}
    let open_regex = Regex::new(r"\{\?(\w+)\}").map_err(|e| {
        RonaError::Io(std::io::Error::other(format!(
            "Invalid conditional regex: {e}"
        )))
    })?;

    // Process conditional blocks iteratively
    while let Some(open_match) = open_regex.find(&result) {
        let open_start = open_match.start();
        let open_end = open_match.end();

        // Extract variable name from the opening tag
        if let Some(captures) = open_regex.captures(&result[open_start..open_end]) {
            let Some(cap) = captures.get(1) else {
                break;
            };
            let var_name = cap.as_str();

            // Look for the matching closing tag {/variable_name}
            let close_pattern = format!("{{/{var_name}}}");
            if let Some(close_pos) = result[open_end..].find(&close_pattern) {
                let close_start = open_end + close_pos;
                let close_end = close_start + close_pattern.len();

                // Extract the content between opening and closing tags
                let content = &result[open_end..close_start];

                // Check if variable has a non-empty value
                let has_value = variable_map.get(var_name).is_some_and(|v| !v.is_empty());

                // Replace the entire block
                let replacement = if has_value { content } else { "" };
                let full_block = &result[open_start..close_end];
                result = result.replace(full_block, replacement);
            } else {
                return Err(RonaError::Io(std::io::Error::other(format!(
                    "Unclosed conditional block: {{?{var_name}}}"
                ))));
            }
        }
    }

    Ok(result)
}

/// Core template substitution from a pre-merged variable map.
fn process_template_from_map(
    template: &str,
    variable_map: &HashMap<String, String>,
) -> Result<String> {
    let after_conditionals = process_conditional_blocks_from_map(template, variable_map)?;

    let regex = Regex::new(r"\{([^}]+)\}").map_err(|e| {
        RonaError::Io(std::io::Error::other(format!(
            "Invalid template regex: {e}"
        )))
    })?;

    let mut result = after_conditionals.clone();

    for capture in regex.captures_iter(&after_conditionals) {
        if let Some(variable_name) = capture.get(1) {
            let var_name = variable_name.as_str();
            let empty_string = String::new();
            let value = variable_map.get(var_name).unwrap_or(&empty_string);
            result = result.replace(&capture[0], value);
        }
    }

    Ok(result)
}

/// Processes a template string by substituting variables with their values.
///
/// # Errors
/// * If the template contains invalid variable syntax or mismatched conditional blocks
pub fn process_template<S: BuildHasher>(
    template: &str,
    variables: &TemplateVariables,
    extra_variables: &HashMap<String, String, S>,
) -> Result<String> {
    let mut variable_map = variables.to_map();
    variable_map.extend(extra_variables.iter().map(|(k, v)| (k.clone(), v.clone())));
    process_template_from_map(template, &variable_map)
}

/// Processes a branch name template using `BranchTemplateVariables` and optional extra fields.
///
/// Available built-in variables: `branch_type`, `description`, `date`, `time`, `author`.
///
/// # Errors
/// * If the template contains invalid variable syntax or mismatched conditional blocks
pub fn process_branch_template<S: BuildHasher>(
    template: &str,
    variables: &BranchTemplateVariables,
    extra_variables: &HashMap<String, String, S>,
) -> Result<String> {
    let mut variable_map = variables.to_map();
    variable_map.extend(extra_variables.iter().map(|(k, v)| (k.clone(), v.clone())));
    process_template_from_map(template, &variable_map)
}

/// Validates a template string against a provided set of valid variable names.
///
/// # Errors
/// * If the template contains unknown variables or mismatched conditional blocks
fn validate_template_with_vars(template: &str, valid_variables: &[&str]) -> Result<()> {
    // First, validate conditional blocks are properly matched
    let conditional_regex = Regex::new(r"\{\?(\w+)\}").map_err(|e| {
        RonaError::Io(std::io::Error::other(format!(
            "Invalid conditional regex: {e}"
        )))
    })?;

    let closing_regex = Regex::new(r"\{/(\w+)\}")
        .map_err(|e| RonaError::Io(std::io::Error::other(format!("Invalid closing regex: {e}"))))?;

    // Collect all opening and closing tags
    let open_tags: Vec<(usize, &str)> = conditional_regex
        .captures_iter(template)
        .filter_map(|cap| {
            let pos = cap.get(0)?.start();
            let name = cap.get(1)?.as_str();
            Some((pos, name))
        })
        .collect();

    let mut close_tags: Vec<(usize, &str)> = closing_regex
        .captures_iter(template)
        .filter_map(|cap| {
            let pos = cap.get(0)?.start();
            let name = cap.get(1)?.as_str();
            Some((pos, name))
        })
        .collect();

    // Check that each opening tag has a matching closing tag
    for (open_pos, open_name) in &open_tags {
        let matching_close = close_tags
            .iter()
            .position(|(close_pos, close_name)| close_pos > open_pos && close_name == open_name);

        let Some(matching_close_idx) = matching_close else {
            return Err(RonaError::Io(std::io::Error::other(format!(
                "Unclosed conditional block: {{?{open_name}}}"
            ))));
        };

        // Validate that the variable in the conditional block is valid
        if !valid_variables.contains(open_name) {
            return Err(RonaError::Io(std::io::Error::other(format!(
                "Unknown variable in conditional block: {{?{open_name}}}. Valid variables are: {}",
                valid_variables.join(", ")
            ))));
        }

        close_tags.remove(matching_close_idx);
    }

    // Check for unmatched closing tags
    if !close_tags.is_empty() {
        let (_, unmatched_name) = close_tags[0];
        return Err(RonaError::Io(std::io::Error::other(format!(
            "Unmatched closing tag: {{/{unmatched_name}}}"
        ))));
    }

    // Now validate regular variables (excluding conditional syntax)
    let regex = Regex::new(r"\{([^}?/]+)\}").map_err(|e| {
        RonaError::Io(std::io::Error::other(format!(
            "Invalid template regex: {e}"
        )))
    })?;

    for capture in regex.captures_iter(template) {
        if let Some(variable_name) = capture.get(1) {
            let var_name = variable_name.as_str();
            // Skip if it's part of a conditional block syntax
            if var_name.starts_with('?') || var_name.starts_with('/') {
                continue;
            }
            if !valid_variables.contains(&var_name) {
                return Err(RonaError::Io(std::io::Error::other(format!(
                    "Unknown template variable: {{{var_name}}}. Valid variables are: {}",
                    valid_variables.join(", ")
                ))));
            }
        }
    }

    Ok(())
}

/// Validates a commit message template string.
///
/// Valid built-in variables: `commit_number`, `commit_type`, `branch_name`, `message`,
/// `date`, `time`, `author`, `email`. Extra field names are also accepted.
///
/// # Errors
/// * If the template contains unknown variables or mismatched conditional blocks
pub fn validate_template(template: &str, extra_variable_names: &[&str]) -> Result<()> {
    let mut valid: Vec<&str> = vec![
        "commit_number",
        "commit_type",
        "branch_name",
        "message",
        "date",
        "time",
        "author",
        "email",
    ];
    valid.extend_from_slice(extra_variable_names);
    validate_template_with_vars(template, &valid)
}

/// Validates a branch name template string.
///
/// Valid built-in variables: `branch_type`, `description`, `date`, `time`, `author`.
/// Extra field names are also accepted.
///
/// # Errors
/// * If the template contains unknown variables or mismatched conditional blocks
pub fn validate_branch_template(template: &str, extra_variable_names: &[&str]) -> Result<()> {
    let mut valid: Vec<&str> = vec!["branch_type", "description", "date", "time", "author"];
    valid.extend_from_slice(extra_variable_names);
    validate_template_with_vars(template, &valid)
}

/// Gets the current git author name and email from git config.
fn get_git_author_info() -> Result<(String, String)> {
    use std::process::Command;

    let name_output = Command::new("git")
        .args(["config", "--get", "user.name"])
        .output()
        .map_err(RonaError::Io)?;
    let name = if name_output.status.success() {
        String::from_utf8_lossy(&name_output.stdout)
            .trim()
            .to_string()
    } else {
        String::new()
    };

    let email_output = Command::new("git")
        .args(["config", "--get", "user.email"])
        .output()
        .map_err(RonaError::Io)?;
    let email = if email_output.status.success() {
        String::from_utf8_lossy(&email_output.stdout)
            .trim()
            .to_string()
    } else {
        String::new()
    };

    Ok((name, email))
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use super::*;

    #[test]
    fn test_template_processing() -> std::result::Result<(), Box<dyn std::error::Error>> {
        let template = "[{commit_number}] ({commit_type} on {branch_name}) {message}";
        let variables = TemplateVariables {
            commit_number: Some(42),
            commit_type: "feat".to_string(),
            branch_name: "feature/new-feature".to_string(),
            message: "Add new functionality".to_string(),
            date: "2024-01-15".to_string(),
            time: "14:30:00".to_string(),
            author: "John Doe".to_string(),
            email: "john@example.com".to_string(),
        };

        let result = process_template(template, &variables, &HashMap::new())?;
        assert_eq!(
            result,
            "[42] (feat on feature/new-feature) Add new functionality"
        );

        Ok(())
    }

    #[test]
    fn test_template_without_commit_number() -> std::result::Result<(), Box<dyn std::error::Error>>
    {
        let template = "({commit_type} on {branch_name}) {message}";
        let variables = TemplateVariables {
            commit_number: None,
            commit_type: "fix".to_string(),
            branch_name: "main".to_string(),
            message: "Fix bug".to_string(),
            date: "2024-01-15".to_string(),
            time: "14:30:00".to_string(),
            author: "John Doe".to_string(),
            email: "john@example.com".to_string(),
        };

        let result = process_template(template, &variables, &HashMap::new())?;
        assert_eq!(result, "(fix on main) Fix bug");

        Ok(())
    }

    #[test]
    fn test_template_validation_valid() {
        let template = "[{commit_number}] ({commit_type} on {branch_name}) {message}";
        assert!(validate_template(template, &[]).is_ok());
    }

    #[test]
    fn test_template_validation_invalid() {
        let template = "[{commit_number}] ({invalid_var} on {branch_name}) {message}";
        assert!(validate_template(template, &[]).is_err());
    }

    #[test]
    fn test_template_variables_to_map() -> std::result::Result<(), Box<dyn std::error::Error>> {
        let variables = TemplateVariables {
            commit_number: Some(42),
            commit_type: "feat".to_string(),
            branch_name: "feature/test".to_string(),
            message: "Test message".to_string(),
            date: "2024-01-15".to_string(),
            time: "14:30:00".to_string(),
            author: "Test Author".to_string(),
            email: "test@example.com".to_string(),
        };

        let map = variables.to_map();
        assert_eq!(
            map.get("commit_number").ok_or("commit_number not found")?,
            "42"
        );
        assert_eq!(
            map.get("commit_type").ok_or("commit_type not found")?,
            "feat"
        );
        assert_eq!(
            map.get("branch_name").ok_or("branch_name not found")?,
            "feature/test"
        );
        assert_eq!(
            map.get("message").ok_or("message not found")?,
            "Test message"
        );
        assert_eq!(map.get("date").ok_or("date not found")?, "2024-01-15");
        assert_eq!(map.get("time").ok_or("time not found")?, "14:30:00");
        assert_eq!(map.get("author").ok_or("author not found")?, "Test Author");
        assert_eq!(
            map.get("email").ok_or("email not found")?,
            "test@example.com"
        );

        Ok(())
    }

    #[test]
    fn test_template_with_all_variables() -> std::result::Result<(), Box<dyn std::error::Error>> {
        let template = "{commit_type}: {message} by {author} <{email}> on {branch_name} at {date} {time} (#{commit_number})";
        let variables = TemplateVariables {
            commit_number: Some(123),
            commit_type: "fix".to_string(),
            branch_name: "hotfix/critical-bug".to_string(),
            message: "Fix critical authentication bug".to_string(),
            date: "2024-01-15".to_string(),
            time: "14:30:00".to_string(),
            author: "Jane Doe".to_string(),
            email: "jane@company.com".to_string(),
        };

        let result = process_template(template, &variables, &HashMap::new())?;
        assert_eq!(
            result,
            "fix: Fix critical authentication bug by Jane Doe <jane@company.com> on hotfix/critical-bug at 2024-01-15 14:30:00 (#123)"
        );

        Ok(())
    }

    #[test]
    fn test_template_with_special_chars() -> std::result::Result<(), Box<dyn std::error::Error>> {
        let template = "* {commit_type}: {message}";
        let variables = TemplateVariables {
            commit_number: None,
            commit_type: "feat".to_string(),
            branch_name: "feature/new-feature".to_string(),
            message: "Add new feature".to_string(),
            date: "2024-01-15".to_string(),
            time: "14:30:00".to_string(),
            author: "John Doe".to_string(),
            email: "john@example.com".to_string(),
        };

        let result = process_template(template, &variables, &HashMap::new())?;
        assert_eq!(result, "* feat: Add new feature");

        Ok(())
    }

    #[test]
    fn test_template_without_commit_number_variable()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let template = "({commit_type} on {branch_name}) {message}";
        let variables = TemplateVariables {
            commit_number: None,
            commit_type: "docs".to_string(),
            branch_name: "main".to_string(),
            message: "Update documentation".to_string(),
            date: "2024-01-15".to_string(),
            time: "14:30:00".to_string(),
            author: "John Doe".to_string(),
            email: "john@example.com".to_string(),
        };

        let result = process_template(template, &variables, &HashMap::new())?;
        assert_eq!(result, "(docs on main) Update documentation");

        Ok(())
    }

    #[test]
    fn test_template_validation_with_unknown_variable()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let template = "[{commit_number}] ({unknown_var} on {branch_name}) {message}";
        let result = validate_template(template, &[]);
        assert!(result.is_err());
        let Err(e) = result else {
            return Err("Expected error".into());
        };
        assert!(e.to_string().contains("Unknown template variable"));

        Ok(())
    }

    /// REGRESSION TEST: This test would have caught the bug where using the default template
    /// with `no_commit_number` flag would produce empty brackets "[]"
    #[test]
    fn test_default_template_with_none_commit_number_produces_empty_brackets()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        // This is the BUG - using default template with None commit_number
        let template = "[{commit_number}] ({commit_type} on {branch_name}) {message}";
        let variables = TemplateVariables {
            commit_number: None,
            commit_type: "docs".to_string(),
            branch_name: "main".to_string(),
            message: "Update docs".to_string(),
            date: "2024-01-15".to_string(),
            time: "14:30:00".to_string(),
            author: "John Doe".to_string(),
            email: "john@example.com".to_string(),
        };

        let result = process_template(template, &variables, &HashMap::new())?;

        // This demonstrates the bug: empty brackets appear
        assert_eq!(result, "[] (docs on main) Update docs");

        // The output should NOT contain empty brackets
        assert!(
            result.contains("[]"),
            "This test documents the bug: empty brackets appear when commit_number is None"
        );

        Ok(())
    }

    /// REGRESSION TEST: Verify that using the correct template avoids empty brackets
    #[test]
    fn test_template_without_commit_number_placeholder_avoids_empty_brackets()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        // This is the FIX - use appropriate template without commit_number placeholder
        let template = "({commit_type} on {branch_name}) {message}";
        let variables = TemplateVariables {
            commit_number: None,
            commit_type: "docs".to_string(),
            branch_name: "main".to_string(),
            message: "Update docs".to_string(),
            date: "2024-01-15".to_string(),
            time: "14:30:00".to_string(),
            author: "John Doe".to_string(),
            email: "john@example.com".to_string(),
        };

        let result = process_template(template, &variables, &HashMap::new())?;

        // Correct output without empty brackets
        assert_eq!(result, "(docs on main) Update docs");

        // Verify no empty brackets
        assert!(
            !result.contains("[]"),
            "Output should not contain empty brackets"
        );
        assert!(
            !result.contains("[{"),
            "Output should not contain unprocessed template variables"
        );

        Ok(())
    }

    /// REGRESSION TEST: Test multiple scenarios with None `commit_number`
    #[test]
    fn test_various_templates_with_none_commit_number()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let variables = TemplateVariables {
            commit_number: None,
            commit_type: "feat".to_string(),
            branch_name: "new-feature".to_string(),
            message: "Add feature".to_string(),
            date: "2024-01-15".to_string(),
            time: "14:30:00".to_string(),
            author: "Jane Doe".to_string(),
            email: "jane@example.com".to_string(),
        };

        // Test template WITH commit_number placeholder (produces empty brackets - the bug)
        let template_with = "[{commit_number}] {commit_type}: {message}";
        let result_with = process_template(template_with, &variables, &HashMap::new())?;
        assert!(
            result_with.starts_with("[]"),
            "Bug: produces empty brackets"
        );

        // Test template WITHOUT commit_number placeholder (correct)
        let template_without = "{commit_type}: {message}";
        let result_without = process_template(template_without, &variables, &HashMap::new())?;
        assert_eq!(result_without, "feat: Add feature");
        assert!(
            !result_without.contains("[]"),
            "Should not contain empty brackets"
        );

        // Test template with optional-style syntax (shows limitation of current implementation)
        let template_prefix = "#{commit_number} {commit_type}: {message}";
        let result_prefix = process_template(template_prefix, &variables, &HashMap::new())?;
        assert_eq!(
            result_prefix, "# feat: Add feature",
            "Empty string for None values"
        );

        Ok(())
    }

    /// REGRESSION TEST: Verify `commit_number` `to_map` behavior
    #[test]
    fn test_variables_to_map_with_none_commit_number()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let variables = TemplateVariables {
            commit_number: None,
            commit_type: "test".to_string(),
            branch_name: "testing".to_string(),
            message: "Test message".to_string(),
            date: "2024-01-15".to_string(),
            time: "14:30:00".to_string(),
            author: "Test User".to_string(),
            email: "test@example.com".to_string(),
        };

        let map = variables.to_map();

        // When commit_number is None, it should map to empty string
        assert_eq!(
            map.get("commit_number").ok_or("commit_number not found")?,
            ""
        );
        assert_eq!(
            map.get("commit_type").ok_or("commit_type not found")?,
            "test"
        );

        // This empty string is what causes the bug when used in "[{commit_number}]"

        Ok(())
    }

    // CONDITIONAL BLOCK TESTS

    #[test]
    fn test_conditional_block_with_value() -> std::result::Result<(), Box<dyn std::error::Error>> {
        let template = "{?commit_number}[{commit_number}] {/commit_number}({commit_type} on {branch_name}) {message}";
        let variables = TemplateVariables {
            commit_number: Some(42),
            commit_type: "feat".to_string(),
            branch_name: "new-feature".to_string(),
            message: "Add feature".to_string(),
            date: "2024-01-15".to_string(),
            time: "14:30:00".to_string(),
            author: "John Doe".to_string(),
            email: "john@example.com".to_string(),
        };

        let result = process_template(template, &variables, &HashMap::new())?;
        assert_eq!(result, "[42] (feat on new-feature) Add feature");

        Ok(())
    }

    #[test]
    fn test_conditional_block_without_value() -> std::result::Result<(), Box<dyn std::error::Error>>
    {
        let template = "{?commit_number}[{commit_number}] {/commit_number}({commit_type} on {branch_name}) {message}";
        let variables = TemplateVariables {
            commit_number: None,
            commit_type: "feat".to_string(),
            branch_name: "new-feature".to_string(),
            message: "Add feature".to_string(),
            date: "2024-01-15".to_string(),
            time: "14:30:00".to_string(),
            author: "John Doe".to_string(),
            email: "john@example.com".to_string(),
        };

        let result = process_template(template, &variables, &HashMap::new())?;
        // The conditional block should be completely removed, including the space after it
        assert_eq!(result, "(feat on new-feature) Add feature");
        // Verify no empty brackets
        assert!(!result.contains("[]"));

        Ok(())
    }

    #[test]
    fn test_multiple_conditional_blocks() -> std::result::Result<(), Box<dyn std::error::Error>> {
        let template = "{?commit_number}[{commit_number}]{/commit_number} {?date}on {date}{/date} ({commit_type}) {message}";
        let variables = TemplateVariables {
            commit_number: Some(5),
            commit_type: "fix".to_string(),
            branch_name: "bugfix".to_string(),
            message: "Fix bug".to_string(),
            date: "2024-01-15".to_string(),
            time: "14:30:00".to_string(),
            author: "Jane Doe".to_string(),
            email: "jane@example.com".to_string(),
        };

        let result = process_template(template, &variables, &HashMap::new())?;
        assert_eq!(result, "[5] on 2024-01-15 (fix) Fix bug");

        Ok(())
    }

    #[test]
    fn test_multiple_conditional_blocks_partial()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let template = "{?commit_number}[{commit_number}]{/commit_number} {?author}by {author}{/author} - {message}";
        let variables = TemplateVariables {
            commit_number: None,
            commit_type: "docs".to_string(),
            branch_name: "docs".to_string(),
            message: "Update docs".to_string(),
            date: "2024-01-15".to_string(),
            time: "14:30:00".to_string(),
            author: "Alice".to_string(),
            email: "alice@example.com".to_string(),
        };

        let result = process_template(template, &variables, &HashMap::new())?;
        // commit_number is None, so first block removed; author has value, so second block kept
        assert_eq!(result, " by Alice - Update docs");

        Ok(())
    }

    #[test]
    fn test_conditional_block_with_static_text()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let template = "{?commit_number}Commit #{commit_number}: {/commit_number}{message}";
        let variables = TemplateVariables {
            commit_number: Some(100),
            commit_type: "chore".to_string(),
            branch_name: "main".to_string(),
            message: "Update dependencies".to_string(),
            date: "2024-01-15".to_string(),
            time: "14:30:00".to_string(),
            author: "Bob".to_string(),
            email: "bob@example.com".to_string(),
        };

        let result = process_template(template, &variables, &HashMap::new())?;
        assert_eq!(result, "Commit #100: Update dependencies");

        Ok(())
    }

    #[test]
    fn test_conditional_block_validation_valid() {
        let template =
            "{?commit_number}[{commit_number}] {/commit_number}({commit_type}) {message}";
        assert!(validate_template(template, &[]).is_ok());
    }

    #[test]
    fn test_conditional_block_validation_unclosed()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let template = "{?commit_number}[{commit_number}] ({commit_type}) {message}";
        let result = validate_template(template, &[]);
        assert!(result.is_err());
        let Err(e) = result else {
            return Err("Expected error".into());
        };
        assert!(e.to_string().contains("Unclosed conditional block"));

        Ok(())
    }

    #[test]
    fn test_conditional_block_validation_unmatched_closing()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let template = "[{commit_number}] {/commit_number}({commit_type}) {message}";
        let result = validate_template(template, &[]);
        assert!(result.is_err());
        let Err(e) = result else {
            return Err("Expected error".into());
        };
        assert!(e.to_string().contains("Unmatched closing tag"));

        Ok(())
    }

    #[test]
    fn test_conditional_block_validation_invalid_variable()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let template = "{?invalid_var}[{invalid_var}]{/invalid_var} {message}";
        let result = validate_template(template, &[]);
        assert!(result.is_err());
        let Err(e) = result else {
            return Err("Expected error".into());
        };
        assert!(
            e.to_string()
                .contains("Unknown variable in conditional block")
        );

        Ok(())
    }

    #[test]
    fn test_conditional_block_empty_string_variable()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        // Test that empty string is treated as "no value"
        let template = "{?commit_number}[{commit_number}] {/commit_number}{message}";
        let variables = TemplateVariables {
            commit_number: None,
            commit_type: "test".to_string(),
            branch_name: "test".to_string(),
            message: "Test".to_string(),
            date: "2024-01-15".to_string(),
            time: "14:30:00".to_string(),
            author: "Tester".to_string(),
            email: "test@example.com".to_string(),
        };

        let result = process_template(template, &variables, &HashMap::new())?;
        assert_eq!(result, "Test");
        assert!(!result.contains("[]"));

        Ok(())
    }

    #[test]
    fn test_original_bug_fix() -> std::result::Result<(), Box<dyn std::error::Error>> {
        // This is the original problem: using -n flag should not produce empty brackets
        let template = "{?commit_number}[{commit_number}] {/commit_number}({commit_type} on {branch_name}) {message}";

        // Scenario 1: With commit number (normal flow)
        let with_number = TemplateVariables {
            commit_number: Some(42),
            commit_type: "feat".to_string(),
            branch_name: "new-feature".to_string(),
            message: "Add feature".to_string(),
            date: "2024-01-15".to_string(),
            time: "14:30:00".to_string(),
            author: "Dev".to_string(),
            email: "dev@example.com".to_string(),
        };

        let result_with = process_template(template, &with_number, &HashMap::new())?;
        assert_eq!(result_with, "[42] (feat on new-feature) Add feature");

        // Scenario 2: Without commit number (-n flag)
        let without_number = TemplateVariables {
            commit_number: None,
            commit_type: "feat".to_string(),
            branch_name: "new-feature".to_string(),
            message: "Add feature".to_string(),
            date: "2024-01-15".to_string(),
            time: "14:30:00".to_string(),
            author: "Dev".to_string(),
            email: "dev@example.com".to_string(),
        };

        let result_without = process_template(template, &without_number, &HashMap::new())?;
        assert_eq!(result_without, "(feat on new-feature) Add feature");
        // CRITICAL: No empty brackets!
        assert!(!result_without.contains("[]"));
        assert!(!result_without.starts_with("[]"));

        Ok(())
    }
}