gix_worktree/stack/state/mod.rs
1use bstr::{BString, ByteSlice};
2use gix_glob::pattern::Case;
3
4use crate::{PathIdMapping, stack::State};
5
6#[cfg(feature = "attributes")]
7type AttributeMatchGroup = gix_attributes::Search;
8type IgnoreMatchGroup = gix_ignore::Search;
9
10/// State related to attributes associated with files in the repository.
11#[derive(Default, Clone)]
12#[cfg(feature = "attributes")]
13pub struct Attributes {
14 /// Attribute patterns which aren't tied to the repository root, hence are global, they contribute first.
15 globals: AttributeMatchGroup,
16 /// Attribute patterns that match the currently set directory (in the stack).
17 ///
18 /// Note that the root-level file is always loaded, if present, followed by, the `$GIT_DIR/info/attributes`, if present, based
19 /// on the location of the `info_attributes` file.
20 stack: AttributeMatchGroup,
21 /// The first time we push the root, we have to load additional information from this file if it exists along with the root attributes
22 /// file if possible, and keep them there throughout.
23 info_attributes: Option<std::path::PathBuf>,
24 /// A lookup table to accelerate searches.
25 collection: gix_attributes::search::MetadataCollection,
26 /// Where to read `.gitattributes` data from.
27 source: attributes::Source,
28}
29
30/// State related to the exclusion of files, supporting static overrides and globals, along with a stack of dynamically read
31/// ignore files from disk or from the index each time the directory changes.
32#[derive(Default, Clone)]
33pub struct Ignore {
34 /// Ignore patterns passed as overrides to everything else, typically passed on the command-line and the first patterns to
35 /// be consulted.
36 overrides: IgnoreMatchGroup,
37 /// Ignore patterns that match the currently set director (in the stack), which is pushed and popped as needed.
38 stack: IgnoreMatchGroup,
39 /// Ignore patterns which aren't tied to the repository root, hence are global. They are consulted last.
40 globals: IgnoreMatchGroup,
41 /// A matching stack of pattern indices which is empty if we have just been initialized to indicate that the
42 /// currently set directory had a pattern matched. Note that this one could be negated.
43 /// (index into match groups, index into list of pattern lists, index into pattern list)
44 matched_directory_patterns_stack: Vec<Option<(usize, usize, usize)>>,
45 /// The name of the file to look for in directories.
46 pub(crate) exclude_file_name_for_directories: BString,
47 /// Where to read ignore files from
48 source: ignore::Source,
49 /// Control how to parse ignore files.
50 parse: gix_ignore::search::Ignore,
51}
52
53///
54#[cfg(feature = "attributes")]
55pub mod attributes;
56///
57pub mod ignore;
58
59/// Initialization
60impl State {
61 /// Configure a state to be suitable for checking out files, which only needs access to attribute files read from the index.
62 #[cfg(feature = "attributes")]
63 pub fn for_checkout(
64 unlink_on_collision: bool,
65 validate: gix_validate::path::component::Options,
66 attributes: Attributes,
67 ) -> Self {
68 State::CreateDirectoryAndAttributesStack {
69 unlink_on_collision,
70 validate,
71 attributes,
72 }
73 }
74
75 /// Configure a state for adding files, with support for ignore files and attribute files.
76 #[cfg(feature = "attributes")]
77 pub fn for_add(attributes: Attributes, ignore: Ignore) -> Self {
78 State::AttributesAndIgnoreStack { attributes, ignore }
79 }
80}
81
82/// Utilities
83impl State {
84 /// Returns a vec of tuples of relative index paths along with the best usable blob OID for
85 /// either *ignore* or *attribute* files or both. This allows files to be accessed directly from
86 /// the object database without the need for a worktree checkout.
87 ///
88 /// Note that this method…
89 /// - ignores entries which aren't blobs.
90 /// - ignores ignore entries which are not skip-worktree.
91 /// - within merges, picks 'our' stage both for *ignore* and *attribute* files.
92 ///
93 /// * `index` is where we look for suitable files by path in order to obtain their blob hash.
94 /// * `paths` is the indices storage backend for paths.
95 /// * `case` determines if the search for files should be case-sensitive or not.
96 pub fn id_mappings_from_index(
97 &self,
98 index: &gix_index::State,
99 paths: &gix_index::PathStorageRef,
100 case: Case,
101 ) -> Vec<PathIdMapping> {
102 let a1_backing;
103 #[cfg(feature = "attributes")]
104 let a2_backing;
105 let names = match self {
106 State::IgnoreStack(ignore) => {
107 a1_backing = [(
108 ignore.exclude_file_name_for_directories.as_bytes().as_bstr(),
109 Some(ignore.source),
110 )];
111 a1_backing.as_ref()
112 }
113 #[cfg(feature = "attributes")]
114 State::AttributesAndIgnoreStack { ignore, .. } => {
115 a2_backing = [
116 (
117 ignore.exclude_file_name_for_directories.as_bytes().as_bstr(),
118 Some(ignore.source),
119 ),
120 (".gitattributes".into(), None),
121 ];
122 a2_backing.as_ref()
123 }
124 #[cfg(feature = "attributes")]
125 State::CreateDirectoryAndAttributesStack { .. } | State::AttributesStack(_) => {
126 a1_backing = [(".gitattributes".into(), None)];
127 a1_backing.as_ref()
128 }
129 };
130
131 index
132 .entries()
133 .iter()
134 .filter_map(move |entry| {
135 let path = entry.path_in(paths);
136
137 // Stage 0 means there is no merge going on, stage 2 means it's 'our' side of the merge, but then
138 // there won't be a stage 0.
139 if entry.mode == gix_index::entry::Mode::FILE && (entry.stage_raw() == 0 || entry.stage_raw() == 2) {
140 let basename = path.rfind_byte(b'/').map_or(path, |pos| path[pos + 1..].as_bstr());
141 let ignore_source = names.iter().find_map(|t| {
142 match case {
143 Case::Sensitive => basename == t.0,
144 Case::Fold => basename.eq_ignore_ascii_case(t.0),
145 }
146 .then_some(t.1)
147 })?;
148 if let Some(source) = ignore_source {
149 match source {
150 ignore::Source::IdMapping => {}
151 ignore::Source::WorktreeThenIdMappingIfNotSkipped => {
152 // See https://github.com/git/git/blob/master/dir.c#L912:L912
153 if !entry.flags.contains(gix_index::entry::Flags::SKIP_WORKTREE) {
154 return None;
155 }
156 }
157 }
158 }
159 Some((path.to_owned(), entry.id))
160 } else {
161 None
162 }
163 })
164 .collect()
165 }
166
167 pub(crate) fn ignore_or_panic(&self) -> &Ignore {
168 match self {
169 State::IgnoreStack(v) => v,
170 #[cfg(feature = "attributes")]
171 State::AttributesAndIgnoreStack { ignore, .. } => ignore,
172 #[cfg(feature = "attributes")]
173 State::AttributesStack(_) | State::CreateDirectoryAndAttributesStack { .. } => {
174 unreachable!("BUG: must not try to check excludes without it being setup")
175 }
176 }
177 }
178
179 #[cfg(feature = "attributes")]
180 pub(crate) fn attributes_or_panic(&self) -> &Attributes {
181 match self {
182 State::AttributesStack(attributes)
183 | State::AttributesAndIgnoreStack { attributes, .. }
184 | State::CreateDirectoryAndAttributesStack { attributes, .. } => attributes,
185 State::IgnoreStack(_) => {
186 unreachable!("BUG: must not try to check excludes without it being setup")
187 }
188 }
189 }
190}