1use crate::errors::{Git2DBError, Git2DBResult};
6use crate::references::{GitRef, IntoGitRef};
7use crate::registry::{Git2DB, RepoId};
8use crate::repo_accessor::RepositoryAccessor;
9use git2::{BranchType, Oid, Repository};
10
11pub struct BranchManager<'a> {
42 registry: &'a Git2DB,
43 repo_id: RepoId,
44}
45
46impl<'a> RepositoryAccessor for BranchManager<'a> {
47 fn registry(&self) -> &Git2DB {
48 self.registry
49 }
50
51 fn repo_id(&self) -> &RepoId {
52 &self.repo_id
53 }
54}
55
56impl<'a> BranchManager<'a> {
57 pub(crate) fn new(registry: &'a Git2DB, repo_id: RepoId) -> Self {
59 Self { registry, repo_id }
60 }
61
62 pub async fn list(&self) -> Git2DBResult<Vec<Branch>> {
66 let path = self.repo_path()?;
67
68 tokio::task::spawn_blocking(move || {
69 let repo = Repository::open(&path).map_err(|e| {
70 Git2DBError::repository(&path, format!("Failed to open repository: {e}"))
71 })?;
72
73 let mut branches = Vec::new();
74
75 let head_ref = repo.head().ok();
77 let head_name = head_ref
78 .as_ref()
79 .and_then(|h| h.shorthand())
80 .map(std::borrow::ToOwned::to_owned);
81
82 for (branch, _) in (repo.branches(Some(BranchType::Local)).map_err(|e| {
84 Git2DBError::internal(format!("Failed to list local branches: {e}"))
85 })?)
86 .flatten()
87 {
88 if let Some(name) = branch.name().ok().flatten() {
89 let is_head = head_name.as_deref() == Some(name);
90 let oid = branch.get().target();
91
92 branches.push(Branch {
93 name: name.to_owned(),
94 branch_type: BranchKind::Local,
95 is_head,
96 oid,
97 tracking: branch.upstream().ok().and_then(|u| {
98 u.name().ok().flatten().map(std::borrow::ToOwned::to_owned)
99 }),
100 });
101 }
102 }
103
104 for (branch, _) in (repo.branches(Some(BranchType::Remote)).map_err(|e| {
106 Git2DBError::internal(format!("Failed to list remote branches: {e}"))
107 })?)
108 .flatten()
109 {
110 if let Some(name) = branch.name().ok().flatten() {
111 let oid = branch.get().target();
112
113 branches.push(Branch {
114 name: name.to_owned(),
115 branch_type: BranchKind::Remote,
116 is_head: false,
117 oid,
118 tracking: None,
119 });
120 }
121 }
122
123 Ok(branches)
124 })
125 .await
126 .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))?
127 }
128
129 pub async fn current(&self) -> Git2DBResult<Option<Branch>> {
133 let path = self.repo_path()?;
134
135 tokio::task::spawn_blocking(move || {
136 let repo = Repository::open(&path).map_err(|e| {
137 Git2DBError::repository(&path, format!("Failed to open repository: {e}"))
138 })?;
139
140 let head = repo
141 .head()
142 .map_err(|e| Git2DBError::reference("HEAD", format!("Failed to get HEAD: {e}")))?;
143
144 if !head.is_branch() {
146 return Ok(None);
147 }
148
149 let name = head
150 .shorthand()
151 .ok_or_else(|| Git2DBError::reference("HEAD", "HEAD has no name"))?
152 .to_owned();
153
154 let oid = head.target();
155
156 let tracking = if let Ok(branch) = repo.find_branch(&name, BranchType::Local) {
158 branch
159 .upstream()
160 .ok()
161 .and_then(|u| u.name().ok().flatten().map(std::borrow::ToOwned::to_owned))
162 } else {
163 None
164 };
165
166 Ok(Some(Branch {
167 name,
168 branch_type: BranchKind::Local,
169 is_head: true,
170 oid,
171 tracking,
172 }))
173 })
174 .await
175 .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))?
176 }
177
178 pub async fn create<R: IntoGitRef>(&self, name: &str, from: Option<R>) -> Git2DBResult<()> {
202 let path = self.repo_path()?;
203 let name = name.to_owned();
204 let from_ref = from.map(super::references::IntoGitRef::into_git_ref);
205
206 tokio::task::spawn_blocking(move || {
207 let repo = Repository::open(&path).map_err(|e| {
208 Git2DBError::repository(&path, format!("Failed to open repository: {e}"))
209 })?;
210
211 let commit = if let Some(git_ref) = from_ref {
213 let ref_str = git_ref.display_name();
214
215 let oid = match git_ref {
217 GitRef::DefaultBranch => {
218 let head = repo.head().map_err(|e| {
219 Git2DBError::reference("HEAD", format!("Failed to get HEAD: {e}"))
220 })?;
221 head.peel_to_commit()
222 .map_err(|e| {
223 Git2DBError::reference("HEAD", format!("HEAD is not a commit: {e}"))
224 })?
225 .id()
226 }
227 GitRef::Commit(oid) => oid,
228 GitRef::Branch(branch_name)
229 | GitRef::Tag(branch_name)
230 | GitRef::Revspec(branch_name) => {
231 let obj = repo.revparse_single(&branch_name).map_err(|e| {
232 Git2DBError::reference(
233 &ref_str,
234 format!("Failed to resolve reference: {e}"),
235 )
236 })?;
237 obj.peel_to_commit()
238 .map_err(|e| {
239 Git2DBError::reference(&ref_str, format!("Not a commit: {e}"))
240 })?
241 .id()
242 }
243 };
244
245 repo.find_commit(oid).map_err(|e| {
246 Git2DBError::reference(&ref_str, format!("Failed to find commit: {e}"))
247 })?
248 } else {
249 let head = repo.head().map_err(|e| {
251 Git2DBError::reference("HEAD", format!("Failed to get HEAD: {e}"))
252 })?;
253 head.peel_to_commit().map_err(|e| {
254 Git2DBError::reference("HEAD", format!("HEAD is not a commit: {e}"))
255 })?
256 };
257
258 repo.branch(&name, &commit, false).map_err(|e| {
260 Git2DBError::reference(&name, format!("Failed to create branch: {e}"))
261 })?;
262
263 Ok(())
264 })
265 .await
266 .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))?
267 }
268
269 pub async fn checkout(&self, name: &str) -> Git2DBResult<()> {
273 let path = self.repo_path()?;
274 let name = name.to_owned();
275
276 tokio::task::spawn_blocking(move || {
277 let repo = Repository::open(&path).map_err(|e| {
278 Git2DBError::repository(&path, format!("Failed to open repository: {e}"))
279 })?;
280
281 let branch = repo
283 .find_branch(&name, BranchType::Local)
284 .map_err(|_| Git2DBError::reference(&name, "Branch not found"))?;
285
286 let reference = branch.into_reference();
287 let commit = reference
288 .peel_to_commit()
289 .map_err(|e| Git2DBError::reference(&name, format!("Failed to get commit: {e}")))?;
290
291 repo.checkout_tree(commit.as_object(), None)
293 .map_err(|e| Git2DBError::internal(format!("Failed to checkout tree: {e}")))?;
294
295 repo.set_head(&format!("refs/heads/{name}"))
297 .map_err(|e| Git2DBError::internal(format!("Failed to update HEAD: {e}")))?;
298
299 Ok(())
300 })
301 .await
302 .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))?
303 }
304
305 pub async fn remove(&self, name: &str, force: bool) -> Git2DBResult<()> {
309 if let Ok(Some(current)) = self.current().await {
311 if current.name == name {
312 return Err(Git2DBError::configuration(format!(
313 "Cannot delete current branch '{name}'"
314 )));
315 }
316 }
317
318 let path = self.repo_path()?;
319 let name = name.to_owned();
320
321 tokio::task::spawn_blocking(move || {
322 let repo = Repository::open(&path).map_err(|e| {
323 Git2DBError::repository(&path, format!("Failed to open repository: {e}"))
324 })?;
325
326 let mut branch = repo
328 .find_branch(&name, BranchType::Local)
329 .map_err(|_| Git2DBError::reference(&name, "Branch not found"))?;
330
331 if !force {
332 let branch_oid = branch
334 .get()
335 .target()
336 .ok_or_else(|| Git2DBError::reference(&name, "Branch has no target"))?;
337
338 let head = repo.head().map_err(|e| {
340 Git2DBError::reference("HEAD", format!("Failed to get HEAD: {e}"))
341 })?;
342 let head_oid = head
343 .target()
344 .ok_or_else(|| Git2DBError::reference("HEAD", "HEAD has no target"))?;
345
346 if !repo
347 .graph_descendant_of(head_oid, branch_oid)
348 .unwrap_or(false)
349 {
350 return Err(Git2DBError::configuration(format!(
351 "Branch '{name}' is not fully merged. Use force=true to delete anyway."
352 )));
353 }
354 }
355
356 branch.delete().map_err(|e| {
357 Git2DBError::reference(&name, format!("Failed to delete branch: {e}"))
358 })?;
359
360 Ok(())
361 })
362 .await
363 .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))?
364 }
365
366 pub async fn rename(&self, old_name: Option<&str>, new_name: &str) -> Git2DBResult<()> {
370 let branch_name = if let Some(name) = old_name {
371 name.to_owned()
372 } else {
373 self.current()
375 .await?
376 .ok_or_else(|| Git2DBError::reference("HEAD", "Not on a branch (detached HEAD)"))?
377 .name
378 };
379
380 let path = self.repo_path()?;
381 let new_name = new_name.to_owned();
382
383 tokio::task::spawn_blocking(move || {
384 let repo = Repository::open(&path).map_err(|e| {
385 Git2DBError::repository(&path, format!("Failed to open repository: {e}"))
386 })?;
387
388 let mut branch = repo
390 .find_branch(&branch_name, BranchType::Local)
391 .map_err(|_| Git2DBError::reference(&branch_name, "Branch not found"))?;
392
393 branch.rename(&new_name, false).map_err(|e| {
394 Git2DBError::reference(&new_name, format!("Failed to rename branch: {e}"))
395 })?;
396
397 Ok(())
398 })
399 .await
400 .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))?
401 }
402}
403
404#[derive(Debug, Clone)]
406pub struct Branch {
407 pub name: String,
408 pub branch_type: BranchKind,
409 pub is_head: bool,
410 pub oid: Option<Oid>,
411 pub tracking: Option<String>,
412}
413
414impl Branch {
415 pub fn is_local(&self) -> bool {
417 matches!(self.branch_type, BranchKind::Local)
418 }
419
420 pub fn is_remote(&self) -> bool {
422 matches!(self.branch_type, BranchKind::Remote)
423 }
424
425 pub fn short_oid(&self) -> Option<String> {
427 self.oid.map(|oid| format!("{oid:.7}"))
428 }
429}
430
431#[derive(Debug, Clone, Copy, PartialEq, Eq)]
433pub enum BranchKind {
434 Local,
435 Remote,
436}