raf-source 0.0.0

Workspace source index: a Tree file seam with disk and memory backends under canonical path containment.
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
// SPDX-FileCopyrightText: 2026 Blackcat InformaticsĀ® Inc. <paudley@blackcatinformatics.ca>
// SPDX-License-Identifier: MIT OR Apache-2.0 OR MulanPSL-2.0

//! Package discovery under explicit roots.
//!
//! The walk descends through directories that are not packages, with an
//! explicit stack and at most [`Budget::DirectoryDepth`] levels below a root.
//! It stops at a `[package]` manifest that has no `[workspace]` table, so a
//! fixture package nested below another is not found. It skips directories
//! named `target` and dot-directories, and a symlinked directory is an error.

use std::collections::BTreeMap;

use purrdf_lex::allocation::{Memory, OrderedTable};
use purrdf_lex::walk::WorkList;

#[cfg(doc)]
use crate::budget::Budget;
use crate::error::{LoadError, LoadErrorKind, Origin, TargetProblem, TreeError};
use crate::manifest::{self, Manifest, PackageDecl};
use crate::members::members;
use crate::meter::{ItemAdmission, Meter, push_item_work};
use crate::path::{RelPath, SourceAuthorityId};
use crate::target::Package;
use crate::tree::{EntryKind, Tree};

/// A package with its parsed manifest. `declared` is the manifest's `[package]`
/// table, moved out of `manifest` (whose `package` is `None` here).
pub(crate) struct Found {
    pub(crate) package: Package,
    pub(crate) declared: PackageDecl,
    pub(crate) manifest: Manifest,
}

struct Walk<'a> {
    tree: &'a dyn Tree,
    meter: &'a Meter,
    found: BTreeMap<RelPath, Found>,
    /// The manifest of each package name found so far.
    names: OrderedTable<(SourceAuthorityId, String), RelPath>,
    /// Requested layouts already retained under the names table's native account.
    name_bytes: usize,
}

/// A step of the walk: a directory and its depth below the root, or a
/// symlink to classify.
enum Step {
    Dir(RelPath, usize),
    Link(RelPath),
}

/// What discovery found.
pub(crate) struct Discovered {
    pub(crate) packages: Vec<Found>,
}

fn skipped(name: &str) -> bool {
    name == "target" || name.starts_with('.')
}

impl<'a> Walk<'a> {
    fn new(tree: &'a dyn Tree, meter: &'a Meter, at: &RelPath) -> Result<Self, LoadError> {
        meter.items(
            size_of::<OrderedTable<(SourceAuthorityId, String), RelPath>>(),
            at,
            None,
        )?;
        Ok(Self {
            tree,
            meter,
            found: BTreeMap::new(),
            names: OrderedTable::default(),
            name_bytes: 0,
        })
    }

    fn finish(self) -> Discovered {
        Discovered {
            packages: self.found.into_values().collect(),
        }
    }

    /// Retain one source-local package name through the original item allowance.
    fn remember_name(&mut self, name: &str, path: &RelPath) -> Result<(), LoadError> {
        let mut admission = ItemAdmission::resume(self.meter, path, self.name_bytes);
        let result = {
            let mut memory = Memory::resume(&mut admission, self.name_bytes);
            let mut owned = String::new();
            let result = memory.push_str(&mut owned, name).and_then(|()| {
                self.names
                    .insert((path.authority(), owned), path.clone(), &mut memory)
            });
            self.name_bytes = memory.admitted_bytes();
            result
        };
        if result.map_err(|error| admission.error(error))?.is_some() {
            return Err(LoadError::new(
                path,
                None,
                LoadErrorKind::Internal {
                    what: "a source-local package name changed during insertion".to_owned(),
                },
            ));
        }
        Ok(())
    }

