use std::{collections::BTreeMap, fmt::Write, path::Path};
use serde::Serialize;
use sha2::{Digest, Sha256};
use crate::{
config::{ArtifactKind, Fingerprint, Profile, RepoConfig, Views},
scope::{Argument, RelationKind},
types::{ArtifactName, EvalId},
};
const FORMAT: &[u8] = b"artifactize-graph-v2\n";
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Structure {
pub artifacts: BTreeMap<ArtifactName, Artifact>,
pub evals: BTreeMap<EvalId, Eval>,
pub relations: Vec<Relation>,
}
#[derive(Debug, Serialize)]
pub struct Artifact {
pub kind: ArtifactKind,
pub path: String,
pub toolsets: Vec<String>,
pub tools: Views,
pub basis: Option<bool>,
pub fingerprint: Coverage,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub select: Vec<crate::config::LogicalPath>,
}
#[derive(Debug, Serialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum Coverage {
Graph,
Disabled,
Artifactsum {
files: Vec<crate::config::LogicalPath>,
ignore: Vec<String>,
},
Script {
command: String,
args: Vec<Argument>,
files: Vec<crate::config::LogicalPath>,
},
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Eval {
pub target: ArtifactName,
pub title: String,
pub criteria: Criteria,
pub instruction: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub inputs: Vec<ArtifactName>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub reads: Vec<ArtifactName>,
}
#[derive(Debug, Serialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum Criteria {
Agent {
#[serde(rename = "redAt", skip_serializing_if = "Option::is_none")]
red_at: Option<crate::config::Priority>,
},
Human,
Runtime {
command: String,
args: Vec<Argument>,
},
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
pub struct Relation {
pub source: ArtifactName,
pub target: ArtifactName,
#[serde(flatten)]
pub kind: Edge,
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum Edge {
Part,
Instruction {
eval_id: EvalId,
name: crate::config::ReferenceName,
},
Argv {
eval_id: EvalId,
index: usize,
name: crate::config::ReferenceName,
path: crate::scope::LogicalTarget,
},
Input {
eval_id: EvalId,
name: crate::config::ReferenceName,
},
}
pub fn extract(config: &RepoConfig) -> Structure {
extract_where(config, |_, _| true)
}
fn extract_where(
config: &RepoConfig,
include: impl Fn(&ArtifactName, &crate::config::Artifact) -> bool,
) -> Structure {
let artifacts: BTreeMap<_, _> = config
.artifacts
.iter()
.filter(|(name, artifact)| include(name, artifact))
.map(|(name, artifact)| {
let fingerprint = match &artifact.fingerprint {
Some(Fingerprint::Graph) => Coverage::Graph,
None => Coverage::Disabled,
Some(Fingerprint::Artifactsum { files, ignore }) => Coverage::Artifactsum {
files: files.clone(),
ignore: ignore.patterns().to_vec(),
},
Some(Fingerprint::Script {
command,
args,
files,
..
}) => Coverage::Script {
command: crate::platform::program_text(command),
args: args.clone(),
files: files.clone(),
},
};
(
name.clone(),
Artifact {
kind: artifact.kind(),
path: artifact.path.to_string(),
toolsets: artifact.toolsets.clone(),
tools: artifact.views.clone(),
basis: artifact.basis,
fingerprint,
select: artifact.select().to_vec(),
},
)
})
.collect();
let evals = config
.evals
.iter()
.filter(|eval| artifacts.contains_key(&eval.target))
.map(|eval| {
let declaration = &eval.declaration;
let criteria = match declaration.profile() {
Profile::Agent { .. } => Criteria::Agent {
red_at: declaration.red_at(),
},
Profile::Human {} => Criteria::Human,
Profile::Runtime { command, args, .. } => Criteria::Runtime {
command: crate::platform::program_text(command),
args: args.clone(),
},
};
(
eval.id.clone(),
Eval {
target: eval.target.clone(),
title: declaration.title.clone(),
criteria,
instruction: declaration.instruction().map(str::to_owned),
inputs: declaration.inputs().to_vec(),
reads: Vec::new(),
},
)
})
.collect();
let mut relations: Vec<_> = config
.relations
.iter()
.filter(|relation| {
artifacts.contains_key(&relation.source) && artifacts.contains_key(&relation.target)
})
.map(|relation| Relation {
source: relation.source.clone(),
target: relation.target.clone(),
kind: match &relation.kind {
RelationKind::Part => Edge::Part,
RelationKind::Instruction { eval_id, name } => Edge::Instruction {
eval_id: eval_id.clone(),
name: name.clone(),
},
RelationKind::Argument {
eval_id,
index,
name,
path,
} => Edge::Argv {
eval_id: eval_id.clone(),
index: *index,
name: name.clone(),
path: path.clone(),
},
RelationKind::Input { eval_id, name } => Edge::Input {
eval_id: eval_id.clone(),
name: name.clone(),
},
},
})
.collect();
relations.sort();
Structure {
artifacts,
evals,
relations,
}
}
pub fn read(repo: &Path) -> Result<Structure, String> {
crate::config::read_workspace_declarations(repo)
.map(|config| extract(&config))
.map_err(|error| error.to_string())
}
pub fn read_scoped(repo: &Path, owner: &crate::config::Artifact) -> Result<Structure, String> {
let Some(target) = owner
.path
.local()
.filter(|path| path.starts_with(".artifactize"))
else {
return Err("The scoped declarations tool must target .artifactize/.".into());
};
let config =
crate::config::read_workspace_declarations(repo).map_err(|error| error.to_string())?;
let mut structure = extract_where(&config, |_, artifact| {
let definition = artifact.declaration_path();
if owner.kind() == ArtifactKind::File {
return definition == target;
}
definition.strip_prefix(target).is_ok_and(|path| {
owner.select().is_empty()
|| owner
.select()
.iter()
.any(|selection| path.starts_with(Path::new(selection.as_str())))
})
});
for eval in &config.evals {
if let Some(scoped) = structure.evals.get_mut(&eval.id) {
scoped.reads.clone_from(&eval.deps);
}
}
Ok(structure)
}
impl Structure {
pub fn fingerprint(&self) -> crate::types::Fingerprint {
let mut value = serde_json::to_value(self).expect("graph structure is JSON");
value.sort_all_objects();
let mut digest = Sha256::new();
digest.update(FORMAT);
digest.update(serde_json::to_vec(&value).expect("graph structure is JSON"));
let hex: String = digest
.finalize()
.iter()
.map(|byte| format!("{byte:02x}"))
.collect();
format!("graph:{hex}")
.parse()
.expect("graph fingerprint is nonblank")
}
pub fn tree(&self) -> String {
let mut text = format!("Artifact graph {}\n", self.fingerprint());
for (name, artifact) in &self.artifacts {
writeln!(text, "{name} [{:?}]", artifact.kind).expect("write to String");
writeln!(
text,
" definition: {}",
serde_json::to_string(artifact).expect("Artifact is JSON")
)
.expect("write to String");
for (id, eval) in self.evals.iter().filter(|(_, eval)| &eval.target == name) {
writeln!(text, " ├─ {id}: {}", eval.title).expect("write to String");
writeln!(
text,
" │ criteria: {}",
serde_json::to_string(eval).expect("Eval is JSON")
)
.expect("write to String");
}
}
for relation in &self.relations {
writeln!(
text,
"{} → {} {}",
relation.source,
relation.target,
serde_json::to_string(&relation.kind).expect("relation is JSON")
)
.expect("write to String");
}
text
}
}
pub(crate) fn launch(
repo: &Path,
run: crate::tools::human::log::Run,
) -> Result<(), (String, crate::tools::human::log::Run)> {
if let Err(error) = read(repo) {
return Err((error, run));
}
let program = match crate::platform::program::resolve(Path::new("artifactize-desktop"), repo) {
Ok(program) => program,
Err(error) => return Err((format!("Cannot find artifactize-desktop: {error}"), run)),
};
crate::process::launch_watched(
program.as_os_str(),
&[
std::ffi::OsStr::new("graph"),
std::ffi::OsStr::new("--repo"),
repo.as_os_str(),
],
repo,
run,
)
.map_err(|(error, run)| (error.to_string(), run))
}
#[cfg(test)]
mod tests;