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
//! Main filesystem interface for Heroforge repositories
//!
//! This module provides the primary API for interacting with a Heroforge repository
//! as if it were a filesystem. It handles all the complexity of the underlying
//! SQLite storage while providing a familiar, intuitive interface.
//!
//! # Overview
//!
//! The `FileSystem` type is the main entry point. It provides methods for:
//! - Reading files and directories (no commits needed)
//! - Writing, copying, moving, and deleting files (auto-commit by default)
//! - Finding files with glob patterns
//! - Checking file status and permissions
//! - Transaction support for batch operations

use crate::fs::errors::{FsError, FsResult};
use crate::fs::operations::{
    DirectoryEntry, FileMetadata, FilePermissions, FindResults, FsOperation,
};
use crate::fs::transaction::{Transaction, TransactionMode};
use crate::repo::Repository;
use std::sync::Arc;
use std::sync::Mutex;

/// Status of the filesystem interface
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileSystemStatus {
    /// Opened in read-only mode
    ReadOnly,
    /// Opened in read-write mode
    ReadWrite,
    /// Transaction is active
    TransactionActive,
    /// Closed/disposed
    Closed,
}

/// Handle to a file in the repository
#[derive(Debug, Clone)]
pub struct FileHandle {
    /// Path to the file
    pub path: String,
    /// File metadata
    pub metadata: FileMetadata,
    /// Commit hash where file exists
    pub commit: String,
}

/// Main filesystem interface for Heroforge repositories
///
/// This provides a filesystem-like API over the Heroforge repository storage.
/// All operations are atomic and maintain version history.
///
/// # Thread Safety
///
/// `FileSystem` is thread-safe. Multiple threads can read simultaneously,
/// but writes are serialized through an internal mutex.
///
/// # Example
///
/// ```no_run
/// use heroforge_core::Repository;
/// use heroforge_core::fs::FileSystem;
/// use std::sync::Arc;
///
/// fn main() -> heroforge_core::Result<()> {
///     let repo = Arc::new(Repository::open_rw("project.forge")?);
///     let fs = FileSystem::new(repo);
///
///     // Read without commit
///     let exists = fs.exists("README.md")?;
///     if !exists {
///         // Write with auto-commit
///         fs.write_file("README.md", b"# My Project", "admin", "Initialize README")?;
///     }
///
///     Ok(())
/// }
/// ```
pub struct FileSystem {
    /// Reference to the underlying repository
    repo: Arc<Repository>,

    /// Current status
    status: Arc<Mutex<FileSystemStatus>>,

    /// Active transaction (if any)
    active_transaction: Arc<Mutex<Option<Transaction>>>,

    /// Write lock for serializing concurrent writes
    write_lock: Arc<Mutex<()>>,
}

impl FileSystem {
    /// Create a new filesystem interface for a repository
    pub fn new(repo: Arc<Repository>) -> Self {
        Self {
            repo,
            status: Arc::new(Mutex::new(FileSystemStatus::ReadWrite)),
            active_transaction: Arc::new(Mutex::new(None)),
            write_lock: Arc::new(Mutex::new(())),
        }
    }

    /// Get current status
    pub fn status(&self) -> FileSystemStatus {
        *self.status.lock().unwrap()
    }

    /// Check if a path exists
    ///
    /// # Arguments
    ///
    /// * `path` - Path to check (relative to repository root)
    ///
    /// # Returns
    ///
    /// `true` if path exists, `false` otherwise
    pub fn exists(&self, path: &str) -> FsResult<bool> {
        self.validate_path(path)?;
        // TODO: Implement by checking manifest at trunk
        Ok(true)
    }

    /// Check if path is a directory
    pub fn is_dir(&self, path: &str) -> FsResult<bool> {
        self.validate_path(path)?;
        let metadata = self.stat(path)?;
        Ok(metadata.is_dir)
    }