    fn root(&mut self, root: &RelPath) -> Result<(), LoadError> {
        let origin = Origin::Discovery;
        match self
            .tree
            .entry(root)
            .map_err(|error| LoadError::tree(root, None, &origin, error))?
        {
            Some(EntryKind::Dir) => self.visit(root),
            Some(EntryKind::Symlink) => {
                Err(LoadError::new(root, None, LoadErrorKind::DirSymlink).reached_by(&origin))
            }
            Some(EntryKind::File | EntryKind::Other) => Err(LoadError::tree(
                root,
                None,
                &origin,
                TreeError::NotRegular {
                    path: root.to_string(),
                },
            )),
            None => Err(LoadError::tree(
                root,
                None,
                &origin,
                TreeError::NotFound {
                    path: root.to_string(),
                },
            )),
        }
    }

    fn manifest_path(dir: &RelPath) -> Result<RelPath, LoadError> {
        let origin = Origin::Discovery;
        dir.join("Cargo.toml")
            .map_err(|error| LoadError::tree(dir, None, &origin, error.into()))
    }

    fn read_manifest(&self, path: &RelPath) -> Result<Option<Manifest>, LoadError> {
        let origin = Origin::Discovery;
        let present = self
            .tree
            .entry(path)
            .map_err(|error| LoadError::tree(path, None, &origin, error))?;
        if present.is_none() {
            return Ok(None);
        }
        let text = self
            .tree
            .read(path, self.meter.options().max_file_bytes)
            .map_err(|error| LoadError::tree(path, None, &origin, error))?;
        self.meter
            .read(path, &text)
            .map_err(|error| error.reached_by(&origin))?;
        manifest::parse(&text).map(Some).map_err(|problem| {
            let origin = problem
                .key
                .map_or(Origin::Discovery, |key| Origin::ManifestKey { key });
            LoadError::new(
                path,
                None,
                LoadErrorKind::Manifest {
                    message: problem.message,
                    source: problem.source,
                },
            )
            .reached_by(&origin)
        })
    }

    /// Read the manifest of `dir`, if it has one. Returns whether the walk goes
    /// on into the directory's children.
    fn manifest(&mut self, dir: &RelPath) -> Result<bool, LoadError> {
        let path = Self::manifest_path(dir)?;
        let Some(parsed) = self.read_manifest(&path)? else {
            return Ok(true);
        };
        self.retain_manifest(dir, path, parsed)
    }

    fn retain_manifest(
        &mut self,
        dir: &RelPath,
        path: RelPath,
        mut parsed: Manifest,
    ) -> Result<bool, LoadError> {
        let descend = parsed.package.is_none() || parsed.has_workspace;
        if let Some(package) = parsed.package.take() {
            match self.names.get_by(|(authority, name)| {
                (path.authority(), package.name.as_str()).cmp(&(*authority, name.as_str()))
            }) {
                Some(other) if *other != path => {
                    return Err(LoadError::new(
                        &path,
                        None,
                        LoadErrorKind::Target(Box::new(TargetProblem::DuplicatePackage {
                            name: package.name.clone(),
                            with: other.clone(),
                        })),
                    )
                    .reached_by(&Origin::ManifestKey {
                        key: "package.name".to_owned(),
                    }));
                }
                Some(_) => {}
                None => {
                    self.remember_name(&package.name, &path)?;
                }
            }
            let entry = Found {
                package: Package {
                    name: package.name.clone(),
                    manifest: path.clone(),
                    dir: dir.clone(),
                },
                declared: package,
                manifest: parsed,
            };
            // The same manifest reached from two overlapping roots is one package.
            self.found.insert(path, entry);
        }
        Ok(descend)
    }

