diplodocus 0.15.0

Build coherent documentation websites for polyglot software projects.
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
//! Resolve explicit filesystem inputs without changing portable declarations.
//!
//! Call [`resolve_workspace_paths`] after parsing or loading a configuration.
//! The resulting absolute paths describe this machine's filesystem at the time
//! of the call. They are runtime data, not serializable documentation IR.

use std::fmt;
use std::fs;
use std::path::{Component, Path, PathBuf};

use thiserror::Error;

use crate::configuration::WorkspaceConfiguration;
use crate::diagnostics::{
    Diagnostic, DiagnosticCode, DiagnosticEntity, DiagnosticPath, DiagnosticSource, Severity,
};
use crate::ir::{SourceLocation, SourceSpan};

/// Canonical local inputs, retaining the configuration's declaration order.
///
/// These records deliberately do not implement serialization. The corresponding
/// [`WorkspaceConfiguration`] retains the original paths for portable storage.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedWorkspacePaths {
    /// Canonical parent of the caller-supplied configuration path.
    pub configuration_directory: PathBuf,
    /// Repository roots, in repository declaration order.
    pub repositories: Vec<ResolvedRepositoryPaths>,
    /// Package roots and inputs, in package declaration order.
    pub packages: Vec<ResolvedPackagePaths>,
    /// Authored roots and environment inputs, in content declaration order.
    pub content: Vec<ResolvedContentPaths>,
}

/// An explicitly supplied repository's local boundary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedRepositoryPaths {
    /// Repository identifier, retained as declared.
    pub id: String,
    /// Canonical absolute repository directory.
    pub path: PathBuf,
}

impl ResolvedRepositoryPaths {
    /// Convert a contained absolute file path to portable source evidence.
    ///
    /// Recheck the repository boundary and every component using the same rules
    /// as configuration resolution. The location names the canonical referent,
    /// relative to this repository. A supplied span is evidence from the caller;
    /// this operation does not read or validate source text.
    ///
    /// # Errors
    ///
    /// Reject missing or nonregular files, nonportable names, relative runtime
    /// paths, and escapes, including intermediate escapes that later return.
    /// Errors retain runtime paths locally; [`PathResolutionError::to_diagnostic`]
    /// removes them from portable diagnostics.
    pub fn source_location(
        &self,
        path: impl AsRef<Path>,
        span: Option<SourceSpan>,
    ) -> Result<SourceLocation, PathResolutionError> {
        let path = path.as_ref();
        let resolver = Resolver {
            configuration_path: &self.path,
        };
        let field = "source_location";
        let relative = path.strip_prefix(&self.path).map_err(|_| {
            resolver.error(
                field,
                PathResolutionErrorKind::OutsideBoundary {
                    path: path.to_owned(),
                    boundary: self.path.clone(),
                },
            )
        })?;
        let relative = if relative.as_os_str().is_empty() {
            Path::new(".")
        } else {
            relative
        };
        let resolved = resolve_input_file(&self.path, field, relative, &self.path)?;
        Ok(SourceLocation {
            repository: self.id.clone(),
            path: portable_relative_path(
                &self.path,
                field,
                resolved
                    .strip_prefix(&self.path)
                    .expect("validated boundary"),
            )?,
            span,
        })
    }
}

/// Reuse component-by-component boundary validation when reading selected files.
pub(crate) fn resolve_input_file(
    configuration_path: &Path,
    field: &str,
    declared: &Path,
    boundary: &Path,
) -> Result<PathBuf, PathResolutionError> {
    let resolver = Resolver { configuration_path };
    let current_boundary = resolver.canonicalize(field, boundary)?;
    if current_boundary != boundary {
        return Err(resolver.error(
            field,
            PathResolutionErrorKind::OutsideBoundary {
                path: current_boundary,
                boundary: boundary.to_owned(),
            },
        ));
    }
    resolver.child(field, declared, boundary, PathType::File)
}

/// Check a repository hyperlink without reading or discovering its target.
pub(crate) fn resolve_repository_target(
    declared: &Path,
    boundary: &Path,
) -> Result<PathBuf, PathResolutionError> {
    let resolver = Resolver {
        configuration_path: boundary,
    };
    let field = "repository hyperlink";
    let current_boundary = resolver.canonicalize(field, boundary)?;
    if current_boundary != boundary {
        return Err(resolver.error(
            field,
            PathResolutionErrorKind::OutsideBoundary {
                path: current_boundary,
                boundary: boundary.to_owned(),
            },
        ));
    }
    resolver.child(field, declared, boundary, PathType::FileOrDirectory)
}

