anyrepair 0.2.4

A comprehensive Rust crate for repairing malformed structured data including JSON, YAML, XML, TOML, CSV, INI, Markdown, and Diff with format auto-detection
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
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
//! Key-value format repair module (INI, .env, .properties)

use crate::error::Result;
use crate::traits::{Repair, RepairStrategy, Validator};
use std::collections::HashSet;

struct FixMissingEqualsStrategy;

impl RepairStrategy for FixMissingEqualsStrategy {
    fn name(&self) -> &str {
        "FixMissingEquals"
    }

    fn apply(&self, content: &str) -> Result<String> {
        let mut result = Vec::new();
        for line in content.lines() {
            let trimmed = line.trim();
            if is_skip_line(trimmed) {
                result.push(line.to_string());
                continue;
            }
            if !trimmed.contains('=') {
                let parts: Vec<&str> = trimmed.split_whitespace().collect();
                if parts.len() >= 2 {
                    result.push(format!("{}={}", parts[0], parts[1..].join(" ")));
                } else if parts.len() == 1 {
                    result.push(format!("{}=", parts[0]));
                } else {
                    result.push(line.to_string());
                }
            } else {
                result.push(line.to_string());
            }
        }
        Ok(result.join("\n"))
    }

    fn priority(&self) -> u8 {
        100
    }
}

struct FixWhitespaceAroundEqualsStrategy;

impl RepairStrategy for FixWhitespaceAroundEqualsStrategy {
    fn name(&self) -> &str {
        "FixWhitespaceAroundEquals"
    }

    fn apply(&self, content: &str) -> Result<String> {
        let mut result = Vec::new();
        for line in content.lines() {
            let trimmed = line.trim();
            if is_skip_line(trimmed) {
                result.push(line.to_string());
                continue;
            }
            if let Some(eq_pos) = trimmed.find('=') {
                let key = trimmed[..eq_pos].trim();
                let value = trimmed[eq_pos + 1..].trim();
                result.push(format!("{}={}", key, value));
            } else {
                result.push(line.to_string());
            }
        }
        Ok(result.join("\n"))
    }

    fn priority(&self) -> u8 {
        90
    }
}

struct FixEmptyKeysStrategy {
    prefix: &'static str,
}

impl RepairStrategy for FixEmptyKeysStrategy {
    fn name(&self) -> &str {
        "FixEmptyKeys"
    }

    fn apply(&self, content: &str) -> Result<String> {
        let mut result = Vec::new();
        for (i, line) in content.lines().enumerate() {
            let trimmed = line.trim();
            if is_skip_line(trimmed) {
                result.push(line.to_string());
                continue;
            }
            if let Some(stripped) = trimmed.strip_prefix('=') {
                let value = stripped.trim();
                result.push(format!("{}_{}={}", self.prefix, i, value));
            } else {
                result.push(line.to_string());
            }
        }
        Ok(result.join("\n"))
    }

    fn priority(&self) -> u8 {
        80
    }
}

struct FixMalformedCommentsStrategy;

impl RepairStrategy for FixMalformedCommentsStrategy {
    fn name(&self) -> &str {
        "FixMalformedComments"
    }

    fn apply(&self, content: &str) -> Result<String> {
        let mut result = Vec::new();
        for line in content.lines() {
            let trimmed = line.trim();
            if trimmed.contains('#') && !trimmed.starts_with('#') && !trimmed.contains('=') {
                if let Some(hash_pos) = trimmed.find('#') {
                    let before = trimmed[..hash_pos].trim();
                    let after = &trimmed[hash_pos..];
                    if before.is_empty() {
                        result.push(after.to_string());
                    } else {
                        result.push(format!("#{} {}", before, after[1..].trim()));
                    }
                } else {
                    result.push(line.to_string());
                }
            } else {
                result.push(line.to_string());
            }
        }
        Ok(result.join("\n"))
    }

    fn priority(&self) -> u8 {
        70
    }
}

