Skip to main content

git2db/
registration_builder.rs

1//! Fluent builder API for registering repositories and worktrees
2//!
3//! Provides a git-native interface for registration with flexible configuration options
4
5use crate::errors::{Git2DBError, Git2DBResult};
6use crate::references::GitRef;
7use crate::registry::{Git2DB, RemoteConfig, RepoId};
8use std::collections::HashMap;
9use std::path::PathBuf;
10
11/// Builder for registering repositories and worktrees
12///
13/// Provides a chainable interface for configuring registration operations.
14/// This is the recommended way to register repos, worktrees, and adapters.
15///
16/// # Examples
17///
18/// ```rust,no_run
19/// # async fn example(registry: &mut git2db::Git2DB) -> Result<(), Box<dyn std::error::Error>> {
20/// use git2db::{RepoId, GitRef};
21/// use std::path::PathBuf;
22///
23/// // Register a worktree (adapter)
24/// let adapter_id = RepoId::new();
25/// registry.register(adapter_id)
26///     .name("my-adapter")
27///     .worktree_path(PathBuf::from("/models/working/adapter-uuid"))
28///     .tracking_ref(GitRef::Branch("adapter/uuid".to_owned()))
29///     .metadata("type", "adapter")
30///     .metadata("base_model", "llama-uuid")
31///     .exec()
32///     .await?;
33///
34/// // Register a cloned repository
35/// let model_id = RepoId::new();
36/// registry.register(model_id)
37///     .name("llama-3")
38///     .url("https://github.com/meta/llama")
39///     .worktree_path(PathBuf::from("/models/llama-uuid"))
40///     .remote("origin", "https://github.com/meta/llama")
41///     .exec()
42///     .await?;
43/// # Ok(())
44/// # }
45/// ```
46pub struct RegistrationBuilder<'a> {
47    registry: &'a mut Git2DB,
48    repo_id: RepoId,
49    name: Option<String>,
50    url: String,
51    worktree_path: Option<PathBuf>,
52    tracking_ref: GitRef,
53    remotes: Vec<RemoteConfig>,
54    metadata: HashMap<String, String>,
55}
56
57impl<'a> RegistrationBuilder<'a> {
58    /// Create a new registration builder
59    pub(crate) fn new(registry: &'a mut Git2DB, repo_id: RepoId) -> Self {
60        Self {
61            registry,
62            repo_id,
63            name: None,
64            url: String::new(),
65            worktree_path: None,
66            tracking_ref: GitRef::DefaultBranch,
67            remotes: Vec::new(),
68            metadata: HashMap::new(),
69        }
70    }
71
72    /// Set the repository name
73    ///
74    /// This is a human-friendly name for looking up the repository.
75    pub fn name(mut self, name: impl Into<String>) -> Self {
76        self.name = Some(name.into());
77        self
78    }
79
80    /// Set the remote URL
81    ///
82    /// For local worktrees/adapters, this can be an empty string.
83    pub fn url(mut self, url: impl Into<String>) -> Self {
84        self.url = url.into();
85        self
86    }
87
88    /// Set the worktree path
89    ///
90    /// This is the actual filesystem location of the repository or worktree.
91    /// **REQUIRED** - must be called before exec().
92    ///
93    /// The path must exist before registration.
94    pub fn worktree_path(mut self, path: impl Into<PathBuf>) -> Self {
95        self.worktree_path = Some(path.into());
96        self
97    }
98
99    /// Set the tracking ref
100    ///
101    /// Specifies which branch, tag, or commit this repository tracks.
102    /// Defaults to `GitRef::DefaultBranch` if not specified.
103    pub fn tracking_ref(mut self, git_ref: GitRef) -> Self {
104        self.tracking_ref = git_ref;
105        self
106    }
107
108    /// Add a remote
109    ///
110    /// Can be called multiple times to add multiple remotes.
111    pub fn remote(mut self, name: impl Into<String>, url: impl Into<String>) -> Self {
112        self.remotes.push(RemoteConfig {
113            name: name.into(),
114            url: url.into(),
115            fetch_refs: vec![],
116        });
117        self
118    }
119
120    /// Add metadata key-value pair
121    ///
122    /// Metadata is stored in the registry and can be used for domain-specific
123    /// information like adapter type, base model ID, etc.
124    ///
125    /// Can be called multiple times to add multiple metadata entries.
126    pub fn metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
127        self.metadata.insert(key.into(), value.into());
128        self
129    }
130
131    /// Execute the registration
132    ///
133    /// Validates configuration and registers the repository/worktree in the registry.
134    ///
135    /// # Errors
136    ///
137    /// Returns an error if:
138    /// - `worktree_path` was not specified
139    /// - The worktree path does not exist
140    /// - The repository ID is already registered
141    /// - Git operations fail (submodule creation, commit, etc.)
142    pub async fn exec(self) -> Git2DBResult<()> {
143        // Validate required fields
144        let worktree_path = self.worktree_path.ok_or_else(|| {
145            Git2DBError::configuration(
146                "worktree_path is required for registration. Call .worktree_path() before .exec()",
147            )
148        })?;
149
150        if !worktree_path.exists() {
151            return Err(Git2DBError::invalid_repository(
152                self.repo_id.to_string(),
153                format!("Worktree path does not exist: {}", worktree_path.display()),
154            ));
155        }
156
157        // Call the internal registration method
158        self.registry
159            .register_repository_internal(
160                self.repo_id,
161                self.name,
162                self.url,
163                worktree_path,
164                self.tracking_ref,
165                self.remotes,
166                self.metadata,
167            )
168            .await
169    }
170}