unityrs-core 1.0.0

Read and write Unity asset bundles, serialized files and typetrees.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
// Ported from UnityPy 1.25.2 (MIT): UnityPy/classes/PPtr.py, UnityPy/environment.py. See THIRD_PARTY_LICENSES.
//! Lookups and dereference: `get_cab`, `find_file` and `PPtr.deref`, by
//! the rules of [`super::pptr`]. "Module docs" below are [`super`]'s.

use std::hash::{Hash, Hasher};
use std::sync::Arc;

use super::container_index::Siblings;
use super::listing::FileMatch;
use super::load::Asked;
use super::registry::from_callers;
use super::registry::{Slot, SlotKind};
use super::resource_data::top_container;
use super::{Cab, DerefError, Environment, Found, HeldCab, PPtr, RawCab, pptr};
use crate::error::{Error, NotFound};
use crate::files::{External, File, FileSlot, ParentKind, SerializedFile};
use crate::limits::Meter;
use crate::object::ObjectRef;
use crate::pystr::{clean_external_path, lower_eq, simplify_name};
use crate::raw::RawStr;

/// `objects[m_PathID]` of a target file (rule 6).
fn object_in(sf: &Arc<SerializedFile>, path_id: i64) -> Result<ObjectRef, DerefError> {
    sf.object(path_id).ok_or_else(|| DerefError::MissingObject {
        file: sf.name().clone(),
        path_id,
    })
}

/// The file a CAB is: the `SerializedFile`, or the raw reader (a bundle
/// entry's, read from its bundle's cell).
fn cab_file(cab: &Cab) -> Result<File, Error> {
    Ok(match cab {
        Cab::Serialized(sf) => File::Serialized(sf.clone()),
        Cab::Raw(RawCab::File(raw)) => File::Raw(raw.clone()),
        Cab::Raw(RawCab::InBundle { bundle, dir_index }) => bundle.entry(*dir_index)?,
    })
}

/// How [`Environment::external`] reached the file it found, which says how
/// long a container preload walk may keep the answer (UnityPy keeps none:
/// each dereference looks again, `classes/PPtr.py:57-85`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Reached {
    /// A sibling in the asking file's bundle, whose names never change.
    Sibling,
    /// This Environment's `files` or registry, which a load may change.
    Lookup,
    /// The resolver's file, loaded now: under the name it was asked for or
    /// another, which only the next lookup tells.
    Load,
}

pub(super) struct HeldLookup<'a> {
    meter: &'a Meter,
    container: Option<File>,
    reuse: Option<&'a mut ReuseTarget<'a>>,
}

type ReuseTarget<'a> = dyn FnMut(FileOccurrence) -> Result<Option<ObjectRef>, Error> + 'a;

impl HeldLookup<'_> {
    fn reused(
        &mut self,
        occurrence: impl FnOnce() -> Option<FileOccurrence>,
    ) -> Result<Option<ObjectRef>, Error> {
        match (self.reuse.as_mut(), occurrence) {
            (Some(reuse), occurrence) => occurrence().map_or(Ok(None), reuse),
            (None, _) => Ok(None),
        }
    }
}

/// A serialized file's occurrence, comparable before its data is loaded.
/// Dependency occurrences are stable across cache reopens.
#[derive(Clone, Debug)]
pub struct FileOccurrence(Occurrence);

const _: () = crate::send_sync::<FileOccurrence>();

#[derive(Clone, Debug)]
enum Occurrence {
    Parsed(Arc<SerializedFile>),
    Dependency(usize, Arc<Slot>),
    DependencySibling(Arc<SerializedFile>, usize),
}

impl FileOccurrence {
    /// The occurrence of an already parsed file.
    #[must_use]
    pub fn of(file: &Arc<SerializedFile>) -> Self {
        Self(Occurrence::Parsed(file.clone()))
    }

