use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use techy::error::{Diagnostic, DiagnosticInfo};
use techy::serialize::SerialValue;
use crate::core::data::table::{PieceClass, ProjectCx, Table};
use crate::core::registry::{FlmRegistry, OutputDef};
use crate::lang::origin::nowhere;
use crate::lang::{FlmDiagnostic, FlmOrigin};
use crate::model::digest::Fnv1a64;
use crate::model::names::{CapName, Name, OutputName};
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RelPath(String);
impl RelPath {
pub fn new(path: impl Into<String>) -> RelPath {
RelPath(path.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for RelPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ArtifactId {
pub owner: Name,
pub name: String,
}
impl ArtifactId {
pub fn new(owner: impl Into<Name>, name: impl Into<String>) -> ArtifactId {
ArtifactId { owner: owner.into(), name: name.into() }
}
}
impl fmt::Display for ArtifactId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{}", self.owner, self.name)
}
}
pub(crate) fn name_safe(text: &str) -> String {
text.chars().map(|c| if c.is_ascii_alphanumeric() || matches!(c, '-' | '_') { c } else { '_' }).collect()
}
pub(crate) fn digest_name(stem: &str, digest: &Fnv1a64) -> String {
format!("{stem}-{:08x}", digest.value() >> 32)
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FileRef {
pub location: String,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub enum ArtifactData {
Bytes(Vec<u8>),
FileRef(FileRef),
Files(Vec<(RelPath, Vec<u8>)>),
}
impl fmt::Debug for ArtifactData {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ArtifactData::Bytes(bytes) => write!(f, "Bytes({} bytes)", bytes.len()),
ArtifactData::FileRef(file) => write!(f, "FileRef({:?})", file.location),
ArtifactData::Files(files) => {
let paths: Vec<&str> = files.iter().map(|(path, _)| path.as_str()).collect();
write!(f, "Files({paths:?})")
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Artifact {
pub id: ArtifactId,
pub entry: bool,
pub media_type: String,
pub data: ArtifactData,
pub fixed_path: Option<RelPath>,
pub refs: Vec<ArtifactId>,
pub extension: Option<String>,
}
impl Artifact {
pub fn bytes(id: ArtifactId, media_type: impl Into<String>, bytes: Vec<u8>) -> Artifact {
Artifact {
id,
entry: false,
media_type: media_type.into(),
data: ArtifactData::Bytes(bytes),
fixed_path: None,
refs: Vec::new(),
extension: None,
}
}
pub fn folder(id: ArtifactId, files: Vec<(RelPath, Vec<u8>)>) -> Artifact {
Artifact {
id,
entry: false,
media_type: String::new(),
data: ArtifactData::Files(files),
fixed_path: None,
refs: Vec::new(),
extension: None,
}
}
pub fn with_extension(mut self, extension: impl Into<String>) -> Artifact {
self.extension = Some(extension.into());
self
}
pub fn as_entry(mut self) -> Artifact {
self.entry = true;
self
}
pub fn as_bytes(&self) -> Option<&[u8]> {
match &self.data {
ArtifactData::Bytes(bytes) => Some(bytes),
ArtifactData::FileRef(_) | ArtifactData::Files(_) => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ArtifactSetViolation {
DuplicateId(ArtifactId),
SecondEntry {
first: ArtifactId,
second: ArtifactId,
},
}
impl fmt::Display for ArtifactSetViolation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ArtifactSetViolation::DuplicateId(id) => {
write!(f, "two different files of an output must not share the identity `{id}`")
}
ArtifactSetViolation::SecondEntry { first, second } => write!(
f,
"an output has only one main file, `{first}`, so `{second}` must not also be \
marked as the main file"
),
}
}
}
impl std::error::Error for ArtifactSetViolation {}
#[derive(Debug, Clone, Default)]
pub struct ArtifactSet {
artifacts: BTreeMap<ArtifactId, Artifact>,
entry: Option<ArtifactId>,
violations: Vec<ArtifactSetViolation>,
}
impl ArtifactSet {
pub fn new() -> ArtifactSet {
ArtifactSet::default()
}
pub fn insert(&mut self, artifact: Artifact) -> Result<(), ArtifactSetViolation> {
if self.artifacts.contains_key(&artifact.id) {
return Err(ArtifactSetViolation::DuplicateId(artifact.id));
}
if artifact.entry {
if let Some(first) = &self.entry {
return Err(ArtifactSetViolation::SecondEntry {
first: first.clone(),
second: artifact.id,
});
}
self.entry = Some(artifact.id.clone());
}
self.artifacts.insert(artifact.id.clone(), artifact);
Ok(())
}
#[must_use = "the returned Error diagnostics report the violations of the artifact set; \
the caller must add them to its diagnostics"]
pub fn insert_entry_with(
&mut self,
entry: Artifact,
beside: &[&ArtifactSet],
) -> Result<Vec<FlmDiagnostic>, ArtifactSetViolation> {
self.insert(entry)?;
for set in beside {
self.absorb((*set).clone());
}
let mut reports = Vec::new();
for violation in &self.violations {
let at = nowhere(FlmOrigin::synthetic(REPORT_LABEL));
reports.push(match violation {
ArtifactSetViolation::DuplicateId(id) => {
Diagnostic::error(DuplicateArtifact { id: id.to_string() }, at)
}
ArtifactSetViolation::SecondEntry { first, second } => Diagnostic::error(
SecondEntryArtifact { first: first.to_string(), second: second.to_string() },
at,
),
});
}
Ok(reports)
}
pub fn entry(&self) -> Option<&Artifact> {
self.entry.as_ref().and_then(|id| self.artifacts.get(id))
}
pub fn get(&self, id: &ArtifactId) -> Option<&Artifact> {
self.artifacts.get(id)
}
pub fn iter(&self) -> impl Iterator<Item = &Artifact> + '_ {
self.artifacts.values()
}
pub fn len(&self) -> usize {
self.artifacts.len()
}
pub fn is_empty(&self) -> bool {
self.artifacts.is_empty()
}
pub fn violations(&self) -> &[ArtifactSetViolation] {
&self.violations
}
}
impl Table for ArtifactSet {
fn absorb(&mut self, piece: ArtifactSet) {
self.violations.extend(piece.violations);
for (_, mut artifact) in piece.artifacts {
if self.artifacts.get(&artifact.id) == Some(&artifact) {
continue;
}
if artifact.entry {
if let Some(first) = &self.entry {
self.violations.push(ArtifactSetViolation::SecondEntry {
first: first.clone(),
second: artifact.id.clone(),
});
artifact.entry = false;
}
}
if let Err(violation) = self.insert(artifact) {
self.violations.push(violation);
}
}
}
fn project(&self, _cx: &dyn ProjectCx) -> SerialValue {
let artifacts = self
.artifacts
.values()
.map(|artifact| {
SerialValue::Map(vec![
("id".to_string(), SerialValue::Str(artifact.id.to_string())),
("entry".to_string(), SerialValue::Bool(artifact.entry)),
("media_type".to_string(), SerialValue::Str(artifact.media_type.clone())),
(
"data".to_string(),
match &artifact.data {
ArtifactData::Bytes(bytes) => SerialValue::Bytes(bytes.clone()),
ArtifactData::FileRef(file) => SerialValue::Str(file.location.clone()),
ArtifactData::Files(files) => SerialValue::Map(
files
.iter()
.map(|(path, bytes)| (path.to_string(), SerialValue::Bytes(bytes.clone())))
.collect(),
),
},
),
])
})
.collect();
SerialValue::Map(vec![
("artifacts".to_string(), SerialValue::List(artifacts)),
(
"violations".to_string(),
SerialValue::List(
self.violations.iter().map(|v| SerialValue::Str(v.to_string())).collect(),
),
),
])
}
fn piece_class(&self) -> PieceClass {
if self.is_empty() { PieceClass::Empty } else { PieceClass::DocumentFact }
}
}
const REPORT_LABEL: &str = "the files of the output";
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.artifacts.duplicate",
message = "two different files of the output must not share the identity `{id}`"
)]
pub struct DuplicateArtifact {
pub id: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.artifacts.second-entry",
message = "an output has only one main file, `{first}`, so `{second}` must not also be \
marked as the main file"
)]
pub struct SecondEntryArtifact {
pub first: String,
pub second: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ArtifactRef<'a> {
pub id: &'a ArtifactId,
pub entry: bool,
pub media_type: &'a str,
pub extension: Option<&'a str>,
pub output: Option<&'a str>,
pub folder: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScopedOutput {
pub name: OutputName,
pub extension: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct NamingScope {
pub outputs: Vec<ScopedOutput>,
}
impl NamingScope {
pub fn of(registry: &FlmRegistry, demands: &BTreeSet<CapName>) -> NamingScope {
NamingScope {
outputs: registry
.outputs()
.filter(|output| demands.contains(&output.def.capability))
.map(|output| ScopedOutput {
name: output.def.name.clone(),
extension: output.def.entry.extension.clone(),
})
.collect(),
}
}
}
pub trait ArtifactNamer: Send + Sync {
fn url_of(&self, artifact: &ArtifactRef<'_>, scope: &NamingScope) -> RelPath;
}
pub fn path_of(
artifact: &Artifact,
output: Option<&OutputDef>,
namer: &dyn ArtifactNamer,
scope: &NamingScope,
) -> RelPath {
if let Some(path) = &artifact.fixed_path {
return path.clone();
}
let extension = match output {
Some(output) if artifact.entry => Some(output.entry.extension.as_str()),
_ => artifact.extension.as_deref(),
};
let named = ArtifactRef {
id: &artifact.id,
entry: artifact.entry,
media_type: &artifact.media_type,
extension,
output: output.map(|output| output.name.as_str()),
folder: matches!(artifact.data, ArtifactData::Files(_)),
};
namer.url_of(&named, scope)
}
pub fn media_type_of(extension: &str) -> Option<&'static str> {
Some(match extension.to_ascii_lowercase().as_str() {
"html" => "text/html",
"css" => "text/css",
"js" => "text/javascript",
"txt" => "text/plain",
"json" => "application/json",
"svg" => "image/svg+xml",
"png" => "image/png",
"jpg" | "jpeg" => "image/jpeg",
"gif" => "image/gif",
"webp" => "image/webp",
"pdf" => "application/pdf",
"tex" | "sty" => "application/x-latex",
"bib" => "application/x-bibtex",
"woff" => "font/woff",
"woff2" => "font/woff2",
"ico" => "image/vnd.microsoft.icon",
_ => return None,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn artifact(name: &str) -> Artifact {
Artifact::bytes(ArtifactId::new("text", name), "text/plain", b"x".to_vec())
}
#[test]
fn a_second_entry_is_refused_at_insert_and_recorded_at_absorb() {
let mut set = ArtifactSet::new();
set.insert(artifact("document").as_entry()).unwrap();
let refused = set.insert(artifact("other").as_entry()).unwrap_err();
assert!(matches!(refused, ArtifactSetViolation::SecondEntry { .. }));
let mut piece = ArtifactSet::new();
piece.insert(artifact("also").as_entry()).unwrap();
set.absorb(piece);
assert_eq!(set.violations().len(), 1);
assert_eq!(set.entry().map(|a| a.id.name.as_str()), Some("document"));
assert_eq!(set.len(), 2);
}
#[test]
fn the_same_artifact_twice_is_one_and_two_under_one_identity_are_reported() {
let mut first = ArtifactSet::new();
first.insert(artifact("copy")).unwrap();
let mut again = ArtifactSet::new();
again.insert(artifact("copy")).unwrap();
let mut other = ArtifactSet::new();
other.insert(Artifact::bytes(ArtifactId::new("text", "copy"), "text/plain", b"y".to_vec())).unwrap();
let mut set = ArtifactSet::new();
let reports = set.insert_entry_with(artifact("document").as_entry(), &[&first, &again]).unwrap();
assert!(reports.is_empty());
assert_eq!(set.len(), 2);
let mut set = ArtifactSet::new();
let reports = set.insert_entry_with(artifact("document").as_entry(), &[&first, &other]).unwrap();
assert_eq!(set.violations(), [ArtifactSetViolation::DuplicateId(ArtifactId::new("text", "copy"))]);
assert_eq!(reports.len(), 1);
assert_eq!(set.get(&ArtifactId::new("text", "copy")).and_then(Artifact::as_bytes), Some(&b"x"[..]));
}
struct Echo;
impl ArtifactNamer for Echo {
fn url_of(&self, artifact: &ArtifactRef<'_>, _: &NamingScope) -> RelPath {
let output = artifact.output.map(|output| format!("@{output}/")).unwrap_or_default();
let entry = if artifact.entry { "!" } else { "" };
let tail = match (artifact.folder, artifact.extension) {
(true, _) => String::from("/"),
(false, Some(extension)) => format!(".{extension}"),
(false, None) => String::new(),
};
RelPath::new(format!("{output}{entry}{}{tail}", artifact.id.name))
}
}
#[test]
fn the_path_of_an_artifact_is_its_fixed_path_else_the_namer_s_answer() {
let output = OutputDef::new("paper", "x.paper", "x.paper", "application/pdf", "pdf");
let scope = NamingScope::default();
let path = |artifact: &Artifact, output: Option<&OutputDef>| path_of(artifact, output, &Echo, &scope).to_string();
let entry = Artifact::bytes(ArtifactId::new("x", "doc"), "text/plain", Vec::new()).with_extension("txt").as_entry();
assert_eq!(path(&entry, Some(&output)), "@paper/!doc.pdf");
assert_eq!(path(&entry, None), "!doc.txt");
let other = Artifact::bytes(ArtifactId::new("x", "fig"), "image/png", Vec::new()).with_extension("png");
assert_eq!(path(&other, Some(&output)), "@paper/fig.png");
let folder = Artifact::folder(ArtifactId::new("x", "icons"), vec![(RelPath::new("a.svg"), Vec::new())]);
assert_eq!(path(&folder, None), "icons/");
let mut fixed = other.clone();
fixed.fixed_path = Some(RelPath::new("fixed/fig.png"));
assert_eq!(path(&fixed, Some(&output)), "fixed/fig.png");
}
}