ricecoder-storage 0.1.71

Storage and configuration management for RiceCoder
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
//! Markdown parser for extracting YAML frontmatter and content

use crate::markdown_config::error::{MarkdownConfigError, MarkdownConfigResult};
use crate::markdown_config::types::ParsedMarkdown;
use std::path::Path;

/// Parser for markdown files with YAML frontmatter
#[derive(Debug, Clone)]
pub struct MarkdownParser;

impl MarkdownParser {
    /// Create a new markdown parser
    pub fn new() -> Self {
        Self
    }

    /// Parse markdown content and extract frontmatter and body
    ///
    /// Expects frontmatter to be delimited by `---` at the start of the file.
    /// Format:
    /// ```text
    /// ---
    /// yaml: frontmatter
    /// ---
    /// # Markdown content
    /// ```
    pub fn parse(&self, content: &str) -> MarkdownConfigResult<ParsedMarkdown> {
        self.parse_with_context(content, None)
    }

    /// Parse markdown content with file path context for better error messages
    pub fn parse_with_context(
        &self,
        content: &str,
        file_path: Option<&Path>,
    ) -> MarkdownConfigResult<ParsedMarkdown> {
        let trimmed = content.trim();

        // Check if content starts with frontmatter delimiter
        if !trimmed.starts_with("---") {
            // No frontmatter, entire content is body
            return Ok(ParsedMarkdown::new(None, content.to_string()));
        }

        // Find the closing delimiter
        let rest = &trimmed[3..]; // Skip opening "---"
        let closing_delimiter_pos = rest.find("---");

        match closing_delimiter_pos {
            Some(pos) => {
                // Extract frontmatter and body
                let frontmatter = rest[..pos].trim().to_string();
                let body_start = pos + 3; // Skip closing "---"
                let body = rest[body_start..].trim().to_string();

                // Validate that frontmatter is not empty
                if frontmatter.is_empty() {
                    let msg = match file_path {
                        Some(path) => format!(
                            "Frontmatter cannot be empty in {}",
                            path.display()
                        ),
                        None => "Frontmatter cannot be empty".to_string(),
                    };
                    return Err(MarkdownConfigError::parse_error(msg));
                }

                Ok(ParsedMarkdown::new(Some(frontmatter), body))
            }
            None => {
                // Opening delimiter found but no closing delimiter
                let msg = match file_path {
                    Some(path) => format!(
                        "Unclosed frontmatter in {}: found opening '---' but no closing '---'",
                        path.display()
                    ),
                    None => "Unclosed frontmatter: found opening '---' but no closing '---'"
                        .to_string(),
                };
                Err(MarkdownConfigError::parse_error(msg))
            }
        }
    }

}

impl Default for MarkdownParser {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_parse_with_frontmatter() {
        let parser = MarkdownParser::new();
        let content = r#"---
name: test-agent
description: A test agent
---
# Test Content
This is the body"#;

        let result = parser.parse(content).unwrap();
        assert_eq!(
            result.frontmatter,
            Some("name: test-agent\ndescription: A test agent".to_string())
        );
        assert_eq!(result.content, "# Test Content\nThis is the body");
    }

    #[test]
    fn test_parse_without_frontmatter() {
        let parser = MarkdownParser::new();
        let content = "# Test Content\nThis is the body";

        let result = parser.parse(content).unwrap();
        assert_eq!(result.frontmatter, None);
        assert_eq!(result.content, "# Test Content\nThis is the body");
    }

