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
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
//! YAML parser for frontmatter validation and deserialization

use crate::markdown_config::error::{MarkdownConfigError, MarkdownConfigResult};
use serde::de::DeserializeOwned;

/// Parser for YAML frontmatter
#[derive(Debug, Clone)]
pub struct YamlParser;

impl YamlParser {
    /// Create a new YAML parser
    pub fn new() -> Self {
        Self
    }

    /// Parse YAML string into a typed structure
    pub fn parse<T: DeserializeOwned>(&self, yaml: &str) -> MarkdownConfigResult<T> {
        serde_yaml::from_str(yaml).map_err(|e| {
            MarkdownConfigError::yaml_error(format!("Failed to parse YAML: {}", e))
        })
    }

    /// Validate YAML structure without deserializing to a specific type
    pub fn validate_structure(&self, yaml: &str) -> MarkdownConfigResult<()> {
        // Try to parse as a generic YAML value to validate structure
        serde_yaml::from_str::<serde_yaml::Value>(yaml).map_err(|e| {
            MarkdownConfigError::yaml_error(format!("Invalid YAML structure: {}", e))
        })?;
        Ok(())
    }

    /// Check if required fields are present in YAML
    pub fn has_required_fields(&self, yaml: &str, required_fields: &[&str]) -> MarkdownConfigResult<()> {
        let value: serde_yaml::Value = serde_yaml::from_str(yaml).map_err(|e| {
            MarkdownConfigError::yaml_error(format!("Failed to parse YAML: {}", e))
        })?;

        let mapping = value.as_mapping().ok_or_else(|| {
            MarkdownConfigError::validation_error("YAML must be a mapping (object)")
        })?;

        for field in required_fields {
            let key = serde_yaml::Value::String(field.to_string());
            if !mapping.contains_key(&key) {
                return Err(MarkdownConfigError::missing_field(*field));
            }
        }

        Ok(())
    }

    /// Get a field value from YAML
    pub fn get_field(&self, yaml: &str, field: &str) -> MarkdownConfigResult<Option<String>> {
        let value: serde_yaml::Value = serde_yaml::from_str(yaml).map_err(|e| {
            MarkdownConfigError::yaml_error(format!("Failed to parse YAML: {}", e))
        })?;

        let mapping = value.as_mapping().ok_or_else(|| {
            MarkdownConfigError::validation_error("YAML must be a mapping (object)")
        })?;

        let key = serde_yaml::Value::String(field.to_string());
        Ok(mapping.get(&key).and_then(|v| v.as_str().map(|s| s.to_string())))
    }

    /// Validate YAML against a schema (checks for required fields and types)
    pub fn validate_schema(
        &self,
        yaml: &str,
        required_fields: &[&str],
    ) -> MarkdownConfigResult<()> {
        // First validate structure
        self.validate_structure(yaml)?;

        // Then check required fields
        self.has_required_fields(yaml, required_fields)?;

        Ok(())
    }

