heroforge-core 0.2.2

Pure Rust core library for reading and writing Fossil SCM repositories
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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
//! Stress tests and edge cases for heroforge using builder pattern
//!
//! Additional tests:
//! - Very large number of commits (200+)
//! - Identical content in different files
//! - Commit with same content as previous (should still work)
//! - Very long file paths
//! - File names with spaces and special chars
//! - Very small changes between versions
//! - Reading historical versions while making new commits
//! - Cross-verification with CLI for all operations

use heroforge_core::{Repository, Result};
use std::fs;
use std::path::Path;
use std::time::Instant;

struct TestResult {
    name: String,
    passed: bool,
    details: String,
    duration_ms: u128,
}

fn main() -> Result<()> {
    let test_dir = Path::new("/tmp/fossil_stress_test");

    if test_dir.exists() {
        fs::remove_dir_all(test_dir).expect("Failed to clean up");
    }
    fs::create_dir_all(test_dir).expect("Failed to create test dir");

    let mut results: Vec<TestResult> = Vec::new();

    println!("=== heroforge Stress Test Suite ===\n");

    results.push(test_many_commits(test_dir));
    results.push(test_identical_content(test_dir));
    results.push(test_unchanged_commits(test_dir));
    results.push(test_long_paths(test_dir));
    results.push(test_special_filenames(test_dir));
    results.push(test_incremental_changes(test_dir));
    results.push(test_historical_reads(test_dir));
    results.push(test_cli_full_verification(test_dir));
    results.push(test_concurrent_repos(test_dir));
    results.push(test_large_commit_messages(test_dir));

    println!("\n=== Test Summary ===\n");

    let mut passed = 0;
    let mut failed = 0;

    for result in &results {
        let status = if result.passed { "PASS" } else { "FAIL" };
        println!("[{}] {} ({} ms)", status, result.name, result.duration_ms);
        if !result.passed {
            println!("      {}", result.details);
            failed += 1;
        } else {
            passed += 1;
        }
    }

    println!("\nTotal: {} passed, {} failed", passed, failed);

    if failed > 0 {
        std::process::exit(1);
    }

    Ok(())
}

/// Test 1: Many commits (200)
fn test_many_commits(base_dir: &Path) -> TestResult {
    let start = Instant::now();
    let name = "200 sequential commits".to_string();

    let repo_path = base_dir.join("test_many_commits.forge");

    let result = (|| -> Result<String> {
        let repo = Repository::init(&repo_path)?;
        let mut parent = repo
            .commit_builder()
            .message("initial empty check-in")
            .author("testuser")
            .initial()
            .execute()?;

        for i in 1..=200 {
            let content = format!("Commit number {}\nLine 2\nLine 3", i);

            let hash = repo
                .commit_builder()
                .message(&format!("Commit {}", i))
                .author("testuser")
                .parent(&parent)
                .branch("trunk")
                .file("counter.txt", content.as_bytes())
                .execute()?;
            parent = hash;
        }

        // Verify checkin count using history builder
        let checkins = repo.history().recent(250)?;
        if checkins.len() != 201 {
            return Err(heroforge_core::FossilError::InvalidArtifact(format!(
                "Expected 201, got {}",
                checkins.len()
            )));
        }

        // Verify last commit content using files builder
        let content = repo.files().at_commit(&parent).read_string("counter.txt")?;
        if !content.contains("Commit number 200") {
            return Err(heroforge_core::FossilError::InvalidArtifact(
                "Last commit content wrong".into(),
            ));
        }

        Ok("200 commits created and verified".into())
    })();

    TestResult {
        name,
        passed: result.is_ok(),
        details: result.unwrap_or_else(|e| e.to_string()),
        duration_ms: start.elapsed().as_millis(),
    }
}