    fn in_entry(container: &File, index: usize) -> Option<Self> {
        match container.parsed_container_entry(index)? {
            File::Serialized(file) => Some(Self::of(file)),
            _ => None,
        }
    }

    fn in_sibling(from: &Arc<SerializedFile>, container: &File, index: usize) -> Option<Self> {
        if from.occurrence_key().1.is_empty() {
            Self::in_entry(container, index)
        } else {
            Some(Self(Occurrence::DependencySibling(from.clone(), index)))
        }
    }

    fn in_slot(slot: &Arc<Slot>) -> Option<Self> {
        match &slot.kind {
            SlotKind::Dependency { dep } => Some(Self(Occurrence::Dependency(
                dep.meter().input_address(),
                slot.clone(),
            ))),
            SlotKind::Ready(Cab::Serialized(file)) => Some(Self::of(file)),
            SlotKind::Entry { bundle, dir_index } => {
                Self::in_entry(&File::Bundle(bundle.clone()), *dir_index)
            }
            SlotKind::Ready(_) => None,
        }
    }

    fn parts(&self) -> (usize, &[usize], Option<usize>) {
        match &self.0 {
            Occurrence::Parsed(file) => {
                let (input, path) = file.occurrence_key();
                (input, path, None)
            }
            Occurrence::Dependency(input, slot) => (*input, slot.rank.path(), None),
            Occurrence::DependencySibling(from, index) => {
                let (input, path) = from.occurrence_key();
                (
                    input,
                    path.split_last().map_or(&[], |(_, parent)| parent),
                    Some(*index),
                )
            }
        }
    }

    /// Number of directory indices in this occurrence, for work accounting.
    #[must_use]
    pub fn path_len(&self) -> usize {
        let (_, path, last) = self.parts();
        path.len() + usize::from(last.is_some())
    }
}

impl PartialEq for FileOccurrence {
    fn eq(&self, other: &Self) -> bool {
        let (input, path, last) = self.parts();
        let (other_input, other_path, other_last) = other.parts();
        input == other_input
            && path
                .iter()
                .copied()
                .chain(last)
                .eq(other_path.iter().copied().chain(other_last))
    }
}

impl Eq for FileOccurrence {}

impl Hash for FileOccurrence {
    fn hash<H: Hasher>(&self, state: &mut H) {
        let (input, path, last) = self.parts();
        input.hash(state);
        (path.len() + usize::from(last.is_some())).hash(state);
        for index in path.iter().copied().chain(last) {
            index.hash(state);
        }
    }
}

fn scan_siblings(
    slots: &[FileSlot],
    clean: &RawStr,
    work: Option<&Meter>,
) -> Result<Option<usize>, Error> {
    for slot in slots {
        if let Some(work) = work {
            work.count_decode((slot.name.as_bytes().len() as u64).saturating_add(1))?;
        }
        if lower_eq(slot.name.as_bytes(), clean.as_bytes()) {
            return Ok(Some(slot.dir_index));
        }
    }
    Ok(None)
}

fn external_name<'a>(
    from: &'a SerializedFile,
    file_id: i32,
    work: Option<&Meter>,
) -> Result<(&'a External, RawStr), DerefError> {
    let externals = from.externals();
    let index = pptr::external_index(file_id, externals.len()).map_err(|error| match error {
        pptr::ExternalIndexError::PastEnd => DerefError::FileIdPastEnd { file_id },
        pptr::ExternalIndexError::BelowStart => DerefError::FileIdBelowStart { file_id },
    })?;
    let external = externals
        .get(index)
        .ok_or(DerefError::FileIdBelowStart { file_id })?;
    if let Some(work) = work {
        work.count_decode(external.path.len() as u64)
            .map_err(Error::from)?;
    }
    let clean = clean_external_path(&external.path, from.meter()).map_err(Error::from)?;
    Ok((external, clean))
}

