1use crate::errors::{Git2DBError, Git2DBResult};
6use crate::registry::{Git2DB, RepoId};
7use crate::repo_accessor::RepositoryAccessor;
8use git2::{IndexAddOption, Repository, Status, StatusOptions};
9use std::path::{Path, PathBuf};
10
11pub struct StageManager<'a> {
36 registry: &'a Git2DB,
37 repo_id: RepoId,
38}
39
40#[derive(Debug, Clone)]
42pub struct StagedFile {
43 pub path: PathBuf,
45 pub status: Status,
47 pub is_staged: bool,
49}
50
51impl<'a> RepositoryAccessor for StageManager<'a> {
52 fn registry(&self) -> &Git2DB {
53 self.registry
54 }
55
56 fn repo_id(&self) -> &RepoId {
57 &self.repo_id
58 }
59}
60
61impl<'a> StageManager<'a> {
62 pub(crate) fn new(registry: &'a Git2DB, repo_id: RepoId) -> Self {
64 Self { registry, repo_id }
65 }
66
67 pub async fn add(&self, path: impl AsRef<Path>) -> Git2DBResult<()> {
71 let repo_path = self.repo_path()?;
72 let file_path = path.as_ref().to_path_buf();
73
74 tokio::task::spawn_blocking(move || -> Git2DBResult<()> {
75 let repo = Repository::open(&repo_path).map_err(|e| {
76 Git2DBError::repository(&repo_path, format!("Failed to open repository: {e}"))
77 })?;
78
79 let mut index = repo
80 .index()
81 .map_err(|e| Git2DBError::internal(format!("Failed to get index: {e}")))?;
82
83 index.add_path(&file_path).map_err(|e| {
84 Git2DBError::internal(format!(
85 "Failed to add path '{}': {}",
86 file_path.display(),
87 e
88 ))
89 })?;
90
91 index
92 .write()
93 .map_err(|e| Git2DBError::internal(format!("Failed to write index: {e}")))?;
94
95 Ok(())
96 })
97 .await
98 .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))?
99 }
100
101 pub async fn add_all(&self) -> Git2DBResult<()> {
105 let repo_path = self.repo_path()?;
106
107 tokio::task::spawn_blocking(move || -> Git2DBResult<()> {
108 let repo = Repository::open(&repo_path).map_err(|e| {
109 Git2DBError::repository(&repo_path, format!("Failed to open repository: {e}"))
110 })?;
111
112 let mut index = repo
113 .index()
114 .map_err(|e| Git2DBError::internal(format!("Failed to get index: {e}")))?;
115
116 index
118 .add_all(["."].iter(), IndexAddOption::DEFAULT, None)
119 .map_err(|e| Git2DBError::internal(format!("Failed to add all: {e}")))?;
120
121 index
122 .write()
123 .map_err(|e| Git2DBError::internal(format!("Failed to write index: {e}")))?;
124
125 Ok(())
126 })
127 .await
128 .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))?
129 }
130
131 pub async fn remove(&self, path: impl AsRef<Path>) -> Git2DBResult<()> {
135 let repo_path = self.repo_path()?;
136 let file_path = path.as_ref().to_path_buf();
137
138 tokio::task::spawn_blocking(move || -> Git2DBResult<()> {
139 let repo = Repository::open(&repo_path).map_err(|e| {
140 Git2DBError::repository(&repo_path, format!("Failed to open repository: {e}"))
141 })?;
142
143 let mut index = repo
144 .index()
145 .map_err(|e| Git2DBError::internal(format!("Failed to get index: {e}")))?;
146
147 index.remove_path(&file_path).map_err(|e| {
148 Git2DBError::internal(format!(
149 "Failed to remove path '{}': {}",
150 file_path.display(),
151 e
152 ))
153 })?;
154
155 index
156 .write()
157 .map_err(|e| Git2DBError::internal(format!("Failed to write index: {e}")))?;
158
159 Ok(())
160 })
161 .await
162 .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))?
163 }
164
165 pub async fn unstage(&self, path: impl AsRef<Path>) -> Git2DBResult<()> {
169 let repo_path = self.repo_path()?;
170 let file_path = path.as_ref().to_path_buf();
171
172 tokio::task::spawn_blocking(move || -> Git2DBResult<()> {
173 let repo = Repository::open(&repo_path).map_err(|e| {
174 Git2DBError::repository(&repo_path, format!("Failed to open repository: {e}"))
175 })?;
176
177 let head = repo
179 .head()
180 .map_err(|e| Git2DBError::reference("HEAD", format!("Failed to get HEAD: {e}")))?;
181
182 let head_commit = head.peel_to_commit().map_err(|e| {
183 Git2DBError::reference("HEAD", format!("Failed to get HEAD commit: {e}"))
184 })?;
185
186 repo.reset_default(Some(head_commit.as_object()), [&file_path].iter())
188 .map_err(|e| {
189 Git2DBError::internal(format!(
190 "Failed to unstage '{}': {}",
191 file_path.display(),
192 e
193 ))
194 })?;
195
196 Ok(())
197 })
198 .await
199 .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))?
200 }
201
202 pub async fn reset(&self) -> Git2DBResult<()> {
206 let repo_path = self.repo_path()?;
207
208 tokio::task::spawn_blocking(move || -> Git2DBResult<()> {
209 let repo = Repository::open(&repo_path).map_err(|e| {
210 Git2DBError::repository(&repo_path, format!("Failed to open repository: {e}"))
211 })?;
212
213 let head = repo
214 .head()
215 .map_err(|e| Git2DBError::reference("HEAD", format!("Failed to get HEAD: {e}")))?;
216
217 let head_commit = head.peel_to_commit().map_err(|e| {
218 Git2DBError::reference("HEAD", format!("Failed to get HEAD commit: {e}"))
219 })?;
220
221 repo.reset(head_commit.as_object(), git2::ResetType::Mixed, None)
222 .map_err(|e| Git2DBError::internal(format!("Failed to reset staging area: {e}")))?;
223
224 Ok(())
225 })
226 .await
227 .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))?
228 }
229
230 pub async fn status(&self) -> Git2DBResult<Vec<StagedFile>> {
234 let repo_path = self.repo_path()?;
235
236 tokio::task::spawn_blocking(move || -> Git2DBResult<Vec<StagedFile>> {
237 let repo = Repository::open(&repo_path).map_err(|e| {
238 Git2DBError::repository(&repo_path, format!("Failed to open repository: {e}"))
239 })?;
240
241 let mut opts = StatusOptions::new();
242 opts.include_untracked(true);
243 opts.recurse_untracked_dirs(true);
244
245 let statuses = repo.statuses(Some(&mut opts)).map_err(|e| {
246 Git2DBError::internal(format!("Failed to get repository status: {e}"))
247 })?;
248
249 let mut files = Vec::new();
250 for entry in statuses.iter() {
251 if let Some(path) = entry.path() {
252 let status = entry.status();
253 let is_staged = status.intersects(
254 Status::INDEX_NEW
255 | Status::INDEX_MODIFIED
256 | Status::INDEX_DELETED
257 | Status::INDEX_RENAMED
258 | Status::INDEX_TYPECHANGE,
259 );
260
261 files.push(StagedFile {
262 path: PathBuf::from(path),
263 status,
264 is_staged,
265 });
266 }
267 }
268
269 Ok(files)
270 })
271 .await
272 .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))?
273 }
274
275 pub async fn staged_files(&self) -> Git2DBResult<Vec<StagedFile>> {
279 let all_files = self.status().await?;
280 Ok(all_files.into_iter().filter(|f| f.is_staged).collect())
281 }
282
283 pub async fn is_empty(&self) -> Git2DBResult<bool> {
285 Ok(self.staged_files().await?.is_empty())
286 }
287}