/// Test 2: Identical content in different files
fn test_identical_content(base_dir: &Path) -> TestResult {
    let start = Instant::now();
    let name = "Identical content in multiple files".to_string();

    let repo_path = base_dir.join("test_identical.forge");

    let result = (|| -> Result<String> {
        let repo = Repository::init(&repo_path)?;
        let initial = repo
            .commit_builder()
            .message("initial empty check-in")
            .author("testuser")
            .initial()
            .execute()?;

        // Create many files with same content (tests hash deduplication)
        let content = b"This exact content appears in 20 different files";
        let mut files_data: Vec<(String, &[u8])> = Vec::new();

        for i in 0..20 {
            files_data.push((format!("same_content_{}.txt", i), content));
        }

        let files: Vec<(&str, &[u8])> = files_data.iter().map(|(n, c)| (n.as_str(), *c)).collect();

        let hash = repo
            .commit_builder()
            .message("Add identical files")
            .author("testuser")
            .parent(&initial)
            .branch("trunk")
            .files(&files)
            .execute()?;

        // Verify all files have same content using files builder
        for i in 0..20 {
            let name = format!("same_content_{}.txt", i);
            let read_content = repo.files().at_commit(&hash).read(&name)?;
            if read_content != content {
                return Err(heroforge_core::FossilError::InvalidArtifact(format!(
                    "Content mismatch for {}",
                    name
                )));
            }
        }

        Ok("20 identical files verified".into())
    })();

    TestResult {
        name,
        passed: result.is_ok(),
        details: result.unwrap_or_else(|e| e.to_string()),
        duration_ms: start.elapsed().as_millis(),
    }
}

/// Test 3: Commits with unchanged content
fn test_unchanged_commits(base_dir: &Path) -> TestResult {
    let start = Instant::now();
    let name = "Commits with unchanged files".to_string();

    let repo_path = base_dir.join("test_unchanged.forge");

    let result = (|| -> Result<String> {
        let repo = Repository::init(&repo_path)?;
        let initial = repo
            .commit_builder()
            .message("initial empty check-in")
            .author("testuser")
            .initial()
            .execute()?;

        let content = b"This content never changes";

        let hash1 = repo
            .commit_builder()
            .message("First commit")
            .author("testuser")
            .parent(&initial)
            .branch("trunk")
            .file("stable.txt", content)
            .execute()?;

        // Commit same content again (with different message)
        let hash2 = repo
            .commit_builder()
            .message("Second commit same content")
            .author("testuser")
            .parent(&hash1)
            .branch("trunk")
            .file("stable.txt", content)
            .execute()?;

        // And again
        let hash3 = repo
            .commit_builder()
            .message("Third commit same content")
            .author("testuser")
            .parent(&hash2)
            .branch("trunk")
            .file("stable.txt", content)
            .execute()?;

        // All three should be readable using files builder
        for hash in [&hash1, &hash2, &hash3] {
            let read_content = repo.files().at_commit(hash).read("stable.txt")?;
            if read_content != content {
                return Err(heroforge_core::FossilError::InvalidArtifact(
                    "Content mismatch".into(),
                ));
            }
        }

        // Verify we have 4 checkins (initial + 3) using history builder
        let checkins = repo.history().recent(10)?;
        if checkins.len() != 4 {
            return Err(heroforge_core::FossilError::InvalidArtifact(format!(
                "Expected 4 checkins, got {}",
                checkins.len()
            )));
        }

        Ok("3 commits with same content verified".into())
    })();

    TestResult {
        name,
        passed: result.is_ok(),
        details: result.unwrap_or_else(|e| e.to_string()),
        duration_ms: start.elapsed().as_millis(),
    }
}

/// Test 4: Very long file paths
fn test_long_paths(base_dir: &Path) -> TestResult {
    let start = Instant::now();
    let name = "Very long file paths".to_string();

    let repo_path = base_dir.join("test_long_paths.forge");

    let result = (|| -> Result<String> {
        let repo = Repository::init(&repo_path)?;
        let initial = repo
            .commit_builder()
            .message("initial empty check-in")
            .author("testuser")
            .initial()
            .execute()?;

        // Create path with many directory levels
        let deep_path = "a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u/v/w/x/y/z/file.txt";

        // Create path with long names
        let long_names = "this_is_a_very_long_directory_name/another_really_long_directory_name_here/yet_another_long_name/file_with_long_name_that_goes_on_and_on.txt";

        let hash = repo
            .commit_builder()
            .message("Add files with long paths")
            .author("testuser")
            .parent(&initial)
            .branch("trunk")
            .file(deep_path, b"Deep file content")
            .file(long_names, b"Long names content")
            .execute()?;

        // Verify using files builder
        let content1 = repo.files().at_commit(&hash).read(deep_path)?;
        if content1 != b"Deep file content" {
            return Err(heroforge_core::FossilError::InvalidArtifact(
                "Deep path mismatch".into(),
            ));
        }

        let content2 = repo.files().at_commit(&hash).read(long_names)?;
        if content2 != b"Long names content" {
            return Err(heroforge_core::FossilError::InvalidArtifact(
                "Long names mismatch".into(),
            ));
        }

        Ok("Long paths verified".into())
    })();

    TestResult {
        name,
        passed: result.is_ok(),
        details: result.unwrap_or_else(|e| e.to_string()),
        duration_ms: start.elapsed().as_millis(),
    }
}