    /// Walk the directories below `root`, depth first and in name order, on
    /// an explicit stack.
    fn visit(&mut self, root: &RelPath) -> Result<(), LoadError> {
        let origin = Origin::Discovery;
        let mut stack = WorkList::<_, 8>::new();
        push_item_work(
            &mut stack,
            Step::Dir(root.clone(), 0),
            self.meter,
            root,
            None,
        )?;
        while let Some(step) = stack.pop() {
            let (dir, depth) = match step {
                Step::Dir(dir, depth) => (dir, depth),
                Step::Link(path) => {
                    self.symlink(&path)?;
                    continue;
                }
            };
            self.meter.directory(depth, &dir)?;
            if !self.manifest(&dir)? {
                continue;
            }
            let entries = self
                .tree
                .list(&dir)
                .map_err(|error| LoadError::tree(&dir, None, &origin, error))?;
            let mut steps = Vec::new();
            for entry in entries {
                if skipped(&entry.name) {
                    continue;
                }
                let child = dir
                    .join(&entry.name)
                    .map_err(|error| LoadError::tree(&dir, None, &origin, error.into()))?;
                match entry.kind {
                    EntryKind::Dir => steps.push(Step::Dir(child, depth + 1)),
                    EntryKind::Symlink => steps.push(Step::Link(child)),
                    EntryKind::File | EntryKind::Other => {}
                }
            }
            // Reversed, so the first entry in name order comes first.
            for step in steps.into_iter().rev() {
                push_item_work(&mut stack, step, self.meter, &dir, None)?;
            }
        }
        Ok(())
    }

    /// A symlink in a directory the walk enters, classified by what it
    /// resolves to: a regular file is left alone; a directory is a
    /// [`LoadErrorKind::DirSymlink`]; anything else is an error of the tree: a
    /// target outside the root, a loop, a dangling link or a special file.
    fn symlink(&self, path: &RelPath) -> Result<(), LoadError> {
        let origin = Origin::Discovery;
        let fail = |error| LoadError::tree(path, None, &origin, error);
        match self.tree.read(path, 0) {
            Ok(_) | Err(TreeError::TooLarge { .. }) => Ok(()),
            Err(TreeError::NotRegular { .. }) => {
                // Only a directory has a parent that `link/..` can name.
                let parent = path.join("..").map_err(|error| fail(error.into()))?;
                match self.tree.entry(&parent).map_err(fail)? {
                    Some(EntryKind::Dir) => {
                        Err(LoadError::new(path, None, LoadErrorKind::DirSymlink)
                            .reached_by(&origin))
                    }
                    Some(EntryKind::File | EntryKind::Symlink | EntryKind::Other) | None => {
                        Err(fail(TreeError::NotRegular {
                            path: path.to_string(),
                        }))
                    }
                }
            }
            Err(error) => Err(fail(error)),
        }
    }
}

fn missing_selection(path: &RelPath, message: &str) -> LoadError {
    LoadError::new(
        path,
        None,
        LoadErrorKind::Manifest {
            message: message.to_owned(),
            source: None,
        },
    )
    .reached_by(&Origin::Discovery)
}

/// Select and retain just the package manifests of one declared workspace.
pub(crate) fn workspace_members(
    tree: &dyn Tree,
    root: &RelPath,
    meter: &Meter,
) -> Result<Discovered, LoadError> {
    let root = crate::root::directory(tree, root)?;
    let path = Walk::manifest_path(&root)?;
    let mut walk = Walk::new(tree, meter, &path)?;
    let root_manifest = walk
        .read_manifest(&path)?
        .filter(|manifest| manifest.has_workspace || manifest.package.is_some())
        .ok_or_else(|| {
            missing_selection(&path, "select a Cargo.toml with a workspace or package")
        })?;
    if root_manifest.has_workspace {
        for member in members(tree, meter, &root, &path, &root_manifest)? {
            if member == root {
                continue;
            }
            let member = crate::root::directory(tree, &member)?;
            let path = Walk::manifest_path(&member)?;
            let parsed = walk
                .read_manifest(&path)?
                .filter(|manifest| manifest.package.is_some())
                .ok_or_else(|| {
                    missing_selection(&path, "workspace member needs a package manifest")
                })?;
            walk.retain_manifest(&member, path, parsed)?;
        }
    }
    walk.retain_manifest(&root, path, root_manifest)?;
    Ok(walk.finish())
}