fn sibling_entry(
    from: &SerializedFile,
    clean: &RawStr,
    siblings: Option<&mut Siblings>,
    work: Option<&Meter>,
) -> Result<Option<(File, usize)>, DerefError> {
    let Some(parent) = from.parent() else {
        return Ok(None);
    };
    let dropped = || DerefError::ContainerDropped {
        name: parent.name.clone(),
    };
    let container = match &parent.kind {
        ParentKind::Bundle { bundle, .. } => File::Bundle(bundle.upgrade().ok_or_else(dropped)?),
        ParentKind::Web { web } => File::Web(web.upgrade().ok_or_else(dropped)?),
    };
    let index = match (siblings, &container) {
        (Some(index), File::Bundle(bundle)) => index.find(bundle, clean)?,
        _ => scan_siblings(container.container_files(), clean, work)?,
    };
    Ok(index.map(|index| (container, index)))
}

impl Environment {
    /// `get_cab`: the registry under `simplify_name(name)`, an entry parsed
    /// now if it was registered lazily. The lowered key a lookup builds is
    /// charged to `meter` while the lookup runs (the meter of the file whose
    /// input chose `name`; a caller's own string may use
    /// [`Meter::unlimited`]), and a name already in its simplified form is
    /// not copied ([`Registry::get`]). A dependency's CAB may outlive its
    /// bundle in the LRU: [`Self::get_cab_held`] returns the handle that
    /// keeps it. A pool refusal anywhere in the lookup, the key's charge to
    /// a dependency's meter included, evicts the others and retries once
    /// (plan section 3.13).
    ///
    /// [`Registry::get`]: super::Registry::get
    pub fn get_cab(&self, name: &RawStr, meter: &Arc<Meter>) -> Result<Option<Cab>, Error> {
        Ok(self.get_cab_held(name, meter)?.map(|h| h.cab))
    }

    /// [`Self::get_cab`], with the handle that keeps a dependency's CAB's
    /// container alive while the caller holds it ([`HeldCab`]): an eviction
    /// drops only the LRU's handle, so the CAB's pointers into its sibling
    /// entries keep resolving (rather than failing with
    /// [`DerefError::ContainerDropped`]).
    pub fn get_cab_held(
        &self,
        name: &RawStr,
        meter: &Arc<Meter>,
    ) -> Result<Option<HeldCab>, Error> {
        self.room(|| self.inner.registry.get_held(name, meter))
    }

    /// `find_file(name, is_dependency)`: what UnityPy's returns
    /// (`environment.py:310-354`), the file itself, of whatever kind. First
    /// the CAB [`Self::get_cab`] finds, as the file it is (UnityPy's `cabs`
    /// hold the file: `environment.py:252-264`): a `SerializedFile`, or a raw
    /// reader, a bundle entry's being that entry
    /// ([`crate::files::BundleFile::entry`]). Else the resolver's source for
    /// `name` ([`CabResolver::find_file`]), loaded: a bundle, a
    /// `SerializedFile`, a raw reader (a WebFile is refused in P1, as
    /// [`Self::load`] refuses one). With [`EnvOptions::keep_resolver_loads`]
    /// that load is a [`FileEntry`] under the resolved source's name, never
    /// evicted, a dependency as `is_dependency` says (UnityPy's default is
    /// true, and a dereference's call takes it): a dependency's objects are
    /// in neither [`Self::objects`] nor [`Self::container`]. Without it
    /// ([`EnvOptions::batch`]) the load is an evictable dependency in the
    /// LRU only, whatever the flag, so it is in none of [`Self::files`],
    /// `objects` or `container`, the one way this call differs from
    /// UnityPy's there (`PARITY.md` section 19.3, "resolver loads under
    /// `keep_resolver_loads` false"). `None` where the resolver answers
    /// none (UnityPy's `None`); the resolver's error where it returns one
    /// (UnityPy's walk's `FileNotFoundError`, [`CabResolver::find_file`]).
    /// `meter` as for [`Self::get_cab`]. A pool refusal in the lookup, in
    /// the resolver's answer (its own, counted as it returns) or in the
    /// load evicts the others and retries that step once (plan section
    /// 3.13; review round 12: the resolver's own refusal was returned
    /// untried, which a dereference retried). A dependency's
    /// `SerializedFile` may outlive its bundle in the LRU, as `get_cab`'s
    /// may: [`Self::get_cab_held`] returns the handle that keeps it.
    /// (Review round 11: a container the resolver loaded was `None`, the
    /// answer a miss gives.)
    ///
    /// [`CabResolver::find_file`]: super::CabResolver::find_file
    /// [`EnvOptions::keep_resolver_loads`]: super::EnvOptions::keep_resolver_loads
    /// [`EnvOptions::batch`]: super::EnvOptions::batch
    /// [`FileEntry`]: super::FileEntry
    pub fn find_file(
        &self,
        name: &RawStr,
        is_dependency: bool,
        meter: &Arc<Meter>,
    ) -> Result<Option<File>, Error> {
        match self.find(name, is_dependency, meter, None)? {
            None => Ok(None),
            Some((Found::File(file), _)) => Ok(Some(file)),
            Some((Found::Reused(object), _)) => Ok(Some(File::Serialized(object.file().clone()))),
            // A raw entry the registry answered is in its bundle's cell, so
            // `entry` reads the cell; it takes the retry all the same.
            Some((Found::Cab(cab), _)) => self.room(|| cab_file(&cab)).map(Some),
        }
    }