struct FixQuotedValuesStrategy;

impl RepairStrategy for FixQuotedValuesStrategy {
    fn name(&self) -> &str {
        "FixQuotedValues"
    }

    fn apply(&self, content: &str) -> Result<String> {
        let mut result = Vec::new();
        for line in content.lines() {
            let trimmed = line.trim();
            if is_skip_line(trimmed) {
                result.push(line.to_string());
                continue;
            }
            if let Some(eq_pos) = trimmed.find('=') {
                let value = trimmed[eq_pos + 1..].trim();
                if value.starts_with('"') && !value.ends_with('"') {
                    result.push(format!("{}=\"{}\"", &trimmed[..=eq_pos], &value[1..]));
                } else if value.starts_with('\'') && !value.ends_with('\'') {
                    result.push(format!("{}='{}'", &trimmed[..=eq_pos], &value[1..]));
                } else if value.ends_with('"') && !value.starts_with('"') {
                    result.push(format!(
                        "{}\"{}\"",
                        &trimmed[..=eq_pos],
                        &value[..value.len() - 1]
                    ));
                } else if value.ends_with('\'') && !value.starts_with('\'') {
                    result.push(format!(
                        "{}'{}'",
                        &trimmed[..=eq_pos],
                        &value[..value.len() - 1]
                    ));
                } else {
                    result.push(line.to_string());
                }
            } else {
                result.push(line.to_string());
            }
        }
        Ok(result.join("\n"))
    }

    fn priority(&self) -> u8 {
        60
    }
}

// --- INI-specific strategies ---

struct FixMalformedSectionsStrategy;

impl RepairStrategy for FixMalformedSectionsStrategy {
    fn apply(&self, content: &str) -> Result<String> {
        let mut result = Vec::new();
        for line in content.lines() {
            let trimmed = line.trim();
            if trimmed.starts_with('[') && !trimmed.ends_with(']') {
                let indent = line
                    .chars()
                    .take_while(|c| c.is_whitespace())
                    .collect::<String>();
                let section_name = trimmed.trim_start_matches('[');
                result.push(format!("{}[{}]", indent, section_name));
            } else {
                result.push(line.to_string());
            }
        }
        Ok(result.join("\n"))
    }

    fn priority(&self) -> u8 {
        6
    }

    fn name(&self) -> &str {
        "FixMalformedSectionsStrategy"
    }
}

struct FixMalformedKeysStrategy;

impl RepairStrategy for FixMalformedKeysStrategy {
    fn apply(&self, content: &str) -> Result<String> {
        let mut result = Vec::new();
        for line in content.lines() {
            let trimmed = line.trim();
            if is_skip_line(trimmed) || trimmed.contains('=') {
                result.push(line.to_string());
                continue;
            }
            let parts: Vec<&str> = trimmed.splitn(2, ' ').collect();
            if parts.len() == 2 {
                let indent = line
                    .chars()
                    .take_while(|c| c.is_whitespace())
                    .collect::<String>();
                result.push(format!("{}{} = {}", indent, parts[0], parts[1]));
            } else {
                result.push(line.to_string());
            }
        }
        Ok(result.join("\n"))
    }

    fn priority(&self) -> u8 {
        5
    }

    fn name(&self) -> &str {
        "FixMalformedKeysStrategy"
    }
}

struct RemoveDuplicateSectionsStrategy;

impl RepairStrategy for RemoveDuplicateSectionsStrategy {
    fn apply(&self, content: &str) -> Result<String> {
        let mut seen = HashSet::new();
        let mut result = Vec::new();
        for line in content.lines() {
            let trimmed = line.trim();
            if trimmed.starts_with('[') && trimmed.ends_with(']') {
                let name = &trimmed[1..trimmed.len() - 1];
                if seen.contains(name) {
                    continue;
                }
                seen.insert(name.to_string());
            }
            result.push(line);
        }
        Ok(result.join("\n"))
    }