    #[test]
    fn test_parse_empty_frontmatter() {
        let parser = MarkdownParser::new();
        let content = r#"---
---
# Test Content"#;

        let result = parser.parse(content);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_unclosed_frontmatter() {
        let parser = MarkdownParser::new();
        let content = r#"---
name: test
# Test Content"#;

        let result = parser.parse(content);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_with_whitespace() {
        let parser = MarkdownParser::new();
        let content = r#"  ---
name: test
  ---
  # Content"#;

        let result = parser.parse(content).unwrap();
        assert_eq!(result.frontmatter, Some("name: test".to_string()));
        assert_eq!(result.content, "# Content");
    }

    #[test]
    fn test_parse_multiline_frontmatter() {
        let parser = MarkdownParser::new();
        let content = r#"---
name: test-agent
description: A test agent
model: gpt-4
temperature: 0.7
---
# Test Content"#;

        let result = parser.parse(content).unwrap();
        assert!(result.frontmatter.is_some());
        let fm = result.frontmatter.unwrap();
        assert!(fm.contains("name: test-agent"));
        assert!(fm.contains("model: gpt-4"));
    }

    #[test]
    fn test_parse_empty_body() {
        let parser = MarkdownParser::new();
        let content = r#"---
name: test
---"#;

        let result = parser.parse(content).unwrap();
        assert_eq!(result.frontmatter, Some("name: test".to_string()));
        assert_eq!(result.content, "");
    }

    #[test]
    fn test_parse_complex_yaml_frontmatter() {
        let parser = MarkdownParser::new();
        let content = r#"---
name: complex-agent
description: Complex agent
model: gpt-4
temperature: 0.7
max_tokens: 2000
tools:
  - tool1
  - tool2
---
# Complex Content
With multiple lines
And formatting"#;

        let result = parser.parse(content).unwrap();
        assert!(result.frontmatter.is_some());
        let fm = result.frontmatter.unwrap();
        assert!(fm.contains("tools:"));
        assert!(fm.contains("- tool1"));
    }

    #[test]
    fn test_parse_frontmatter_with_special_characters() {
        let parser = MarkdownParser::new();
        let content = r#"---
name: test-agent
description: "Agent with special chars: @#$%^&*()"
---
Content"#;

        let result = parser.parse(content).unwrap();
        assert!(result.frontmatter.is_some());
        assert!(result.frontmatter.unwrap().contains("@#$%^&*()"));
    }

    #[test]
    fn test_parse_frontmatter_with_quotes() {
        let parser = MarkdownParser::new();
        let content = r#"---
name: "test-agent"
description: 'Single quoted'
---
Content"#;

        let result = parser.parse(content).unwrap();
        assert!(result.frontmatter.is_some());
    }

    #[test]
    fn test_parse_body_with_code_blocks() {
        let parser = MarkdownParser::new();
        let content = r#"---
name: test
---
# Content

```rust
fn main() {
    println!("Hello");
}
```

More content"#;

        let result = parser.parse(content).unwrap();
        assert!(result.content.contains("```rust"));
        assert!(result.content.contains("fn main()"));
    }

    #[test]
    fn test_parse_body_with_frontmatter_like_content() {
        let parser = MarkdownParser::new();
        let content = r#"---
name: test
---
# Content

This mentions --- but it's in the body
So it should be fine"#;

        let result = parser.parse(content).unwrap();
        assert!(result.content.contains("---"));
    }

    #[test]
    fn test_parse_with_context_error_message() {
        let parser = MarkdownParser::new();
        let content = r#"---
---
Content"#;
        let path = Path::new("test.agent.md");

        let result = parser.parse_with_context(content, Some(path));
        assert!(result.is_err());
        let error_msg = result.unwrap_err().to_string();
        assert!(error_msg.contains("test.agent.md"));
    }

    #[test]
    fn test_parse_consistency() {
        let parser = MarkdownParser::new();
        let content = r#"---
name: test-agent
description: Test
---
Body content"#;

        let result1 = parser.parse(content).unwrap();
        let result2 = parser.parse(content).unwrap();

        assert_eq!(result1, result2);
    }

    #[test]
    fn test_parse_only_frontmatter_delimiter() {
        let parser = MarkdownParser::new();
        let content = "---";

        // Single "---" is treated as opening delimiter with no closing
        let result = parser.parse(content);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_multiple_delimiters_in_body() {
        let parser = MarkdownParser::new();
        let content = r#"---
name: test
---
First section
---
Second section
---
Third section"#;

        let result = parser.parse(content).unwrap();
        assert_eq!(result.frontmatter, Some("name: test".to_string()));
        assert!(result.content.contains("First section"));
        assert!(result.content.contains("Second section"));
        assert!(result.content.contains("Third section"));
    }

    #[test]
    fn test_parse_very_long_frontmatter() {
        let parser = MarkdownParser::new();
        let mut frontmatter = String::from("---\n");
        for i in 0..100 {
            frontmatter.push_str(&format!("field{}: value{}\n", i, i));
        }
        frontmatter.push_str("---\nBody");

        let result = parser.parse(&frontmatter).unwrap();
        assert!(result.frontmatter.is_some());
        assert!(result.frontmatter.unwrap().contains("field99"));
    }

    #[test]
    fn test_parse_very_long_body() {
        let parser = MarkdownParser::new();
        let mut body = String::from("# Content\n");
        for i in 0..1000 {
            body.push_str(&format!("Line {}\n", i));
        }
        let content = format!("---\nname: test\n---\n{}", body);

        let result = parser.parse(&content).unwrap();
        assert!(result.content.contains("Line 999"));
    }

    #[test]
    fn test_parse_unicode_content() {
        let parser = MarkdownParser::new();
        let content = r#"---
name: 测试代理
description: 日本語のテスト
---
# 内容
Ελληνικά
العربية"#;

        let result = parser.parse(content).unwrap();
        assert!(result.frontmatter.unwrap().contains("测试代理"));
        assert!(result.content.contains("Ελληνικά"));
    }

    #[test]
    fn test_parse_windows_line_endings() {
        let parser = MarkdownParser::new();
        let content = "---\r\nname: test\r\n---\r\nBody";

        let result = parser.parse(content).unwrap();
        assert!(result.frontmatter.is_some());
    }

    #[test]
    fn test_parse_mixed_line_endings() {
        let parser = MarkdownParser::new();
        let content = "---\nname: test\r\n---\nBody";

        let result = parser.parse(content).unwrap();
        assert!(result.frontmatter.is_some());
    }

    #[test]
    fn test_parse_tabs_in_frontmatter() {
        let parser = MarkdownParser::new();
        let content = "---\nname:\ttest\n---\nBody";

        let result = parser.parse(content).unwrap();
        assert!(result.frontmatter.is_some());
    }

    #[test]
    fn test_parse_empty_content() {
        let parser = MarkdownParser::new();
        let content = "";

        let result = parser.parse(content).unwrap();
        assert_eq!(result.frontmatter, None);
        assert_eq!(result.content, "");
    }

    #[test]
    fn test_parse_only_whitespace() {
        let parser = MarkdownParser::new();
        let content = "   \n  \n   ";

        let result = parser.parse(content).unwrap();
        assert_eq!(result.frontmatter, None);
    }
}