gix_diff/blob/
pipeline.rs

1use std::{
2    io::{Read, Write},
3    path::{Path, PathBuf},
4    process::{Command, Stdio},
5};
6
7use bstr::{BStr, ByteSlice};
8use gix_filter::{
9    driver::apply::{Delay, MaybeDelayed},
10    pipeline::convert::{ToGitOutcome, ToWorktreeOutcome},
11};
12use gix_object::tree::EntryKind;
13
14use crate::blob::{Driver, Pipeline, ResourceKind};
15
16/// A way to access roots for different kinds of resources that are possibly located and accessible in a worktree.
17#[derive(Clone, Debug, Default)]
18pub struct WorktreeRoots {
19    /// A place where the source of a rewrite, rename or copy, or generally the previous version of resources, are located.
20    pub old_root: Option<PathBuf>,
21    /// A place where the destination of a rewrite, rename or copy, or generally the new version of resources, are located.
22    pub new_root: Option<PathBuf>,
23}
24
25/// Access
26impl WorktreeRoots {
27    /// Return the root path for the given `kind`
28    pub fn by_kind(&self, kind: ResourceKind) -> Option<&Path> {
29        match kind {
30            ResourceKind::OldOrSource => self.old_root.as_deref(),
31            ResourceKind::NewOrDestination => self.new_root.as_deref(),
32        }
33    }
34
35    /// Return `true` if all worktree roots are unset.
36    pub fn is_unset(&self) -> bool {
37        self.new_root.is_none() && self.old_root.is_none()
38    }
39}
40
41/// Data as part of an [Outcome].
42#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug)]
43pub enum Data {
44    /// The data to use for diffing was written into the buffer that was passed during the call to [`Pipeline::convert_to_diffable()`].
45    Buffer {
46        /// If `true`, a [binary to text filter](Driver::binary_to_text_command) was used to obtain the buffer,
47        /// making it a derived value.
48        ///
49        /// Applications should check for this to avoid treating the buffer content as (original) resource content.
50        is_derived: bool,
51    },
52    /// The size that the binary blob had at the given revision, without having applied filters, as it's either
53    /// considered binary or above the big-file threshold.
54    ///
55    /// In this state, the binary file cannot be diffed.
56    Binary {
57        /// The size of the object prior to performing any filtering or as it was found on disk.
58        ///
59        /// Note that technically, the size isn't always representative of the same 'state' of the
60        /// content, as once it can be the size of the blob in git, and once it's the size of file
61        /// in the worktree.
62        size: u64,
63    },
64}
65
66/// The outcome returned by [Pipeline::convert_to_diffable()](super::Pipeline::convert_to_diffable()).
67#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug)]
68pub struct Outcome {
69    /// If available, an index into the `drivers` field to access more diff-related information of the driver for items
70    /// at the given path, as previously determined by git-attributes.
71    ///
72    /// Note that drivers are queried even if there is no object available.
73    pub driver_index: Option<usize>,
74    /// The data itself, suitable for diffing, and if the object or worktree item is present at all.
75    pub data: Option<Data>,
76}
77
78/// Options for use in a [`Pipeline`].
79#[derive(Default, Clone, Copy, PartialEq, Eq, Debug, Hash, Ord, PartialOrd)]
80pub struct Options {
81    /// The amount of bytes that an object has to reach before being treated as binary.
82    /// These objects will not be queried, nor will their data be processed in any way.
83    /// If `0`, no file is ever considered binary due to their size.
84    ///
85    /// Note that for files stored in `git`, what counts is their stored, decompressed size,
86    /// thus `git-lfs` files would typically not be considered binary unless one explicitly sets
87    /// them
88    pub large_file_threshold_bytes: u64,
89    /// Capabilities of the file system which affect how we read worktree files.
90    pub fs: gix_fs::Capabilities,
91}
92
93/// The specific way to convert a resource.
94#[derive(Default, Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
95pub enum Mode {
96    /// Always prepare the version of the resource as it would be in the work-tree, and
97    /// apply binary-to-text filters if present.
98    ///
99    /// This is typically free for resources in the worktree, and will apply filters to resources in the
100    /// object database.
101    #[default]
102    ToWorktreeAndBinaryToText,
103    /// Prepare the version of the resource as it would be in the work-tree if
104    /// binary-to-text filters are present (and apply them), or use the version in `git` otherwise.
105    ToGitUnlessBinaryToTextIsPresent,
106    /// Always prepare resources as they are stored in `git`.
107    ///
108    /// This is usually fastest, even though resources in the worktree needed to be converted files.
109    ToGit,
110}
111
112impl Mode {
113    fn to_worktree(self) -> bool {
114        matches!(
115            self,
116            Mode::ToGitUnlessBinaryToTextIsPresent | Mode::ToWorktreeAndBinaryToText
117        )
118    }
119
120    fn to_git(self) -> bool {
121        matches!(self, Mode::ToGitUnlessBinaryToTextIsPresent | Mode::ToGit)
122    }
123}
124
125///
126pub mod convert_to_diffable {
127    use std::collections::TryReserveError;
128
129    use bstr::BString;
130    use gix_object::tree::EntryKind;
131
132    /// The error returned by [Pipeline::convert_to_diffable()](super::Pipeline::convert_to_diffable()).
133    #[derive(Debug, thiserror::Error)]
134    #[allow(missing_docs)]
135    pub enum Error {
136        #[error("Entry at '{rela_path}' must be regular file or symlink, but was {actual:?}")]
137        InvalidEntryKind { rela_path: BString, actual: EntryKind },
138        #[error("Entry at '{rela_path}' could not be read as symbolic link")]
139        ReadLink { rela_path: BString, source: std::io::Error },
140        #[error("Entry at '{rela_path}' could not be opened for reading or read from")]
141        OpenOrRead { rela_path: BString, source: std::io::Error },
142        #[error("Entry at '{rela_path}' could not be copied from a filter process to a memory buffer")]
143        StreamCopy { rela_path: BString, source: std::io::Error },
144        #[error("Failed to run '{cmd}' for binary-to-text conversion of entry at {rela_path}")]
145        RunTextConvFilter {
146            rela_path: BString,
147            cmd: String,
148            source: std::io::Error,
149        },
150        #[error("Tempfile for binary-to-text conversion for entry at {rela_path} could not be created")]
151        CreateTempfile { rela_path: BString, source: std::io::Error },
152        #[error("Binary-to-text conversion '{cmd}' for entry at {rela_path} failed with: {stderr}")]
153        TextConvFilterFailed {
154            rela_path: BString,
155            cmd: String,
156            stderr: BString,
157        },
158        #[error(transparent)]
159        FindObject(#[from] gix_object::find::existing_object::Error),
160        #[error(transparent)]
161        ConvertToWorktree(#[from] gix_filter::pipeline::convert::to_worktree::Error),
162        #[error(transparent)]
163        ConvertToGit(#[from] gix_filter::pipeline::convert::to_git::Error),
164        #[error("Memory allocation failed")]
165        OutOfMemory(#[from] TryReserveError),
166    }
167}
168
169/// Lifecycle
170impl Pipeline {
171    /// Create a new instance of a pipeline which produces blobs suitable for diffing. `roots` allow to read worktree files directly, otherwise
172    /// `worktree_filter` is used to transform object database data directly. `drivers` further configure individual paths.
173    /// `options` are used to further configure the way we act..
174    pub fn new(
175        roots: WorktreeRoots,
176        worktree_filter: gix_filter::Pipeline,
177        mut drivers: Vec<super::Driver>,
178        options: Options,
179    ) -> Self {
180        drivers.sort_by(|a, b| a.name.cmp(&b.name));
181        Pipeline {
182            roots,
183            worktree_filter,
184            drivers,
185            options,
186            attrs: {
187                let mut out = gix_filter::attributes::search::Outcome::default();
188                out.initialize_with_selection(&Default::default(), Some("diff"));
189                out
190            },
191            path: Default::default(),
192        }
193    }
194}
195
196/// Access
197impl Pipeline {
198    /// Return all drivers that this instance was initialized with.
199    ///
200    /// They are sorted by [`name`](Driver::name) to support binary searches.
201    pub fn drivers(&self) -> &[super::Driver] {
202        &self.drivers
203    }
204}
205
206/// Conversion
207impl Pipeline {
208    /// Convert the object at `id`, `mode`, `rela_path` and `kind`, providing access to `attributes` and `objects`.
209    /// The resulting diff-able data is written into `out`, assuming it's not too large. The returned [`Outcome`]
210    /// contains information on how to use `out`, or if it's filled at all.
211    ///
212    /// `attributes` must be returning the attributes at `rela_path`, and `objects` must be usable if `kind` is
213    /// a resource in the object database, i.e. has no worktree root available.
214    ///
215    /// If `id` [is null](gix_hash::ObjectId::is_null()) or the file in question doesn't exist in the worktree in case
216    /// [a root](WorktreeRoots) is present, then `out` will be left cleared and [Outcome::data] will be `None`.
217    ///
218    /// Note that `mode` is trusted, and we will not re-validate that the entry in the worktree actually is of that mode.
219    ///
220    /// Use `convert` to control what kind of the resource will be produced.
221    ///
222    /// ### About Tempfiles
223    ///
224    /// When querying from the object database and a binary and a [binary-to-text](Driver::binary_to_text_command) is set,
225    /// a temporary file will be created to serve as input for the converter program, containing the worktree-data that
226    /// exactly as it would be present in the worktree if checked out.
227    ///
228    /// As these files are ultimately named tempfiles, they will be leaked unless the [gix_tempfile] is configured with
229    /// a signal handler. If they leak, they would remain in the system's `$TMP` directory.
230    #[allow(clippy::too_many_arguments)]
231    pub fn convert_to_diffable(
232        &mut self,
233        id: &gix_hash::oid,
234        mode: EntryKind,
235        rela_path: &BStr,
236        kind: ResourceKind,
237        attributes: &mut dyn FnMut(&BStr, &mut gix_filter::attributes::search::Outcome),
238        objects: &dyn gix_object::FindObjectOrHeader,
239        convert: Mode,
240        out: &mut Vec<u8>,
241    ) -> Result<Outcome, convert_to_diffable::Error> {
242        let is_symlink = match mode {
243            EntryKind::Link if self.options.fs.symlink => true,
244            EntryKind::Blob | EntryKind::BlobExecutable => false,
245            _ => {
246                return Err(convert_to_diffable::Error::InvalidEntryKind {
247                    rela_path: rela_path.to_owned(),
248                    actual: mode,
249                })
250            }
251        };
252
253        out.clear();
254        attributes(rela_path, &mut self.attrs);
255        let attr = self.attrs.iter_selected().next().expect("pre-initialized with 'diff'");
256        let driver_index = attr
257            .assignment
258            .state
259            .as_bstr()
260            .and_then(|name| self.drivers.binary_search_by(|d| d.name.as_bstr().cmp(name)).ok());
261        let driver = driver_index.map(|idx| &self.drivers[idx]);
262        let mut is_binary = if let Some(driver) = driver {
263            driver
264                .is_binary
265                .map(|is_binary| is_binary && driver.binary_to_text_command.is_none())
266        } else {
267            attr.assignment.state.is_unset().then_some(true)
268        };
269        match self.roots.by_kind(kind) {
270            Some(root) => {
271                self.path.clear();
272                self.path.push(root);
273                self.path.push(gix_path::from_bstr(rela_path));
274                let data = if is_symlink {
275                    let target = none_if_missing(std::fs::read_link(&self.path)).map_err(|err| {
276                        convert_to_diffable::Error::ReadLink {
277                            rela_path: rela_path.to_owned(),
278                            source: err,
279                        }
280                    })?;
281                    target.map(|target| {
282                        out.extend_from_slice(gix_path::into_bstr(target).as_ref());
283                        Data::Buffer { is_derived: false }
284                    })
285                } else {
286                    let need_size_only = is_binary == Some(true);
287                    let size_in_bytes = (need_size_only
288                        || (is_binary != Some(false) && self.options.large_file_threshold_bytes > 0))
289                        .then(|| {
290                            none_if_missing(self.path.metadata().map(|md| md.len())).map_err(|err| {
291                                convert_to_diffable::Error::OpenOrRead {
292                                    rela_path: rela_path.to_owned(),
293                                    source: err,
294                                }
295                            })
296                        })
297                        .transpose()?;
298                    match size_in_bytes {
299                        Some(None) => None, // missing as identified by the size check
300                        Some(Some(size)) if size > self.options.large_file_threshold_bytes || need_size_only => {
301                            Some(Data::Binary { size })
302                        }
303                        _ => {
304                            match driver
305                                .filter(|_| convert.to_worktree())
306                                .and_then(|d| d.prepare_binary_to_text_cmd(&self.path))
307                            {
308                                Some(cmd) => {
309                                    // Avoid letting the driver program fail if it doesn't exist.
310                                    if self.options.large_file_threshold_bytes == 0
311                                        && none_if_missing(std::fs::symlink_metadata(&self.path))
312                                            .map_err(|err| convert_to_diffable::Error::OpenOrRead {
313                                                rela_path: rela_path.to_owned(),
314                                                source: err,
315                                            })?
316                                            .is_none()
317                                    {
318                                        None
319                                    } else {
320                                        run_cmd(rela_path, cmd, out)?;
321                                        Some(Data::Buffer { is_derived: true })
322                                    }
323                                }
324                                None => {
325                                    let file = none_if_missing(std::fs::File::open(&self.path)).map_err(|err| {
326                                        convert_to_diffable::Error::OpenOrRead {
327                                            rela_path: rela_path.to_owned(),
328                                            source: err,
329                                        }
330                                    })?;
331
332                                    match file {
333                                        Some(mut file) => {
334                                            if convert.to_git() {
335                                                let res = self.worktree_filter.convert_to_git(
336                                                    file,
337                                                    gix_path::from_bstr(rela_path).as_ref(),
338                                                    attributes,
339                                                    &mut |buf| objects.try_find(id, buf).map(|obj| obj.map(|_| ())),
340                                                )?;
341
342                                                match res {
343                                                    ToGitOutcome::Unchanged(mut file) => {
344                                                        file.read_to_end(out).map_err(|err| {
345                                                            convert_to_diffable::Error::OpenOrRead {
346                                                                rela_path: rela_path.to_owned(),
347                                                                source: err,
348                                                            }
349                                                        })?;
350                                                    }
351                                                    ToGitOutcome::Process(mut stream) => {
352                                                        stream.read_to_end(out).map_err(|err| {
353                                                            convert_to_diffable::Error::OpenOrRead {
354                                                                rela_path: rela_path.to_owned(),
355                                                                source: err,
356                                                            }
357                                                        })?;
358                                                    }
359                                                    ToGitOutcome::Buffer(buf) => {
360                                                        out.clear();
361                                                        out.try_reserve(buf.len())?;
362                                                        out.extend_from_slice(buf);
363                                                    }
364                                                }
365                                            } else {
366                                                file.read_to_end(out).map_err(|err| {
367                                                    convert_to_diffable::Error::OpenOrRead {
368                                                        rela_path: rela_path.to_owned(),
369                                                        source: err,
370                                                    }
371                                                })?;
372                                            }
373
374                                            Some(if is_binary.unwrap_or_else(|| is_binary_buf(out)) {
375                                                let size = out.len() as u64;
376                                                out.clear();
377                                                Data::Binary { size }
378                                            } else {
379                                                Data::Buffer { is_derived: false }
380                                            })
381                                        }
382                                        None => None,
383                                    }
384                                }
385                            }
386                        }
387                    }
388                };
389                Ok(Outcome { driver_index, data })
390            }
391            None => {
392                let data = if id.is_null() {
393                    None
394                } else {
395                    let header = objects
396                        .try_header(id)
397                        .map_err(gix_object::find::existing_object::Error::Find)?
398                        .ok_or_else(|| gix_object::find::existing_object::Error::NotFound { oid: id.to_owned() })?;
399                    if is_binary.is_none()
400                        && self.options.large_file_threshold_bytes > 0
401                        && header.size > self.options.large_file_threshold_bytes
402                    {
403                        is_binary = Some(true);
404                    }
405                    let data = if is_binary == Some(true) {
406                        Data::Binary { size: header.size }
407                    } else {
408                        objects
409                            .try_find(id, out)
410                            .map_err(gix_object::find::existing_object::Error::Find)?
411                            .ok_or_else(|| gix_object::find::existing_object::Error::NotFound { oid: id.to_owned() })?;
412                        let mut is_derived = false;
413                        if matches!(mode, EntryKind::Blob | EntryKind::BlobExecutable)
414                            && convert == Mode::ToWorktreeAndBinaryToText
415                            || (convert == Mode::ToGitUnlessBinaryToTextIsPresent
416                                && driver.is_some_and(|d| d.binary_to_text_command.is_some()))
417                        {
418                            let res =
419                                self.worktree_filter
420                                    .convert_to_worktree(out, rela_path, attributes, Delay::Forbid)?;
421
422                            let cmd_and_file = driver
423                                .and_then(|d| {
424                                    d.binary_to_text_command.is_some().then(|| {
425                                        gix_tempfile::new(
426                                            std::env::temp_dir(),
427                                            gix_tempfile::ContainingDirectory::Exists,
428                                            gix_tempfile::AutoRemove::Tempfile,
429                                        )
430                                        .and_then(|mut tmp_file| {
431                                            self.path.clear();
432                                            tmp_file.with_mut(|tmp| self.path.push(tmp.path()))?;
433                                            Ok(tmp_file)
434                                        })
435                                        .map(|tmp_file| {
436                                            (
437                                                d.prepare_binary_to_text_cmd(&self.path)
438                                                    .expect("always get cmd if command is set"),
439                                                tmp_file,
440                                            )
441                                        })
442                                    })
443                                })
444                                .transpose()
445                                .map_err(|err| convert_to_diffable::Error::CreateTempfile {
446                                    source: err,
447                                    rela_path: rela_path.to_owned(),
448                                })?;
449                            match cmd_and_file {
450                                Some((cmd, mut tmp_file)) => {
451                                    match res {
452                                        ToWorktreeOutcome::Unchanged(buf) | ToWorktreeOutcome::Buffer(buf) => {
453                                            tmp_file.write_all(buf)
454                                        }
455                                        ToWorktreeOutcome::Process(MaybeDelayed::Immediate(mut stream)) => {
456                                            std::io::copy(&mut stream, &mut tmp_file).map(|_| ())
457                                        }
458                                        ToWorktreeOutcome::Process(MaybeDelayed::Delayed(_)) => {
459                                            unreachable!("we prohibit this")
460                                        }
461                                    }
462                                    .map_err(|err| {
463                                        convert_to_diffable::Error::StreamCopy {
464                                            source: err,
465                                            rela_path: rela_path.to_owned(),
466                                        }
467                                    })?;
468                                    out.clear();
469                                    run_cmd(rela_path, cmd, out)?;
470                                    is_derived = true;
471                                }
472                                None => match res {
473                                    ToWorktreeOutcome::Unchanged(_) => {}
474                                    ToWorktreeOutcome::Buffer(src) => {
475                                        out.clear();
476                                        out.try_reserve(src.len())?;
477                                        out.extend_from_slice(src);
478                                    }
479                                    ToWorktreeOutcome::Process(MaybeDelayed::Immediate(mut stream)) => {
480                                        std::io::copy(&mut stream, out).map_err(|err| {
481                                            convert_to_diffable::Error::StreamCopy {
482                                                rela_path: rela_path.to_owned(),
483                                                source: err,
484                                            }
485                                        })?;
486                                    }
487                                    ToWorktreeOutcome::Process(MaybeDelayed::Delayed(_)) => {
488                                        unreachable!("we prohibit this")
489                                    }
490                                },
491                            }
492                        }
493
494                        if driver.map_or(true, |d| d.binary_to_text_command.is_none())
495                            && is_binary.unwrap_or_else(|| is_binary_buf(out))
496                        {
497                            let size = out.len() as u64;
498                            out.clear();
499                            Data::Binary { size }
500                        } else {
501                            Data::Buffer { is_derived }
502                        }
503                    };
504                    Some(data)
505                };
506                Ok(Outcome { driver_index, data })
507            }
508        }
509    }
510}
511
512fn is_binary_buf(buf: &[u8]) -> bool {
513    let buf = &buf[..buf.len().min(8000)];
514    buf.contains(&0)
515}
516
517fn none_if_missing<T>(res: std::io::Result<T>) -> std::io::Result<Option<T>> {
518    match res {
519        Ok(data) => Ok(Some(data)),
520        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
521        Err(err) => Err(err),
522    }
523}
524
525fn run_cmd(rela_path: &BStr, mut cmd: Command, out: &mut Vec<u8>) -> Result<(), convert_to_diffable::Error> {
526    gix_trace::debug!(cmd = ?cmd, "Running binary-to-text command");
527    let mut res = cmd
528        .output()
529        .map_err(|err| convert_to_diffable::Error::RunTextConvFilter {
530            rela_path: rela_path.to_owned(),
531            cmd: format!("{cmd:?}"),
532            source: err,
533        })?;
534    if !res.status.success() {
535        return Err(convert_to_diffable::Error::TextConvFilterFailed {
536            rela_path: rela_path.to_owned(),
537            cmd: format!("{cmd:?}"),
538            stderr: res.stderr.into(),
539        });
540    }
541    out.append(&mut res.stdout);
542    Ok(())
543}
544
545impl Driver {
546    /// Produce an invocable command pre-configured to produce the filtered output on stdout after reading `path`.
547    pub fn prepare_binary_to_text_cmd(&self, path: &Path) -> Option<std::process::Command> {
548        let command: &BStr = self.binary_to_text_command.as_ref()?.as_ref();
549        let cmd = gix_command::prepare(gix_path::from_bstr(command).into_owned())
550            // TODO: Add support for an actual Context, validate it *can* match Git
551            .with_context(Default::default())
552            .command_may_be_shell_script()
553            .stdin(Stdio::null())
554            .stdout(Stdio::piped())
555            .stderr(Stdio::piped())
556            .arg(path)
557            .into();
558        Some(cmd)
559    }
560}