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
//! Full demo: Create a complete project history with branches, tags, and changes
//! Then open the heroforge web UI to explore

use heroforge_core::Repository;
use std::path::Path;
use std::process::Command;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let demo_dir = Path::new("/tmp/fossil_full_demo");
    let repo_path = demo_dir.join("myproject.forge");

    // Clean up and create fresh
    if demo_dir.exists() {
        std::fs::remove_dir_all(demo_dir)?;
    }
    std::fs::create_dir_all(demo_dir)?;

    println!("=== Creating Full Demo Repository ===\n");
    println!("Repository: {}\n", repo_path.display());

    // Initialize repository
    let repo = Repository::init(&repo_path)?;
    println!("✓ Repository initialized");

    // Create initial check-in using builder
    let init_hash = repo
        .commit_builder()
        .message("initial empty check-in")
        .author("admin")
        .initial()
        .execute()?;
    println!("✓ Initial check-in: {}", &init_hash[..12]);

    // ========================================
    // Phase 1: Initial project setup (v0.1.0)
    // ========================================
    println!("\n--- Phase 1: Project Setup (v0.1.0) ---");

    let readme = r#"# MyProject

A demonstration project for heroforge.

## Features
- Feature A
- Feature B

## Installation
Run `cargo install myproject`
"#;

    let cargo_toml = r#"[package]
name = "myproject"
version = "0.1.0"
edition = "2021"

[dependencies]
"#;

    let main_rs = r#"fn main() {
    println!("MyProject v0.1.0");
}
"#;

    let lib_rs = r#"//! MyProject library

pub fn greet(name: &str) -> String {
    format!("Hello, {}!", name)
}

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

    #[test]
    fn test_greet() {
        assert_eq!(greet("World"), "Hello, World!");
    }
}
"#;

    let v010 = repo
        .commit_builder()
        .message("Initial project structure")
        .author("alice")
        .parent(&init_hash)
        .file("README.md", readme.as_bytes())
        .file("Cargo.toml", cargo_toml.as_bytes())
        .file("src/main.rs", main_rs.as_bytes())
        .file("src/lib.rs", lib_rs.as_bytes())
        .execute()?;
    println!("  Commit: Initial project structure");

    repo.tags()
        .create("v0.1.0")
        .at_commit(&v010)
        .author("alice")
        .execute()?;
    println!("  Tagged: v0.1.0");

    // ========================================
    // Phase 2: Add configuration (v0.2.0)
    // ========================================
    println!("\n--- Phase 2: Add Configuration (v0.2.0) ---");

    let config_rs = r#"//! Configuration module

use std::path::PathBuf;

#[derive(Debug, Clone)]
pub struct Config {
    pub data_dir: PathBuf,
    pub verbose: bool,
    pub max_connections: usize,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            data_dir: PathBuf::from("./data"),
            verbose: false,
            max_connections: 10,
        }
    }
}

impl Config {
    pub fn load() -> Self {
        // TODO: Load from file
        Self::default()
    }
}
"#;

    let lib_rs_v2 = r#"//! MyProject library

pub mod config;

pub use config::Config;

pub fn greet(name: &str) -> String {
    format!("Hello, {}!", name)
}

pub fn init() -> Config {
    Config::load()
}

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

    #[test]
    fn test_greet() {
        assert_eq!(greet("World"), "Hello, World!");
    }

    #[test]
    fn test_config_default() {
        let config = Config::default();
        assert!(!config.verbose);
    }
}
"#;

    let main_rs_v2 = r#"use myproject::{greet, init};

fn main() {
    let config = init();
    println!("MyProject v0.2.0");
    println!("{}", greet("User"));
    println!("Config: {:?}", config);
}
"#;

    let v020 = repo
        .commit_builder()
        .message("Add configuration module")
        .author("alice")
        .parent(&v010)
        .file("README.md", readme.as_bytes())
        .file("Cargo.toml", cargo_toml.as_bytes())
        .file("src/main.rs", main_rs_v2.as_bytes())
        .file("src/lib.rs", lib_rs_v2.as_bytes())
        .file("src/config.rs", config_rs.as_bytes())
        .execute()?;
    println!("  Commit: Add configuration module");

    repo.tags()
        .create("v0.2.0")
        .at_commit(&v020)
        .author("alice")
        .execute()?;
    println!("  Tagged: v0.2.0");

    // ========================================
    // Phase 3: Create feature branch
    // ========================================
    println!("\n--- Phase 3: Feature Branch (feature/database) ---");

    let feature_db = repo
        .branches()
        .create("feature/database")
        .from_commit(&v020)
        .author("bob")
        .execute()?;
    println!("  Branch created: feature/database");

    // Add database module on feature branch
    let db_rs = r#"//! Database module

