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};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedWorkspacePaths {
pub configuration_directory: PathBuf,
pub repositories: Vec<ResolvedRepositoryPaths>,
pub packages: Vec<ResolvedPackagePaths>,
pub content: Vec<ResolvedContentPaths>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedRepositoryPaths {
pub id: String,
pub path: PathBuf,
}
impl ResolvedRepositoryPaths {
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,
})
}
}
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)
}
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)
}
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())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedPackagePaths {
pub id: String,
pub repository_index: usize,
pub path: PathBuf,
pub metadata_path: PathBuf,
pub overview: Option<PathBuf>,
pub targets: Vec<ResolvedTargetPath>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedTargetPath {
pub id: String,
pub path: PathBuf,
pub julia_extensions: Vec<PathBuf>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedContentPaths {
pub id: String,
pub repository_index: usize,
pub path: PathBuf,
pub source_root: PathBuf,
pub declared_environment_inputs: Vec<PathBuf>,
pub julia_project: Option<PathBuf>,
pub julia_environment_inputs: Vec<PathBuf>,
}
#[derive(Debug, Error)]
#[error("could not resolve configuration `{}` field `{field}`: {kind}", configuration_path.display())]
pub struct PathResolutionError {
pub configuration_path: PathBuf,
pub field: String,
#[source]
pub kind: PathResolutionErrorKind,
}
impl PathResolutionError {
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(),
})
}
}
#[derive(Debug, Error)]
pub enum PathResolutionErrorKind {
#[error("invalid path `{}`: {reason}", path.display())]
InvalidPath {
path: PathBuf,
reason: &'static str,
},
#[error("could not inspect `{}`: {source}", path.display())]
FileSystem {
path: PathBuf,
source: std::io::Error,
},
#[error("expected {expected} at `{}`", path.display())]
WrongType {
path: PathBuf,
expected: PathType,
},
#[error("path `{}` escapes boundary `{}`", path.display(), boundary.display())]
OutsideBoundary {
path: PathBuf,
boundary: PathBuf,
},
#[error("repository `{repository}` matches {matches} declarations; expected exactly one")]
RepositoryReference {
repository: String,
matches: usize,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PathType {
Directory,
File,
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",
})
}
}
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);
}
next.as_mut_os_string().push(name);
resolved = self.canonicalize(field, &next)?;
}
Component::ParentDir => {
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)?;
}
}
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'\\')
}