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
//! Git import builder for importing git repositories into heroforge.
//!
//! This module provides functionality to clone a git repository and import
//! its contents (without history) into a heroforge repository.
//!
//! # Overview
//!
//! The git import feature allows you to:
//! - Clone a git repository to a temporary location
//! - Checkout a specific branch, tag, or commit
//! - Import all files into a new heroforge repository
//! - Optionally filter files during import
//!
//! # Example
//!
//! ```no_run
//! use heroforge_core::Repository;
//!
//! let repo = Repository::init("imported.fossil")?;
//!
//! repo.git_import()
//!     .url("https://github.com/user/project.git")
//!     .branch("main")
//!     .message("Import from git repository")
//!     .author("developer")
//!     .execute()?;
//! # Ok::<(), heroforge_core::FossilError>(())
//! ```

use crate::error::{FossilError, Result};
use crate::repo::Repository;
use std::fs;
use std::path::Path;

/// Builder for importing a git repository into heroforge.
///
/// This builder clones a git repository and imports its contents
/// (without git history) into a heroforge repository as a single commit.
///
/// # Examples
///
/// ## Import from a branch
///
/// ```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("Initial import from git")
///     .author("developer")
///     .execute()?;
/// # Ok::<(), heroforge_core::FossilError>(())
/// ```
///
/// ## Import from a tag
///
/// ```no_run
/// # use heroforge_core::Repository;
/// # let repo = Repository::init("project.fossil")?;
/// repo.git_import()
///     .url("https://github.com/user/project.git")
///     .tag("v1.0.0")
///     .message("Import v1.0.0 release")
///     .author("developer")
///     .execute()?;
/// # Ok::<(), heroforge_core::FossilError>(())
/// ```
///
/// ## Import with file filtering
///
/// ```no_run
/// # use heroforge_core::Repository;
/// # let repo = Repository::init("project.fossil")?;
/// repo.git_import()
///     .url("https://github.com/user/project.git")
///     .branch("main")
///     .include_pattern("src/**/*.rs")
///     .include_pattern("Cargo.toml")
///     .exclude_pattern("**/test/**")
///     .message("Import source files only")
///     .author("developer")
///     .execute()?;
/// # Ok::<(), heroforge_core::FossilError>(())
/// ```
pub struct GitImportBuilder<'a> {
    repo: &'a Repository,
    git_url: Option<String>,
    branch: Option<String>,
    tag: Option<String>,
    commit: Option<String>,
    message: Option<String>,
    author: Option<String>,
    include_patterns: Vec<String>,
    exclude_patterns: Vec<String>,
    target_branch: Option<String>,
    parent_commit: Option<String>,
}

impl<'a> GitImportBuilder<'a> {
    pub(crate) fn new(repo: &'a Repository) -> Self {
        Self {
            repo,
            git_url: None,
            branch: None,
            tag: None,
            commit: None,
            message: None,
            author: None,
            include_patterns: Vec::new(),
            exclude_patterns: Vec::new(),
            target_branch: None,
            parent_commit: None,
        }
    }

    /// Set the git repository URL to clone.
    ///
    /// Supports HTTPS and SSH URLs.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use heroforge_core::Repository;
    /// # let repo = Repository::init("project.fossil")?;
    /// repo.git_import()
    ///     .url("https://github.com/user/project.git")
    ///     // ...
    /// # ;
    /// # Ok::<(), heroforge_core::FossilError>(())
    /// ```
    pub fn url(mut self, url: &str) -> Self {
        self.git_url = Some(url.to_string());
        self
    }

    /// Checkout a specific branch after cloning.
    ///
    /// If neither branch, tag, nor commit is specified, the default branch is used.
    pub fn branch(mut self, branch: &str) -> Self {
        self.branch = Some(branch.to_string());
        self
    }

    /// Checkout a specific tag after cloning.
    pub fn tag(mut self, tag: &str) -> Self {
        self.tag = Some(tag.to_string());
        self
    }