use std::collections::HashMap;

pub struct Database {
    data: HashMap<String, String>,
}

impl Database {
    pub fn new() -> Self {
        Self {
            data: HashMap::new(),
        }
    }

    pub fn insert(&mut self, key: &str, value: &str) {
        self.data.insert(key.to_string(), value.to_string());
    }

    pub fn get(&self, key: &str) -> Option<&String> {
        self.data.get(key)
    }

    pub fn delete(&mut self, key: &str) -> Option<String> {
        self.data.remove(key)
    }
}

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

    #[test]
    fn test_database_crud() {
        let mut db = Database::new();
        db.insert("key1", "value1");
        assert_eq!(db.get("key1"), Some(&"value1".to_string()));
        db.delete("key1");
        assert_eq!(db.get("key1"), None);
    }
}
"#;

    let lib_rs_db = r#"//! MyProject library

pub mod config;
pub mod db;

pub use config::Config;
pub use db::Database;

pub fn greet(name: &str) -> String {
    format!("Hello, {}!", name)
}

pub fn init() -> Config {
    Config::load()
}
"#;

    let db_commit1 = repo
        .commit_builder()
        .message("Add database module with CRUD operations")
        .author("bob")
        .parent(&feature_db)
        .branch("feature/database")
        .file("README.md", readme.as_bytes())
        .file("Cargo.toml", cargo_toml.as_bytes())
        .file("src/main.rs", main_rs_v2.as_bytes())
        .file("src/lib.rs", lib_rs_db.as_bytes())
        .file("src/config.rs", config_rs.as_bytes())
        .file("src/db.rs", db_rs.as_bytes())
        .execute()?;
    println!("  Commit: Add database module");

    // Add persistence to database
    let db_rs_v2 = r#"//! Database module with persistence

use std::collections::HashMap;
use std::fs;
use std::path::Path;

pub struct Database {
    data: HashMap<String, String>,
    path: Option<String>,
}

impl Database {
    pub fn new() -> Self {
        Self {
            data: HashMap::new(),
            path: None,
        }
    }

    pub fn open(path: &str) -> std::io::Result<Self> {
        let mut db = Self::new();
        db.path = Some(path.to_string());

        if Path::new(path).exists() {
            let content = fs::read_to_string(path)?;
            for line in content.lines() {
                if let Some((key, value)) = line.split_once('=') {
                    db.data.insert(key.to_string(), value.to_string());
                }
            }
        }

        Ok(db)
    }

    pub fn save(&self) -> std::io::Result<()> {
        if let Some(path) = &self.path {
            let content: String = self.data
                .iter()
                .map(|(k, v)| format!("{}={}", k, v))
                .collect::<Vec<_>>()
                .join("\n");
            fs::write(path, content)?;
        }
        Ok(())
    }

    pub fn insert(&mut self, key: &str, value: &str) {
        self.data.insert(key.to_string(), value.to_string());
    }

    pub fn get(&self, key: &str) -> Option<&String> {
        self.data.get(key)
    }

    pub fn delete(&mut self, key: &str) -> Option<String> {
        self.data.remove(key)
    }
}
"#;

    let _db_commit2 = repo
        .commit_builder()
        .message("Add persistence to database module")
        .author("bob")
        .parent(&db_commit1)
        .branch("feature/database")
        .file("README.md", readme.as_bytes())
        .file("Cargo.toml", cargo_toml.as_bytes())
        .file("src/main.rs", main_rs_v2.as_bytes())
        .file("src/lib.rs", lib_rs_db.as_bytes())
        .file("src/config.rs", config_rs.as_bytes())
        .file("src/db.rs", db_rs_v2.as_bytes())
        .execute()?;
    println!("  Commit: Add persistence");

    // ========================================
    // Phase 4: Continue trunk development (v0.3.0)
    // ========================================
    println!("\n--- Phase 4: Trunk Development (v0.3.0) ---");

    let cli_rs = r#"//! Command-line interface