    /// Check if path is a file
    pub fn is_file(&self, path: &str) -> FsResult<bool> {
        self.validate_path(path)?;
        let metadata = self.stat(path)?;
        Ok(!metadata.is_dir)
    }

    /// Get file metadata
    ///
    /// # Arguments
    ///
    /// * `path` - Path to file/directory
    ///
    /// # Returns
    ///
    /// File metadata including size, permissions, etc.
    pub fn stat(&self, path: &str) -> FsResult<FileMetadata> {
        self.validate_path(path)?;
        // TODO: Implement by querying manifest
        Ok(FileMetadata {
            path: path.to_string(),
            is_dir: false,
            size: 0,
            permissions: FilePermissions::file(),
            is_symlink: false,
            symlink_target: None,
            modified: 0,
            hash: None,
            kind: crate::fs::operations::FileKind::File,
        })
    }

    /// Read file content as bytes
    ///
    /// # Arguments
    ///
    /// * `path` - Path to file
    ///
    /// # Returns
    ///
    /// File content as `Vec<u8>`
    pub fn read_file(&self, path: &str) -> FsResult<Vec<u8>> {
        self.validate_path(path)?;
        self.validate_is_file(path)?;
        // TODO: Implement by reading from blob storage
        Ok(Vec::new())
    }

    /// Read file content as string
    ///
    /// # Arguments
    ///
    /// * `path` - Path to file
    ///
    /// # Returns
    ///
    /// File content as `String`
    pub fn read_file_string(&self, path: &str) -> FsResult<String> {
        let bytes = self.read_file(path)?;
        String::from_utf8(bytes).map_err(|e| FsError::Encoding(e.to_string()))
    }

    /// List directory contents
    ///
    /// # Arguments
    ///
    /// * `path` - Directory path
    ///
    /// # Returns
    ///
    /// Vector of directory entries
    pub fn list_dir(&self, path: &str) -> FsResult<Vec<DirectoryEntry>> {
        self.validate_path(path)?;
        self.validate_is_directory(path)?;
        // TODO: Implement by traversing manifest
        Ok(Vec::new())
    }

    /// Write file content (creates or overwrites)
    ///
    /// # Arguments
    ///
    /// * `path` - Path to file
    /// * `content` - File content
    /// * `author` - Author name
    /// * `message` - Commit message
    ///
    /// # Returns
    ///
    /// Commit hash of the change
    pub fn write_file(
        &self,
        path: &str,
        content: &[u8],
        author: &str,
        message: &str,
    ) -> FsResult<String> {
        self.validate_path(path)?;
        let _lock = self.write_lock.lock();

        // Create operation
        let _op = FsOperation::WriteFile {
            path: path.to_string(),
            content: content.to_vec(),
        };

        // TODO: Execute operation and create commit
        // For now, return a dummy hash
        let _ = (author, message); // Use parameters
        Ok("commit_abc123def".to_string())
    }

    /// Copy a file
    pub fn copy_file(&self, src: &str, dst: &str, author: &str, message: &str) -> FsResult<String> {
        self.validate_path(src)?;
        self.validate_path(dst)?;
        self.validate_is_file(src)?;
        let _lock = self.write_lock.lock();

        let _op = FsOperation::CopyFile {
            src: src.to_string(),
            dst: dst.to_string(),
        };

        // TODO: Execute operation and create commit
        let _ = (author, message); // Use parameters
        Ok("commit_abc123def".to_string())
    }

    /// Copy a directory recursively
    pub fn copy_dir(&self, src: &str, dst: &str, author: &str, message: &str) -> FsResult<String> {
        self.validate_path(src)?;
        self.validate_path(dst)?;
        self.validate_is_directory(src)?;
        let _lock = self.write_lock.lock();

        let _op = FsOperation::CopyDir {
            src: src.to_string(),
            dst: dst.to_string(),
        };

        // TODO: Execute operation and create commit
        let _ = (author, message); // Use parameters
        Ok("commit_abc123def".to_string())
    }

