ggen-core 26.6.11

Core graph-aware code generation engine
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
//! Frozen section preservation during regeneration
//!
//! This module provides functionality for preserving user-modified code sections
//! during template regeneration using `{% frozen %}` tags. This allows users to
//! customize generated code while still benefiting from template updates.
//!
//! ## Features
//!
//! - **Frozen Tag Parsing**: Parses `{% frozen %}` and `{% endfrozen %}` tags
//! - **Section Identification**: Supports named sections with `id` attribute
//! - **Content Preservation**: Preserves user code during regeneration
//! - **Merge Support**: Merges preserved sections into regenerated content
//! - **Tag Stripping**: Removes frozen tags while preserving content
//!
//! ## Frozen Section Syntax
//!
//! ### Basic Frozen Section
//!
//! ```text
//! {% frozen %}
//! // User's custom code here
//! // This will be preserved during regeneration
//! {% endfrozen %}
//! ```
//!
//! ### Named Frozen Section
//!
//! ```text
//! {% frozen id="custom_logic" %}
//! // User's custom implementation
//! // Can be referenced by ID during merge
//! {% endfrozen %}
//! ```
//!
//! ## Use Cases
//!
//! - **Business Logic**: Preserve custom business logic implementations
//! - **Configuration**: Keep user-specific configuration values
//! - **Custom Functions**: Maintain user-added helper functions
//! - **Integration Code**: Preserve integration with other systems
//!
//! ## Examples
//!
//! ### Parsing Frozen Sections
//!
//! ```rust,no_run
//! use crate::templates::frozen::FrozenParser;
//!
//! # fn main() -> crate::utils::error::Result<()> {
//! let content = r#"
//! // Generated code
//! {% frozen id="custom" %}
//! fn my_custom_function() {
//!     println!("Custom logic");
//! }
//! {% endfrozen %}
//! // More generated code
//! "#;
//!
//! let sections = FrozenParser::parse_frozen_tags(content)?;
//! assert_eq!(sections.len(), 1);
//! assert_eq!(sections[0].id, Some("custom".to_string()));
//! # Ok(())
//! # }
//! ```
//!
//! ### Merging Frozen Sections
//!
//! ```rust,no_run
//! use crate::templates::frozen::FrozenMerger;
//!
//! # fn main() -> crate::utils::error::Result<()> {
//! let old_content = r#"
//! {% frozen id="logic" %}
//! // User's preserved code
//! {% endfrozen %}
//! "#;
//!
//! let new_content = r#"
//! {% frozen id="logic" %}
//! // New generated code (will be replaced)
//! {% endfrozen %}
//! "#;
//!
//! let merged = FrozenMerger::merge_with_frozen(old_content, new_content)?;
//! // merged contains "User's preserved code", not "New generated code"
//! # Ok(())
//! # }
//! ```

use crate::utils::error::{Error, Result};
use regex::Regex;

/// Represents a frozen section in a template
///
/// A frozen section is a region of code that should be preserved during
/// template regeneration. Users can mark sections with `{% frozen %}` tags
/// to prevent them from being overwritten.
///
/// # Examples
///
/// ```rust,no_run
/// use crate::templates::frozen::{FrozenSection, FrozenParser};
///
/// # fn main() -> crate::utils::error::Result<()> {
/// let content = r#"
/// {% frozen id="custom" %}
/// fn my_function() {
///     println!("Custom code");
/// }
/// {% endfrozen %}
/// "#;
///
/// let sections = FrozenParser::parse_frozen_tags(content)?;
/// let section = &sections[0];
/// assert_eq!(section.id, Some("custom".to_string()));
/// assert!(section.content.contains("my_function"));
/// # Ok(())
/// # }
/// ```
/// PartialEq without Eq: All fields (usize, String, Option) implement Eq
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FrozenSection {
    /// Start position in the content
    pub start: usize,
    /// End position in the content
    pub end: usize,
    /// Content of the frozen section
    pub content: String,
    /// Optional identifier for the frozen section
    pub id: Option<String>,
}

/// Parser for frozen section tags in templates
///
/// Parses `{% frozen %}` and `{% endfrozen %}` tags from template content
/// and extracts the sections for preservation during regeneration.
///
/// # Examples
///
/// ```rust,no_run
/// use crate::templates::frozen::FrozenParser;
///
/// # fn main() -> crate::utils::error::Result<()> {
/// let content = r#"
/// {% frozen %}
/// preserved code
/// {% endfrozen %}
/// "#;
///
/// let sections = FrozenParser::parse_frozen_tags(content)?;
/// assert_eq!(sections.len(), 1);
/// # Ok(())
/// # }
/// ```
pub struct FrozenParser;