/// Normalize a relative spelling without losing case or Unicode identity.
pub(crate) fn portable_relative_path(
    configuration_path: &Path,
    field: &str,
    declared: &Path,
) -> Result<DiagnosticPath, PathResolutionError> {
    let resolver = Resolver { configuration_path };
    resolver.check_spelling(field, declared, true)?;
    let invalid = || {
        resolver.error(
            field,
            PathResolutionErrorKind::InvalidPath {
                path: declared.to_owned(),
                reason: "source files require normalized, UTF-8, portable relative paths",
            },
        )
    };
    let mut names = Vec::new();
    for component in declared.components() {
        match component {
            Component::Normal(name) => names.push(name.to_str().ok_or_else(invalid)?),
            Component::CurDir => {}
            Component::ParentDir => {
                names.pop().ok_or_else(invalid)?;
            }
            Component::Prefix(_) | Component::RootDir => return Err(invalid()),
        }
    }
    DiagnosticPath::try_from(names.join("/")).map_err(|_| invalid())
}

/// A package's local boundary and explicit extractor inputs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedPackagePaths {
    /// Package identifier, retained as declared.
    pub id: String,
    /// Index of the containing repository in [`ResolvedWorkspacePaths::repositories`].
    pub repository_index: usize,
    /// Canonical absolute package directory, contained in its repository.
    pub path: PathBuf,
    /// Canonical regular metadata file, contained in the package directory.
    pub metadata_path: PathBuf,
    /// Explicit GFM overview file, contained in the package directory.
    pub overview: Option<PathBuf>,
    /// Explicit targets, in target declaration order; never inferred.
    pub targets: Vec<ResolvedTargetPath>,
}

/// One explicitly declared source file or directory for extraction.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedTargetPath {
    /// Target identifier, retained as declared.
    pub id: String,
    /// Canonical absolute file or directory, contained in its package.
    pub path: PathBuf,
    /// Canonical explicitly supplied Julia extension entry files inside the package.
    pub julia_extensions: Vec<PathBuf>,
}

/// An authored collection's root and explicitly declared environment files.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedContentPaths {
    /// Collection identifier, retained as declared.
    pub id: String,
    /// Index of the containing repository in [`ResolvedWorkspacePaths::repositories`].
    pub repository_index: usize,
    /// Canonical absolute source directory or file, contained in its repository.
    pub path: PathBuf,
    /// Source directory, or the parent directory of a single-file collection.
    pub source_root: PathBuf,
    /// Canonical regular files relative to the repository, in declaration order.
    pub declared_environment_inputs: Vec<PathBuf>,
    /// Prepared native Julia project file, contained in the repository.
    pub julia_project: Option<PathBuf>,
    /// Project and available Julia manifest files, in sorted order.
    pub julia_environment_inputs: Vec<PathBuf>,
}

/// A filesystem resolution failure tied to a specific configuration field.
#[derive(Debug, Error)]
#[error("could not resolve configuration `{}` field `{field}`: {kind}", configuration_path.display())]
pub struct PathResolutionError {
    /// Configuration path supplied to [`resolve_workspace_paths`].
    pub configuration_path: PathBuf,
    /// Indexed configuration field and declaring ID, or `configuration_directory`.
    pub field: String,
    /// Underlying path or repository-reference failure.
    #[source]
    pub kind: PathResolutionErrorKind,
}