    /// Move/rename a file
    pub fn move_file(&self, src: &str, dst: &str, author: &str, message: &str) -> FsResult<String> {
        self.validate_path(src)?;
        self.validate_path(dst)?;
        self.validate_is_file(src)?;
        let _lock = self.write_lock.lock();

        let _op = FsOperation::MoveFile {
            src: src.to_string(),
            dst: dst.to_string(),
        };

        // TODO: Execute operation and create commit
        let _ = (author, message); // Use parameters
        Ok("commit_abc123def".to_string())
    }

    /// Move/rename a directory
    pub fn move_dir(&self, src: &str, dst: &str, author: &str, message: &str) -> FsResult<String> {
        self.validate_path(src)?;
        self.validate_path(dst)?;
        self.validate_is_directory(src)?;
        let _lock = self.write_lock.lock();

        let _op = FsOperation::MoveDir {
            src: src.to_string(),
            dst: dst.to_string(),
        };

        // TODO: Execute operation and create commit
        let _ = (author, message); // Use parameters
        Ok("commit_abc123def".to_string())
    }

    /// Delete a file
    pub fn delete_file(&self, path: &str, author: &str, message: &str) -> FsResult<String> {
        self.validate_path(path)?;
        self.validate_is_file(path)?;
        let _lock = self.write_lock.lock();

        let _op = FsOperation::DeleteFile {
            path: path.to_string(),
        };

        // TODO: Execute operation and create commit
        let _ = (author, message); // Use parameters
        Ok("commit_abc123def".to_string())
    }

    /// Delete a directory recursively
    pub fn delete_dir(&self, path: &str, author: &str, message: &str) -> FsResult<String> {
        self.validate_path(path)?;
        self.validate_is_directory(path)?;
        let _lock = self.write_lock.lock();

        let _op = FsOperation::DeleteDir {
            path: path.to_string(),
        };

        // TODO: Execute operation and create commit
        let _ = (author, message); // Use parameters
        Ok("commit_abc123def".to_string())
    }

    /// Change file permissions
    pub fn chmod(
        &self,
        path: &str,
        permissions: FilePermissions,
        author: &str,
        message: &str,
    ) -> FsResult<String> {
        self.validate_path(path)?;
        let _lock = self.write_lock.lock();

        let _op = FsOperation::Chmod {
            path: path.to_string(),
            permissions,
            recursive: false,
        };

        // TODO: Execute operation and create commit
        let _ = (author, message); // Use parameters
        Ok("commit_abc123def".to_string())
    }

    /// Change permissions recursively
    pub fn chmod_recursive(
        &self,
        path: &str,
        permissions: FilePermissions,
        author: &str,
        message: &str,
    ) -> FsResult<String> {
        self.validate_path(path)?;
        let _lock = self.write_lock.lock();

        let _op = FsOperation::Chmod {
            path: path.to_string(),
            permissions,
            recursive: true,
        };

        // TODO: Execute operation and create commit
        let _ = (author, message); // Use parameters
        Ok("commit_abc123def".to_string())
    }

    /// Make file executable
    pub fn make_executable(&self, path: &str, author: &str, message: &str) -> FsResult<String> {
        self.validate_path(path)?;
        self.validate_is_file(path)?;
        let _lock = self.write_lock.lock();

        let _op = FsOperation::MakeExecutable {
            path: path.to_string(),
        };

        // TODO: Execute operation and create commit
        let _ = (author, message); // Use parameters
        Ok("commit_abc123def".to_string())
    }

    /// Create a symbolic link
    pub fn symlink(
        &self,
        link_path: &str,
        target_path: &str,
        author: &str,
        message: &str,
    ) -> FsResult<String> {
        self.validate_path(link_path)?;
        let _lock = self.write_lock.lock();

        let _op = FsOperation::Symlink {
            link_path: link_path.to_string(),
            target_path: target_path.to_string(),
        };

        // TODO: Execute operation and create commit
        let _ = (author, message); // Use parameters
        Ok("commit_abc123def".to_string())
    }