    /// [`Self::find_file`]'s lookup, and how it reached what it found. A
    /// pool refusal in the registry's lookup, or one the resolver's
    /// `find_file` returns, evicts the others and retries that step once;
    /// the resolver's load takes its own (`load_resolved`), so a retry never
    /// loads again what a load before it loaded (plan section 3.13; review
    /// round 12: the resolver's refusal was retried inside a dereference
    /// only, whose retry encloses this lookup).
    fn find(
        &self,
        name: &RawStr,
        is_dependency: bool,
        meter: &Arc<Meter>,
        mut work: Option<&mut HeldLookup<'_>>,
    ) -> Result<Option<(Found, Reached)>, Error> {
        // UnityPy environment.py:326-329: `get_cab(simplify_name(name))`,
        // which simplifies again.
        let found = self.room(|| -> Result<Option<Found>, Error> {
            let simple = simplify_name(name, meter)?;
            let registry = &self.inner.registry;
            if let Some(work) = work.as_deref_mut() {
                let Some(slot) = registry.slot(&simple, meter)? else {
                    return Ok(None);
                };
                if let Some(object) = work.reused(|| FileOccurrence::in_slot(&slot))? {
                    return Ok(Some(Found::Reused(object)));
                }
                Ok(registry.resolve_held(&slot)?.map(|held| {
                    work.container = held.hold;
                    Found::Cab(held.cab)
                }))
            } else {
                Ok(registry.get(&simple, meter)?.map(Found::Cab))
            }
        })?;
        if let Some(found) = found {
            return Ok(Some((found, Reached::Lookup)));
        }
        // :330-354: the resolver stands for the walk of `env.path`. What it
        // returns is the caller's code's, a pool refusal in it counted as it
        // enters the core (`from_callers`) and retried as the core's own.
        let Some(resolver) = self.inner.options.resolver.clone() else {
            return Ok(None);
        };
        let Some(source) = self.room(|| from_callers(resolver.find_file(name.as_bytes())))? else {
            return Ok(None);
        };
        let file = self.load_resolved(&source, Asked::Find { is_dependency })?;
        Ok(Some((Found::File(file), Reached::Load)))
    }