    fn priority(&self) -> u8 {
        1
    }

    fn name(&self) -> &str {
        "RemoveDuplicateSectionsStrategy"
    }
}

struct AddDefaultSectionStrategy;

impl RepairStrategy for AddDefaultSectionStrategy {
    fn apply(&self, content: &str) -> Result<String> {
        let lines: Vec<&str> = content.lines().collect();
        if lines.is_empty() {
            return Ok(content.to_string());
        }
        let first = lines[0].trim();
        if first.contains('=') && !first.starts_with('[') {
            let mut result = vec!["[default]".to_string()];
            result.extend(lines.iter().map(|s| s.to_string()));
            Ok(result.join("\n"))
        } else {
            Ok(content.to_string())
        }
    }

    fn priority(&self) -> u8 {
        0
    }

    fn name(&self) -> &str {
        "AddDefaultSectionStrategy"
    }
}

// --- Helpers ---

fn is_skip_line(trimmed: &str) -> bool {
    trimmed.is_empty()
        || trimmed.starts_with('#')
        || trimmed.starts_with('!')
        || trimmed.starts_with('[')
}

// --- Public types ---

pub struct IniRepairer {
    inner: crate::repairer_base::GenericRepairer,
}

impl IniRepairer {
    pub fn new() -> Self {
        let strategies: Vec<Box<dyn RepairStrategy>> = vec![
            Box::new(FixMalformedSectionsStrategy),
            Box::new(FixMalformedKeysStrategy),
            Box::new(FixMissingEqualsStrategy),
            Box::new(FixWhitespaceAroundEqualsStrategy),
            Box::new(FixMalformedCommentsStrategy),
            Box::new(RemoveDuplicateSectionsStrategy),
            Box::new(AddDefaultSectionStrategy),
        ];
        let validator: Box<dyn Validator> = Box::new(IniValidator);
        Self {
            inner: crate::repairer_base::GenericRepairer::new(validator, strategies),
        }
    }
}

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

impl Repair for IniRepairer {
    fn repair(&mut self, content: &str) -> Result<String> {
        self.inner.repair(content)
    }

    fn needs_repair(&self, content: &str) -> bool {
        self.inner.needs_repair(content)
    }

    fn confidence(&self, content: &str) -> f64 {
        if content.trim().is_empty() {
            return 0.0;
        }
        let mut score: f64 = 0.0;
        if content.contains('[') && content.contains(']') {
            score += 0.3;
        }
        if content.contains('=') {
            score += 0.3;
        }
        if content.contains('#') {
            score += 0.1;
        }
        let lines: Vec<&str> = content.lines().collect();
        let has_sections = lines.iter().any(|l| l.trim().starts_with('['));
        let has_keys = lines
            .iter()
            .any(|l| l.contains('=') && !l.trim().starts_with('#'));
        if has_sections || has_keys {
            score += 0.2;
        }
        if content.contains('\n') {
            score += 0.1;
        }
        score.min(1.0)
    }
}

pub struct IniValidator;

impl Validator for IniValidator {
    fn is_valid(&self, content: &str) -> bool {
        if content.trim().is_empty() {
            return false;
        }
        let lines: Vec<&str> = content.lines().collect();
        for line in &lines {
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') || line.starts_with('!') {
                continue;
            }
            if line.starts_with('[') && !line.ends_with(']') {
                return false;
            }
            if line.contains(' ') && !line.contains('=') && !line.starts_with('[') {
                return false;
            }
        }
        let has_sections = lines
            .iter()
            .any(|l| l.trim().starts_with('[') && l.contains(']'));
        let has_keys = lines
            .iter()
            .any(|l| l.contains('=') && !l.trim().starts_with('#') && !l.trim().starts_with('['));
        has_sections || has_keys
    }

    fn validate(&self, content: &str) -> Vec<String> {
        let mut errors = Vec::new();
        if content.trim().is_empty() {
            errors.push("Empty INI content".to_string());
            return errors;
        }
        for (i, line) in content.lines().enumerate() {
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') {
                continue;
            }
            if line.starts_with('[') && !line.contains(']') {
                errors.push(format!(
                    "Malformed section header at line {}: {}",
                    i + 1,
                    line
                ));
            } else if line.contains('=') {
                let parts: Vec<&str> = line.splitn(2, '=').collect();
                if parts.len() != 2 {
                    errors.push(format!(
                        "Malformed key-value pair at line {}: {}",
                        i + 1,
                        line
                    ));
                }
            }
        }
        errors
    }
}