impl FrozenParser {
    /// Parse frozen sections from template content
    ///
    /// Looks for patterns like:
    /// ```text
    /// {% frozen %}
    /// user code here
    /// {% endfrozen %}
    /// ```
    ///
    /// Or with identifiers:
    /// ```text
    /// {% frozen id="custom_logic" %}
    /// user code here
    /// {% endfrozen %}
    /// ```
    ///
    /// # Arguments
    ///
    /// * `template_content` - The template content to parse
    ///
    /// # Returns
    ///
    /// A vector of `FrozenSection` structs representing all frozen sections found.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - A frozen tag is not properly closed
    /// - The regex pattern fails to compile
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use crate::templates::frozen::FrozenParser;
    ///
    /// # fn main() -> crate::utils::error::Result<()> {
    /// let content = r#"
    /// {% frozen id="logic" %}
    /// fn custom_logic() {}
    /// {% endfrozen %}
    /// "#;
    ///
    /// let sections = FrozenParser::parse_frozen_tags(content)?;
    /// assert_eq!(sections.len(), 1);
    /// assert_eq!(sections[0].id, Some("logic".to_string()));
    /// # Ok(())
    /// # }
    /// ```
    pub fn parse_frozen_tags(template_content: &str) -> Result<Vec<FrozenSection>> {
        let mut sections = Vec::new();

        // Regex to match {% frozen %} or {% frozen id="..." %}
        let start_regex = Regex::new(r#"\{%\s*frozen(?:\s+id\s*=\s*"([^"]+)")?\s*%\}"#)
            .map_err(|e| Error::new(&format!("Invalid frozen tag regex: {}", e)))?;

        let end_regex = Regex::new(r"\{%\s*endfrozen\s*%\}")
            .map_err(|e| Error::new(&format!("Invalid endfrozen tag regex: {}", e)))?;

        // Find all start tags
        for start_match in start_regex.captures_iter(template_content) {
            let full_match = start_match
                .get(0)
                .ok_or_else(|| Error::new("Regex matched but group 0 is missing"))?;
            let start_pos = full_match.end();
            let id = start_match.get(1).map(|m| m.as_str().to_string());

            // Find corresponding end tag
            if let Some(end_match) = end_regex.find_at(template_content, start_pos) {
                let end_pos = end_match.start();
                let content = template_content[start_pos..end_pos].to_string();

                sections.push(FrozenSection {
                    start: full_match.start(),
                    end: end_match.end(),
                    content,
                    id,
                });
            } else {
                return Err(Error::new(&format!(
                    "Unclosed frozen tag at position {}",
                    full_match.start()
                )));
            }
        }

        Ok(sections)
    }

    /// Extract frozen sections indexed by ID or position
    ///
    /// Parses frozen sections and returns a map where keys are section IDs
    /// (or generated position-based keys like "section_0") and values are
    /// the section content.
    ///
    /// # Arguments
    ///
    /// * `content` - The template content to parse
    ///
    /// # Returns
    ///
    /// A `HashMap` mapping section identifiers to their content.
    ///
    /// # Errors
    ///
    /// Returns an error if parsing fails (see `parse_frozen_tags()`).
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use crate::templates::frozen::FrozenParser;
    ///
    /// # fn main() -> crate::utils::error::Result<()> {
    /// let content = r#"
    /// {% frozen id="custom" %}
    /// preserved code
    /// {% endfrozen %}
    /// "#;
    ///
    /// let map = FrozenParser::extract_frozen_map(content)?;
    /// assert_eq!(map.get("custom"), Some(&"preserved code\n".to_string()));
    /// # Ok(())
    /// # }
    /// ```
    pub fn extract_frozen_map(content: &str) -> Result<std::collections::HashMap<String, String>> {
        let sections = Self::parse_frozen_tags(content)?;
        let mut map = std::collections::HashMap::new();

        for (index, section) in sections.iter().enumerate() {
            let key = section
                .id
                .clone()
                .unwrap_or_else(|| format!("section_{}", index));
            map.insert(key, section.content.clone());
        }

        Ok(map)
    }
}

/// Merger for frozen sections during regeneration
///
/// Merges preserved frozen sections from old content into newly generated content,
/// ensuring user modifications are not lost during template regeneration.
///
/// # Examples
///
/// ```rust,no_run
/// use crate::templates::frozen::FrozenMerger;
///
/// # fn main() -> crate::utils::error::Result<()> {
/// let old = r#"{% frozen id="custom" %}old code{% endfrozen %}"#;
/// let new = r#"{% frozen id="custom" %}new code{% endfrozen %}"#;
/// let merged = FrozenMerger::merge_with_frozen(old, new)?;
/// assert!(merged.contains("old code"));
/// # Ok(())
/// # }
/// ```
pub struct FrozenMerger;

impl FrozenMerger {
    /// Merge frozen sections from old content into new content
    ///
    /// Extracts frozen sections from `old_content` and replaces corresponding
    /// sections in `new_content` with the preserved content. Sections are
    /// matched by ID if present, or by position if no ID is specified.
    ///
    /// # Arguments
    ///
    /// * `old_content` - The existing file content with frozen sections to preserve
    /// * `new_content` - The newly generated content with frozen placeholders
    ///
    /// # Returns
    ///
    /// Merged content with preserved frozen sections from old content.
    ///
    /// # Errors
    ///
    /// Returns an error if parsing fails or if section matching fails.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use crate::templates::frozen::FrozenMerger;
    ///
    /// # fn main() -> crate::utils::error::Result<()> {
    /// let old_content = r#"
    /// {% frozen id="logic" %}
    /// fn my_custom_function() {
    ///     println!("User's code");
    /// }
    /// {% endfrozen %}
    /// "#;
    ///
    /// let new_content = r#"
    /// {% frozen id="logic" %}
    /// // Generated placeholder
    /// {% endfrozen %}
    /// "#;
    ///
    /// let merged = FrozenMerger::merge_with_frozen(old_content, new_content)?;
    /// assert!(merged.contains("my_custom_function"));
    /// assert!(merged.contains("User's code"));
    /// # Ok(())
    /// # }
    /// ```
    pub fn merge_with_frozen(old_content: &str, new_content: &str) -> Result<String> {
        // Extract frozen sections from old content
        let old_sections = FrozenParser::extract_frozen_map(old_content)?;

        if old_sections.is_empty() {
            // No frozen sections to preserve
            return Ok(new_content.to_string());
        }

        // Replace frozen sections in new content
        let mut result = new_content.to_string();

        // Regex to match frozen tags in new content
        let frozen_regex = Regex::new(
            r#"(?s)\{%\s*frozen(?:\s+id\s*=\s*"([^"]+)")?\s*%\}.*?\{%\s*endfrozen\s*%\}"#,
        )
        .map_err(|e| Error::new(&format!("Invalid frozen merge regex: {}", e)))?;

        let mut section_index = 0;
        result = frozen_regex
            .replace_all(&result, |caps: &regex::Captures| {
                let id = caps
                    .get(1)
                    .map(|m| m.as_str().to_string())
                    .unwrap_or_else(|| {
                        let idx = section_index;
                        section_index += 1;
                        format!("section_{}", idx)
                    });

                // Get preserved content or keep new content
                if let Some(preserved_content) = old_sections.get(&id) {
                    let mut result = String::from("{%");
                    if let Some(id_match) = caps.get(1) {
                        // With ID
                        result.push_str(" frozen id=\"");
                        result.push_str(id_match.as_str());
                        result.push_str("\" %");
                    } else {
                        // Without ID
                        result.push_str(" frozen %");
                    }
                    result.push('}');
                    result.push_str(preserved_content);
                    result.push_str("{%");
                    result.push_str(" endfrozen %");
                    result.push('}');
                    result
                } else {
                    // Keep new content if no preserved version exists
                    caps.get(0)
                        .map(|m| m.as_str().to_string())
                        .unwrap_or_default()
                }
            })
            .to_string();

        Ok(result)
    }