    /// `PPtr.deref` from an object in `from` (`classes/PPtr.py:43-90`), by
    /// the rules of [`pptr`]: `from`'s container is its bundle
    /// ([`crate::files::ParentKind::Bundle`]'s handle), or, for a file loaded
    /// at top level, this Environment, whose [`Self::files`] keys the sibling
    /// scan compares. `from` need not have been loaded here (a batch job's
    /// own bundle handle): its bundle siblings come from its parent, every
    /// other CAB from this Environment. When `from`'s bundle has been
    /// dropped (its weak handle no longer upgrades) the dereference fails
    /// with [`DerefError::ContainerDropped`] rather than guess: UnityPy
    /// cannot reach that state, since an object keeps its file's parent
    /// alive, so the bindings and a batch engine keep a strong bundle handle
    /// beside every `SerializedFile` they hand out. A pool refusal anywhere
    /// in the dereference (reading or looking up from a dependency's file)
    /// evicts the others and retries once, `from`'s top-level bundle held
    /// meanwhile (plan section 3.13; review round 8: it had no retry).
    pub fn deref(&self, from: &Arc<SerializedFile>, pptr: PPtr) -> Result<ObjectRef, DerefError> {
        self.deref_inner(from, pptr, None)
    }

    /// Resolve as in [`Self::deref`], retaining the target's top-level
    /// container when available. Hold the returned file to preserve access
    /// to the target's siblings across dependency cache evictions.
    ///
    /// Charge the caller's work meter for the external path and each sibling
    /// name examined, including any scan on retry.
    pub fn deref_held(
        &self,
        from: &Arc<SerializedFile>,
        pptr: PPtr,
        meter: &Meter,
    ) -> Result<(ObjectRef, Option<File>), DerefError> {
        let mut work = HeldLookup {
            meter,
            container: None,
            reuse: None,
        };
        let object = self.deref_inner(from, pptr, Some(&mut work))?;
        Ok((object, work.container))
    }

    /// Resolve as in [`Self::deref_held`]. Before opening a known target,
    /// offer its file occurrence to `reuse`. The callback may return a
    /// retained object at the requested path ID in that occurrence. A hit
    /// needs no new target container hold, even after a dependency eviction.
    ///
    /// Reuse assumes a dependency's source stays stable across reopens.
    /// A resolver alias may load another copy of a dependency.
    pub fn deref_held_reusing(
        &self,
        from: &Arc<SerializedFile>,
        pptr: PPtr,
        meter: &Meter,
        mut reuse: impl FnMut(FileOccurrence) -> Result<Option<ObjectRef>, Error>,
    ) -> Result<(ObjectRef, Option<File>), DerefError> {
        let mut work = HeldLookup {
            meter,
            container: None,
            reuse: Some(&mut reuse),
        };
        let object = self.deref_inner(from, pptr, Some(&mut work))?;
        Ok((object, work.container))
    }

    fn deref_inner(
        &self,
        from: &Arc<SerializedFile>,
        pptr: PPtr,
        mut work: Option<&mut HeldLookup<'_>>,
    ) -> Result<ObjectRef, DerefError> {
        // UnityPy classes/PPtr.py:49-50
        if pptr.path_id == 0 {
            return Err(DerefError::Null);
        }
        // :53-54
        if pptr.file_id == 0 {
            if let Some(work) = work {
                if let Some(object) = work.reused(|| Some(FileOccurrence::of(from)))? {
                    return Ok(object);
                }
                work.container = top_container(from);
            }
            return object_in(from, pptr.path_id);
        }
        let _top = top_container(from);
        // Nothing after a resolver's load charges anything, so a retry never
        // loads again what the first run loaded.
        self.room(|| {
            self.reach_chain(from)?;
            let (target, _) = self.external(from, pptr.file_id, None, work.as_deref_mut())?;
            if let Found::Reused(object) = target {
                return Ok(object);
            }
            let object = Self::object_of(&target, pptr.path_id)?;
            if let Some(work) = work.as_deref_mut()
                && work.container.is_none()
            {
                work.container = top_container(object.file());
            }
            Ok(object)
        })
    }