pub struct EnvRepairer {
    inner: crate::repairer_base::GenericRepairer,
}

impl EnvRepairer {
    pub fn new() -> Self {
        let strategies: Vec<Box<dyn RepairStrategy>> = vec![
            Box::new(FixMissingEqualsStrategy),
            Box::new(FixWhitespaceAroundEqualsStrategy),
            Box::new(FixEmptyKeysStrategy { prefix: "ENV_VAR" }),
            Box::new(FixMalformedCommentsStrategy),
            Box::new(FixQuotedValuesStrategy),
        ];
        let validator: Box<dyn Validator> = Box::new(EnvValidator);
        Self {
            inner: crate::repairer_base::GenericRepairer::new(validator, strategies),
        }
    }
}

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

impl Repair for EnvRepairer {
    fn repair(&mut self, content: &str) -> Result<String> {
        self.inner.repair(content)
    }

    fn needs_repair(&self, content: &str) -> bool {
        self.inner.needs_repair(content)
    }

    fn confidence(&self, content: &str) -> f64 {
        if content.trim().is_empty() {
            return 0.0;
        }
        let mut score: f64 = 0.0;
        if content.contains('=') {
            score += 0.4;
        }
        if content.contains('#') {
            score += 0.2;
        }
        let uppercase_count = content.matches(char::is_uppercase).count();
        let total_chars = content.len();
        if total_chars > 0 && uppercase_count as f64 / total_chars as f64 > 0.2 {
            score += 0.2;
        }
        if content.contains('_') {
            score += 0.1;
        }
        if content.contains('"') || content.contains('\'') {
            score += 0.1;
        }
        score.clamp(0.0, 1.0)
    }
}

pub struct EnvValidator;

impl Validator for EnvValidator {
    fn is_valid(&self, content: &str) -> bool {
        for line in content.lines() {
            let trimmed = line.trim();
            if trimmed.is_empty() || trimmed.starts_with('#') {
                continue;
            }
            if !trimmed.contains('=') {
                return false;
            }
            if let Some(eq_pos) = trimmed.find('=') {
                let key = trimmed[..eq_pos].trim();
                if key.is_empty() {
                    return false;
                }
            }
        }
        true
    }

    fn validate(&self, content: &str) -> Vec<String> {
        let mut errors = Vec::new();
        for (line_num, line) in content.lines().enumerate() {
            let trimmed = line.trim();
            if trimmed.is_empty() || trimmed.starts_with('#') {
                continue;
            }
            if !trimmed.contains('=') {
                errors.push(format!("Line {}: Missing '=' delimiter", line_num + 1));
                continue;
            }
            if trimmed.starts_with('=') {
                errors.push(format!("Line {}: Empty key", line_num + 1));
            }
        }
        errors
    }
}

pub struct PropertiesRepairer {
    inner: crate::repairer_base::GenericRepairer,
}

impl PropertiesRepairer {
    pub fn new() -> Self {
        let strategies: Vec<Box<dyn RepairStrategy>> = vec![
            Box::new(FixMissingEqualsStrategy),
            Box::new(FixWhitespaceAroundEqualsStrategy),
            Box::new(FixEmptyKeysStrategy { prefix: "key" }),
            Box::new(FixMalformedCommentsStrategy),
            Box::new(FixQuotedValuesStrategy),
        ];
        let validator: Box<dyn Validator> = Box::new(PropertiesValidator);
        Self {
            inner: crate::repairer_base::GenericRepairer::new(validator, strategies),
        }
    }
}

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

