Skip to main content

grit_lib/index/
handle.rs

1//! Repository-scoped index load/write via [`IndexFile`].
2use std::path::Path;
3
4use crate::error::Result;
5use crate::index::{Index, IndexParseContext};
6use crate::repo::Repository;
7use crate::split_index::WriteSplitIndexRequest;
8
9/// How [`IndexFile::load`] treats sparse-directory placeholders.
10#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
11#[non_exhaustive]
12pub enum SparseIndexLoad {
13    /// Replace every placeholder with the blob entries of its tree, so each path is a row.
14    #[default]
15    Expand,
16    /// Keep placeholders as they are (no tree reads). For read-mostly operations such as
17    /// `status` and `diff` on cone sparse-index checkouts.
18    Preserve,
19}
20
21/// Options for [`IndexFile::load`].
22#[derive(Debug, Clone, Copy, Default)]
23#[non_exhaustive]
24pub struct IndexLoadOptions<'a> {
25    /// Index file to read; `None` uses `GIT_INDEX_FILE` or `$GIT_DIR/index`.
26    pub path: Option<&'a Path>,
27    /// Whether sparse-directory placeholders are expanded.
28    pub sparse: SparseIndexLoad,
29    /// Thread policy for parallel entry loading; `None` uses the repository's policy.
30    pub parse_context: Option<IndexParseContext>,
31}
32
33impl<'a> IndexLoadOptions<'a> {
34    /// Sets [`path`](Self::path).
35    #[must_use]
36    pub fn with_path(mut self, path: &'a Path) -> Self {
37        self.path = Some(path);
38        self
39    }
40
41    /// Sets [`sparse`](Self::sparse).
42    #[must_use]
43    pub fn with_sparse(mut self, sparse: SparseIndexLoad) -> Self {
44        self.sparse = sparse;
45        self
46    }
47
48    /// Sets [`parse_context`](Self::parse_context).
49    #[must_use]
50    pub fn with_parse_context(mut self, parse_context: IndexParseContext) -> Self {
51        self.parse_context = Some(parse_context);
52        self
53    }
54}
55
56/// Options for [`IndexFile::write`].
57#[derive(Debug, Clone, Copy, Default)]
58#[non_exhaustive]
59pub struct IndexWriteOptions<'a> {
60    /// Index file to write; `None` uses `GIT_INDEX_FILE` or `$GIT_DIR/index`.
61    pub path: Option<&'a Path>,
62    /// Split-index emission (`core.splitIndex` decides when not explicit).
63    pub split: WriteSplitIndexRequest,
64}
65
66impl<'a> IndexWriteOptions<'a> {
67    /// Sets [`path`](Self::path).
68    #[must_use]
69    pub fn with_path(mut self, path: &'a Path) -> Self {
70        self.path = Some(path);
71        self
72    }
73
74    /// Sets [`split`](Self::split).
75    #[must_use]
76    pub fn with_split(mut self, split: WriteSplitIndexRequest) -> Self {
77        self.split = split;
78        self
79    }
80}
81
82/// Load and persist the Git index for one repository.
83///
84/// # Examples
85///
86/// ```
87/// use grit_lib::index::IndexLoadOptions;
88/// use grit_lib::repo::{InitOptions, Repository};
89///
90/// # fn main() -> grit_lib::error::Result<()> {
91/// let dir = tempfile::tempdir()?;
92/// let (repo, _) = Repository::init(dir.path(), &InitOptions::default())?;
93/// let handle = repo.index();
94/// let index = handle.load(&IndexLoadOptions::default())?;
95/// assert!(index.entries().is_empty());
96/// # Ok(())
97/// # }
98/// ```
99#[derive(Debug, Copy, Clone)]
100pub struct IndexFile<'repo> {
101    repo: &'repo Repository,
102}
103
104impl<'repo> IndexFile<'repo> {
105    /// Bind index operations to `repo`.
106    #[inline]
107    #[must_use]
108    pub fn new(repo: &'repo Repository) -> Self {
109        Self { repo }
110    }
111
112    /// Underlying repository.
113    #[inline]
114    #[must_use]
115    pub fn repository(&self) -> &'repo Repository {
116        self.repo
117    }
118
119    /// Path to the index file this repository uses by default.
120    #[inline]
121    #[must_use]
122    pub fn path(&self) -> std::path::PathBuf {
123        self.repo.index_path()
124    }
125
126    /// Resolve the index path honoring `GIT_INDEX_FILE` when set.
127    ///
128    /// # Errors
129    ///
130    /// Propagates configuration errors.
131    #[inline]
132    pub fn path_for_env(&self) -> Result<std::path::PathBuf> {
133        self.repo.index_path_for_env()
134    }
135
136    /// Load the index, by default from the path selected by `GIT_INDEX_FILE` / the default
137    /// `.git/index`, resolving a split index and expanding sparse-directory placeholders.
138    ///
139    /// A missing index file loads as an empty index.
140    ///
141    /// # Errors
142    ///
143    /// Propagates index parse, sparse, and split-index errors.
144    pub fn load(&self, options: &IndexLoadOptions<'_>) -> crate::error::Result<Index> {
145        let path = match options.path {
146            Some(path) => path.to_path_buf(),
147            None => self.repo.index_path_for_env()?,
148        };
149        let parse_ctx = options
150            .parse_context
151            .unwrap_or_else(|| IndexParseContext::from_policy(self.repo.thread_policy()));
152        match options.sparse {
153            SparseIndexLoad::Expand => self.repo.load_index_at_with_context(&path, parse_ctx),
154            SparseIndexLoad::Preserve => {
155                self.repo.load_index_at_preserving_sparse(&path, parse_ctx)
156            }
157        }
158    }
159
160    /// Write `index`, by default to the path selected by `GIT_INDEX_FILE` / the default
161    /// `.git/index`.
162    ///
163    /// Collapses skip-worktree subtrees into sparse-directory placeholders when the sparse
164    /// index is enabled, writes a split index when [`IndexWriteOptions::split`] or
165    /// `core.splitIndex` asks for one, and runs the `post-index-change` hook.
166    ///
167    /// # Errors
168    ///
169    /// Propagates index serialization and I/O errors.
170    pub fn write(
171        &self,
172        index: &mut Index,
173        options: &IndexWriteOptions<'_>,
174    ) -> crate::error::Result<()> {
175        let path = match options.path {
176            Some(path) => path.to_path_buf(),
177            None => self.repo.index_path_for_env()?,
178        };
179        self.repo.write_index_at_split(&path, index, options.split)
180    }
181
182    /// Mark stage-0 entries of `index` that the sparse-checkout patterns exclude as
183    /// skip-worktree, as Git does after building an index from a tree (`read-tree`, branch
184    /// checkout, fast-forward merge).
185    ///
186    /// A no-op when `core.sparseCheckout` is false or `info/sparse-checkout` is missing. The
187    /// index is bumped to version 3 when any entry is marked. On-disk directories in the work
188    /// tree can match directory-only non-cone patterns.
189    ///
190    /// Returns cone-parse warnings when `core.sparseCheckoutCone` is set but the file is not a
191    /// valid cone definition (matching then falls back to non-cone rules).
192    ///
193    /// # Errors
194    ///
195    /// Propagates config load failures.
196    pub fn apply_sparse_checkout(&self, index: &mut Index) -> Result<Vec<String>> {
197        let config = self.repo.config().snapshot()?;
198        Ok(crate::sparse_checkout::apply_sparse_checkout_with_config(
199            self.repo.git_dir(),
200            self.repo.work_tree(),
201            index,
202            config.as_ref(),
203        ))
204    }
205
206    /// Acquire a lock on the index path selected by `GIT_INDEX_FILE` / the default `.git/index`.
207    #[inline]
208    pub fn begin_update(&self) -> crate::error::Result<crate::index::IndexLock> {
209        self.repo.begin_index_update()
210    }
211
212    /// Write `index` using a lock from [`Self::begin_update`].
213    #[inline]
214    pub fn commit_update(
215        &self,
216        lock: &mut crate::index::IndexLock,
217        index: &mut Index,
218        updated_workdir: bool,
219    ) -> crate::error::Result<()> {
220        self.repo.commit_index_update(lock, index, updated_workdir)
221    }
222
223    /// Persist the index when the lock can be acquired (Git `repo_update_index_if_able`),
224    /// using the path selected by `GIT_INDEX_FILE` when set.
225    #[inline]
226    pub fn try_write(&self, index: &mut Index) -> crate::error::Result<bool> {
227        self.repo.try_write_index(index)
228    }
229
230    /// Stage paths matching [`StageOptions`](crate::porcelain::add::StageOptions) into the index.
231    ///
232    /// # Errors
233    ///
234    /// Propagates index, worktree, and pathspec failures; returns [`crate::error::Error::Cancelled`]
235    /// when `cancel` is set.
236    pub fn stage(
237        &self,
238        options: &crate::porcelain::add::StageOptions,
239        progress: &mut dyn crate::progress::ProgressSink,
240        cancel: &crate::progress::CancelToken,
241    ) -> crate::error::Result<crate::porcelain::add::StageOutcome> {
242        crate::porcelain::add::stage(self.repo, options, progress, cancel)
243    }
244
245    /// Stage worktree changes for commit auto-staging.
246    ///
247    /// # Errors
248    ///
249    /// Same as [`Self::stage`] for the implicit all-paths staging pass.
250    pub fn stage_for_commit(
251        &self,
252        progress: &mut dyn crate::progress::ProgressSink,
253        cancel: &crate::progress::CancelToken,
254    ) -> crate::error::Result<crate::porcelain::add::StageOutcome> {
255        crate::porcelain::add::stage_for_commit(self.repo, progress, cancel)
256    }
257
258    /// Stage paths into a caller-owned index without writing it to disk.
259    ///
260    /// # Errors
261    ///
262    /// Same as [`Self::stage`], without persisting `index`.
263    pub fn stage_on(
264        &self,
265        index: &mut Index,
266        options: &crate::porcelain::add::StageOptions,
267        progress: &mut dyn crate::progress::ProgressSink,
268        cancel: &crate::progress::CancelToken,
269    ) -> crate::error::Result<crate::porcelain::add::StageOutcome> {
270        crate::porcelain::add::stage_on_index(self.repo, index, options, progress, cancel)
271    }
272
273    /// Stage paths matching `pathspecs` without a full status pass.
274    ///
275    /// # Errors
276    ///
277    /// Propagates index refresh and worktree scan failures.
278    pub fn stage_worktree_paths(
279        &self,
280        pathspecs: &[String],
281    ) -> crate::error::Result<crate::porcelain::staging::StageWorktreeChangesOutcome> {
282        crate::porcelain::staging::stage_worktree_changes(self.repo, pathspecs)
283    }
284
285    /// Refresh tracked modifications from the worktree into the index.
286    ///
287    /// # Errors
288    ///
289    /// Propagates index load, stat refresh, and worktree scan failures.
290    pub fn stage_tracked_modifications(
291        &self,
292        work_tree: &Path,
293    ) -> crate::error::Result<crate::porcelain::stage_tracked::StageTrackedSummary> {
294        let thresholds =
295            self.staging_thresholds_from_options(&crate::porcelain::add::StageOptions::default());
296        crate::porcelain::stage_tracked::stage_tracked_modifications_with_thresholds(
297            self.repo, work_tree, thresholds,
298        )
299    }
300
301    /// Like [`Self::stage_tracked_modifications`], updating a caller-owned index only.
302    ///
303    /// # Errors
304    ///
305    /// Same as [`Self::stage_tracked_modifications`].
306    pub fn stage_tracked_modifications_on(
307        &self,
308        work_tree: &Path,
309        index_path: &Path,
310        index: &mut Index,
311        options: &crate::porcelain::add::StageOptions,
312    ) -> crate::error::Result<crate::porcelain::stage_tracked::StageTrackedSummary> {
313        let thresholds = self.staging_thresholds_from_options(options);
314        crate::porcelain::stage_tracked::stage_tracked_modifications_in_index_with_thresholds(
315            self.repo, work_tree, index_path, index, thresholds,
316        )
317    }
318
319    fn staging_thresholds_from_options(
320        &self,
321        options: &crate::porcelain::add::StageOptions,
322    ) -> crate::porcelain::bulk_index::IndexStagingThresholds {
323        #[cfg(any(test, feature = "test-support"))]
324        {
325            options.staging_thresholds.unwrap_or_default()
326        }
327        #[cfg(not(any(test, feature = "test-support")))]
328        {
329            options.staging_thresholds.unwrap_or_default()
330        }
331    }
332
333    /// Stage structured diff hunks by stable id.
334    ///
335    /// # Errors
336    ///
337    /// Propagates diff, index, and hunk-resolution failures.
338    pub fn stage_hunks(
339        &self,
340        side: crate::diff::DiffSide,
341        selection: &crate::porcelain::hunk_select::HunkSelection,
342        pathspecs: &[String],
343        diff_options: crate::diff::DiffOptions,
344        dry_run: bool,
345        cancel: &crate::progress::CancelToken,
346    ) -> crate::error::Result<crate::porcelain::hunk_select::StageHunksOutcome> {
347        crate::porcelain::hunk_select::stage_hunks(
348            self.repo,
349            side,
350            selection,
351            pathspecs,
352            diff_options,
353            dry_run,
354            cancel,
355        )
356    }
357
358    /// Discard or unstage hunks in `selection`.
359    ///
360    /// # Errors
361    ///
362    /// Propagates diff and index update failures.
363    pub fn restore_hunks(
364        &self,
365        selection: &crate::porcelain::hunk_select::HunkSelection,
366        pathspecs: &[String],
367        restore_staged: bool,
368        restore_worktree: bool,
369        dry_run: bool,
370    ) -> crate::error::Result<crate::porcelain::hunk_select::RestoreHunksOutcome> {
371        crate::porcelain::hunk_select::restore_hunks(
372            self.repo,
373            selection,
374            pathspecs,
375            restore_staged,
376            restore_worktree,
377            dry_run,
378        )
379    }
380
381    /// Diff options for hunk id resolution (same boundaries as `grit diff --json`).
382    ///
383    /// # Errors
384    ///
385    /// Propagates config and diff-option construction failures.
386    pub fn hunk_diff_options(&self) -> crate::error::Result<crate::diff::DiffOptions> {
387        crate::porcelain::hunk_select::diff_options_for_hunk_select(self.repo)
388    }
389
390    /// Unstaged file diffs with staged peer hunks on the same path.
391    ///
392    /// # Errors
393    ///
394    /// Propagates index load and diff failures.
395    pub fn unstaged_file_diffs(
396        &self,
397        pathspecs: &[String],
398    ) -> crate::error::Result<
399        Vec<(
400            crate::diff::FileDiff,
401            Vec<crate::diff::structured::StructuredHunk>,
402        )>,
403    > {
404        crate::porcelain::hunk_select::unstaged_file_diffs(self.repo, pathspecs)
405    }
406
407    /// Unstaged hunk ids per path (same rules as `grit diff --json` on `--unstaged`).
408    ///
409    /// # Errors
410    ///
411    /// Propagates diff failures for the given pathspecs.
412    pub fn list_unstaged_hunk_ids(
413        &self,
414        pathspecs: &[String],
415        diff_options: crate::diff::DiffOptions,
416    ) -> crate::error::Result<std::collections::BTreeMap<String, Vec<crate::diff::HunkId>>> {
417        crate::porcelain::hunk_select::list_unstaged_hunk_ids(self.repo, pathspecs, diff_options)
418    }
419
420    /// Resolve a hunk selection to index-ready patches.
421    ///
422    /// # Errors
423    ///
424    /// Propagates diff and selection validation failures.
425    pub fn resolve_hunk_selection(
426        &self,
427        side: crate::diff::DiffSide,
428        selection: &crate::porcelain::hunk_select::HunkSelection,
429        pathspecs: &[String],
430        diff_options: crate::diff::DiffOptions,
431    ) -> crate::error::Result<Vec<crate::apply::FilePatch>> {
432        crate::porcelain::hunk_select::resolve_selection(
433            self.repo,
434            side,
435            selection,
436            pathspecs,
437            diff_options,
438        )
439    }
440
441    /// Whether `resolved` matches a known path in this repository.
442    ///
443    /// # Errors
444    ///
445    /// Propagates index and ref resolution failures.
446    pub fn pathspec_matches_known(&self, resolved: &str) -> crate::error::Result<bool> {
447        crate::porcelain::pathspec_match::pathspec_matches_known_in_repository(self.repo, resolved)
448    }
449
450    /// Require that `resolved` matches a known path, else return a pathspec error.
451    ///
452    /// # Errors
453    ///
454    /// Returns a pathspec error when the path is unknown.
455    pub fn ensure_pathspec_matches_known(
456        &self,
457        display_spec: &str,
458        resolved: &str,
459    ) -> crate::error::Result<()> {
460        crate::porcelain::pathspec_match::ensure_pathspec_matches_known_in_repository(
461            self.repo,
462            display_spec,
463            resolved,
464        )
465    }
466}