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
//! Repository access and manipulation.
//!
//! This module provides the main [`Repository`] type for interacting with Heroforge repositories.
//!
//! # Examples
//!
//! ## Opening an existing repository
//!
//! ```no_run
//! use heroforge_core::Repository;
//!
//! let repo = Repository::open("project.forge")?;
//! let files = repo.files().on_trunk().list()?;
//! for file in files {
//!     println!("{}", file.name);
//! }
//! # Ok::<(), heroforge_core::FossilError>(())
//! ```
//!
//! ## Creating a new repository
//!
//! ```no_run
//! use heroforge_core::Repository;
//!
//! let repo = Repository::init("new.forge")?;
//! let hash = repo.commit_builder()
//!     .message("Initial commit")
//!     .author("admin")
//!     .initial()
//!     .execute()?;
//! # Ok::<(), heroforge_core::FossilError>(())
//! ```

mod builders;
mod database;

pub use builders::{
    BranchBuilder, BranchesBuilder, CommitBuilder, FileEntry, FileQuery, FileType, FilesBuilder,
    FindBuilder, FindResult, FsBuilder, FsOperation, FsOpsBuilder, FsPreview, HistoryBuilder,
    Permissions, TagBuilder, TagsBuilder, UserBuilder, UsersBuilder,
};
pub use database::Database;

use crate::artifact::{blob, manifest};
use crate::error::{FossilError, Result};
use crate::hash;
use crate::sync::SyncBuilder;
use chrono::Utc;
use std::path::Path;

/// A Heroforge repository handle.
///
/// This is the main entry point for interacting with Heroforge repositories.
/// It provides a fluent builder API for all operations.
///
/// # Opening Repositories
///
/// - [`Repository::open`] - Open read-only
/// - [`Repository::open_rw`] - Open read-write
/// - [`Repository::init`] - Create new repository
///
/// # Builder API
///
/// - [`Repository::files`] - File operations
/// - [`Repository::fs`] - Filesystem operations (copy, move, delete, chmod, find, symlinks)
/// - [`Repository::branches`] - Branch operations
/// - [`Repository::tags`] - Tag operations
/// - [`Repository::history`] - Browse history
/// - [`Repository::users`] - User management
/// - [`Repository::sync`] - Sync operations
pub struct Repository {
    db: Database,
}

/// A check-in (commit) in the repository.
#[derive(Debug, Clone)]
pub struct CheckIn {
    /// Internal row ID in the database
    pub rid: i64,
    /// SHA3-256 hash of the check-in manifest
    pub hash: String,
    /// ISO 8601 timestamp
    pub timestamp: String,
    /// Username who created the check-in
    pub user: String,
    /// Commit message
    pub comment: String,
    /// Parent check-in hashes
    pub parents: Vec<String>,
    /// Branch name (if available)
    pub branch: Option<String>,
}

/// Information about a file in a check-in.
#[derive(Debug, Clone)]
pub struct FileInfo {
    /// File path relative to repository root
    pub name: String,
    /// SHA3-256 hash of file content
    pub hash: String,
    /// Unix permissions (if set)
    pub permissions: Option<String>,
    /// File size in bytes (if known)
    pub size: Option<usize>,
}

impl Repository {
    // ========================================================================
    // Constructors
    // ========================================================================