impl PathResolutionError {
    /// Convert a resolution failure to a portable configuration diagnostic.
    ///
    /// The caller supplies the configuration-relative path. The schema field
    /// identifies the declaration, while runtime paths and custom I/O messages
    /// stay in this error for local troubleshooting. Resolution has no source
    /// text, so it cannot supply a byte range.
    pub fn to_diagnostic(&self, path: DiagnosticPath) -> Diagnostic {
        let (code, message) = match &self.kind {
            PathResolutionErrorKind::InvalidPath { reason, .. } => (
                DiagnosticCode::InvalidSourcePath,
                format!("invalid source path: {reason}"),
            ),
            PathResolutionErrorKind::FileSystem { source, .. } => (
                DiagnosticCode::SourcePathIo,
                format!("could not inspect source path: {}", source.kind()),
            ),
            PathResolutionErrorKind::WrongType { expected, .. } => (
                DiagnosticCode::SourcePathWrongType,
                format!("source path must identify {expected}"),
            ),
            PathResolutionErrorKind::OutsideBoundary { .. } => (
                DiagnosticCode::SourcePathOutsideBoundary,
                "source path escapes its declared boundary".to_owned(),
            ),
            PathResolutionErrorKind::RepositoryReference {
                repository,
                matches,
            } => (
                DiagnosticCode::InvalidRepositoryReference,
                format!(
                    "repository `{repository}` matches {matches} declarations; expected exactly one"
                ),
            ),
        };
        Diagnostic::new(code, Severity::Error, message)
            .with_source(DiagnosticSource::Configuration { path })
            .with_entity(DiagnosticEntity::ConfigurationField {
                path: self.field.clone(),
            })
    }
}

/// The reason a declared filesystem input could not be resolved.
#[derive(Debug, Error)]
pub enum PathResolutionErrorKind {
    /// A path is empty or cannot be interpreted relative to its boundary.
    #[error("invalid path `{}`: {reason}", path.display())]
    InvalidPath {
        /// Path as declared.
        path: PathBuf,
        /// Explanation of the rejected spelling.
        reason: &'static str,
    },
    /// A path could not be inspected or canonicalized.
    #[error("could not inspect `{}`: {source}", path.display())]
    FileSystem {
        /// Attempted path, preserving unresolved components when relevant.
        path: PathBuf,
        /// Underlying filesystem failure, including missing or inaccessible inputs.
        source: std::io::Error,
    },
    /// A path exists but has the wrong filesystem type.
    #[error("expected {expected} at `{}`", path.display())]
    WrongType {
        /// Canonical path with the wrong type.
        path: PathBuf,
        /// Type required by the declaring field.
        expected: PathType,
    },
    /// A resolved component leaves its declared repository or package.
    #[error("path `{}` escapes boundary `{}`", path.display(), boundary.display())]
    OutsideBoundary {
        /// First canonical path outside the boundary.
        path: PathBuf,
        /// Canonical repository or package root that contains this input.
        boundary: PathBuf,
    },
    /// A reference cannot select one unambiguous repository root.
    #[error("repository `{repository}` matches {matches} declarations; expected exactly one")]
    RepositoryReference {
        /// Repository ID referenced by a package or collection.
        repository: String,
        /// Number of matching repository declarations, either zero or more than one.
        matches: usize,
    },
}

/// Filesystem type required by a configuration field.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PathType {
    /// Repository or package root.
    Directory,
    /// Package metadata or declared environment input.
    File,
    /// Explicit extraction target or authored content source.
    FileOrDirectory,
}

impl fmt::Display for PathType {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::Directory => "a directory",
            Self::File => "a regular file",
            Self::FileOrDirectory => "a regular file or directory",
        })
    }
}