    /// Find files matching a glob pattern
    ///
    /// # Arguments
    ///
    /// * `pattern` - Glob pattern (e.g., "**/*.rs")
    ///
    /// # Returns
    ///
    /// List of matching file paths
    pub fn find(&self, pattern: &str) -> FsResult<FindResults> {
        // Validate pattern
        if pattern.is_empty() {
            return Err(FsError::PatternError("Pattern cannot be empty".to_string()));
        }

        // TODO: Implement glob matching
        Ok(FindResults::new())
    }

    /// Calculate disk usage of a path
    ///
    /// # Arguments
    ///
    /// * `path` - Path to directory or file
    ///
    /// # Returns
    ///
    /// Total size in bytes
    pub fn disk_usage(&self, path: &str) -> FsResult<u64> {
        self.validate_path(path)?;
        // TODO: Implement by traversing manifests
        Ok(0)
    }

    /// Count files matching a pattern
    ///
    /// # Arguments
    ///
    /// * `pattern` - Glob pattern
    ///
    /// # Returns
    ///
    /// Number of matching files
    pub fn count_files(&self, pattern: &str) -> FsResult<usize> {
        let results = self.find(pattern)?;
        Ok(results.count)
    }

    /// Begin a transaction for batch operations
    ///
    /// # Returns
    ///
    /// A transaction that can be used to group multiple operations
    pub fn begin_transaction(&self) -> FsResult<Transaction> {
        let tx = Transaction::new(TransactionMode::ReadWrite);

        let mut active = self.active_transaction.lock().unwrap();
        if active.is_some() {
            return Err(FsError::TransactionError(
                "Transaction already active".to_string(),
            ));
        }

        *active = Some(tx.clone());
        Ok(tx)
    }

    /// End the active transaction
    pub fn end_transaction(&self) -> FsResult<()> {
        let mut active = self.active_transaction.lock().unwrap();
        *active = None;
        Ok(())
    }

    /// Check if a transaction is active
    pub fn has_active_transaction(&self) -> bool {
        self.active_transaction.lock().unwrap().is_some()
    }

    /// Get the active transaction (if any)
    pub fn active_transaction(&self) -> Option<Transaction> {
        self.active_transaction.lock().unwrap().clone()
    }

    // Helper methods

    /// Validate path format
    fn validate_path(&self, path: &str) -> FsResult<()> {
        if path.is_empty() {
            return Err(FsError::InvalidPath("Path cannot be empty".to_string()));
        }

        if path.contains('\0') {
            return Err(FsError::InvalidPath(
                "Path cannot contain null bytes".to_string(),
            ));
        }

        // Normalize path - remove double slashes, etc.
        Ok(())
    }

    /// Validate that path points to a file
    fn validate_is_file(&self, path: &str) -> FsResult<()> {
        let metadata = self.stat(path)?;
        if metadata.is_dir {
            return Err(FsError::NotAFile(path.to_string()));
        }
        Ok(())
    }

    /// Validate that path points to a directory
    fn validate_is_directory(&self, path: &str) -> FsResult<()> {
        let metadata = self.stat(path)?;
        if !metadata.is_dir {
            return Err(FsError::NotADirectory(path.to_string()));
        }
        Ok(())
    }
}

impl Clone for FileSystem {
    fn clone(&self) -> Self {
        Self {
            repo: Arc::clone(&self.repo),
            status: Arc::clone(&self.status),
            active_transaction: Arc::clone(&self.active_transaction),
            write_lock: Arc::clone(&self.write_lock),
        }
    }
}

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

    #[test]
    fn test_filesystem_creation() {
        // This would need a real repo to test
        // let fs = FileSystem::new(Arc::new(repo));
        // assert_eq!(fs.status(), FileSystemStatus::ReadWrite);
    }

    #[test]
    fn test_path_validation() {
        // Test with a mock setup
    }
}