grit_lib/status/handle.rs
1//! [`Status`] — structured working-tree status for one repository.
2
3use crate::diff::DiffEntry;
4use crate::error::Result;
5use crate::index::Index;
6use crate::pathspec::Pathspec;
7use crate::porcelain::status::{
8 collect_untracked_and_ignored_inner, status as status_impl,
9 status_diff_entry_matches_pathspec_typed, status_options_from_config, IgnoredMode, StatusModel,
10 StatusOptions, UntrackedCollectMeta, UntrackedScan,
11};
12use crate::progress::{CancelToken, ProgressSink};
13use crate::repo::Repository;
14use crate::status::summary::{assemble_status_summary, StatusSummary, StatusSummaryOptions};
15use crate::worktree_rules::WorktreeRules;
16
17/// Whether untracked collection may refresh and read the index UNTR extension.
18///
19/// Used by [`UntrackedOptions::cache`](UntrackedOptions::cache) for [`Status::untracked`] walks.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
21#[non_exhaustive]
22pub enum UntrackedCachePolicy {
23 /// Use UNTR when configured (status default).
24 #[default]
25 Refresh,
26 /// Skip UNTR refresh (staging/`git add` must not pay a full status-style rebuild).
27 Skip,
28}
29
30/// Options for [`Status::untracked`] and related untracked walks.
31///
32/// Defaults match a normal `git status` untracked scan (no ignored files, collapsed directories).
33#[derive(Debug, Clone)]
34#[non_exhaustive]
35pub struct UntrackedOptions {
36 /// How ignored paths are reported.
37 pub ignored_mode: IgnoredMode,
38 /// When true, list every file under untracked directories (`--untracked-files=all`).
39 pub show_all: bool,
40 /// Limit the walk to paths matching this pathspec.
41 pub pathspec: Pathspec,
42 /// UNTR cache use for this walk.
43 pub cache: UntrackedCachePolicy,
44}
45
46impl Default for UntrackedOptions {
47 fn default() -> Self {
48 Self {
49 ignored_mode: IgnoredMode::No,
50 show_all: false,
51 pathspec: Pathspec::entire_tree(crate::pathspec::PathspecGlobalFlags::default()),
52 cache: UntrackedCachePolicy::default(),
53 }
54 }
55}
56
57impl UntrackedOptions {
58 /// Sets [`ignored_mode`](Self::ignored_mode).
59 #[must_use]
60 pub fn with_ignored_mode(mut self, ignored_mode: IgnoredMode) -> Self {
61 self.ignored_mode = ignored_mode;
62 self
63 }
64
65 /// Sets [`show_all`](Self::show_all).
66 #[must_use]
67 pub fn with_show_all(mut self, show_all: bool) -> Self {
68 self.show_all = show_all;
69 self
70 }
71
72 /// Sets [`pathspec`](Self::pathspec).
73 #[must_use]
74 pub fn with_pathspec(mut self, pathspec: Pathspec) -> Self {
75 self.pathspec = pathspec;
76 self
77 }
78
79 /// Sets [`cache`](Self::cache).
80 #[must_use]
81 pub fn with_cache(mut self, cache: UntrackedCachePolicy) -> Self {
82 self.cache = cache;
83 self
84 }
85}
86
87/// Compute staged, unstaged, untracked, and ignored paths for one repository.
88#[derive(Debug, Copy, Clone)]
89pub struct Status<'repo> {
90 repo: &'repo Repository,
91}
92
93impl<'repo> Status<'repo> {
94 /// Bind status operations to `repo`.
95 #[inline]
96 #[must_use]
97 pub fn new(repo: &'repo Repository) -> Self {
98 Self { repo }
99 }
100
101 /// Underlying repository.
102 #[inline]
103 #[must_use]
104 pub fn repository(&self) -> &'repo Repository {
105 self.repo
106 }
107
108 /// Full status model from [`StatusOptions`].
109 ///
110 /// # Errors
111 ///
112 /// Propagates repository, diff, index, and untracked-walk failures. Returns
113 /// [`crate::error::Error::Cancelled`] when `cancel` is set.
114 ///
115 /// # Examples
116 ///
117 /// ```
118 /// use grit_lib::progress::{CancelToken, NullProgress};
119 /// use grit_lib::repo::{InitOptions, Repository};
120 /// use grit_lib::status::StatusOptions;
121 ///
122 /// # fn main() -> grit_lib::error::Result<()> {
123 /// let dir = tempfile::tempdir()?;
124 /// let (repo, _) = Repository::init(dir.path(), &InitOptions::default())?;
125 /// let model = repo.status().run(
126 /// &StatusOptions::default(),
127 /// &mut NullProgress,
128 /// &CancelToken::never(),
129 /// )?;
130 /// assert!(model.staged.is_empty() && model.unstaged.is_empty());
131 /// # Ok(())
132 /// # }
133 /// ```
134 pub fn run(
135 &self,
136 options: &StatusOptions,
137 progress: &mut dyn ProgressSink,
138 cancel: &CancelToken,
139 ) -> Result<StatusModel> {
140 status_impl(self.repo, options, progress, cancel)
141 }
142
143 /// Dashboard summary: branch standing, guidance, and conflict grouping for a [`StatusModel`].
144 ///
145 /// Call after [`Self::run`] when the CLI or an embedder needs header and integration hints
146 /// without rescanning the worktree.
147 ///
148 /// # Errors
149 ///
150 /// Propagates [`crate::branch_tracking::BranchStanding::compute`] failures.
151 ///
152 /// # Examples
153 ///
154 /// ```
155 /// use grit_lib::progress::{CancelToken, NullProgress};
156 /// use grit_lib::repo::{InitOptions, Repository};
157 /// use grit_lib::status::{StatusOptions, StatusSummaryOptions};
158 ///
159 /// # fn main() -> grit_lib::error::Result<()> {
160 /// let dir = tempfile::tempdir()?;
161 /// let (repo, _) = Repository::init(dir.path(), &InitOptions::default())?;
162 /// let status = repo.status();
163 /// let model = status.run(&StatusOptions::default(), &mut NullProgress, &CancelToken::never())?;
164 /// let summary = status.assemble_summary(model, StatusSummaryOptions::default())?;
165 /// assert!(summary.conflict_groups.is_empty());
166 /// # Ok(())
167 /// # }
168 /// ```
169 pub fn assemble_summary(
170 &self,
171 model: StatusModel,
172 options: StatusSummaryOptions,
173 ) -> Result<StatusSummary> {
174 assemble_status_summary(self.repo, model, options)
175 }
176
177 /// Walk the work tree and collect untracked and ignored paths into sorted lists.
178 ///
179 /// Honors [`UntrackedOptions`] (ignored mode, `show_all`, pathspec limit, UNTR cache policy).
180 ///
181 /// # Errors
182 ///
183 /// Propagates ignore-rule load, index, and walk failures. Returns
184 /// [`crate::error::Error::Cancelled`] when `cancel` is set.
185 pub fn untracked(
186 &self,
187 index: &mut Index,
188 options: &UntrackedOptions,
189 progress: &mut dyn ProgressSink,
190 cancel: &CancelToken,
191 ) -> Result<(Vec<String>, Vec<String>)> {
192 let _ = progress;
193 let (untracked, ignored, _) = self.untracked_with_meta(index, options, None, cancel)?;
194 Ok((untracked, ignored))
195 }
196
197 /// Like [`Self::untracked`], also returning walk metadata (collapsed clean units, etc.).
198 ///
199 /// When `rules` is `Some`, ignore and attribute files already loaded for this operation are
200 /// reused instead of reading them again.
201 ///
202 /// # Errors
203 ///
204 /// Same as [`Self::untracked`].
205 pub fn untracked_with_meta(
206 &self,
207 index: &mut Index,
208 options: &UntrackedOptions,
209 rules: Option<&WorktreeRules>,
210 cancel: &CancelToken,
211 ) -> Result<(Vec<String>, Vec<String>, UntrackedCollectMeta)> {
212 let work_tree = self
213 .repo
214 .work_tree()
215 .ok_or(crate::repo::RepositoryError::RequiresWorkTree)?;
216 let owned_rules;
217 let rules = match rules {
218 Some(rules) => rules,
219 None => {
220 owned_rules = WorktreeRules::from_repository(self.repo, index)?;
221 &owned_rules
222 }
223 };
224 let specs = if options.pathspec.is_entire_tree() {
225 &[] as &[String]
226 } else {
227 options.pathspec.specs()
228 };
229 let use_cache = matches!(options.cache, UntrackedCachePolicy::Refresh);
230 collect_untracked_and_ignored_inner(
231 self.repo,
232 index,
233 work_tree,
234 specs,
235 Some(&options.pathspec),
236 UntrackedScan {
237 ignored_mode: options.ignored_mode,
238 show_all: options.show_all,
239 sort_paths: true,
240 use_untracked_cache: use_cache,
241 cache_miss: Default::default(),
242 clean_unit_dirs: None,
243 listing_cache: None,
244 },
245 rules,
246 Some(cancel.clone()),
247 )
248 }
249
250 /// Expand collapsed untracked directory markers (`dir/`) into concrete file paths for staging.
251 ///
252 /// # Errors
253 ///
254 /// Propagates ignore-rule and walk failures.
255 pub fn expand_untracked_for_staging(
256 &self,
257 index: &mut Index,
258 untracked: Vec<String>,
259 pathspecs: &[String],
260 ) -> Result<Vec<String>> {
261 crate::porcelain::status::expand_untracked_for_staging(
262 self.repo,
263 index,
264 self.repo
265 .work_tree()
266 .ok_or(crate::repo::RepositoryError::RequiresWorkTree)?,
267 untracked,
268 pathspecs,
269 )
270 }
271
272 /// Whether a diff entry matches `pathspec` using typed pathspec evaluation (rename-aware).
273 ///
274 /// # Errors
275 ///
276 /// Same as [`Pathspec::matches_change`](crate::pathspec::Pathspec::matches_change).
277 pub fn diff_entry_matches_pathspec(
278 &self,
279 entry: &DiffEntry,
280 pathspec: &Pathspec,
281 ) -> Result<bool> {
282 status_diff_entry_matches_pathspec_typed(self.repo, entry, pathspec)
283 }
284}
285
286impl StatusOptions {
287 /// Build default status options from repository configuration.
288 ///
289 /// # Errors
290 ///
291 /// Returns [`crate::error::ConfigError::InvalidUntrackedFilesMode`] when
292 /// `status.showUntrackedFiles` is invalid.
293 pub fn from_config(config: &crate::config::Config<'_>) -> Result<Self> {
294 Ok(status_options_from_config(config.snapshot()?.as_ref())?)
295 }
296}