    /// Check if content contains frozen sections
    ///
    /// Performs a simple string check to determine if the content contains
    /// any frozen section tags. This is faster than parsing but less precise.
    ///
    /// # Arguments
    ///
    /// * `content` - The content to check
    ///
    /// # Returns
    ///
    /// `true` if the content contains `{% frozen` tags, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use crate::templates::frozen::FrozenMerger;
    ///
    /// assert!(FrozenMerger::has_frozen_sections("{% frozen %}code{% endfrozen %}"));
    /// assert!(!FrozenMerger::has_frozen_sections("regular code"));
    /// ```
    pub fn has_frozen_sections(content: &str) -> bool {
        content.contains("{% frozen")
    }

    /// Remove all frozen tags but keep content
    ///
    /// Strips `{% frozen %}` and `{% endfrozen %}` tags from content while
    /// preserving the actual content within frozen sections. Useful for
    /// extracting user code without the template markers.
    ///
    /// # Arguments
    ///
    /// * `content` - The content to strip tags from
    ///
    /// # Returns
    ///
    /// Content with frozen tags removed but section content preserved.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use crate::templates::frozen::FrozenMerger;
    ///
    /// let content = r#"
    /// {% frozen id="test" %}
    /// preserved code
    /// {% endfrozen %}
    /// "#;
    ///
    /// let stripped = FrozenMerger::strip_frozen_tags(content);
    /// assert!(!stripped.contains("{% frozen"));
    /// assert!(stripped.contains("preserved code"));
    /// ```
    #[allow(clippy::panic)] // SAFETY: compile-time constant regex literals — invalid syntax is a programmer error
    pub fn strip_frozen_tags(content: &str) -> String {
        // SAFETY: These regex literals are compile-time constants with valid syntax.
        // Failure here means the literal was edited incorrectly — a programmer
        // error that must surface immediately, not be swallowed.
        let start_regex = Regex::new(r#"\{%\s*frozen(?:\s+id\s*=\s*"[^"]+")?\s*%\}"#)
            .unwrap_or_else(|e| panic!("invariant violated: frozen start regex is invalid: {e}"));
        let end_regex = Regex::new(r"\{%\s*endfrozen\s*%\}")
            .unwrap_or_else(|e| panic!("invariant violated: frozen end regex is invalid: {e}"));

        let content = start_regex.replace_all(content, "");
        end_regex.replace_all(&content, "").to_string()
    }
}

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