/// Resolve and validate only the filesystem inputs explicitly declared in a workspace.
///
/// Repository paths use the configuration directory as their base. Explicit
/// sibling roots (`../checkout`) and absolute repository roots are permitted.
/// Packages are relative to repositories; metadata and extraction targets are
/// relative to packages; content and environment inputs are relative to
/// repositories. Child declarations must be relative and cannot leave their
/// boundary, including through symlinks or intermediate `..` components that
/// later return. Contained `..` components and symlinks are permitted.
/// Each declared prefix is checked by its canonical referent; intermediate link
/// metadata in a symlink chain does not establish an additional input boundary.
///
/// The parent of `configuration_path` must exist as a directory, but the file
/// itself need not exist. A relative configuration path uses the current working
/// directory. A configuration-file symlink retains the caller-supplied parent
/// as the base, rather than using the target file's directory.
///
/// This does not change declarations, discover descendants, parse file contents,
/// validate owners or relationships, or run code. It checks paths at call time;
/// later discovery and reads must enforce containment again if paths can change.
/// Execution settings and document authority require their separate validators.
///
/// # Errors
///
/// Returns the first invalid path or unresolved/ambiguous repository reference.
/// Order is configuration directory, repository declarations, package declarations
/// (root, metadata, targets), then content declarations (root, environment inputs).
/// Repository and package roots must be directories, metadata and environment
/// inputs regular files, and targets and content sources regular files or
/// directories. Content files must match their declared format's extension.
/// Errors retain the configuration path, indexed field and declaration ID, and
/// underlying filesystem cause when present.
pub fn resolve_workspace_paths(
    configuration_path: impl AsRef<Path>,
    configuration: &WorkspaceConfiguration,
) -> Result<ResolvedWorkspacePaths, PathResolutionError> {
    let resolver = Resolver {
        configuration_path: configuration_path.as_ref(),
    };
    let parent = resolver
        .configuration_path
        .parent()
        .filter(|path| !path.as_os_str().is_empty())
        .unwrap_or(Path::new("."));
    let configuration_directory =
        resolver.resolve_path("configuration_directory", parent, None, None)?;
    resolver.check_type(
        "configuration_directory",
        &configuration_directory,
        PathType::Directory,
    )?;

    let mut repositories = Vec::with_capacity(configuration.repositories.len());
    for (index, repository) in configuration.repositories.iter().enumerate() {
        let field = format!("repositories[{index}] (`{}`).path", repository.id);
        let path = resolver.resolve_path(
            &field,
            &repository.path,
            Some(&configuration_directory),
            None,
        )?;
        resolver.check_type(&field, &path, PathType::Directory)?;
        repositories.push(ResolvedRepositoryPaths {
            id: repository.id.clone(),
            path,
        });
    }

    let mut packages = Vec::with_capacity(configuration.packages.len());
    for (index, package) in configuration.packages.iter().enumerate() {
        let field = format!("packages[{index}] (`{}`)", package.id);
        let repository_index = resolver.repository_index(
            &format!("{field}.repository"),
            &package.repository,
            &repositories,
        )?;
        let path = resolver.child(
            &format!("{field}.path"),
            &package.path,
            &repositories[repository_index].path,
            PathType::Directory,
        )?;
        let metadata_path = resolver.child(
            &format!("{field}.metadata-path"),
            &package.metadata_path,
            &path,
            PathType::File,
        )?;
        let overview = package
            .overview
            .as_ref()
            .map(|declared| {
                let field = format!("{field}.overview");
                if declared
                    .extension()
                    .is_none_or(|extension| extension != "md")
                {
                    return Err(resolver.error(
                        &field,
                        PathResolutionErrorKind::InvalidPath {
                            path: declared.clone(),
                            reason: "overview files must use the GFM .md extension",
                        },
                    ));
                }
                resolver.child(&field, declared, &path, PathType::File)
            })
            .transpose()?;
        let mut targets = Vec::with_capacity(package.targets.len());
        for (index, target) in package.targets.iter().enumerate() {
            let mut julia_extensions = Vec::new();
            if let Some(settings) = &target.julia {
                for (extension_index, declared) in settings.extensions.iter().enumerate() {
                    let extension_field =
                        format!("{field}.targets[{index}].julia.extensions[{extension_index}]");
                    if declared
                        .extension()
                        .is_none_or(|extension| extension != "jl")
                    {
                        return Err(resolver.error(
                            &extension_field,
                            PathResolutionErrorKind::InvalidPath {
                                path: declared.clone(),
                                reason: "Julia extension entries must be .jl files",
                            },
                        ));
                    }
                    let resolved =
                        resolver.child(&extension_field, declared, &path, PathType::File)?;
                    if julia_extensions.contains(&resolved) {
                        return Err(resolver.error(
                            &extension_field,
                            PathResolutionErrorKind::InvalidPath {
                                path: declared.clone(),
                                reason: "Julia extension entries must be unique",
                            },
                        ));
                    }
                    julia_extensions.push(resolved);
                }
            }
            targets.push(ResolvedTargetPath {
                id: target.id.clone(),
                path: resolver.child(
                    &format!("{field}.targets[{index}] (`{}`).path", target.id),
                    &target.path,
                    &path,
                    PathType::FileOrDirectory,
                )?,
                julia_extensions,
            });
        }
        packages.push(ResolvedPackagePaths {
            id: package.id.clone(),
            repository_index,
            path,
            metadata_path,
            overview,
            targets,
        });
    }

    let mut content = Vec::with_capacity(configuration.content.len());
    for (index, collection) in configuration.content.iter().enumerate() {
        let field = format!("content[{index}] (`{}`)", collection.id);
        let repository_index = resolver.repository_index(
            &format!("{field}.repository"),
            &collection.repository,
            &repositories,
        )?;
        let root = &repositories[repository_index].path;
        let path = resolver.child(
            &format!("{field}.path"),
            &collection.path,
            root,
            PathType::FileOrDirectory,
        )?;
        let source_root = if path.is_file() {
            if !collection.format.matches_path(&path) {
                return Err(resolver.error(
                    &format!("{field}.path"),
                    PathResolutionErrorKind::InvalidPath {
                        path,
                        reason: "content file extension does not match the declared format",
                    },
                ));
            }
            path.parent()
                .expect("contained content file parent")
                .to_owned()
        } else {
            path.clone()
        };
        let mut declared_environment_inputs = Vec::new();
        for (index, input) in collection
            .execution
            .declared_environment_inputs
            .iter()
            .enumerate()
        {
            declared_environment_inputs.push(resolver.child(
                &format!("{field}.execution.declared-environment-inputs[{index}]"),
                input,
                root,
                PathType::File,
            )?);
        }
        let julia_project = collection
            .execution
            .julia_project
            .as_ref()
            .map(|project| {
                resolver.child(
                    &format!("{field}.execution.julia-project"),
                    project,
                    root,
                    PathType::File,
                )
            })
            .transpose()?;
        let mut julia_environment_inputs = Vec::new();
        if let Some(project) = &julia_project {
            julia_environment_inputs.push(project.clone());
            let directory = project.parent().expect("project parent");
            for entry in fs::read_dir(directory)
                .map_err(|error| resolver.io_error(&field, directory, error))?
            {
                let entry = entry.map_err(|error| resolver.io_error(&field, directory, error))?;
                let name = entry.file_name();
                let name = name.to_string_lossy();
                if (name.starts_with("Manifest") || name.starts_with("JuliaManifest"))
                    && name.ends_with(".toml")
                {
                    julia_environment_inputs.push(resolver.child(
                        &format!("{field}.execution.julia-project manifest"),
                        Path::new(name.as_ref()),
                        directory,
                        PathType::File,
                    )?);
                }
            }
            julia_environment_inputs.sort();
        }
        content.push(ResolvedContentPaths {
            id: collection.id.clone(),
            repository_index,
            path,
            source_root,
            declared_environment_inputs,
            julia_project,
            julia_environment_inputs,
        });
    }

    Ok(ResolvedWorkspacePaths {
        configuration_directory,
        repositories,
        packages,
        content,
    })
}

