use super::validation::validate_scoped;
use super::{Node, Origin, ValueKind};
use crate::ValidationError;
use crate::interop::raw::AttrPath;
use std::path::{Component, PathBuf};
#[derive(Clone, Debug)]
pub enum Source {
Builtins,
Packages {
overlays: Vec<Node>,
},
Library,
PinnedPath {
path: String,
},
NixosPackages {
overlays: Vec<Node>,
},
ModuleFile {
path: String,
},
Input {
name: String,
file: PathBuf,
},
}
#[derive(Clone, Debug)]
pub struct Reference {
pub source: Source,
pub path: Option<AttrPath>,
pub origin: Origin,
}
impl Reference {
pub fn validate(&self) -> Result<(), ValidationError> {
self.validate_scoped(&[])
}
pub(crate) fn validate_scoped(&self, scope: &[u64]) -> Result<(), ValidationError> {
if let Some(path) = &self.path {
path.validate(&self.origin)?;
}
match &self.source {
Source::Packages { overlays } | Source::NixosPackages { overlays } => {
for overlay in overlays {
validate_scoped(overlay, scope)?;
}
}
Source::ModuleFile { path } | Source::PinnedPath { path } => {
if path.is_empty()
|| path.contains('\0')
|| PathBuf::from(path)
.components()
.any(|c| !matches!(c, Component::Normal(_)))
{
return Err(ValidationError {
origin: self.origin.clone(),
message: if matches!(self.source, Source::PinnedPath { .. }) {
"source paths must be relative, nonempty paths without parent traversal"
} else {
"module paths must be relative, nonempty paths without parent traversal"
}
.into(),
});
}
}
Source::Input { name, file } => {
if name.is_empty()
|| name.contains('\0')
|| file
.to_str()
.is_none_or(|s| s.is_empty() || s.contains('\0'))
{
return Err(ValidationError {
origin: self.origin.clone(),
message: "input identities and paths must be nonempty, UTF-8 and NUL-free"
.into(),
});
}
}
Source::Library | Source::Builtins => {}
}
Ok(())
}
pub(crate) fn node(&self) -> Node {
Node {
origin: self.origin.clone(),
kind: ValueKind::Reference(self.clone()),
}
}
}