    /// Checkout a specific commit hash after cloning.
    pub fn commit_hash(mut self, hash: &str) -> Self {
        self.commit = Some(hash.to_string());
        self
    }

    /// Set the commit message for the import.
    pub fn message(mut self, msg: &str) -> Self {
        self.message = Some(msg.to_string());
        self
    }

    /// Set the author for the import commit.
    pub fn author(mut self, author: &str) -> Self {
        self.author = Some(author.to_string());
        self
    }

    /// Add a glob pattern to include files.
    ///
    /// If no include patterns are specified, all files are included.
    /// If any include patterns are specified, only matching files are included.
    ///
    /// # 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")
    ///     .include_pattern("**/*.rs")
    ///     .include_pattern("**/*.toml")
    ///     .message("Import Rust files only")
    ///     .author("developer")
    ///     .execute()?;
    /// # Ok::<(), heroforge_core::FossilError>(())
    /// ```
    pub fn include_pattern(mut self, pattern: &str) -> Self {
        self.include_patterns.push(pattern.to_string());
        self
    }

    /// Add a glob pattern to exclude files.
    ///
    /// Exclude patterns are applied after include patterns.
    ///
    /// # 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")
    ///     .exclude_pattern("**/test/**")
    ///     .exclude_pattern("**/*.md")
    ///     .message("Import without tests and docs")
    ///     .author("developer")
    ///     .execute()?;
    /// # Ok::<(), heroforge_core::FossilError>(())
    /// ```
    pub fn exclude_pattern(mut self, pattern: &str) -> Self {
        self.exclude_patterns.push(pattern.to_string());
        self
    }

    /// Set the target branch in the heroforge repository.
    ///
    /// If not specified, commits to trunk.
    pub fn to_branch(mut self, branch: &str) -> Self {
        self.target_branch = Some(branch.to_string());
        self
    }

    /// Set the parent commit for the import.
    ///
    /// If not specified, creates an initial commit or uses trunk tip.
    pub fn parent(mut self, hash: &str) -> Self {
        self.parent_commit = Some(hash.to_string());
        self
    }

    /// Execute the git import operation.
    ///
    /// This will:
    /// 1. Clone the git repository to a temporary directory
    /// 2. Checkout the specified branch/tag/commit
    /// 3. Collect all files (applying include/exclude filters)
    /// 4. Create a commit in the heroforge repository
    ///
    /// Returns the hash of the created commit.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No git URL was specified
    /// - No commit message was specified
    /// - No author was specified
    /// - Git clone or checkout fails
    /// - File reading fails
    pub fn execute(self) -> Result<String> {
        use herolib_os::git::GitTree;

        let git_url = self.git_url.clone().ok_or_else(|| {
            FossilError::InvalidArtifact("git URL is required for git import".to_string())
        })?;

        let message = self.message.clone().ok_or_else(|| {
            FossilError::InvalidArtifact("commit message is required for git import".to_string())
        })?;

        let author = self.author.clone().ok_or_else(|| {
            FossilError::InvalidArtifact("author is required for git import".to_string())
        })?;

        // Create a temporary directory for the clone
        let temp_base =
            std::env::temp_dir().join(format!("heroforge_git_import_{}", uuid::Uuid::new_v4()));
        fs::create_dir_all(&temp_base)?;

        // Use herolib-os's GitTree for cloning
        let git_tree = GitTree::new(temp_base.to_string_lossy().as_ref()).map_err(|e| {
            let _ = fs::remove_dir_all(&temp_base);
            FossilError::InvalidArtifact(format!("Failed to create git tree: {}", e))
        })?;

        // Clone the repository with optional branch
        let branch_ref = self
            .branch
            .as_deref()
            .or(self.tag.as_deref())
            .or(self.commit.as_deref());

        let clone_result = if let Some(branch) = branch_ref {
            git_tree.clone_repo(&git_url).branch(branch).execute()
        } else {
            git_tree.clone_repo(&git_url).execute()
        };

        let cloned_path = clone_result.map_err(|e| {
            let _ = fs::remove_dir_all(&temp_base);
            FossilError::InvalidArtifact(format!("Failed to clone git repository: {}", e))
        })?;

        // Collect files from the cloned repository
        let cloned_dir = Path::new(&cloned_path);
        let files = self.collect_files(cloned_dir).map_err(|e| {
            let _ = fs::remove_dir_all(&temp_base);
            e
        })?;

        // Clean up the temp directory
        let _ = fs::remove_dir_all(&temp_base);

        if files.is_empty() {
            return Err(FossilError::InvalidArtifact(
                "No files found to import (check include/exclude patterns)".to_string(),
            ));
        }

        // Determine parent commit
        let parent = if let Some(ref p) = self.parent_commit {
            Some(p.clone())
        } else {
            // Try to get trunk tip, if it exists
            self.repo
                .branch_tip_internal("trunk")
                .ok()
                .map(|tip| tip.hash)
        };

        // Create the commit
        let files_refs: Vec<(&str, &[u8])> = files
            .iter()
            .map(|(path, content)| (path.as_str(), content.as_slice()))
            .collect();

        self.repo.commit_internal(
            &files_refs,
            &message,
            &author,
            parent.as_deref(),
            self.target_branch.as_deref(),
        )
    }