/// Test 5: Special characters in filenames
fn test_special_filenames(base_dir: &Path) -> TestResult {
    let start = Instant::now();
    let name = "Special characters in filenames".to_string();

    let repo_path = base_dir.join("test_special_names.forge");

    let result = (|| -> Result<String> {
        let repo = Repository::init(&repo_path)?;
        let initial = repo
            .commit_builder()
            .message("initial empty check-in")
            .author("testuser")
            .initial()
            .execute()?;

        // Various special filename patterns (avoiding truly problematic ones)
        let hash = repo
            .commit_builder()
            .message("Add special filenames")
            .author("testuser")
            .parent(&initial)
            .branch("trunk")
            .file("file with spaces.txt", b"spaces")
            .file("file-with-dashes.txt", b"dashes")
            .file("file_with_underscores.txt", b"underscores")
            .file("file.multiple.dots.txt", b"dots")
            .file("UPPERCASE.TXT", b"upper")
            .file("MixedCase.Txt", b"mixed")
            .file("file123numbers456.txt", b"numbers")
            .file(".hidden_file", b"hidden")
            .file("file.tar.gz", b"double ext")
            .execute()?;

        // Verify all using files builder
        let files = [
            ("file with spaces.txt", b"spaces".as_slice()),
            ("file-with-dashes.txt", b"dashes"),
            ("file_with_underscores.txt", b"underscores"),
            ("file.multiple.dots.txt", b"dots"),
            ("UPPERCASE.TXT", b"upper"),
            ("MixedCase.Txt", b"mixed"),
            ("file123numbers456.txt", b"numbers"),
            (".hidden_file", b"hidden"),
            ("file.tar.gz", b"double ext"),
        ];

        for (name, expected) in &files {
            let content = repo.files().at_commit(&hash).read(name)?;
            if &content != expected {
                return Err(heroforge_core::FossilError::InvalidArtifact(format!(
                    "Mismatch for '{}'",
                    name
                )));
            }
        }

        Ok(format!("{} special filenames verified", files.len()))
    })();

    TestResult {
        name,
        passed: result.is_ok(),
        details: result.unwrap_or_else(|e| e.to_string()),
        duration_ms: start.elapsed().as_millis(),
    }
}

/// Test 6: Incremental small changes
fn test_incremental_changes(base_dir: &Path) -> TestResult {
    let start = Instant::now();
    let name = "Incremental small changes".to_string();

    let repo_path = base_dir.join("test_incremental.forge");

    let result = (|| -> Result<String> {
        let repo = Repository::init(&repo_path)?;
        let mut parent = repo
            .commit_builder()
            .message("initial empty check-in")
            .author("testuser")
            .initial()
            .execute()?;

        let mut hashes: Vec<String> = Vec::new();

        // Start with a base file
        let mut content = String::from("Line 1\nLine 2\nLine 3\n");

        for i in 1..=30 {
            // Make a tiny change each time
            content.push_str(&format!("Line {} added\n", i + 3));

            let hash = repo
                .commit_builder()
                .message(&format!("Add line {}", i + 3))
                .author("testuser")
                .parent(&parent)
                .branch("trunk")
                .file("growing.txt", content.as_bytes())
                .execute()?;

            hashes.push(hash.clone());
            parent = hash;
        }

        // Verify each version has correct number of lines using files builder
        for (i, hash) in hashes.iter().enumerate() {
            let content = repo.files().at_commit(hash).read("growing.txt")?;
            let line_count = content.iter().filter(|&&b| b == b'\n').count();
            let expected = 3 + i + 1; // 3 base lines + (i+1) added lines

            if line_count != expected {
                return Err(heroforge_core::FossilError::InvalidArtifact(format!(
                    "Version {} has {} lines, expected {}",
                    i + 1,
                    line_count,
                    expected
                )));
            }
        }

        Ok("30 incremental changes verified".into())
    })();

    TestResult {
        name,
        passed: result.is_ok(),
        details: result.unwrap_or_else(|e| e.to_string()),
        duration_ms: start.elapsed().as_millis(),
    }
}

