Skip to main content

git2db/
stage.rs

1//! Staging area management for tracked repositories
2//!
3//! Provides git-native staging operations similar to `git add`, `git rm`, etc.
4
5use 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
11/// Manager for repository staging area
12///
13/// Provides operations similar to `git add` and `git rm` commands.
14///
15/// # Examples
16///
17/// ```rust,ignore
18/// // Add file to staging area
19/// repo.staging().add("src/main.rs")?;
20///
21/// // Add all changes
22/// repo.staging().add_all()?;
23///
24/// // Remove file from staging area
25/// repo.staging().remove("old.txt")?;
26///
27/// // Check what's staged
28/// let staged = repo.staging().status()?;
29/// for file in staged {
30///     println!("{:?}: {}", file.status, file.path);
31/// }
32/// # Ok(())
33/// # }
34/// ```
35pub struct StageManager<'a> {
36    registry: &'a Git2DB,
37    repo_id: RepoId,
38}
39
40/// Staged file information
41#[derive(Debug, Clone)]
42pub struct StagedFile {
43    /// File path relative to repository root
44    pub path: PathBuf,
45    /// Git status flags
46    pub status: Status,
47    /// Whether file is staged for commit
48    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    /// Create a new stage manager
63    pub(crate) fn new(registry: &'a Git2DB, repo_id: RepoId) -> Self {
64        Self { registry, repo_id }
65    }
66
67    /// Add a file or directory to the staging area
68    ///
69    /// Similar to `git add <path>`
70    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    /// Add all changes to the staging area
102    ///
103    /// Similar to `git add -A` or `git add .`
104    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            // Add all files (new, modified, deleted)
117            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    /// Remove a file from the staging area and working directory
132    ///
133    /// Similar to `git rm <path>`
134    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    /// Unstage a file (remove from staging area but keep changes)
166    ///
167    /// Similar to `git reset HEAD <path>`
168    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            // Get HEAD commit
178            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            // Reset the path to HEAD
187            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    /// Reset all staged changes
203    ///
204    /// Similar to `git reset HEAD`
205    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    /// Get status of all files in the repository
231    ///
232    /// Returns information about staged and unstaged changes.
233    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    /// Get only staged files
276    ///
277    /// Returns files that are ready to be committed.
278    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    /// Check if staging area is empty
284    pub async fn is_empty(&self) -> Git2DBResult<bool> {
285        Ok(self.staged_files().await?.is_empty())
286    }
287}