Debian Codegraph @

src/checkout/chunk.rs

raw symbols SCIP
1 use std::{
2 collections::BTreeSet,
3 sync::atomic::{AtomicUsize, Ordering},
4 };
5
6 use bstr::{BStr, BString};
7 use gix_worktree::Stack;
8
9 use crate::{checkout, checkout::entry};
10
11 mod reduce {
12 use crate::checkout;
13
14 pub struct Reduce<'entry> {
15 pub aggregate: super::Outcome<'entry>,
16 }
17
18 impl<'entry> gix_features::parallel::Reduce for Reduce<'entry> {
19 type Input = Result<super::Outcome<'entry>, checkout::Error>;
20 type FeedProduce = ();
21 type Output = super::Outcome<'entry>;
22 type Error = checkout::Error;
23
24 fn feed(&mut self, item: Self::Input) -> Result<Self::FeedProduce, Self::Error> {
25 let item = item?;
26 let super::Outcome {
27 bytes_written,
28 files,
29 delayed_symlinks,
30 errors,
31 collisions,
32 delayed_paths_unknown,
33 delayed_paths_unprocessed,
34 } = item;
35 self.aggregate.bytes_written += bytes_written;
36 self.aggregate.files += files;
37 self.aggregate.delayed_symlinks.extend(delayed_symlinks);
38 self.aggregate.errors.extend(errors);
39 self.aggregate.collisions.extend(collisions);
40 self.aggregate.delayed_paths_unknown.extend(delayed_paths_unknown);
41 self.aggregate
42 .delayed_paths_unprocessed
43 .extend(delayed_paths_unprocessed);
44
45 Ok(())
46 }
47
48 fn finalize(self) -> Result<Self::Output, Self::Error> {
49 Ok(self.aggregate)
50 }
51 }
52 }
53 pub use reduce::Reduce;
54
55 use crate::checkout::entry::DelayedFilteredStream;
56
57 #[derive(Default)]
58 pub struct Outcome<'a> {
59 pub collisions: Vec<checkout::Collision>,
60 pub errors: Vec<checkout::ErrorRecord>,
61 pub delayed_symlinks: Vec<(&'a mut gix_index::Entry, &'a BStr)>,
62 // all (immediately) written bytes
63 pub bytes_written: u64,
64 // the amount of files we processed
65 pub files: usize,
66 /// Relative paths that the process listed as 'delayed' even though we never passed them.
67 pub delayed_paths_unknown: Vec<BString>,
68 /// All paths that were left unprocessed, because they were never listed by the process even though we passed them.
69 pub delayed_paths_unprocessed: Vec<BString>,
70 }
71
72 #[derive(Clone)]
73 pub struct Context<Find: Clone> {
74 pub objects: Find,
75 pub path_cache: Stack,
76 pub filters: gix_filter::Pipeline,
77 pub buf: Vec<u8>,
78 pub options: Options,
79 }
80
81 #[derive(Clone, Copy)]
82 pub struct Options {
83 pub fs: gix_fs::Capabilities,
84 pub destination_is_initially_empty: bool,
85 pub overwrite_existing: bool,
86 pub keep_going: bool,
87 pub filter_process_delay: gix_filter::driver::apply::Delay,
88 }
89
90 impl From<&checkout::Options> for Options {
91 fn from(opts: &checkout::Options) -> Self {
92 Options {
93 fs: opts.fs,
94 destination_is_initially_empty: opts.destination_is_initially_empty,
95 overwrite_existing: opts.overwrite_existing,
96 keep_going: opts.keep_going,
97 filter_process_delay: opts.filter_process_delay,
98 }
99 }
100 }
101
102 pub fn process<'entry, Find>(
103 entries_with_paths: impl Iterator<Item = (&'entry mut gix_index::Entry, &'entry BStr)>,
104 files: &AtomicUsize,
105 bytes: &AtomicUsize,
106 delayed_filter_results: &mut Vec<DelayedFilteredStream<'entry>>,
107 ctx: &mut Context<Find>,
108 ) -> Result<Outcome<'entry>, checkout::Error>
109 where
110 Find: gix_object::Find + Clone,
111 {
112 let mut delayed_symlinks = Vec::new();
113 let mut collisions = Vec::new();
114 let mut errors = Vec::new();
115 let mut bytes_written = 0;
116 let mut files_in_chunk = 0;
117
118 for (entry, entry_path) in entries_with_paths {
119 // TODO: write test for that
120 if entry.flags.contains(gix_index::entry::Flags::SKIP_WORKTREE) {
121 files.fetch_add(1, Ordering::Relaxed);
122 files_in_chunk += 1;
123 continue;
124 }
125
126 // Symlinks always have to be delayed on windows as they have to point to something that exists on creation.
127 // And even if not, there is a distinction between file and directory symlinks, hence we have to check what the target is
128 // before creating it.
129 // And to keep things sane, we just do the same on non-windows as well which is similar to what git does and adds some safety
130 // around writing through symlinks (even though we handle this).
131 // This also means that we prefer content in files over symlinks in case of collisions, which probably is for the better, too.
132 if entry.mode == gix_index::entry::Mode::SYMLINK {
133 delayed_symlinks.push((entry, entry_path));
134 continue;
135 }
136
137 match checkout_entry_handle_result(entry, entry_path, &mut errors, &mut collisions, files, bytes, ctx)? {
138 entry::Outcome::Written { bytes } => {
139 bytes_written += bytes as u64;
140 files_in_chunk += 1;
141 }
142 entry::Outcome::Delayed(delayed) => delayed_filter_results.push(delayed),
143 }
144 }
145
146 Ok(Outcome {
147 bytes_written,
148 files: files_in_chunk,
149 errors,
150 collisions,
151 delayed_symlinks,
152 delayed_paths_unknown: Vec::new(),
153 delayed_paths_unprocessed: Vec::new(),
154 })
155 }
156
157 pub fn process_delayed_filter_results<Find>(
158 mut delayed_filter_results: Vec<DelayedFilteredStream<'_>>,
159 files: &AtomicUsize,
160 bytes: &AtomicUsize,
161 out: &mut Outcome<'_>,
162 ctx: &mut Context<Find>,
163 ) -> Result<(), checkout::Error>
164 where
165 Find: gix_object::Find + Clone,
166 {
167 let Options {
168 destination_is_initially_empty,
169 overwrite_existing,
170 keep_going,
171 ..
172 } = ctx.options;
173 let mut bytes_written = 0;
174 let mut delayed_files = 0;
175 // Sort by path for fast lookups
176 delayed_filter_results.sort_by(|a, b| a.entry_path.cmp(b.entry_path));
177 // We process each key and do as the filter process tells us, while collecting data about the overall progress.
178 let keys: BTreeSet<_> = delayed_filter_results.iter().map(|d| d.key.clone()).collect();
179 let mut unknown_paths = Vec::new();
180 for key in keys {
181 loop {
182 let rela_paths = ctx.filters.driver_state_mut().list_delayed_paths(&key)?;
183 if rela_paths.is_empty() {
184 break;
185 }
186
187 for rela_path in rela_paths {
188 let delayed = match delayed_filter_results.binary_search_by(|d| d.entry_path.cmp(rela_path.as_ref())) {
189 Ok(idx) => &mut delayed_filter_results[idx],
190 Err(_) => {
191 if keep_going {
192 unknown_paths.push(rela_path);
193 continue;
194 } else {
195 return Err(checkout::Error::FilterPathUnknown { rela_path });
196 }
197 }
198 };
199 let mut read = std::io::BufReader::with_capacity(
200 512 * 1024,
201 ctx.filters.driver_state_mut().fetch_delayed(
202 &key,
203 rela_path.as_ref(),
204 gix_filter::driver::Operation::Smudge,
205 )?,
206 );
207 let (file, set_executable_after_creation) = match entry::open_file(
208 &std::mem::take(&mut delayed.validated_file_path), // mark it as seen, relevant for `unprocessed_paths`
209 destination_is_initially_empty,
210 overwrite_existing,
211 delayed.needs_executable_bit,
212 delayed.entry.mode,
213 ) {
214 Ok(res) => res,
215 Err(err) => {
216 if !is_collision(&err, delayed.entry_path, &mut out.collisions, files) {
217 handle_error(err, delayed.entry_path, files, &mut out.errors, ctx.options.keep_going)?;
218 }
219 std::io::copy(&mut read, &mut std::io::sink())?;
220 continue;
221 }
222 };
223 let mut write = WriteWithProgress {
224 inner: std::io::BufWriter::with_capacity(512 * 1024, file),
225 progress: bytes,
226 };
227 let actual_bytes = std::io::copy(&mut read, &mut write)?;
228 bytes_written += actual_bytes;
229 entry::finalize_entry(
230 delayed.entry,
231 write.inner.into_inner().map_err(std::io::IntoInnerError::into_error)?,
232 actual_bytes,
233 set_executable_after_creation,
234 )?;
235 delayed_files += 1;
236 files.fetch_add(1, Ordering::Relaxed);
237 }
238 }
239 }
240
241 let unprocessed_paths = delayed_filter_results
242 .into_iter()
243 .filter_map(|d| (!d.validated_file_path.as_os_str().is_empty()).then(|| d.entry_path.to_owned()))
244 .collect();
245
246 if !keep_going && !unknown_paths.is_empty() {
247 return Err(checkout::Error::FilterPathsUnprocessed {
248 rela_paths: unprocessed_paths,
249 });
250 }
251
252 out.delayed_paths_unknown = unknown_paths;
253 out.delayed_paths_unprocessed = unprocessed_paths;
254 out.bytes_written += bytes_written;
255 out.files += delayed_files;
256 Ok(())
257 }
258
259 pub struct WriteWithProgress<'a, T> {
260 pub inner: T,
261 pub progress: &'a AtomicUsize,
262 }
263
264 impl<T> std::io::Write for WriteWithProgress<'_, T>
265 where
266 T: std::io::Write,
267 {
268 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
269 let written = self.inner.write(buf)?;
270 self.progress
271 .fetch_add(written as gix_features::progress::Step, Ordering::SeqCst);
272 Ok(written)
273 }
274
275 fn flush(&mut self) -> std::io::Result<()> {
276 self.inner.flush()
277 }
278 }
279
280 pub fn checkout_entry_handle_result<'entry, Find>(
281 entry: &'entry mut gix_index::Entry,
282 entry_path: &'entry BStr,
283 errors: &mut Vec<checkout::ErrorRecord>,
284 collisions: &mut Vec<checkout::Collision>,
285 files: &AtomicUsize,
286 bytes: &AtomicUsize,
287 Context {
288 objects,
289 path_cache,
290 filters,
291 buf,
292 options,
293 }: &mut Context<Find>,
294 ) -> Result<entry::Outcome<'entry>, checkout::Error>
295 where
296 Find: gix_object::Find + Clone,
297 {
298 let res = entry::checkout(
299 entry,
300 entry_path,
301 entry::Context {
302 objects,
303 path_cache,
304 filters,
305 buf,
306 },
307 *options,
308 );
309 match res {
310 Ok(out) => {
311 if let Some(num) = out.as_bytes() {
312 bytes.fetch_add(num, Ordering::Relaxed);
313 files.fetch_add(1, Ordering::Relaxed);
314 }
315 Ok(out)
316 }
317 Err(checkout::Error::Io(err)) if is_collision(&err, entry_path, collisions, files) => {
318 Ok(entry::Outcome::Written { bytes: 0 })
319 }
320 Err(err) => handle_error(err, entry_path, files, errors, options.keep_going)
321 .map(|()| entry::Outcome::Written { bytes: 0 }),
322 }
323 }
324
325 fn handle_error<E>(
326 err: E,
327 entry_path: &BStr,
328 files: &AtomicUsize,
329 errors: &mut Vec<checkout::ErrorRecord>,
330 keep_going: bool,
331 ) -> Result<(), E>
332 where
333 E: std::error::Error + Send + Sync + 'static,
334 {
335 if keep_going {
336 errors.push(checkout::ErrorRecord {
337 path: entry_path.into(),
338 error: Box::new(err),
339 });
340 files.fetch_add(1, Ordering::Relaxed);
341 Ok(())
342 } else {
343 Err(err)
344 }
345 }
346
347 fn is_collision(
348 err: &std::io::Error,
349 entry_path: &BStr,
350 collisions: &mut Vec<checkout::Collision>,
351 files: &AtomicUsize,
352 ) -> bool {
353 if !gix_fs::symlink::is_collision_error(err) {
354 return false;
355 }
356 // We are here because a file existed or was blocked by a directory which shouldn't be possible unless
357 // we are on a file insensitive file system.
358 gix_features::trace::error!("{entry_path}: collided ({:?})", err.kind());
359 collisions.push(checkout::Collision {
360 path: entry_path.into(),
361 error_kind: err.kind(),
362 });
363 files.fetch_add(1, Ordering::Relaxed);
364 true
365 }