    /// Get all validation errors from YAML
    pub fn get_all_validation_errors(
        &self,
        yaml: &str,
        required_fields: &[&str],
    ) -> Vec<MarkdownConfigError> {
        let mut errors = Vec::new();

        // Check structure
        if let Err(e) = self.validate_structure(yaml) {
            errors.push(e);
            return errors; // Can't check fields if structure is invalid
        }

        // Check required fields
        for field in required_fields {
            if let Err(e) = self.has_required_fields(yaml, &[field]) {
                errors.push(e);
            }
        }

        errors
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use serde::{Deserialize, Serialize};

    #[derive(Debug, Serialize, Deserialize, PartialEq)]
    struct TestConfig {
        name: String,
        value: i32,
    }

    #[test]
    fn test_parse_valid_yaml() {
        let parser = YamlParser::new();
        let yaml = "name: test\nvalue: 42";

        let result: TestConfig = parser.parse(yaml).unwrap();
        assert_eq!(result.name, "test");
        assert_eq!(result.value, 42);
    }

    #[test]
    fn test_parse_invalid_yaml() {
        let parser = YamlParser::new();
        let yaml = "name: test\n  invalid: [unclosed";

        let result: Result<TestConfig, _> = parser.parse(yaml);
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_structure_valid() {
        let parser = YamlParser::new();
        let yaml = "name: test\nvalue: 42";

        let result = parser.validate_structure(yaml);
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_structure_invalid() {
        let parser = YamlParser::new();
        let yaml = "name: test\n  invalid: [unclosed";

        let result = parser.validate_structure(yaml);
        assert!(result.is_err());
    }

    #[test]
    fn test_has_required_fields_present() {
        let parser = YamlParser::new();
        let yaml = "name: test\nvalue: 42\ndescription: optional";

        let result = parser.has_required_fields(yaml, &["name", "value"]);
        assert!(result.is_ok());
    }

    #[test]
    fn test_has_required_fields_missing() {
        let parser = YamlParser::new();
        let yaml = "name: test";

        let result = parser.has_required_fields(yaml, &["name", "value"]);
        assert!(result.is_err());
    }

    #[test]
    fn test_get_field_exists() {
        let parser = YamlParser::new();
        let yaml = "name: test-value\nother: data";

        let result = parser.get_field(yaml, "name").unwrap();
        assert_eq!(result, Some("test-value".to_string()));
    }

    #[test]
    fn test_get_field_missing() {
        let parser = YamlParser::new();
        let yaml = "name: test-value";

        let result = parser.get_field(yaml, "missing").unwrap();
        assert_eq!(result, None);
    }

    #[test]
    fn test_get_field_non_string() {
        let parser = YamlParser::new();
        let yaml = "name: test\nvalue: 42";

        let result = parser.get_field(yaml, "value").unwrap();
        assert_eq!(result, None); // Non-string values return None
    }

    #[test]
    fn test_parse_complex_yaml() {
        let parser = YamlParser::new();
        let _yaml = r#"
name: complex-agent
description: A complex agent
model: gpt-4
temperature: 0.7
max_tokens: 2000
tools:
  - tool1
  - tool2
  - tool3
"#;

        let result: TestConfig = parser.parse("name: test\nvalue: 42").unwrap();
        assert_eq!(result.name, "test");
    }

    #[test]
    fn test_parse_yaml_with_nested_objects() {
        let parser = YamlParser::new();
        let yaml = r#"
name: test
config:
  nested: value
  deep:
    deeper: data
"#;

        let result = parser.validate_structure(yaml);
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_yaml_with_arrays() {
        let parser = YamlParser::new();
        let yaml = r#"
name: test
items:
  - item1
  - item2
  - item3
"#;

        let result = parser.validate_structure(yaml);
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_schema_all_required_present() {
        let parser = YamlParser::new();
        let yaml = "name: test\nvalue: 42\ndescription: optional";

        let result = parser.validate_schema(yaml, &["name", "value"]);
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_schema_missing_required() {
        let parser = YamlParser::new();
        let yaml = "name: test";

        let result = parser.validate_schema(yaml, &["name", "value", "description"]);
        assert!(result.is_err());
    }

    #[test]
    fn test_get_all_validation_errors_valid() {
        let parser = YamlParser::new();
        let yaml = "name: test\nvalue: 42";

        let errors = parser.get_all_validation_errors(yaml, &["name", "value"]);
        assert_eq!(errors.len(), 0);
    }

    #[test]
    fn test_get_all_validation_errors_invalid_structure() {
        let parser = YamlParser::new();
        let yaml = "name: test\n  invalid: [unclosed";

        let errors = parser.get_all_validation_errors(yaml, &["name"]);
        assert!(!errors.is_empty());
    }

    #[test]
    fn test_get_all_validation_errors_missing_fields() {
        let parser = YamlParser::new();
        let yaml = "name: test";

        let errors = parser.get_all_validation_errors(yaml, &["name", "value", "description"]);
        assert!(!errors.is_empty());
    }

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

        let result = parser.validate_structure(yaml);
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_yaml_with_quotes() {
        let parser = YamlParser::new();
        let yaml = r#"
name: 'single-quoted'
description: "double-quoted"
"#;

        let result = parser.validate_structure(yaml);
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_yaml_with_multiline_strings() {
        let parser = YamlParser::new();
        let yaml = r#"
name: test
description: |
  This is a multiline
  description that spans
  multiple lines
"#;

        let result = parser.validate_structure(yaml);
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_yaml_with_numbers() {
        let parser = YamlParser::new();
        let yaml = r#"
name: test
integer: 42
float: 3.14
negative: -10
"#;

        let result = parser.validate_structure(yaml);
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_yaml_with_booleans() {
        let parser = YamlParser::new();
        let yaml = r#"
name: test
enabled: true
disabled: false
"#;

        let result = parser.validate_structure(yaml);
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_yaml_with_null() {
        let parser = YamlParser::new();
        let yaml = r#"
name: test
optional: null
"#;

        let result = parser.validate_structure(yaml);
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_empty_yaml() {
        let parser = YamlParser::new();
        let yaml = "";

        let result = parser.validate_structure(yaml);
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_yaml_only_comments() {
        let parser = YamlParser::new();
        let yaml = r#"
# This is a comment
# Another comment
"#;

        let result = parser.validate_structure(yaml);
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_yaml_with_anchors_and_aliases() {
        let parser = YamlParser::new();
        let yaml = r#"
defaults: &defaults
  name: default
  value: 0

config:
  <<: *defaults
  name: custom
"#;

        let result = parser.validate_structure(yaml);
        assert!(result.is_ok());
    }

    #[test]
    fn test_has_required_fields_empty_list() {
        let parser = YamlParser::new();
        let yaml = "name: test";

        let result = parser.has_required_fields(yaml, &[]);
        assert!(result.is_ok());
    }

    #[test]
    fn test_get_field_from_empty_yaml() {
        let parser = YamlParser::new();
        let yaml = "";

        let result = parser.get_field(yaml, "name");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_yaml_consistency() {
        let parser = YamlParser::new();
        let yaml = "name: test\nvalue: 42";

        let result1: TestConfig = parser.parse(yaml).unwrap();
        let result2: TestConfig = parser.parse(yaml).unwrap();

        assert_eq!(result1, result2);
    }

    #[test]
    fn test_parse_yaml_with_unicode() {
        let parser = YamlParser::new();
        let yaml = r#"
name: 测试
description: 日本語のテスト
"#;

        let result = parser.validate_structure(yaml);
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_yaml_with_windows_line_endings() {
        let parser = YamlParser::new();
        let yaml = "name: test\r\nvalue: 42";

        let result: Result<TestConfig, _> = parser.parse(yaml);
        assert!(result.is_ok());
    }
}