    #[test]
    fn test_parse_simple_frozen_section() {
        let content = r#"
Before frozen
{% frozen %}
user custom code
{% endfrozen %}
After frozen
"#;

        let sections = FrozenParser::parse_frozen_tags(content).unwrap();
        assert_eq!(sections.len(), 1);
        assert!(sections[0].content.contains("user custom code"));
        assert_eq!(sections[0].id, None);
    }

    #[test]
    fn test_parse_frozen_section_with_id() {
        let content = r#"
{% frozen id="custom_logic" %}
my implementation
{% endfrozen %}
"#;

        let sections = FrozenParser::parse_frozen_tags(content).unwrap();
        assert_eq!(sections.len(), 1);
        assert!(sections[0].content.contains("my implementation"));
        assert_eq!(sections[0].id, Some("custom_logic".to_string()));
    }

    #[test]
    fn test_parse_multiple_frozen_sections() {
        let content = r#"
{% frozen id="section1" %}
code 1
{% endfrozen %}

some content

{% frozen id="section2" %}
code 2
{% endfrozen %}
"#;

        let sections = FrozenParser::parse_frozen_tags(content).unwrap();
        assert_eq!(sections.len(), 2);
        assert_eq!(sections[0].id, Some("section1".to_string()));
        assert_eq!(sections[1].id, Some("section2".to_string()));
    }

    #[test]
    fn test_parse_unclosed_frozen_tag() {
        let content = r#"
{% frozen %}
unclosed section
"#;

        let result = FrozenParser::parse_frozen_tags(content);
        assert!(result.is_err());
    }

    #[test]
    fn test_extract_frozen_map() {
        let content = r#"
{% frozen id="logic" %}
preserved code
{% endfrozen %}
"#;

        let map = FrozenParser::extract_frozen_map(content).unwrap();
        assert_eq!(map.len(), 1);
        assert!(map.get("logic").unwrap().contains("preserved code"));
    }

    #[test]
    fn test_merge_with_frozen() {
        let old_content = r#"
{% frozen id="custom" %}
old user code
{% endfrozen %}
"#;

        let new_content = r#"
{% frozen id="custom" %}
new generated code
{% endfrozen %}
"#;

        let merged = FrozenMerger::merge_with_frozen(old_content, new_content).unwrap();
        assert!(merged.contains("old user code"));
        assert!(!merged.contains("new generated code"));
    }

    #[test]
    fn test_merge_without_frozen_sections() {
        let old_content = "no frozen sections";
        let new_content = "new content";

        let merged = FrozenMerger::merge_with_frozen(old_content, new_content).unwrap();
        assert_eq!(merged, "new content");
    }

    #[test]
    fn test_has_frozen_sections() {
        assert!(FrozenMerger::has_frozen_sections(
            "{% frozen %}code{% endfrozen %}"
        ));
        assert!(!FrozenMerger::has_frozen_sections("no frozen sections"));
    }

    #[test]
    fn test_strip_frozen_tags() {
        let content = r#"
Before
{% frozen id="test" %}
keep this content
{% endfrozen %}
After
"#;

        let stripped = FrozenMerger::strip_frozen_tags(content);
        assert!(!stripped.contains("{% frozen"));
        assert!(!stripped.contains("{% endfrozen %}"));
        assert!(stripped.contains("keep this content"));
    }

    #[test]
    fn test_merge_numbered_sections() {
        let old_content = r#"
{% frozen %}
first section
{% endfrozen %}
{% frozen %}
second section
{% endfrozen %}
"#;

        let new_content = r#"
{% frozen %}
new first
{% endfrozen %}
{% frozen %}
new second
{% endfrozen %}
"#;

        let merged = FrozenMerger::merge_with_frozen(old_content, new_content).unwrap();
        assert!(merged.contains("first section"));
        assert!(merged.contains("second section"));
        assert!(!merged.contains("new first"));
        assert!(!merged.contains("new second"));
    }
}