use std::{collections::BTreeMap, path::Path};
use serde::{Deserialize, Serialize};
use crate::domain::{
ContextEntry,
collection::{Scope, matching_files},
};
#[derive(Debug)]
pub(crate) struct Domain;
#[derive(Debug, Deserialize)]
#[serde(transparent)]
pub(crate) struct Config(BTreeMap<String, Collection>);
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct Collection {
include: crate::config::Patterns,
#[serde(default)]
scope: Scope,
}
#[derive(Debug, Serialize)]
struct Workflow {
name: String,
file: String,
triggers: Box<[String]>,
}
#[derive(Debug, thiserror::Error)]
enum ParseError {
#[error("invalid YAML: {0}")]
Yaml(#[from] serde_norway::Error),
#[error("workflow root must be a mapping")]
Root,
#[error("workflow is missing a string name")]
Name,
}
impl crate::domain::registry::Domain for Domain {
type Config = Config;
type State = ();
const NAME: &'static str = "github-workflows";
fn context(
config: &Self::Config,
_state: &Self::State,
context: &crate::RenderCtx<'_>,
) -> Result<Vec<ContextEntry>, crate::domain::Error> {
let mut output = Vec::new();
for (namespace, collection) in &config.0 {
let Some(base) = collection.scope.base(context) else {
continue;
};
let mut workflows = Vec::new();
for path in matching_files(context, base, &collection.include) {
let source = context.workspace.contents(path).ok_or_else(|| {
crate::domain::Error::message(path, Self::NAME, "workflow is not UTF-8 text")
})?;
let file = path
.strip_prefix(base)
.unwrap_or(path)
.to_string_lossy()
.replace('\\', "/");
let workflow = parse_workflow(source, file)
.map_err(|error| crate::domain::Error::parse(path, "GitHub workflow", error))?;
workflows.push(workflow);
}
workflows.sort_by(|left, right| left.name.cmp(&right.name));
if !workflows.is_empty() {
output.push((
namespace.clone().into_boxed_str(),
crate::domain::to_value(&workflows),
));
}
}
Ok(output)
}
fn is_source_input(
config: &Self::Config,
_state: &Self::State,
root: &Path,
path: &Path,
) -> bool {
config.0.values().any(|collection| {
crate::domain::collection::pattern_matches(
root,
collection.scope,
&collection.include,
path,
)
})
}
fn namespaces(config: &Self::Config) -> Vec<Box<str>> {
config
.0
.keys()
.map(|namespace| namespace.clone().into_boxed_str())
.collect()
}
}
fn parse_workflow(source: &str, file: String) -> Result<Workflow, ParseError> {
let document: serde_norway::Value = serde_norway::from_str(source)?;
let mapping = document.as_mapping().ok_or(ParseError::Root)?;
let name = mapping
.get(serde_norway::Value::String("name".into()))
.and_then(serde_norway::Value::as_str)
.ok_or(ParseError::Name)?
.to_string();
let triggers = mapping
.get(serde_norway::Value::String("on".into()))
.and_then(extract_triggers)
.unwrap_or_default();
Ok(Workflow {
name,
file,
triggers,
})
}
fn extract_triggers(value: &serde_norway::Value) -> Option<Box<[String]>> {
let mut triggers = match value {
serde_norway::Value::String(trigger) => vec![trigger.clone()],
serde_norway::Value::Sequence(sequence) => sequence
.iter()
.filter_map(|value| value.as_str().map(String::from))
.collect(),
serde_norway::Value::Mapping(mapping) => mapping
.keys()
.filter_map(|value| value.as_str().map(String::from))
.collect(),
_ => return None,
};
triggers.sort();
Some(triggers.into_boxed_slice())
}
crate::domain::registry::register_domain!(Domain);
#[cfg(test)]
mod tests {
use googletest::prelude::*;
use super::*;
#[gtest]
fn parses_workflow_triggers() -> Result<()> {
let workflow = parse_workflow(
"name: CI\non:\n push:\n pull_request:\n",
".github/workflows/ci.yml".to_string(),
)
.or_fail()?;
verify_eq!(workflow.name, "CI")?;
verify_that!(
workflow.triggers,
elements_are![eq("pull_request"), eq("push")]
)
}
}