/// Test 7: Reading historical versions during new commits
fn test_historical_reads(base_dir: &Path) -> TestResult {
    let start = Instant::now();
    let name = "Historical reads during commits".to_string();

    let repo_path = base_dir.join("test_historical.forge");

    let result = (|| -> Result<String> {
        let repo = Repository::init(&repo_path)?;
        let mut parent = repo
            .commit_builder()
            .message("initial empty check-in")
            .author("testuser")
            .initial()
            .execute()?;

        let mut all_hashes: Vec<(String, String)> = Vec::new(); // (hash, expected_content)

        // Create 20 versions
        for i in 1..=20 {
            let content = format!("Version {} content", i);

            let hash = repo
                .commit_builder()
                .message(&format!("Version {}", i))
                .author("testuser")
                .parent(&parent)
                .branch("trunk")
                .file("data.txt", content.as_bytes())
                .execute()?;

            all_hashes.push((hash.clone(), content));
            parent = hash;

            // After every 5 commits, verify all previous versions are still readable
            if i % 5 == 0 {
                for (old_hash, expected) in &all_hashes {
                    let content = repo.files().at_commit(old_hash).read_string("data.txt")?;
                    if content != *expected {
                        return Err(heroforge_core::FossilError::InvalidArtifact(format!(
                            "Historical read failed at commit {}",
                            i
                        )));
                    }
                }
            }
        }

        // Final verification of all versions
        for (hash, expected) in &all_hashes {
            let content = repo.files().at_commit(hash).read_string("data.txt")?;
            if content != *expected {
                return Err(heroforge_core::FossilError::InvalidArtifact(
                    "Final verification failed".into(),
                ));
            }
        }

        Ok("20 versions with historical reads verified".into())
    })();

    TestResult {
        name,
        passed: result.is_ok(),
        details: result.unwrap_or_else(|e| e.to_string()),
        duration_ms: start.elapsed().as_millis(),
    }
}

/// Test 8: Diverse file types verification (replaces CLI verification since heroforge is a library)
fn test_cli_full_verification(base_dir: &Path) -> TestResult {
    let start = Instant::now();
    let name = "Diverse file types verification".to_string();

    let repo_path = base_dir.join("test_diverse_files.forge");

    let result = (|| -> Result<String> {
        let repo = Repository::init(&repo_path)?;
        let initial = repo
            .commit_builder()
            .message("initial empty check-in")
            .author("testuser")
            .initial()
            .execute()?;

        // Create diverse files
        let binary_content = vec![0u8, 1, 2, 255, 254, 253];
        let unicode_content = "Hello 世界 🌍".as_bytes();

        let hash = repo
            .commit_builder()
            .message("Test commit with diverse files")
            .author("testuser")
            .parent(&initial)
            .branch("trunk")
            .file("text.txt", b"Plain text content")
            .file("binary.bin", &binary_content)
            .file("dir/nested.txt", b"Nested file")
            .file("unicode.txt", unicode_content)
            .file("empty.txt", b"")
            .file("deep/path/to/file.txt", b"Deep nested")
            .execute()?;

        // Verify each file can be read back correctly using files builder
        let files = [
            ("text.txt", b"Plain text content".to_vec()),
            ("binary.bin", binary_content.clone()),
            ("dir/nested.txt", b"Nested file".to_vec()),
            ("unicode.txt", unicode_content.to_vec()),
            ("empty.txt", Vec::new()),
            ("deep/path/to/file.txt", b"Deep nested".to_vec()),
        ];

        for (name, expected) in &files {
            let content = repo.files().at_commit(&hash).read(name)?;
            if content != *expected {
                return Err(heroforge_core::FossilError::InvalidArtifact(format!(
                    "Content mismatch for '{}': expected {} bytes, got {} bytes",
                    name,
                    expected.len(),
                    content.len()
                )));
            }
        }

        // Verify file listing using files builder
        let file_list = repo.files().at_commit(&hash).list()?;
        if file_list.len() != files.len() {
            return Err(heroforge_core::FossilError::InvalidArtifact(format!(
                "Expected {} files, got {}",
                files.len(),
                file_list.len()
            )));
        }

        Ok(format!("{} diverse files verified", files.len()))
    })();

    TestResult {
        name,
        passed: result.is_ok(),
        details: result.unwrap_or_else(|e| e.to_string()),
        duration_ms: start.elapsed().as_millis(),
    }
}