    /// Open a repository in read-only mode.
    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
        let db = Database::open(path)?;
        Ok(Self { db })
    }

    /// Open a repository in read-write mode.
    pub fn open_rw<P: AsRef<Path>>(path: P) -> Result<Self> {
        let db = Database::open_rw(path)?;
        Ok(Self { db })
    }

    /// Create a new repository.
    pub fn init<P: AsRef<Path>>(path: P) -> Result<Self> {
        let db = Database::init(path)?;
        Ok(Self { db })
    }

    // ========================================================================
    // Builder Entry Points
    // ========================================================================

    /// Access file operations.
    pub fn files(&self) -> FilesBuilder<'_> {
        FilesBuilder::new(self)
    }

    /// Start building a commit using the builder pattern.
    pub fn commit_builder(&self) -> CommitBuilder<'_> {
        CommitBuilder::new(self)
    }

    /// Access branch operations.
    pub fn branches(&self) -> BranchesBuilder<'_> {
        BranchesBuilder::new(self)
    }

    /// Access tag operations.
    pub fn tags(&self) -> TagsBuilder<'_> {
        TagsBuilder::new(self)
    }

    /// Access history/commit browsing.
    pub fn history(&self) -> HistoryBuilder<'_> {
        HistoryBuilder::new(self)
    }

    /// Access user operations.
    pub fn users(&self) -> UsersBuilder<'_> {
        UsersBuilder::new(self)
    }

    /// Access sync operations.
    pub fn sync(&self) -> SyncBuilder<'_> {
        SyncBuilder::new(self)
    }

    /// Access filesystem operations (copy, move, delete, chmod, find, symlinks).
    pub fn fs(&self) -> FsOpsBuilder<'_> {
        FsOpsBuilder::new(self)
    }

    /// Import a git repository (requires `git-import` feature).
    ///
    /// Clones a git repository and imports its contents (without history)
    /// into this heroforge repository as a single commit.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use heroforge_core::Repository;
    ///
    /// let repo = Repository::init("project.fossil")?;
    ///
    /// repo.git_import()
    ///     .url("https://github.com/user/project.git")
    ///     .branch("main")
    ///     .message("Import from git")
    ///     .author("developer")
    ///     .execute()?;
    /// # Ok::<(), heroforge_core::FossilError>(())
    /// ```
    #[cfg(feature = "git-import")]
    pub fn git_import(&self) -> crate::tools::GitImportBuilder<'_> {
        crate::tools::GitImportBuilder::new(self)
    }

    // ========================================================================
    // Direct Access
    // ========================================================================

    /// Get the project code.
    pub fn project_code(&self) -> Result<String> {
        self.db.get_project_code()
    }

    /// Get the project name.
    pub fn project_name(&self) -> Result<Option<String>> {
        self.db.get_project_name()
    }

    /// Get the underlying database handle.
    pub fn database(&self) -> &Database {
        &self.db
    }

    /// Rebuild repository metadata.
    pub fn rebuild(&self) -> Result<()> {
        self.db.connection().execute("DELETE FROM leaf", [])?;
        self.db.connection().execute(
            "INSERT INTO leaf SELECT rid FROM blob WHERE rid NOT IN (SELECT pid FROM plink)
             AND rid IN (SELECT objid FROM event WHERE type='ci')",
            [],
        )?;
        Ok(())
    }

    // ========================================================================
    // Internal Implementation Methods
    // ========================================================================

    pub(crate) fn get_checkin_internal(&self, hash: &str) -> Result<CheckIn> {
        let rid = self.db.get_rid_by_hash(hash)?;
        let full_hash = self.db.get_hash_by_rid(rid)?;

        let content = blob::get_artifact_content(&self.db, rid)?;
        let manifest = manifest::parse_manifest(&content)?;

        Ok(CheckIn {
            rid,
            hash: full_hash,
            timestamp: manifest.timestamp,
            user: manifest.user,
            comment: manifest.comment,
            parents: manifest.parents,
            branch: None,
        })
    }

    pub(crate) fn branch_tip_internal(&self, branch: &str) -> Result<CheckIn> {
        let rid = if branch == "trunk" {
            self.db.get_trunk_tip()?
        } else {
            self.db.get_branch_tip(branch)?
        };
        let hash = self.db.get_hash_by_rid(rid)?;
        self.get_checkin_internal(&hash)
    }

    pub(crate) fn recent_checkins_internal(&self, limit: usize) -> Result<Vec<CheckIn>> {
        let raw = self.db.get_recent_checkins(limit)?;
        let mut result = Vec::with_capacity(raw.len());

        for (rid, hash, _mtime, user, comment) in raw {
            let content = blob::get_artifact_content(&self.db, rid)?;
            let manifest = manifest::parse_manifest(&content)?;

            result.push(CheckIn {
                rid,
                hash,
                timestamp: manifest.timestamp,
                user,
                comment,
                parents: manifest.parents,
                branch: None,
            });
        }

        Ok(result)
    }

    pub(crate) fn list_files_internal(&self, checkin_hash: &str) -> Result<Vec<FileInfo>> {
        let rid = self.db.get_rid_by_hash(checkin_hash)?;
        let files = self.db.get_files_for_manifest(rid)?;

        Ok(files
            .into_iter()
            .map(|(name, hash)| FileInfo {
                name,
                hash,
                permissions: None,
                size: None,
            })
            .collect())
    }

    pub(crate) fn read_file_internal(&self, checkin_hash: &str, path: &str) -> Result<Vec<u8>> {
        let rid = self.db.get_rid_by_hash(checkin_hash)?;
        let file_hash = self.db.get_file_hash_from_manifest(rid, path)?;
        blob::get_artifact_by_hash(&self.db, &file_hash)
    }

    pub(crate) fn find_files_internal(
        &self,
        checkin_hash: &str,
        pattern: &str,
    ) -> Result<Vec<FileInfo>> {
        let all_files = self.list_files_internal(checkin_hash)?;
        let glob_pattern =
            glob::Pattern::new(pattern).map_err(|e| FossilError::InvalidArtifact(e.to_string()))?;

        Ok(all_files
            .into_iter()
            .filter(|f| glob_pattern.matches(&f.name))
            .collect())
    }

    pub(crate) fn list_directory_internal(
        &self,
        checkin_hash: &str,
        dir: &str,
    ) -> Result<Vec<FileInfo>> {
        let all_files = self.list_files_internal(checkin_hash)?;
        let dir = dir.trim_end_matches('/');

        Ok(all_files
            .into_iter()
            .filter(|f| {
                if dir.is_empty() {
                    !f.name.contains('/')
                } else {
                    f.name.starts_with(&format!("{}/", dir))
                        && !f.name[dir.len() + 1..].contains('/')
                }
            })
            .collect())
    }

    pub(crate) fn list_subdirs_internal(
        &self,
        checkin_hash: &str,
        dir: &str,
    ) -> Result<Vec<String>> {
        let all_files = self.list_files_internal(checkin_hash)?;
        let dir = dir.trim_end_matches('/');
        let prefix = if dir.is_empty() {
            String::new()
        } else {
            format!("{}/", dir)
        };

        let mut subdirs: Vec<String> = all_files
            .into_iter()
            .filter_map(|f| {
                if f.name.starts_with(&prefix) {
                    let rest = &f.name[prefix.len()..];
                    if let Some(idx) = rest.find('/') {
                        return Some(rest[..idx].to_string());
                    }
                }
                None
            })
            .collect();

        subdirs.sort();
        subdirs.dedup();
        Ok(subdirs)
    }

    pub(crate) fn list_branches_internal(&self) -> Result<Vec<String>> {
        self.db.list_branches()
    }

    pub(crate) fn list_tags_internal(&self) -> Result<Vec<String>> {
        let mut stmt = self.db.connection().prepare(
            "SELECT DISTINCT substr(tagname, 5) FROM tag
             WHERE tagname LIKE 'sym-%'
             AND substr(tagname, 5) NOT IN (SELECT value FROM tagxref WHERE tagid IN
                 (SELECT tagid FROM tag WHERE tagname = 'branch'))",
        )?;

        let tags: Vec<String> = stmt
            .query_map([], |row| row.get(0))?
            .filter_map(|r| r.ok())
            .collect();

        Ok(tags)
    }

    pub(crate) fn get_tag_checkin_internal(&self, tag_name: &str) -> Result<String> {
        let tag_full = format!("sym-{}", tag_name);
        let hash: String = self.db.connection().query_row(
            "SELECT b.uuid FROM blob b
             JOIN tagxref x ON x.rid = b.rid
             JOIN tag t ON t.tagid = x.tagid
             WHERE t.tagname = ?1
             ORDER BY x.mtime DESC LIMIT 1",
            rusqlite::params![tag_full],
            |row| row.get(0),
        )?;
        Ok(hash)
    }

    pub(crate) fn commit_internal(
        &self,
        files: &[(&str, &[u8])],
        comment: &str,
        user: &str,
        parent_hash: Option<&str>,
        branch: Option<&str>,
    ) -> Result<String> {
        self.db.begin_transaction()?;

        let result = self.commit_inner(files, comment, user, parent_hash, branch);

        match result {
            Ok(hash) => {
                self.db.commit_transaction()?;
                Ok(hash)
            }
            Err(e) => {
                self.db.rollback_transaction()?;
                Err(e)
            }
        }
    }

    fn commit_inner(
        &self,
        files: &[(&str, &[u8])],
        comment: &str,
        user: &str,
        parent_hash: Option<&str>,
        branch: Option<&str>,
    ) -> Result<String> {
        let now = Utc::now();
        let timestamp = now.format("%Y-%m-%dT%H:%M:%S%.3f").to_string();
        let mtime = now.timestamp() as f64 / 86400.0 + 2440587.5;

        let mut sorted_files: Vec<(&str, &[u8])> = files.to_vec();
        sorted_files.sort_by(|a, b| a.0.cmp(&b.0));

        let mut blobs_to_insert: Vec<(Vec<u8>, String, i64)> =
            Vec::with_capacity(sorted_files.len());
        let mut file_entries: Vec<(String, String)> = Vec::with_capacity(sorted_files.len());
        let mut r_hasher = md5::Context::new();

        for (name, content) in &sorted_files {
            let file_hash = hash::sha3_256_hex(content);
            let compressed = blob::compress(content)?;
            blobs_to_insert.push((compressed, file_hash.clone(), content.len() as i64));
            file_entries.push((name.to_string(), file_hash));
            r_hasher.consume(content);
        }

        let blob_refs: Vec<(&[u8], &str, i64)> = blobs_to_insert
            .iter()
            .map(|(c, h, s)| (c.as_slice(), h.as_str(), *s))
            .collect();
        let file_rids = self.db.insert_blobs(&blob_refs)?;

        let r_hash = format!("{:x}", r_hasher.compute());

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

        let escaped_comment = manifest::encode_fossil_string(comment);
        manifest_lines.push(format!("C {}", escaped_comment));
        manifest_lines.push(format!("D {}", timestamp));

        for (name, file_hash) in &file_entries {
            let escaped_name = manifest::encode_fossil_string(name);
            manifest_lines.push(format!("F {} {}", escaped_name, file_hash));
        }

        if let Some(parent) = parent_hash {
            manifest_lines.push(format!("P {}", parent));
        }

        manifest_lines.push(format!("R {}", r_hash));

        let branch_name = branch.unwrap_or("trunk");
        if parent_hash.is_none() || branch.is_some() {
            manifest_lines.push(format!("T *branch * {}", branch_name));
            manifest_lines.push(format!("T *sym-{} *", branch_name));
        }

        manifest_lines.push(format!("U {}", user));

        let manifest_without_z = manifest_lines.join("\n") + "\n";
        let z_hash = format!("{:x}", md5::compute(manifest_without_z.as_bytes()));
        manifest_lines.push(format!("Z {}", z_hash));

        let manifest_content = manifest_lines.join("\n") + "\n";
        let manifest_bytes = manifest_content.as_bytes();
        let manifest_hash = hash::sha3_256_hex(manifest_bytes);
        let manifest_compressed = blob::compress(manifest_bytes)?;
        let manifest_rid = self.db.insert_blob(
            &manifest_compressed,
            &manifest_hash,
            manifest_bytes.len() as i64,
        )?;

        self.db
            .insert_event("ci", manifest_rid, mtime, user, comment)?;

        if let Some(parent) = parent_hash {
            let parent_rid = self.db.get_rid_by_hash(parent)?;
            self.db.insert_plink(parent_rid, manifest_rid, mtime)?;
        } else {
            self.db.insert_leaf(manifest_rid)?;
        }

        let branch_tag_id = self.db.get_or_create_tag("branch")?;
        self.db
            .insert_tagxref(branch_tag_id, 2, manifest_rid, mtime, Some(branch_name))?;

        let sym_tag_id = self.db.get_or_create_tag(&format!("sym-{}", branch_name))?;
        self.db
            .insert_tagxref(sym_tag_id, 2, manifest_rid, mtime, None)?;

        if branch.is_some() && parent_hash.is_some() {
            let parent_rid = self.db.get_rid_by_hash(parent_hash.unwrap())?;
            if let Ok(parent_branch) = self.get_checkin_branch(parent_rid) {
                if parent_branch != branch_name {
                    let old_sym_tag_id = self
                        .db
                        .get_or_create_tag(&format!("sym-{}", parent_branch))?;
                    self.db
                        .insert_tagxref(old_sym_tag_id, 0, manifest_rid, mtime, None)?;
                }
            }
        }

        let names: Vec<&str> = file_entries.iter().map(|(n, _)| n.as_str()).collect();
        let fnid_map = self.db.get_or_create_filenames(&names)?;

        let mlink_entries: Vec<(i64, i64)> = file_entries
            .iter()
            .map(|(name, file_hash)| {
                let fnid = fnid_map.get(name).copied().unwrap_or(0);
                let frid = file_rids.get(file_hash).copied().unwrap_or(0);
                (frid, fnid)
            })
            .collect();
        self.db.insert_mlinks(manifest_rid, &mlink_entries)?;

        Ok(manifest_hash)
    }

    fn get_checkin_branch(&self, rid: i64) -> Result<String> {
        let branch: String = self.db.connection().query_row(
            "SELECT value FROM tagxref WHERE rid = ?1 AND tagid = (SELECT tagid FROM tag WHERE tagname = 'branch')",
            rusqlite::params![rid],
            |row| row.get(0),
        )?;
        Ok(branch)
    }

    pub(crate) fn create_branch_internal(
        &self,
        branch_name: &str,
        parent_hash: &str,
        user: &str,
    ) -> Result<String> {
        let comment = format!("Create new branch named \"{}\"", branch_name);

        let parent_files = self.list_files_internal(parent_hash)?;
        let mut files_content: Vec<(String, Vec<u8>)> = Vec::new();

        for file in &parent_files {
            let content = self.read_file_internal(parent_hash, &file.name)?;
            files_content.push((file.name.clone(), content));
        }

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

        self.commit_internal(&files, &comment, user, Some(parent_hash), Some(branch_name))
    }

    pub(crate) fn add_tag_internal(
        &self,
        tag_name: &str,
        checkin_hash: &str,
        user: &str,
    ) -> Result<String> {
        let rid = self.db.get_rid_by_hash(checkin_hash)?;
        let full_hash = self.db.get_hash_by_rid(rid)?;
        let now = Utc::now();
        let timestamp = now.format("%Y-%m-%dT%H:%M:%S").to_string();
        let mtime = now.timestamp() as f64 / 86400.0 + 2440587.5;

        let mut lines: Vec<String> = Vec::new();
        lines.push(format!("D {}", timestamp));
        lines.push(format!("T +sym-{} {}", tag_name, full_hash));
        lines.push(format!("U {}", user));

        let content_without_z = lines.join("\n") + "\n";
        let z_hash = format!("{:x}", md5::compute(content_without_z.as_bytes()));
        lines.push(format!("Z {}", z_hash));

        let control_content = lines.join("\n") + "\n";
        let control_bytes = control_content.as_bytes();
        let control_hash = hash::sha3_256_hex(control_bytes);
        let control_compressed = blob::compress(control_bytes)?;

        let control_rid = self.db.insert_blob(
            &control_compressed,
            &control_hash,
            control_bytes.len() as i64,
        )?;

        self.db.insert_event(
            "g",
            control_rid,
            mtime,
            user,
            &format!("Add tag {}", tag_name),
        )?;

        let tag_id = self.db.get_or_create_tag(&format!("sym-{}", tag_name))?;
        self.db.insert_tagxref(tag_id, 1, rid, mtime, None)?;

        Ok(control_hash)
    }

    pub(crate) fn create_user_internal(
        &self,
        login: &str,
        password: &str,
        capabilities: &str,
    ) -> Result<()> {
        self.db.create_user(login, password, capabilities)
    }

    pub(crate) fn set_user_capabilities_internal(
        &self,
        login: &str,
        capabilities: &str,
    ) -> Result<()> {
        self.db.set_user_capabilities(login, capabilities)
    }

    pub(crate) fn get_user_capabilities_internal(&self, login: &str) -> Result<Option<String>> {
        self.db.get_user_capabilities(login)
    }

    pub(crate) fn list_users_internal(&self) -> Result<Vec<(String, String)>> {
        self.db.list_users()
    }
}