use std::env;

pub struct Cli {
    pub command: String,
    pub args: Vec<String>,
}

impl Cli {
    pub fn parse() -> Self {
        let args: Vec<String> = env::args().collect();
        let command = args.get(1).cloned().unwrap_or_else(|| "help".to_string());
        let args = args.into_iter().skip(2).collect();

        Self { command, args }
    }
}
"#;

    let main_rs_v3 = r#"mod cli;

use myproject::{greet, init};
use cli::Cli;

fn main() {
    let cli = Cli::parse();
    let config = init();

    match cli.command.as_str() {
        "greet" => {
            let name = cli.args.first().map(|s| s.as_str()).unwrap_or("World");
            println!("{}", greet(name));
        }
        "config" => {
            println!("Config: {:?}", config);
        }
        _ => {
            println!("MyProject v0.3.0");
            println!("Commands: greet [name], config");
        }
    }
}
"#;

    let v030 = repo
        .commit_builder()
        .message("Add CLI interface")
        .author("alice")
        .parent(&v020)
        .file("README.md", readme.as_bytes())
        .file("Cargo.toml", cargo_toml.as_bytes())
        .file("src/main.rs", main_rs_v3.as_bytes())
        .file("src/lib.rs", lib_rs_v2.as_bytes())
        .file("src/config.rs", config_rs.as_bytes())
        .file("src/cli.rs", cli_rs.as_bytes())
        .execute()?;
    println!("  Commit: Add CLI interface");

    repo.tags()
        .create("v0.3.0")
        .at_commit(&v030)
        .author("alice")
        .execute()?;
    println!("  Tagged: v0.3.0");

    // ========================================
    // Phase 5: Hotfix branch from v0.2.0
    // ========================================
    println!("\n--- Phase 5: Hotfix (hotfix/config-panic) ---");

    let hotfix_branch = repo
        .branches()
        .create("hotfix/config-panic")
        .from_commit(&v020)
        .author("charlie")
        .execute()?;
    println!("  Branch created: hotfix/config-panic");

    let config_rs_fixed = r#"//! Configuration module (with panic fix)

use std::path::PathBuf;

#[derive(Debug, Clone)]
pub struct Config {
    pub data_dir: PathBuf,
    pub verbose: bool,
    pub max_connections: usize,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            data_dir: PathBuf::from("./data"),
            verbose: false,
            max_connections: 10,
        }
    }
}

impl Config {
    pub fn load() -> Self {
        // Fixed: Handle missing config file gracefully
        match std::fs::read_to_string("config.toml") {
            Ok(_content) => {
                // TODO: Parse TOML
                Self::default()
            }
            Err(_) => Self::default(),
        }
    }
}
"#;

    let hotfix_commit = repo
        .commit_builder()
        .message("Fix panic when config file is missing")
        .author("charlie")
        .parent(&hotfix_branch)
        .branch("hotfix/config-panic")
        .file("README.md", readme.as_bytes())
        .file("Cargo.toml", cargo_toml.as_bytes())
        .file("src/main.rs", main_rs_v2.as_bytes())
        .file("src/lib.rs", lib_rs_v2.as_bytes())
        .file("src/config.rs", config_rs_fixed.as_bytes())
        .execute()?;
    println!("  Commit: Fix config panic");

    repo.tags()
        .create("v0.2.1")
        .at_commit(&hotfix_commit)
        .author("charlie")
        .execute()?;
    println!("  Tagged: v0.2.1");

    // ========================================
    // Phase 6: More trunk work (v0.4.0)
    // ========================================
    println!("\n--- Phase 6: More Features (v0.4.0) ---");

    let utils_rs = r#"//! Utility functions

/// Format a size in bytes to human-readable format
pub fn format_size(bytes: u64) -> String {
    const KB: u64 = 1024;
    const MB: u64 = KB * 1024;
    const GB: u64 = MB * 1024;

    if bytes >= GB {
        format!("{:.2} GB", bytes as f64 / GB as f64)
    } else if bytes >= MB {
        format!("{:.2} MB", bytes as f64 / MB as f64)
    } else if bytes >= KB {
        format!("{:.2} KB", bytes as f64 / KB as f64)
    } else {
        format!("{} B", bytes)
    }
}