/// Find every package under `roots`, sorted by manifest path.
///
/// # Errors
///
/// Returns the first [`LoadError`]: a missing or symlinked root, an unreadable
/// or invalid manifest, a symlinked directory, two packages with one name, a
/// directory more than [`Budget::DirectoryDepth`] levels below its root, or a
/// load that passes [`Budget::TotalBytes`].
pub(crate) fn discover(
    tree: &dyn Tree,
    roots: &[RelPath],
    meter: &Meter,
) -> Result<Discovered, LoadError> {
    let mut walk = Walk::new(tree, meter, &RelPath::root())?;
    for root in roots {
        walk.root(root)?;
    }
    Ok(walk.finish())
}

/// Read exactly the selected package header, retaining its workspace context
/// for the ordinary loader without discovering neighbouring packages.
pub(crate) fn single(
    tree: &dyn Tree,
    manifest: &RelPath,
    meter: &Meter,
) -> Result<Discovered, LoadError> {
    let dir = manifest
        .parent()
        .ok_or_else(|| LoadError::new(manifest, None, LoadErrorKind::NoRoots))?;
    if manifest.file_name() != Some("Cargo.toml") {
        return Err(LoadError::new(
            manifest,
            None,
            LoadErrorKind::Internal {
                what: "select an actual Cargo.toml manifest".into(),
            },
        ));
    }
    let mut walk = Walk::new(tree, meter, manifest)?;
    match tree
        .entry(&dir)
        .map_err(|error| LoadError::tree(&dir, None, &Origin::Discovery, error))?
    {
        Some(EntryKind::Dir) => {}
        Some(EntryKind::Symlink) => {
            return Err(LoadError::new(&dir, None, LoadErrorKind::DirSymlink)
                .reached_by(&Origin::Discovery));
        }
        _ => return Err(LoadError::new(&dir, None, LoadErrorKind::NoRoots)),
    }
    walk.manifest(&dir)?;
    if walk.found.len() != 1 {
        return Err(LoadError::new(
            manifest,
            None,
            LoadErrorKind::Internal {
                what: "selected manifest has no package identity".into(),
            },
        ));
    }
    Ok(walk.finish())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Budget, LoadOptions, MemoryTree};

    fn populate_names(limit: usize) -> Result<usize, LoadError> {
        let tree = MemoryTree::default();
        let meter = Meter::new(&LoadOptions {
            max_item_bytes: limit,
            ..LoadOptions::default()
        });
        let mut walk = Walk {
            tree: &tree,
            meter: &meter,
            found: BTreeMap::new(),
            names: OrderedTable::default(),
            name_bytes: 0,
        };
        let path = RelPath::new("Cargo.toml")
            .expect("manifest")
            .in_source(SourceAuthorityId(1));
        for index in 0..40 {
            walk.remember_name(&format!("package-{index:02}"), &path)?;
        }
        let spent = meter.usage().item_bytes;
        for index in 0..40 {
            let name = format!("package-{index:02}");
            assert_eq!(
                walk.names.get_by(|(authority, stored)| {
                    (path.authority(), name.as_str()).cmp(&(*authority, stored.as_str()))
                }),
                Some(&path)
            );
        }
        assert_eq!(meter.usage().item_bytes, spent);
        Ok(spent)
    }

    #[test]
    fn native_discovery_names_resume_retained_storage_and_refuse_the_original_grant() {
        let spent = populate_names(LoadOptions::default().max_item_bytes).expect("populated");
        assert_eq!(populate_names(spent).expect("exact allowance"), spent);
        let error = populate_names(spent - 1).expect_err("one byte too little");
        assert_eq!(error.file.authority(), SourceAuthorityId(1));
        assert!(matches!(
            error.kind,
            LoadErrorKind::Budget {
                budget: Budget::ItemBytes,
                ..
            }
        ));
    }
}