    /// The file `from`'s external `file_id` names (`classes/PPtr.py:57-85`):
    /// a sibling in `from`'s container (the bundle's `files`, or for a
    /// top-level file this Environment's), else `find_file`; and how it was
    /// reached ([`Reached`]). `siblings` is a container pass's index of
    /// bundle names; without it the bundle's names are scanned.
    pub(super) fn external(
        &self,
        from: &Arc<SerializedFile>,
        file_id: i32,
        siblings: Option<&mut Siblings>,
        mut work: Option<&mut HeldLookup<'_>>,
    ) -> Result<(Found, Reached), DerefError> {
        let meter = from.meter();
        let meter_work = work.as_ref().map(|work| work.meter);
        let (external, clean) = external_name(from, file_id, meter_work)?;
        // :63-78: the container's `files`, each key lower-cased, the first
        // equal one wins.
        let sibling = if let Some((parent, i)) = sibling_entry(from, &clean, siblings, meter_work)?
        {
            if let Some(work) = work.as_deref_mut()
                && let Some(object) =
                    work.reused(|| FileOccurrence::in_sibling(from, &parent, i))?
            {
                return Ok((Found::Reused(object), Reached::Sibling));
            }
            let file = parent.container_entry(i)?;
            // Named as a sibling, a nested container is reached as a get
            // of its name would reach it.
            if matches!(file, File::Bundle(_) | File::Web(_))
                && let File::Bundle(bundle) = parent
            {
                self.reach_sibling(from, &bundle, i, &file)?;
            }
            Some((file, Reached::Sibling))
        } else if from.parent().is_none() {
            match self.files_match(&clean) {
                Some(FileMatch::File(f)) => {
                    if let (File::Serialized(file), Some(work)) = (&f, work.as_deref_mut())
                        && let Some(object) = work.reused(|| Some(FileOccurrence::of(file)))?
                    {
                        return Ok((Found::Reused(object), Reached::Lookup));
                    }
                    Some((f, Reached::Lookup))
                }
                // A matching key breaks the loop even when its value is
                // None; only an absent key runs the for-else fallback
                // (classes/PPtr.py:75-88).
                Some(FileMatch::ZipNone) => {
                    return Err(DerefError::NotFound {
                        path: external.path.clone(),
                    });
                }
                None => None,
            }
        } else {
            None
        };
        match sibling {
            Some((f, reached)) => Ok((Found::File(f), reached)),
            // :80-85: `find_file`'s `None`, and its walk's
            // `FileNotFoundError`, are the pointer's `FileNotFoundError`.
            None => match self.find(&clean, true, meter, work) {
                Ok(Some(t)) => Ok(t),
                Ok(None) | Err(Error::NotFound(NotFound::Cab(_))) => Err(DerefError::NotFound {
                    path: external.path.clone(),
                }),
                Err(e) => Err(e.into()),
            },
        }
    }

    /// The object holding `path_id` in what a dereference reached
    /// (`classes/PPtr.py:90`, `assetsfile_dst.objects[m_PathID]`).
    pub(super) fn object_of(target: &Found, path_id: i64) -> Result<ObjectRef, DerefError> {
        match target.clone() {
            Found::Reused(object) => Ok(object),
            Found::Cab(Cab::Serialized(sf)) | Found::File(File::Serialized(sf)) => {
                object_in(&sf, path_id)
            }
            Found::Cab(Cab::Raw(RawCab::InBundle { bundle, dir_index })) => {
                Err(DerefError::RawTarget {
                    name: bundle
                        .directory()
                        .get(dir_index)
                        .map(|d| d.path.clone())
                        .unwrap_or_default(),
                })
            }
            Found::Cab(Cab::Raw(RawCab::File(raw))) | Found::File(File::Raw(raw)) => {
                Err(DerefError::RawTarget {
                    name: raw.name.clone(),
                })
            }
            Found::File(File::Bundle(b)) => Err(DerefError::RawTarget {
                name: b.name().clone(),
            }),
            Found::File(File::Web(w)) => Err(DerefError::RawTarget {
                name: w.name().clone(),
            }),
        }
    }
}