/// Truncate a string to a maximum length
pub fn truncate(s: &str, max_len: usize) -> String {
    if s.len() <= max_len {
        s.to_string()
    } else {
        format!("{}...", &s[..max_len.saturating_sub(3)])
    }
}

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

    #[test]
    fn test_format_size() {
        assert_eq!(format_size(500), "500 B");
        assert_eq!(format_size(1024), "1.00 KB");
        assert_eq!(format_size(1536), "1.50 KB");
    }

    #[test]
    fn test_truncate() {
        assert_eq!(truncate("hello", 10), "hello");
        assert_eq!(truncate("hello world", 8), "hello...");
    }
}
"#;

    let lib_rs_v4 = r#"//! MyProject library

pub mod config;
pub mod utils;

pub use config::Config;

pub fn greet(name: &str) -> String {
    format!("Hello, {}!", name)
}

pub fn init() -> Config {
    Config::load()
}
"#;

    let v040 = repo
        .commit_builder()
        .message("Add utility functions")
        .author("alice")
        .parent(&v030)
        .file("README.md", readme.as_bytes())
        .file("Cargo.toml", cargo_toml.as_bytes())
        .file("src/main.rs", main_rs_v3.as_bytes())
        .file("src/lib.rs", lib_rs_v4.as_bytes())
        .file("src/config.rs", config_rs.as_bytes())
        .file("src/cli.rs", cli_rs.as_bytes())
        .file("src/utils.rs", utils_rs.as_bytes())
        .execute()?;
    println!("  Commit: Add utility functions");

    repo.tags()
        .create("v0.4.0")
        .at_commit(&v040)
        .author("alice")
        .execute()?;
    println!("  Tagged: v0.4.0");

    // Add documentation
    let readme_v2 = r#"# MyProject

A demonstration project for heroforge.

## Features
- Configuration management
- CLI interface
- Utility functions

## Installation

```bash
cargo install myproject
```

## Usage

```bash
# Show help
myproject

# Greet someone
myproject greet Alice

# Show configuration
myproject config
```

## Development

```bash
# Run tests
cargo test

# Build release
cargo build --release
```

## License

MIT
"#;

    let _docs_commit = repo
        .commit_builder()
        .message("Update documentation")
        .author("alice")
        .parent(&v040)
        .file("README.md", readme_v2.as_bytes())
        .file("Cargo.toml", cargo_toml.as_bytes())
        .file("src/main.rs", main_rs_v3.as_bytes())
        .file("src/lib.rs", lib_rs_v4.as_bytes())
        .file("src/config.rs", config_rs.as_bytes())
        .file("src/cli.rs", cli_rs.as_bytes())
        .file("src/utils.rs", utils_rs.as_bytes())
        .execute()?;
    println!("  Commit: Update documentation");

    // ========================================
    // Summary
    // ========================================
    println!("\n=== Repository Summary ===\n");

    println!("Branches:");
    for branch in repo.branches().list()? {
        println!("  - {}", branch);
    }

    println!("\nTags:");
    for tag in repo.tags().list()? {
        let hash = repo.tags().get(&tag)?.commit_hash()?;
        println!("  - {} -> {}", tag, &hash[..12]);
    }

    println!("\nRecent Check-ins:");
    for ci in repo.history().recent(15)? {
        println!(
            "  [{}] {} - {}",
            &ci.hash[..8],
            &ci.timestamp[..10],
            ci.comment
        );
    }

    // ========================================
    // Open Web UI
    // ========================================
    println!("\n=== Opening Web UI ===\n");

    // Run rebuild first
    let _ = Command::new("heroforge")
        .args(["rebuild", repo_path.to_str().unwrap()])
        .output();

    println!("Starting heroforge web UI...");
    println!("Repository: {}", repo_path.display());
    println!("\nPress Ctrl+C to stop the server.\n");

    // Open the web UI
    let status = Command::new("heroforge")
        .args(["ui", repo_path.to_str().unwrap()])
        .status()?;

    if !status.success() {
        eprintln!("Failed to start heroforge ui");
    }

    Ok(())
}