/// Test 9: Multiple concurrent repositories
fn test_concurrent_repos(base_dir: &Path) -> TestResult {
    let start = Instant::now();
    let name = "Multiple concurrent repositories".to_string();

    let result = (|| -> Result<String> {
        // Create 5 separate repositories
        let mut repos: Vec<(Repository, String)> = Vec::new();

        for i in 0..5 {
            let repo_path = base_dir.join(format!("concurrent_repo_{}.forge", i));
            let repo = Repository::init(&repo_path)?;
            let initial = repo
                .commit_builder()
                .message("initial empty check-in")
                .author(&format!("user{}", i))
                .initial()
                .execute()?;
            repos.push((repo, initial));
        }

        // Make commits to each in round-robin fashion
        for round in 1..=10 {
            for (i, (repo, parent)) in repos.iter_mut().enumerate() {
                let content = format!("Repo {} round {}", i, round);

                let hash = repo
                    .commit_builder()
                    .message(&format!("Round {}", round))
                    .author(&format!("user{}", i))
                    .parent(parent)
                    .branch("trunk")
                    .file("data.txt", content.as_bytes())
                    .execute()?;

                *parent = hash;
            }
        }

        // Verify each repo independently using builders
        for (i, (repo, last_hash)) in repos.iter().enumerate() {
            let content = repo.files().at_commit(last_hash).read_string("data.txt")?;
            let expected = format!("Repo {} round 10", i);

            if content != expected {
                return Err(heroforge_core::FossilError::InvalidArtifact(format!(
                    "Repo {} verification failed",
                    i
                )));
            }

            let checkins = repo.history().recent(15)?;
            if checkins.len() != 11 {
                // initial + 10 rounds
                return Err(heroforge_core::FossilError::InvalidArtifact(format!(
                    "Repo {} has {} checkins, expected 11",
                    i,
                    checkins.len()
                )));
            }
        }

        Ok("5 concurrent repos with 10 commits each verified".into())
    })();

    TestResult {
        name,
        passed: result.is_ok(),
        details: result.unwrap_or_else(|e| e.to_string()),
        duration_ms: start.elapsed().as_millis(),
    }
}

/// Test 10: Large commit messages
fn test_large_commit_messages(base_dir: &Path) -> TestResult {
    let start = Instant::now();
    let name = "Large commit messages".to_string();

    let repo_path = base_dir.join("test_large_messages.forge");

    let result = (|| -> Result<String> {
        let repo = Repository::init(&repo_path)?;
        let mut parent = repo
            .commit_builder()
            .message("initial empty check-in")
            .author("testuser")
            .initial()
            .execute()?;

        // Test various message sizes and content
        let msg1 = "Short message".to_string();
        let msg2 =
            "A longer message with more details about the changes made in this commit.".to_string();
        let msg3 = "x".repeat(1000); // 1KB message
        let msg4 = format!(
            "Multi-line message\nLine 2\nLine 3\nLine 4\n{}",
            "more ".repeat(100)
        );
        let msg5 = format!("Unicode message: 你好世界 🎉 {}", "test ".repeat(50));
        let messages: Vec<&str> = vec![&msg1, &msg2, &msg3, &msg4, &msg5];

        for (i, msg) in messages.iter().enumerate() {
            let content = format!("Commit {}", i);

            let hash = repo
                .commit_builder()
                .message(msg)
                .author("testuser")
                .parent(&parent)
                .branch("trunk")
                .file("file.txt", content.as_bytes())
                .execute()?;
            parent = hash;
        }

        // Verify checkins using history builder
        let checkins = repo.history().recent(10)?;
        if checkins.len() != 6 {
            return Err(heroforge_core::FossilError::InvalidArtifact(format!(
                "Expected 6 checkins, got {}",
                checkins.len()
            )));
        }

        Ok("Large commit messages verified".into())
    })();

    TestResult {
        name,
        passed: result.is_ok(),
        details: result.unwrap_or_else(|e| e.to_string()),
        duration_ms: start.elapsed().as_millis(),
    }
}