    /// Collect files from a directory, applying include/exclude filters.
    fn collect_files(&self, dir: &Path) -> Result<Vec<(String, Vec<u8>)>> {
        let mut files = Vec::new();

        // Compile include patterns
        let include_patterns: Vec<glob::Pattern> = self
            .include_patterns
            .iter()
            .filter_map(|p| glob::Pattern::new(p).ok())
            .collect();

        // Compile exclude patterns
        let exclude_patterns: Vec<glob::Pattern> = self
            .exclude_patterns
            .iter()
            .filter_map(|p| glob::Pattern::new(p).ok())
            .collect();

        // Always exclude .git directory
        let git_exclude = glob::Pattern::new(".git/**").unwrap();
        let git_dir_exclude = glob::Pattern::new(".git").unwrap();

        self.collect_files_recursive(
            dir,
            dir,
            &include_patterns,
            &exclude_patterns,
            &git_exclude,
            &git_dir_exclude,
            &mut files,
        )?;

        Ok(files)
    }

    fn collect_files_recursive(
        &self,
        base_dir: &Path,
        current_dir: &Path,
        include_patterns: &[glob::Pattern],
        exclude_patterns: &[glob::Pattern],
        git_exclude: &glob::Pattern,
        git_dir_exclude: &glob::Pattern,
        files: &mut Vec<(String, Vec<u8>)>,
    ) -> Result<()> {
        let entries = fs::read_dir(current_dir)?;

        for entry in entries {
            let entry = entry?;

            let path = entry.path();
            let relative_path = path
                .strip_prefix(base_dir)
                .unwrap_or(&path)
                .to_string_lossy()
                .to_string();

            // Skip .git directory
            if git_exclude.matches(&relative_path) || git_dir_exclude.matches(&relative_path) {
                continue;
            }

            if path.is_dir() {
                self.collect_files_recursive(
                    base_dir,
                    &path,
                    include_patterns,
                    exclude_patterns,
                    git_exclude,
                    git_dir_exclude,
                    files,
                )?;
            } else if path.is_file() {
                // Check include patterns (if any specified)
                let included = if include_patterns.is_empty() {
                    true
                } else {
                    include_patterns.iter().any(|p| p.matches(&relative_path))
                };

                // Check exclude patterns
                let excluded = exclude_patterns.iter().any(|p| p.matches(&relative_path));

                if included && !excluded {
                    let content = fs::read(&path)?;

                    // Normalize path separators
                    let normalized_path = relative_path.replace('\\', "/");
                    files.push((normalized_path, content));
                }
            }
        }

        Ok(())
    }
}

/// Result of a git import operation.
#[derive(Debug)]
pub struct GitImportResult {
    /// Hash of the created commit.
    pub commit_hash: String,
    /// Number of files imported.
    pub files_imported: usize,
    /// Total size of imported files in bytes.
    pub total_size: usize,
}