struct Resolver<'a> {
    configuration_path: &'a Path,
}

impl Resolver<'_> {
    fn error(&self, field: &str, kind: PathResolutionErrorKind) -> PathResolutionError {
        PathResolutionError {
            configuration_path: self.configuration_path.to_owned(),
            field: field.to_owned(),
            kind,
        }
    }

    fn io_error(&self, field: &str, path: &Path, source: std::io::Error) -> PathResolutionError {
        self.error(
            field,
            PathResolutionErrorKind::FileSystem {
                path: path.to_owned(),
                source,
            },
        )
    }

    fn canonicalize(&self, field: &str, path: &Path) -> Result<PathBuf, PathResolutionError> {
        fs::canonicalize(path).map_err(|source| self.io_error(field, path, source))
    }

    fn check_spelling(
        &self,
        field: &str,
        path: &Path,
        child: bool,
    ) -> Result<(), PathResolutionError> {
        let reason = if path.as_os_str().is_empty() {
            Some("paths must not be empty; use `.` to select a root")
        } else if path
            .components()
            .any(|component| matches!(component, Component::Prefix(_) | Component::RootDir))
        {
            if child {
                Some("child paths must be relative to their declared boundary")
            } else if !path.is_absolute() {
                Some("paths must be fully absolute or relative without a drive or root")
            } else {
                None
            }
        } else {
            None
        };
        if let Some(reason) = reason {
            return Err(self.error(
                field,
                PathResolutionErrorKind::InvalidPath {
                    path: path.to_owned(),
                    reason,
                },
            ));
        }
        Ok(())
    }

    fn check_type(
        &self,
        field: &str,
        path: &Path,
        expected: PathType,
    ) -> Result<(), PathResolutionError> {
        let metadata = fs::metadata(path).map_err(|source| self.io_error(field, path, source))?;
        let valid = match expected {
            PathType::Directory => metadata.is_dir(),
            PathType::File => metadata.is_file(),
            PathType::FileOrDirectory => metadata.is_file() || metadata.is_dir(),
        };
        if !valid {
            return Err(self.error(
                field,
                PathResolutionErrorKind::WrongType {
                    path: path.to_owned(),
                    expected,
                },
            ));
        }
        Ok(())
    }

    fn child(
        &self,
        field: &str,
        declared: &Path,
        boundary: &Path,
        expected: PathType,
    ) -> Result<PathBuf, PathResolutionError> {
        let resolved = self.resolve_path(field, declared, Some(boundary), Some(boundary))?;
        self.check_type(field, &resolved, expected)?;
        Ok(resolved)
    }

    fn resolve_path(
        &self,
        field: &str,
        declared: &Path,
        base: Option<&Path>,
        boundary: Option<&Path>,
    ) -> Result<PathBuf, PathResolutionError> {
        self.check_spelling(field, declared, boundary.is_some())?;
        let mut components = declared.components().peekable();
        let mut resolved = if declared.is_absolute() {
            let mut root = PathBuf::new();
            while let Some(component) = components
                .next_if(|component| matches!(component, Component::Prefix(_) | Component::RootDir))
            {
                root.push(component);
            }
            self.canonicalize(field, &root)?
        } else if let Some(base) = base {
            base.to_owned()
        } else {
            self.canonicalize(field, Path::new("."))?
        };

        for component in components {
            self.require_directory(field, &resolved)?;
            match component {
                Component::Normal(name) => {
                    let mut next = resolved.clone();
                    if !next
                        .as_os_str()
                        .as_encoded_bytes()
                        .last()
                        .is_some_and(|byte| is_separator(*byte))
                    {
                        next.as_mut_os_string().push(std::path::MAIN_SEPARATOR_STR);
                    }
                    // A normal component can resemble a Windows drive prefix
                    // when parsed alone. Appending it must not change the base.
                    next.as_mut_os_string().push(name);
                    resolved = self.canonicalize(field, &next)?;
                }
                Component::ParentDir => {
                    // Canonical Windows bases use verbatim prefixes, whose joins
                    // erase dot components. Resolve links first, then take the
                    // actual parent without joining an unresolved `..`.
                    resolved.pop();
                }
                Component::CurDir => {}
                Component::Prefix(_) | Component::RootDir => {
                    unreachable!("root components are consumed before traversal");
                }
            }
            if let Some(boundary) = boundary {
                self.check_boundary(field, &resolved, boundary)?;
            }
        }

        // Components omits trailing separators and dots, but their directory
        // requirement must survive on both ordinary and verbatim paths.
        let last = declared
            .as_os_str()
            .as_encoded_bytes()
            .rsplit(|byte| is_separator(*byte))
            .next()
            .unwrap_or_default();
        if last.is_empty() || last == b"." {
            self.require_directory(field, &resolved)?;
        }
        Ok(resolved)
    }

    fn require_directory(&self, field: &str, path: &Path) -> Result<(), PathResolutionError> {
        let metadata = fs::metadata(path).map_err(|source| self.io_error(field, path, source))?;
        if !metadata.is_dir() {
            return Err(self.io_error(field, path, std::io::ErrorKind::NotADirectory.into()));
        }
        Ok(())
    }

    fn check_boundary(
        &self,
        field: &str,
        path: &Path,
        boundary: &Path,
    ) -> Result<(), PathResolutionError> {
        if !path.starts_with(boundary) {
            return Err(self.error(
                field,
                PathResolutionErrorKind::OutsideBoundary {
                    path: path.to_owned(),
                    boundary: boundary.to_owned(),
                },
            ));
        }
        Ok(())
    }

    fn repository_index(
        &self,
        field: &str,
        id: &str,
        repositories: &[ResolvedRepositoryPaths],
    ) -> Result<usize, PathResolutionError> {
        let mut matches = repositories
            .iter()
            .enumerate()
            .filter(|(_, repository)| repository.id == id);
        if let Some((index, _)) = matches.next() {
            let additional = matches.count();
            if additional == 0 {
                return Ok(index);
            }
            return Err(self.error(
                field,
                PathResolutionErrorKind::RepositoryReference {
                    repository: id.to_owned(),
                    matches: additional + 1,
                },
            ));
        }
        Err(self.error(
            field,
            PathResolutionErrorKind::RepositoryReference {
                repository: id.to_owned(),
                matches: 0,
            },
        ))
    }
}

fn is_separator(byte: u8) -> bool {
    byte == b'/' || (cfg!(windows) && byte == b'\\')
}