Skip to main content

subspace_client_github/actions/
definition.rs

1use std::collections::BTreeMap;
2
3use serde_yaml_ng::{Mapping, Value};
4
5use super::{
6    Definition, DispatchDefinition, DispatchInput, DispatchInputType, Job, JobDependency,
7    WorkflowDefinition, WorkflowJob,
8};
9
10pub const MAX_WORKFLOW_BYTES: usize = 1024 * 1024;
11
12pub fn parse_workflow_definition(text: &str) -> Definition<WorkflowDefinition> {
13    if text.len() > MAX_WORKFLOW_BYTES {
14        return unreadable("workflow file exceeds the 1 MB limit");
15    }
16    let root: Value = match serde_yaml_ng::from_str(text) {
17        Ok(value) => value,
18        Err(error) => return unreadable(format!("invalid workflow YAML: {error}")),
19    };
20    let Some(root) = root.as_mapping() else {
21        return unreadable("workflow YAML root is not a mapping");
22    };
23    let dispatch = match parse_dispatch(root) {
24        Ok(value) => value,
25        Err(reason) => return unreadable(reason),
26    };
27    let jobs = match parse_jobs(root) {
28        Ok(value) => value,
29        Err(reason) => return unreadable(reason),
30    };
31    Definition::Readable(WorkflowDefinition { dispatch, jobs })
32}
33
34fn parse_dispatch(root: &Mapping) -> Result<Option<DispatchDefinition>, String> {
35    let Some(on) = get(root, "on") else {
36        return Ok(None);
37    };
38    if scalar_is(on, "workflow_dispatch") {
39        return Ok(Some(DispatchDefinition::default()));
40    }
41    let Some(on) = on.as_mapping() else {
42        return Ok(None);
43    };
44    let Some(dispatch) = get(on, "workflow_dispatch") else {
45        return Ok(None);
46    };
47    if dispatch.is_null() {
48        return Ok(Some(DispatchDefinition::default()));
49    }
50    let map = dispatch
51        .as_mapping()
52        .ok_or_else(|| "workflow_dispatch is not a mapping".to_owned())?;
53    let inputs = match get(map, "inputs") {
54        None => Vec::new(),
55        Some(value) => parse_inputs(value)?,
56    };
57    Ok(Some(DispatchDefinition { inputs }))
58}
59
60fn parse_inputs(value: &Value) -> Result<Vec<DispatchInput>, String> {
61    let inputs = value
62        .as_mapping()
63        .ok_or_else(|| "workflow_dispatch.inputs is not a mapping".to_owned())?;
64    inputs
65        .iter()
66        .map(|(name, definition)| {
67            let name = string(name, "dispatch input name")?;
68            let fields = definition
69                .as_mapping()
70                .ok_or_else(|| format!("dispatch input {name} is not a mapping"))?;
71            let kind = input_type(fields, &name)?;
72            let required = bool_field(fields, "required")?.unwrap_or(false);
73            let default = get(fields, "default").map(scalar_string).transpose()?;
74            let description = get(fields, "description").map(scalar_string).transpose()?;
75            let options = parse_options(fields, &name)?;
76            if kind == DispatchInputType::Choice && options.is_empty() {
77                return Err(format!("choice input {name} has no options"));
78            }
79            Ok(DispatchInput {
80                name,
81                kind,
82                required,
83                default,
84                options,
85                description,
86            })
87        })
88        .collect()
89}
90
91fn input_type(fields: &Mapping, name: &str) -> Result<DispatchInputType, String> {
92    match get(fields, "type")
93        .map(|value| string(value, "input type"))
94        .transpose()?
95        .as_deref()
96    {
97        None | Some("string") => Ok(DispatchInputType::String),
98        Some("boolean") => Ok(DispatchInputType::Boolean),
99        Some("choice") => Ok(DispatchInputType::Choice),
100        Some("environment") => Ok(DispatchInputType::Environment),
101        Some(other) => Err(format!(
102            "dispatch input {name} has unsupported type {other}"
103        )),
104    }
105}
106
107fn parse_options(fields: &Mapping, name: &str) -> Result<Vec<String>, String> {
108    let Some(value) = get(fields, "options") else {
109        return Ok(Vec::new());
110    };
111    value
112        .as_sequence()
113        .ok_or_else(|| format!("choice input {name} options are not a list"))?
114        .iter()
115        .map(scalar_string)
116        .collect()
117}
118
119fn parse_jobs(root: &Mapping) -> Result<Vec<WorkflowJob>, String> {
120    let Some(value) = get(root, "jobs") else {
121        return Err("workflow has no jobs mapping".into());
122    };
123    let jobs = value
124        .as_mapping()
125        .ok_or_else(|| "workflow jobs is not a mapping".to_owned())?;
126    jobs.iter()
127        .map(|(key, definition)| {
128            let key = string(key, "job key")?;
129            let fields = definition
130                .as_mapping()
131                .ok_or_else(|| format!("job {key} is not a mapping"))?;
132            let name = get(fields, "name").map(scalar_string).transpose()?;
133            let needs = get(fields, "needs")
134                .map(parse_needs)
135                .transpose()?
136                .unwrap_or_default();
137            Ok(WorkflowJob { key, name, needs })
138        })
139        .collect()
140}
141
142fn parse_needs(value: &Value) -> Result<Vec<String>, String> {
143    if let Some(value) = value.as_str() {
144        return Ok(vec![value.to_owned()]);
145    }
146    value
147        .as_sequence()
148        .ok_or_else(|| "job needs is neither a string nor a list".to_owned())?
149        .iter()
150        .map(|value| string(value, "job need"))
151        .collect()
152}
153
154// qual:api
155pub fn match_job_dependencies(
156    jobs: &[Job],
157    definitions: &[WorkflowJob],
158) -> Definition<Vec<JobDependency>> {
159    let mut matched = Vec::with_capacity(jobs.len());
160    for job in jobs {
161        let candidates = matching_definitions(&job.name, definitions);
162        let [definition] = candidates.as_slice() else {
163            let reason = if candidates.is_empty() {
164                "no match"
165            } else {
166                "ambiguous match"
167            };
168            return unreadable(format!("{reason} for API job {:?}", job.name));
169        };
170        matched.push((job, *definition));
171    }
172    let by_key = jobs_by_key(&matched);
173    let dependencies = matched
174        .into_iter()
175        .map(|(job, definition)| JobDependency {
176            job_id: job.id,
177            job_key: definition.key.clone(),
178            needs: definition
179                .needs
180                .iter()
181                .flat_map(|key| by_key.get(key).into_iter().flatten().copied())
182                .collect(),
183        })
184        .collect();
185    Definition::Readable(dependencies)
186}
187
188fn matching_definitions<'a>(name: &str, jobs: &'a [WorkflowJob]) -> Vec<&'a WorkflowJob> {
189    let exact: Vec<_> = jobs
190        .iter()
191        .filter(|job| job.key == name || job.name.as_deref() == Some(name))
192        .collect();
193    if !exact.is_empty() {
194        return exact;
195    }
196    jobs.iter()
197        .filter(|job| {
198            let base = job.name.as_deref().unwrap_or(&job.key);
199            name.strip_prefix(base)
200                .is_some_and(|suffix| suffix.starts_with(" (") && suffix.ends_with(')'))
201        })
202        .collect()
203}
204
205fn jobs_by_key(matched: &[(&Job, &WorkflowJob)]) -> BTreeMap<String, Vec<u64>> {
206    let mut result = BTreeMap::<String, Vec<u64>>::new();
207    for (job, definition) in matched {
208        result
209            .entry(definition.key.clone())
210            .or_default()
211            .push(job.id);
212    }
213    result
214}
215
216fn get<'a>(map: &'a Mapping, key: &str) -> Option<&'a Value> {
217    map.get(Value::String(key.to_owned()))
218}
219
220fn string(value: &Value, what: &str) -> Result<String, String> {
221    value
222        .as_str()
223        .map(str::to_owned)
224        .ok_or_else(|| format!("{what} is not a string"))
225}
226
227fn scalar_string(value: &Value) -> Result<String, String> {
228    match value {
229        Value::String(value) => Ok(value.clone()),
230        Value::Bool(value) => Ok(value.to_string()),
231        Value::Number(value) => Ok(value.to_string()),
232        Value::Null => Ok(String::new()),
233        _ => Err("workflow input value is not a scalar".into()),
234    }
235}
236
237fn bool_field(map: &Mapping, key: &str) -> Result<Option<bool>, String> {
238    get(map, key)
239        .map(|value| {
240            value
241                .as_bool()
242                .ok_or_else(|| format!("{key} is not a boolean"))
243        })
244        .transpose()
245}
246
247fn scalar_is(value: &Value, expected: &str) -> bool {
248    value.as_str() == Some(expected)
249        || value
250            .as_sequence()
251            .is_some_and(|values| values.iter().any(|value| value.as_str() == Some(expected)))
252}
253
254fn unreadable<T>(reason: impl Into<String>) -> Definition<T> {
255    Definition::Unreadable(reason.into())
256}