impl Repair for PropertiesRepairer {
    fn repair(&mut self, content: &str) -> Result<String> {
        self.inner.repair(content)
    }

    fn needs_repair(&self, content: &str) -> bool {
        self.inner.needs_repair(content)
    }

    fn confidence(&self, content: &str) -> f64 {
        if content.trim().is_empty() {
            return 0.0;
        }
        let mut score: f64 = 0.0;
        if content.contains('=') {
            score += 0.5;
        }
        if content.contains('#') || content.contains('!') {
            score += 0.2;
        }
        if content.matches('.').count() > 0 {
            score += 0.2;
        }
        if content.contains("\\\n") {
            score += 0.1;
        }
        score.clamp(0.0, 1.0)
    }
}

pub struct PropertiesValidator;

impl Validator for PropertiesValidator {
    fn is_valid(&self, content: &str) -> bool {
        for line in content.lines() {
            let trimmed = line.trim();
            if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with('!') {
                continue;
            }
            if !trimmed.contains('=') {
                return false;
            }
            if let Some(eq_pos) = trimmed.find('=')
                && trimmed[..eq_pos].trim().is_empty()
            {
                return false;
            }
        }
        true
    }

    fn validate(&self, content: &str) -> Vec<String> {
        let mut errors = Vec::new();
        for (line_num, line) in content.lines().enumerate() {
            let trimmed = line.trim();
            if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with('!') {
                continue;
            }
            if !trimmed.contains('=') {
                errors.push(format!("Line {}: Missing '=' delimiter", line_num + 1));
                continue;
            }
            if trimmed.starts_with('=') {
                errors.push(format!("Line {}: Empty key", line_num + 1));
            }
        }
        errors
    }
}

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

    #[test]
    fn test_ini_repair() {
        let mut r = IniRepairer::new();
        let result = r.repair("[section]\nkey value\nother = ok").unwrap();
        assert!(result.contains("[section]"));
        assert!(result.contains("key = value") || result.contains("key=value"));
    }

    #[test]
    fn test_env_repair() {
        let mut r = EnvRepairer::new();
        let result = r
            .repair("DATABASE_URL postgresql://localhost/mydb\nAPI_KEY secret_key")
            .unwrap();
        assert!(result.contains("DATABASE_URL="));
        assert!(result.contains("API_KEY="));
    }

    #[test]
    fn test_properties_repair() {
        let mut r = PropertiesRepairer::new();
        let result = r.repair("key1 value1\nkey2 value2").unwrap();
        assert!(result.contains("key1=value1"));
        assert!(result.contains("key2=value2"));
    }

    #[test]
    fn test_ini_validator() {
        let v = IniValidator;
        assert!(v.is_valid("[section]\nkey=value"));
        assert!(!v.is_valid(""));
    }

    #[test]
    fn test_env_validator() {
        let v = EnvValidator;
        assert!(v.is_valid("KEY=value\nOTHER=val2"));
        assert!(!v.is_valid("KEY value"));
    }

    #[test]
    fn test_properties_validator() {
        let v = PropertiesValidator;
        assert!(v.is_valid("key=value\nother=val"));
        assert!(!v.is_valid("key value"));
    }

    #[test]
    fn test_ini_sections() {
        let mut r = IniRepairer::new();
        let result = r.repair("[section\nkey=value").unwrap();
        assert!(result.contains("[section]"));
    }

    #[test]
    fn test_env_confidence() {
        let r = EnvRepairer::new();
        assert!(
            r.confidence("DATABASE_URL=postgresql://localhost/mydb\nAPI_KEY=secret_key") >= 0.5
        );
        assert!(r.confidence("some random text") < 0.5);
    }
}