Skip to content
1,154 linesCodeBlameRaw
1//! Reading a workflow file: its triggers, jobs and steps, and notes on
2//! anything in it that runs differently on g1t, so moving a repository
3//! from GitHub says plainly what to expect.
4
5use serde::{Deserialize, Serialize};
6use serde_json::{Map, Value};
7
8use crate::filter::{Filter, Patterns};
9use crate::permissions::{self, Permissions};
10use crate::syntax;
11
12/// Where workflows live: GitHub's `.github/workflows`, under g1t's own
13/// folder, so moving a repository to g1t is renaming `.github` to `.g1t`.
14/// g1t reads `.github` only for a mirror of a GitHub repository in CI
15/// failover or taken over (services/actions/src/mirrored.rs); otherwise it
16/// stays GitHub's.
17pub const FOLDER: &str = ".g1t/workflows";
18
19/// The events a workflow can name that g1t starts runs for.
20pub const SUPPORTED_EVENTS: &[&str] = &[
21 "push",
22 "pull_request",
23 "pull_request_target",
24 "pull_request_review",
25 "issues",
26 "issue_comment",
27 "schedule",
28 "workflow_dispatch",
29 "repository_dispatch",
30 "workflow_call",
31 "workflow_run",
32 "merge_group",
33 "create",
34 "release",
35 "deployment",
36 "deployment_status",
37];
38
39/// Events GitHub has that g1t knows of but never sends: a workflow on one
40/// of them is told so, rather than waiting for a run that never comes.
41pub const UNSENT_EVENTS: &[(&str, &str)] = &[(
42 "delete",
43 "g1t does not start runs when a branch or tag is deleted yet, so the `delete` trigger never starts it. New branches and tags start `create` and `push` workflows.",
44)];
45
46/// The `types` each event has when a workflow gives none, as on GitHub.
47pub fn default_types(event: &str) -> &'static [&'static str] {
48 match event {
49 "pull_request" | "pull_request_target" => &["opened", "synchronize", "reopened"],
50 "merge_group" => &["checks_requested"],
51 _ => &[],
52 }
53}
54
55/// How much a note matters.
56#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
57#[serde(rename_all = "snake_case")]
58pub enum Severity {
59 /// Runs, slightly differently.
60 Info,
61 /// Runs, but something in it does nothing or may not work.
62 Warning,
63 /// Does not run on g1t.
64 Unsupported,
65}
66
67#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
68pub struct Note {
69 pub severity: Severity,
70 /// The job, if the note is about one.
71 #[serde(skip_serializing_if = "Option::is_none")]
72 pub job: Option<String>,
73 pub message: String,
74}
75
76/// One event a workflow is started by, with its filters.
77#[derive(Clone, Debug, Default, PartialEq, Eq)]
78pub struct Trigger {
79 pub event: String,
80 /// Activity types; empty means the event's defaults (or all).
81 pub types: Vec<String>,
82 pub branches: Filter,
83 pub tags: Filter,
84 pub paths: Filter,
85 /// For `schedule`.
86 pub crons: Vec<String>,
87 /// For `workflow_dispatch` and `workflow_call`: the inputs, as written.
88 pub inputs: Map<String, Value>,
89 /// For `workflow_run`: the names of the workflows it follows.
90 pub workflows: Vec<String>,
91}
92
93impl Trigger {
94 /// Whether an activity type starts it.
95 pub fn wants_type(&self, action: Option<&str>) -> bool {
96 let Some(action) = action else { return true };
97 if self.types.is_empty() {
98 // A g1t agent's pull request has no code until it is marked
99 // ready, so that is when its default runs start, as `opened`
100 // would on GitHub.
101 if action == "ready_for_review" && self.event.starts_with("pull_request") && self.event != "pull_request_review" {
102 return true;
103 }
104 let defaults = default_types(&self.event);
105 return defaults.is_empty() || defaults.contains(&action);
106 }
107 self.types.iter().any(|t| t == action)
108 }
109}
110
111#[derive(Clone, Debug, PartialEq)]
112pub struct Step {
113 pub id: Option<String>,
114 pub name: Option<String>,
115 pub condition: Option<String>,
116 pub uses: Option<String>,
117 pub run: Option<String>,
118 /// Its `g1t` settings, as written: g1t's own, beside GitHub's keys.
119 pub g1t: Option<Value>,
120 /// The whole step as written, for the sandbox.
121 pub raw: Value,
122}
123
124impl Step {
125 /// How the step is shown when it has no name.
126 pub fn title(&self) -> String {
127 if let Some(name) = &self.name {
128 return name.clone();
129 }
130 if let Some(uses) = &self.uses {
131 return format!("Run {uses}");
132 }
133 let first = self.run.as_deref().unwrap_or_default().lines().find(|line| !line.trim().is_empty()).unwrap_or_default();
134 format!("Run {}", first.trim())
135 }
136}
137
138#[derive(Clone, Debug, PartialEq)]
139pub struct Job {
140 /// Its key under `jobs:`.
141 pub id: String,
142 pub name: Option<String>,
143 pub needs: Vec<String>,
144 pub condition: Option<String>,
145 pub runs_on: Value,
146 /// `strategy.matrix`, as written (it may be an expression).
147 pub matrix: Option<Value>,
148 pub fail_fast: bool,
149 pub max_parallel: Option<u32>,
150 /// A reusable workflow it calls (`uses:` on a job).
151 pub uses: Option<String>,
152 /// Its own `permissions`, which replace the workflow's.
153 pub permissions: Option<Permissions>,
154 /// Its own `concurrency`: at most one job of its group runs at a time.
155 pub concurrency: Option<Concurrency>,
156 pub steps: Vec<Step>,
157 /// Its `g1t` settings, as written: g1t's own, beside GitHub's keys.
158 pub g1t: Option<Value>,
159 /// The whole job as written, for the sandbox.
160 pub raw: Value,
161}
162
163impl Job {
164 /// What its token may do: its own `permissions`, else its workflow's,
165 /// else `default` (the repository's choice).
166 pub fn permissions(&self, workflow: &Workflow, default: permissions::TokenDefault) -> Permissions {
167 self.permissions
168 .clone()
169 .or_else(|| workflow.permissions.clone())
170 .unwrap_or_else(|| Permissions::default_for(default))
171 }
172}
173
174#[derive(Clone, Debug, PartialEq)]
175pub struct Workflow {
176 pub name: Option<String>,
177 pub run_name: Option<String>,
178 pub triggers: Vec<Trigger>,
179 pub env: Map<String, Value>,
180 pub concurrency: Option<Concurrency>,
181 /// Its top-level `permissions`, for every job that writes none.
182 pub permissions: Option<Permissions>,
183 pub jobs: Vec<Job>,
184 pub notes: Vec<Note>,
185 /// Its top-level `g1t` settings, as written: g1t's own, beside
186 /// GitHub's keys.
187 pub g1t: Option<Value>,
188 /// The whole workflow as written.
189 pub raw: Value,
190}
191
192#[derive(Clone, Debug, PartialEq, Eq)]
193pub struct Concurrency {
194 /// May hold an expression.
195 pub group: String,
196 pub cancel_in_progress: Value,
197}
198
199impl Workflow {
200 pub fn trigger(&self, event: &str) -> Option<&Trigger> {
201 self.triggers.iter().find(|trigger| trigger.event == event)
202 }
203
204 /// The name shown for it: its `name`, or its file's path.
205 pub fn display_name(&self, path: &str) -> String {
206 self.name.clone().unwrap_or_else(|| path.to_owned())
207 }
208
209 /// The job ids in an order where each comes after the jobs it needs.
210 pub fn job_order(&self) -> Vec<&str> {
211 let mut ordered: Vec<&str> = Vec::new();
212 while ordered.len() < self.jobs.len() {
213 let before = ordered.len();
214 for job in &self.jobs {
215 if !ordered.contains(&job.id.as_str()) && job.needs.iter().all(|need| ordered.contains(&need.as_str())) {
216 ordered.push(&job.id);
217 }
218 }
219 if ordered.len() == before {
220 break;
221 }
222 }
223 ordered
224 }
225}
226
227/// YAML to JSON, keeping the order of keys. Keys that are not strings
228/// (`on: true` in YAML 1.1, numbers) become their text.
229pub fn yaml_to_json(value: &serde_yaml::Value) -> Value {
230 match value {
231 serde_yaml::Value::Null => Value::Null,
232 serde_yaml::Value::Bool(flag) => Value::Bool(*flag),
233 serde_yaml::Value::Number(number) => {
234 if let Some(n) = number.as_i64() {
235 Value::from(n)
236 } else if let Some(n) = number.as_u64() {
237 Value::from(n)
238 } else {
239 number.as_f64().and_then(serde_json::Number::from_f64).map_or(Value::Null, Value::Number)
240 }
241 }
242 serde_yaml::Value::String(text) => Value::String(text.clone()),
243 serde_yaml::Value::Sequence(items) => Value::Array(items.iter().map(yaml_to_json).collect()),
244 serde_yaml::Value::Mapping(map) => {
245 let mut out = Map::new();
246 for (key, value) in map {
247 let key = match key {
248 serde_yaml::Value::String(text) => text.clone(),
249 serde_yaml::Value::Bool(flag) => flag.to_string(),
250 serde_yaml::Value::Number(number) => number.to_string(),
251 _ => continue,
252 };
253 out.insert(key, yaml_to_json(value));
254 }
255 Value::Object(out)
256 }
257 serde_yaml::Value::Tagged(tagged) => yaml_to_json(&tagged.value),
258 }
259}
260
261fn texts(value: Option<&Value>) -> Vec<String> {
262 match value {
263 Some(Value::String(text)) => vec![text.clone()],
264 Some(Value::Array(items)) => items
265 .iter()
266 .filter_map(|item| match item {
267 Value::String(text) => Some(text.clone()),
268 Value::Number(n) => Some(n.to_string()),
269 _ => None,
270 })
271 .collect(),
272 _ => Vec::new(),
273 }
274}
275
276fn text(value: Option<&Value>) -> Option<String> {
277 match value? {
278 Value::String(text) => Some(text.clone()),
279 Value::Number(n) => Some(n.to_string()),
280 Value::Bool(flag) => Some(flag.to_string()),
281 _ => None,
282 }
283}
284
285fn filter(spec: &Map<String, Value>, only: &str, ignore: &str) -> Filter {
286 let list = |key: &str| spec.get(key).map(|value| Patterns::new(&texts(Some(value))));
287 Filter { only: list(only), ignore: list(ignore) }
288}
289
290fn trigger(event: &str, spec: &Value) -> Trigger {
291 let mut trigger = Trigger { event: event.to_owned(), ..Trigger::default() };
292 match spec {
293 Value::Object(spec) => {
294 trigger.types = texts(spec.get("types"));
295 trigger.branches = filter(spec, "branches", "branches-ignore");
296 trigger.tags = filter(spec, "tags", "tags-ignore");
297 trigger.paths = filter(spec, "paths", "paths-ignore");
298 if let Some(Value::Object(inputs)) = spec.get("inputs") {
299 trigger.inputs = inputs.clone();
300 }
301 trigger.workflows = texts(spec.get("workflows"));
302 }
303 Value::Array(entries) if event == "schedule" => {
304 trigger.crons = entries.iter().filter_map(|entry| text(entry.get("cron"))).collect();
305 }
306 _ => {}
307 }
308 trigger
309}
310
311/// Reads a workflow. `Err` is what is wrong with the file, for the person
312/// who wrote it; what reads but runs differently is in `notes`.
313///
314/// It accepts what GitHub accepts and refuses what GitHub refuses: every
315/// mapping has only the keys GitHub's schema gives it ([`syntax`]), plus
316/// `g1t`, g1t's own settings, on the workflow, a job and a step.
317pub fn parse(source: &str) -> Result<Workflow, String> {
318 let yaml: serde_yaml::Value = serde_yaml::from_str(source).map_err(|error| format!("It is not valid YAML: {error}"))?;
319 if has_merge_key(&yaml) {
320 return Err("It uses a YAML merge key (`<<`), which GitHub does not read, so g1t does not either. Write the keys out, or give a whole value an anchor (`&name`) and repeat it with `*name`.".to_owned());
321 }
322 let raw = yaml_to_json(&yaml);
323 let Value::Object(root) = &raw else {
324 return Err("A workflow is a mapping with `on` and `jobs`.".to_owned());
325 };
326 let mut notes = Vec::new();
327 let mut note = |severity, job: Option<&str>, message: String| notes.push(Note { severity, job: job.map(str::to_owned), message });
328 check_keys(root, syntax::WORKFLOW, true, "", "the workflow")?;
329
330 // `on`, in any of its three shapes.
331 let on = root.get("on").ok_or("`on` is missing: say which events start the workflow.")?;
332 let known = |event: &str| syntax::event(event).ok_or_else(|| format!("`on`: GitHub has no `{event}` event, so neither does g1t."));
333 let mut triggers = Vec::new();
334 match on {
335 Value::String(event) => {
336 known(event)?;
337 triggers.push(trigger(event, &Value::Null));
338 }
339 Value::Array(events) => {
340 for event in events {
341 let Value::String(event) = event else { return Err("`on` lists event names.".to_owned()) };
342 known(event)?;
343 triggers.push(trigger(event, &Value::Null));
344 }
345 }
346 Value::Object(events) => {
347 for (event, spec) in events {
348 check_event(event, known(event)?, spec, &mut note)?;
349 triggers.push(trigger(event, spec));
350 }
351 }
352 _ => return Err("`on` is an event, a list of events, or a mapping of events to their filters.".to_owned()),
353 }
354 for trigger in &triggers {
355 if let Some((_, why)) = UNSENT_EVENTS.iter().find(|(event, _)| *event == trigger.event) {
356 note(Severity::Unsupported, None, (*why).to_owned());
357 } else if !SUPPORTED_EVENTS.contains(&trigger.event.as_str()) {
358 note(
359 Severity::Unsupported,
360 None,
361 format!("g1t does not send GitHub's `{}` event, so that trigger never starts it.", trigger.event),
362 );
363 }
364 if trigger.event == "pull_request_target" {
365 note(
366 Severity::Info,
367 None,
368 "`pull_request_target` runs in the base's context: the default branch's copy of this workflow, at the default branch's head, with the repository's secrets. It does not check out the pull request's changes; a step that does runs code anyone could have written, with those secrets.".to_owned(),
369 );
370 }
371 if trigger.event == "workflow_call" && triggers.len() == 1 {
372 note(Severity::Info, None, "It is a reusable workflow: it runs when another workflow calls it.".to_owned());
373 }
374 }
375
376 let env = match root.get("env") {
377 Some(Value::Object(env)) => env.clone(),
378 _ => Map::new(),
379 };
380 if let Some(defaults) = root.get("defaults") {
381 check_defaults(defaults, "")?;
382 }
383 if let Some(concurrency) = root.get("concurrency") {
384 check_concurrency(concurrency, "", None, &mut note)?;
385 }
386 let concurrency = concurrency_of(root.get("concurrency"));
387 let permissions = match root.get("permissions") {
388 None => None,
389 Some(value) => {
390 if let Value::Object(map) = value {
391 check_keys(map, syntax::PERMISSIONS, false, "", "`permissions`")?;
392 }
393 let (permissions, unknown) = permissions::parse(value)?;
394 permission_notes(&unknown, None, &mut note);
395 Some(permissions)
396 }
397 };
398
399 let Some(Value::Object(job_specs)) = root.get("jobs") else {
400 return Err("`jobs` is missing: a workflow needs at least one job.".to_owned());
401 };
402 if job_specs.is_empty() {
403 return Err("`jobs` is empty: a workflow needs at least one job.".to_owned());
404 }
405 let mut jobs = Vec::new();
406 let mut seen_ids: Vec<String> = Vec::new();
407 for (id, spec) in job_specs {
408 if !syntax::valid_id(id) {
409 return Err(format!("`{id}` is not a job id GitHub accepts: {ID_RULE}"));
410 }
411 let lower = id.to_ascii_lowercase();
412 if let Some(index) = seen_ids.iter().position(|seen| *seen == lower) {
413 let other = job_specs.keys().nth(index).cloned().unwrap_or_default();
414 return Err(format!("Job `{id}` is already defined as `{other}`: GitHub compares job ids without case."));
415 }
416 seen_ids.push(lower);
417 let Value::Object(spec) = spec else {
418 return Err(format!("Job `{id}` is a mapping."));
419 };
420 let place = format!("Job `{id}`");
421 let uses = text(spec.get("uses"));
422 if spec.contains_key("uses") {
423 for key in ["runs-on", "steps"] {
424 if spec.contains_key(key) {
425 return Err(format!("Job `{id}` calls a reusable workflow with `uses`, so it has no `{key}`: the called workflow's jobs say that."));
426 }
427 }
428 check_keys(spec, syntax::CALLER_JOB, true, &place, "a job that calls a reusable workflow")?;
429 if uses.as_deref().is_none_or(|uses| uses.trim().is_empty()) {
430 return Err(format!("Job `{id}`: `uses` names the reusable workflow it calls."));
431 }
432 match spec.get("secrets") {
433 None | Some(Value::Object(_)) => {}
434 Some(Value::String(inherit)) if inherit == "inherit" => {}
435 Some(_) => return Err(format!("Job `{id}`: `secrets` is a mapping of the secrets it passes, or `inherit`.")),
436 }
437 } else {
438 check_keys(spec, syntax::JOB, true, &place, "a job")?;
439 if !spec.contains_key("runs-on") {
440 return Err(format!("Job `{id}` has no `runs-on`: say which runner it runs on, such as `runs-on: ubuntu-latest`."));
441 }
442 }
443 check_job_parts(id, spec, &mut note)?;
444 let steps_raw = match spec.get("steps") {
445 Some(Value::Array(steps)) => steps.clone(),
446 None if uses.is_some() => Vec::new(),
447 None => return Err(format!("Job `{id}` has no `steps`.")),
448 Some(_) => return Err(format!("Job `{id}`: `steps` is a list.")),
449 };
450 let runs_on = spec.get("runs-on").cloned().unwrap_or(Value::Null);
451 let labels: Vec<String> =
452 texts(Some(&runs_on)).into_iter().chain(runs_on.get("labels").map(|l| texts(Some(l))).unwrap_or_default()).collect();
453 // `self-hosted`, or a runner group, sends the job to the workspace's
454 // own runners, which may be Linux, macOS or Windows.
455 let self_hosted = runs_on.get("group").is_some() || labels.iter().any(|label| label.eq_ignore_ascii_case("self-hosted"));
456 let mut steps = Vec::new();
457 let mut step_ids: Vec<String> = Vec::new();
458 for (index, step) in steps_raw.iter().enumerate() {
459 let place = format!("Job `{id}`, step {}", index + 1);
460 let Value::Object(fields) = step else {
461 return Err(format!("{place}: a step is a mapping."));
462 };
463 if let Some(key) = syntax::BACKGROUND_STEPS.iter().find(|key| fields.contains_key(**key)) {
464 return Err(format!(
465 "{place}: `{key}` is one of GitHub's background steps (`background`, `wait`, `wait-all`, `cancel`, `parallel`), which g1t does not run yet."
466 ));
467 }
468 let step = Step {
469 id: text(fields.get("id")),
470 name: text(fields.get("name")),
471 condition: text(fields.get("if")),
472 uses: text(fields.get("uses")),
473 run: text(fields.get("run")),
474 g1t: fields.get(syntax::EXTENSION).cloned(),
475 raw: step.clone(),
476 };
477 match (&step.uses, &step.run) {
478 (Some(_), Some(_)) => return Err(format!("{place}: a step has `uses` or `run`, not both.")),
479 (None, None) => return Err(format!("{place}: a step needs `uses` or `run`.")),
480 (Some(_), None) => check_keys(fields, syntax::ACTION_STEP, true, &place, "a step that uses an action")?,
481 (None, Some(_)) => check_keys(fields, syntax::RUN_STEP, true, &place, "a step that runs a command")?,
482 }
483 if let Some(step_id) = &step.id {
484 if !syntax::valid_id(step_id) {
485 return Err(format!("{place}: `{step_id}` is not a step id GitHub accepts: {ID_RULE}"));
486 }
487 let lower = step_id.to_ascii_lowercase();
488 if step_ids.contains(&lower) {
489 return Err(format!("{place}: another step of job `{id}` has the id `{step_id}` already (GitHub compares step ids without case)."));
490 }
491 step_ids.push(lower);
492 }
493 if let Some(uses) = &step.uses
494 && let Some((severity, message)) = action_note(uses, fields.get("with").and_then(|with| with.get("cache")).is_some())
495 {
496 note(severity, Some(id), message);
497 }
498 if let Some(shell) = text(fields.get("shell"))
499 && !self_hosted
500 && matches!(shell.as_str(), "pwsh" | "powershell" | "cmd")
501 {
502 note(Severity::Unsupported, Some(id), format!("Steps with `shell: {shell}` need Windows or PowerShell, which g1t's Linux runners do not have."));
503 }
504 steps.push(step);
505 }
506 if self_hosted {
507 note(
508 Severity::Info,
509 Some(id),
510 "`self-hosted`: the job runs on one of the workspace's self-hosted runners that has every label in its `runs-on`, and waits until one does.".to_owned(),
511 );
512 } else {
513 for label in &labels {
514 let lower = label.to_ascii_lowercase();
515 if lower.contains("windows") || lower.contains("macos") {
516 note(
517 Severity::Unsupported,
518 Some(id),
519 format!("`runs-on: {label}`: g1t's own runners are Linux only, so this job fails. To run it on a Windows or macOS machine of your own, add a self-hosted runner and use `runs-on: [self-hosted, ...]`."),
520 );
521 }
522 }
523 }
524 if spec.contains_key("services") {
525 note(
526 Severity::Info,
527 Some(id),
528 "`services`: each service runs in Docker beside the steps and is reached at `localhost:<port>`. On g1t's machines it is the job's own Docker Engine, the service is also reached by its name, and two services cannot listen on the same port.".to_owned(),
529 );
530 }
531 if spec.contains_key("container") {
532 note(
533 Severity::Info,
534 Some(id),
535 "`container`: the steps run inside that image, in Docker (on g1t's machines, the job's own Engine), with the workspace at the same path as on the runner (`/home/runner/work`), not `/__w`.".to_owned(),
536 );
537 }
538 if spec.contains_key("environment") {
539 note(Severity::Info, Some(id), "`environment`: the job gets the values its secrets and variables give this environment once the environment's protection rules (required reviewers, a wait timer, which branches may deploy) let it through. Unless it says `deployment: false`, the run records a deployment to it.".to_owned());
540 }
541 let job_permissions = match spec.get("permissions") {
542 None => None,
543 Some(value) => {
544 if let Value::Object(map) = value {
545 check_keys(map, syntax::PERMISSIONS, false, &place, "`permissions`")?;
546 }
547 let (permissions, unknown) = permissions::parse(value).map_err(|problem| format!("Job `{id}`: {problem}"))?;
548 permission_notes(&unknown, Some(id), &mut note);
549 Some(permissions)
550 }
551 };
552 let (matrix, fail_fast, max_parallel) = match spec.get("strategy") {
553 Some(Value::Object(strategy)) => (
554 strategy.get("matrix").cloned(),
555 strategy.get("fail-fast").and_then(Value::as_bool).unwrap_or(true),
556 strategy.get("max-parallel").and_then(Value::as_u64).map(|n| n as u32),
557 ),
558 _ => (None, true, None),
559 };
560 if let Some(called) = uses.as_deref().filter(|uses| !uses.starts_with("./")) {
561 note(
562 Severity::Info,
563 Some(id),
564 format!(
565 "`{called}` is read from that repository on g1t when it is there and this repository may use it (a private one allows it under Settings, Actions, Access), and otherwise from a public repository on GitHub."
566 ),
567 );
568 }
569 jobs.push(Job {
570 id: id.clone(),
571 name: text(spec.get("name")),
572 needs: texts(spec.get("needs")),
573 condition: text(spec.get("if")),
574 runs_on,
575 matrix,
576 fail_fast,
577 max_parallel,
578 uses,
579 permissions: job_permissions,
580 concurrency: concurrency_of(spec.get("concurrency")),
581 steps,
582 g1t: spec.get(syntax::EXTENSION).cloned(),
583 raw: Value::Object(spec.clone()),
584 });
585 }
586 for job in &jobs {
587 for need in &job.needs {
588 if !jobs.iter().any(|other| &other.id == need) {
589 return Err(format!("Job `{}` needs `{need}`, and there is no job called that.", job.id));
590 }
591 }
592 }
593 let workflow = Workflow {
594 name: text(root.get("name")),
595 run_name: text(root.get("run-name")),
596 triggers,
597 env,
598 concurrency,
599 permissions,
600 jobs,
601 notes,
602 g1t: root.get(syntax::EXTENSION).cloned(),
603 raw,
604 };
605 if workflow.job_order().len() < workflow.jobs.len() {
606 return Err("The jobs' `needs` go round in a circle.".to_owned());
607 }
608 Ok(workflow)
609}
610
611/// Whether a job (as written) records a deployment to its environment:
612/// unless it says `deployment: false`, in its `environment` as on GitHub,
613/// or in its `g1t` settings.
614pub fn records_deployment(job: &Value) -> bool {
615 let off = |value: Option<&Value>| match value {
616 Some(Value::Bool(flag)) => !flag,
617 Some(Value::String(text)) => text.trim() == "false",
618 _ => false,
619 };
620 !off(job.get("environment").and_then(|environment| environment.get("deployment")))
621 && !off(job.get(syntax::EXTENSION).and_then(|settings| settings.get("deployment")))
622}
623
624/// GitHub's rule for job and step ids, as said when one breaks it.
625const ID_RULE: &str = "it starts with a letter or `_`, has only letters, digits, `-` and `_`, is under 100 characters, and does not start with `__`.";
626
627/// Whether a YAML merge key (`<<`) is anywhere in it.
628fn has_merge_key(value: &serde_yaml::Value) -> bool {
629 match value {
630 serde_yaml::Value::Mapping(map) => map.iter().any(|(key, value)| key.as_str() == Some("<<") || has_merge_key(value)),
631 serde_yaml::Value::Sequence(items) => items.iter().any(has_merge_key),
632 serde_yaml::Value::Tagged(tagged) => has_merge_key(&tagged.value),
633 _ => false,
634 }
635}
636
637/// Keys as a sentence: `a`, `b` or `c`.
638fn listed(keys: &[&str]) -> String {
639 let quoted: Vec<String> = keys.iter().map(|key| format!("`{key}`")).collect();
640 match quoted.split_last() {
641 None => String::new(),
642 Some((last, [])) => last.clone(),
643 Some((last, rest)) => format!("{} or {last}", rest.join(", ")),
644 }
645}
646
647/// `message`, said of `place` ("Job `build`, step 2"), or on its own for
648/// the workflow's top level.
649fn at(place: &str, message: &str) -> String {
650 if place.is_empty() {
651 let mut chars = message.chars();
652 chars.next().map(|first| first.to_uppercase().chain(chars).collect()).unwrap_or_default()
653 } else {
654 format!("{place}: {message}")
655 }
656}
657
658/// Refuses any key of `map` that is not `allowed`, as GitHub does
659/// ("Unexpected value"). With `extension`, `g1t` is allowed too, as a
660/// mapping of anything. `what` names the mapping in the message.
661fn check_keys(map: &Map<String, Value>, allowed: &[&str], extension: bool, place: &str, what: &str) -> Result<(), String> {
662 for (key, value) in map {
663 if extension && key == syntax::EXTENSION {
664 if !value.is_object() {
665 return Err(at(place, "`g1t` is a mapping of g1t's own settings."));
666 }
667 continue;
668 }
669 if !allowed.contains(&key.as_str()) {
670 return Err(at(place, &format!("unexpected `{key}` in {what}; it can have {}.", listed(allowed))));
671 }
672 }
673 Ok(())
674}
675
676/// Refuses a mapping without `key`.
677fn require(map: &Map<String, Value>, key: &str, place: &str, what: &str) -> Result<(), String> {
678 if map.contains_key(key) { Ok(()) } else { Err(at(place, &format!("{what} needs `{key}`."))) }
679}
680
681/// One event under `on` and what it is given.
682fn check_event(event: &str, kind: syntax::EventSpec, spec: &Value, note: &mut impl FnMut(Severity, Option<&str>, String)) -> Result<(), String> {
683 let what = format!("`on.{event}`");
684 match (kind, spec) {
685 (syntax::EventSpec::Schedule, Value::Array(entries)) => {
686 for entry in entries {
687 let Value::Object(entry) = entry else { return Err("`on.schedule` is a list of `cron:` entries.".to_owned()) };
688 check_keys(entry, syntax::CRON, false, "", "an entry of `on.schedule`")?;
689 require(entry, "cron", "", "Each entry of `on.schedule`")?;
690 if entry.contains_key("timezone") {
691 note(
692 Severity::Warning,
693 None,
694 "`on.schedule`: g1t reads every `cron` in UTC and does not read `timezone` yet, so the schedule runs at those times in UTC.".to_owned(),
695 );
696 }
697 }
698 Ok(())
699 }
700 (syntax::EventSpec::Schedule, _) => Err("`on.schedule` is a list of `cron:` entries.".to_owned()),
701 (_, Value::Null) => Ok(()),
702 (syntax::EventSpec::Bare, _) => Err(format!("{what} takes no settings: write `{event}:` with nothing after it.")),
703 (syntax::EventSpec::Filters(keys), Value::Object(map)) => {
704 check_keys(map, keys, false, "", &what)?;
705 for only in ["branches", "tags", "paths"] {
706 let ignore = format!("{only}-ignore");
707 if map.contains_key(only) && map.contains_key(&ignore) {
708 return Err(format!(
709 "{what} has both `{only}` and `{ignore}`: GitHub takes one or the other for an event. To leave some out of `{only}`, start a pattern with `!`."
710 ));
711 }
712 }
713 let definitions = |key: &str| -> Result<Vec<(&String, &Value)>, String> {
714 match map.get(key) {
715 None | Some(Value::Null) => Ok(Vec::new()),
716 Some(Value::Object(entries)) => Ok(entries.iter().collect()),
717 Some(_) => Err(format!("`on.{event}.{key}` is a mapping of names to their definitions.")),
718 }
719 };
720 if event == "workflow_dispatch" {
721 for (name, input) in definitions("inputs")? {
722 match input {
723 Value::Null => {}
724 Value::Object(input) => check_keys(input, syntax::DISPATCH_INPUT, false, "", &format!("input `{name}` of {what}"))?,
725 _ => return Err(format!("Input `{name}` of {what} is a mapping.")),
726 }
727 }
728 }
729 if event == "workflow_call" {
730 for (name, input) in definitions("inputs")? {
731 let Value::Object(input) = input else { return Err(format!("Input `{name}` of {what} is a mapping with its `type`.")) };
732 let place = format!("input `{name}` of {what}");
733 check_keys(input, syntax::CALL_INPUT, false, "", &place)?;
734 require(input, "type", "", &format!("Input `{name}` of {what}"))?;
735 }
736 for (name, output) in definitions("outputs")? {
737 let Value::Object(output) = output else { return Err(format!("Output `{name}` of {what} is a mapping with its `value`.")) };
738 check_keys(output, syntax::CALL_OUTPUT, false, "", &format!("output `{name}` of {what}"))?;
739 require(output, "value", "", &format!("Output `{name}` of {what}"))?;
740 }
741 for (name, secret) in definitions("secrets")? {
742 match secret {
743 Value::Null => {}
744 Value::Object(secret) => check_keys(secret, syntax::CALL_SECRET, false, "", &format!("secret `{name}` of {what}"))?,
745 _ => return Err(format!("Secret `{name}` of {what} is a mapping, or nothing.")),
746 }
747 }
748 }
749 Ok(())
750 }
751 (syntax::EventSpec::Filters(_), _) => Err(format!("{what} is a mapping of its filters, or nothing.")),
752 }
753}
754
755/// `defaults`, at the top level or on a job.
756fn check_defaults(value: &Value, place: &str) -> Result<(), String> {
757 let Value::Object(defaults) = value else { return Err(at(place, "`defaults` is a mapping with `run`.")) };
758 check_keys(defaults, syntax::DEFAULTS, false, place, "`defaults`")?;
759 match defaults.get("run") {
760 None | Some(Value::Null) => Ok(()),
761 Some(Value::Object(run)) => check_keys(run, syntax::DEFAULTS_RUN, false, place, "`defaults.run`"),
762 Some(_) => Err(at(place, "`defaults.run` is a mapping with `shell` or `working-directory`.")),
763 }
764}
765
766/// `concurrency`, at the top level or on a job (`job`).
767fn check_concurrency(value: &Value, place: &str, job: Option<&str>, note: &mut impl FnMut(Severity, Option<&str>, String)) -> Result<(), String> {
768 let Value::Object(concurrency) = value else { return Ok(()) };
769 check_keys(concurrency, syntax::CONCURRENCY, false, place, "`concurrency`")?;
770 require(concurrency, "group", place, "`concurrency`")?;
771 if let Some(queue) = concurrency.get("queue")
772 && text(Some(queue)).as_deref() != Some("single")
773 {
774 note(
775 Severity::Warning,
776 job,
777 "`concurrency.queue`: g1t keeps one run or job waiting in a group, as `queue: single` does, and does not read `queue` yet.".to_owned(),
778 );
779 }
780 Ok(())
781}
782
783/// A job's mappings other than its steps: each has only GitHub's keys.
784fn check_job_parts(id: &str, spec: &Map<String, Value>, note: &mut impl FnMut(Severity, Option<&str>, String)) -> Result<(), String> {
785 let place = format!("Job `{id}`");
786 let credentials = |container: &Map<String, Value>, what: &str| -> Result<(), String> {
787 match container.get("credentials") {
788 Some(Value::Object(credentials)) => check_keys(credentials, syntax::CREDENTIALS, false, &place, &format!("the `credentials` of {what}")),
789 _ => Ok(()),
790 }
791 };
792 if let Some(Value::Object(runs_on)) = spec.get("runs-on") {
793 check_keys(runs_on, syntax::RUNS_ON, false, &place, "`runs-on`")?;
794 }
795 if let Some(Value::Object(strategy)) = spec.get("strategy") {
796 check_keys(strategy, syntax::STRATEGY, false, &place, "`strategy`")?;
797 }
798 if let Some(Value::Object(container)) = spec.get("container") {
799 check_keys(container, syntax::CONTAINER, false, &place, "`container`")?;
800 credentials(container, "`container`")?;
801 }
802 if let Some(Value::Object(services)) = spec.get("services") {
803 for (name, service) in services {
804 if let Value::Object(service) = service {
805 let what = format!("service `{name}`");
806 check_keys(service, syntax::SERVICE, false, &place, &what)?;
807 credentials(service, &what)?;
808 }
809 }
810 }
811 if let Some(Value::Object(environment)) = spec.get("environment") {
812 check_keys(environment, syntax::ENVIRONMENT, false, &place, "`environment`")?;
813 require(environment, "name", &place, "`environment`")?;
814 }
815 if let Some(concurrency) = spec.get("concurrency") {
816 check_concurrency(concurrency, &place, Some(id), note)?;
817 }
818 if let Some(defaults) = spec.get("defaults") {
819 check_defaults(defaults, &place)?;
820 }
821 if spec.contains_key("snapshot") {
822 note(Severity::Unsupported, Some(id), "`snapshot`: g1t does not make custom runner images from a job yet, so the job runs and no image is made.".to_owned());
823 }
824 if spec.contains_key("cancel-timeout-minutes") {
825 note(Severity::Warning, Some(id), "`cancel-timeout-minutes`: g1t does not read it yet, so a cancelled job stops in its usual time.".to_owned());
826 }
827 Ok(())
828}
829
830/// `concurrency`, as a group's name or a mapping with `group` and
831/// `cancel-in-progress`.
832fn concurrency_of(value: Option<&Value>) -> Option<Concurrency> {
833 match value {
834 Some(Value::String(group)) => Some(Concurrency { group: group.clone(), cancel_in_progress: Value::Bool(false) }),
835 Some(Value::Object(spec)) => text(spec.get("group")).map(|group| Concurrency {
836 group,
837 cancel_in_progress: spec.get("cancel-in-progress").cloned().unwrap_or(Value::Bool(false)),
838 }),
839 _ => None,
840 }
841}
842
843/// What to say about `permissions` names GitHub has that g1t's token has
844/// nothing behind.
845fn permission_notes(unknown: &[String], job: Option<&str>, note: &mut impl FnMut(Severity, Option<&str>, String)) {
846 for name in unknown {
847 note(Severity::Warning, job, format!("`permissions.{name}`: g1t's token has nothing behind that permission yet, so it grants nothing."));
848 }
849}
850
851/// What to say about an action g1t runs differently, if anything.
852/// `caches`: the step sets a `cache` input.
853fn action_note(uses: &str, caches: bool) -> Option<(Severity, String)> {
854 if uses.starts_with("docker://") {
855 return Some((Severity::Info, format!("`{uses}` runs in Docker (on g1t's machines, the job's own Engine).")));
856 }
857 let name = uses.split('@').next().unwrap_or(uses).to_ascii_lowercase();
858 match name.as_str() {
859 "actions/checkout" => Some((Severity::Info, "`actions/checkout` checks out from g1t.".to_owned())),
860 "actions/cache" | "actions/cache/restore" | "actions/cache/save" => Some((
861 Severity::Info,
862 format!("`{name}`: g1t keeps the cache per repository: up to 2 GiB an entry and 10 GiB a repository, until it goes 7 days unused, and at most 28 days."),
863 )),
864 "actions/upload-artifact" | "actions/download-artifact" => Some((
865 Severity::Info,
866 format!("`{name}`: g1t keeps artifacts with the run for 14 days, up to 60 MB each."),
867 )),
868 _ if caches && name.starts_with("actions/setup-") => Some((
869 Severity::Warning,
870 format!("`{name}` with `cache:` runs without that cache on g1t. Add an `actions/cache` step for the same effect."),
871 )),
872 _ => None,
873 }
874}
875
876#[cfg(test)]
877mod tests {
878 use super::*;
879
880 const CI: &str = r#"
881name: CI
882on:
883 push:
884 branches: [main]
885 paths-ignore: ["docs/**"]
886 pull_request:
887 workflow_dispatch:
888 inputs:
889 debug:
890 type: boolean
891 default: false
892 schedule:
893 - cron: "0 3 * * *"
894concurrency:
895 group: ci-${{ github.ref }}
896 cancel-in-progress: true
897env:
898 CARGO_TERM_COLOR: always
899jobs:
900 test:
901 runs-on: ${{ matrix.os }}
902 strategy:
903 matrix:
904 os: [ubuntu-latest, windows-latest]
905 node: [22, 24]
906 steps:
907 - uses: actions/checkout@v7
908 - uses: actions/setup-node@v7
909 with:
910 node-version: ${{ matrix.node }}
911 - run: npm ci
912 - name: Test
913 run: npm test
914 deploy:
915 needs: test
916 if: github.ref == 'refs/heads/main'
917 runs-on: ubuntu-latest
918 steps:
919 - run: echo deploy
920"#;
921
922 #[test]
923 fn a_whole_workflow_reads() {
924 let workflow = parse(CI).unwrap();
925 assert_eq!(workflow.name.as_deref(), Some("CI"));
926 assert_eq!(workflow.triggers.iter().map(|t| t.event.as_str()).collect::<Vec<_>>(), ["push", "pull_request", "workflow_dispatch", "schedule"]);
927 let push = workflow.trigger("push").unwrap();
928 assert!(push.branches.allows("main"));
929 assert!(!push.branches.allows("dev"));
930 assert!(!push.paths.allows_paths(&["docs/a.md".into()]));
931 assert_eq!(workflow.trigger("schedule").unwrap().crons, ["0 3 * * *"]);
932 assert!(workflow.trigger("workflow_dispatch").unwrap().inputs.contains_key("debug"));
933 assert_eq!(workflow.concurrency.as_ref().unwrap().group, "ci-${{ github.ref }}");
934 assert_eq!(workflow.jobs.len(), 2);
935 assert_eq!(workflow.jobs[1].needs, ["test"]);
936 assert_eq!(workflow.jobs[0].steps[0].title(), "Run actions/checkout@v7");
937 assert_eq!(workflow.jobs[0].steps[2].title(), "Run npm ci");
938 assert_eq!(workflow.jobs[0].steps[3].title(), "Test");
939 assert_eq!(workflow.job_order(), ["test", "deploy"]);
940 assert_eq!(workflow.env["CARGO_TERM_COLOR"], "always");
941 }
942
943 #[test]
944 fn short_forms_of_on() {
945 let one = parse("on: push\njobs:\n a:\n runs-on: ubuntu-latest\n steps: [{ run: 'true' }]").unwrap();
946 assert_eq!(one.triggers[0].event, "push");
947 let list = parse("on: [push, pull_request]\njobs:\n a:\n runs-on: ubuntu-latest\n steps: [{ run: 'true' }]").unwrap();
948 assert_eq!(list.triggers.len(), 2);
949 let pr = list.trigger("pull_request").unwrap();
950 assert!(pr.wants_type(Some("opened")));
951 assert!(pr.wants_type(Some("synchronize")));
952 assert!(!pr.wants_type(Some("closed")));
953 assert!(pr.wants_type(Some("ready_for_review")));
954 let typed = parse("on:\n pull_request:\n types: [closed]\njobs:\n a:\n runs-on: ubuntu-latest\n steps: [{ run: 'true' }]").unwrap();
955 assert!(typed.trigger("pull_request").unwrap().wants_type(Some("closed")));
956 assert!(!typed.trigger("pull_request").unwrap().wants_type(Some("opened")));
957 }
958
959 #[test]
960 fn notes_say_what_runs_differently() {
961 let workflow = parse(
962 "on: [push, watch]\njobs:\n win:\n runs-on: windows-latest\n services:\n db: { image: postgres }\n steps:\n - uses: actions/cache@v6\n - uses: actions/setup-node@v7\n with: { cache: npm }\n - uses: docker://alpine\n - run: dir\n shell: pwsh",
963 )
964 .unwrap();
965 let unsupported: Vec<&str> =
966 workflow.notes.iter().filter(|n| n.severity == Severity::Unsupported).map(|n| n.message.as_str()).collect();
967 assert!(unsupported.iter().any(|m| m.contains("`watch`")));
968 let released = parse("on:\n release:\n types: [published]\n deployment_status:\njobs:\n a:\n runs-on: ubuntu-latest\n steps: [{ run: 'true' }]").unwrap();
969 assert!(!released.notes.iter().any(|n| n.severity == Severity::Unsupported));
970 assert!(released.trigger("release").unwrap().wants_type(Some("published")));
971 assert!(!released.trigger("release").unwrap().wants_type(Some("created")));
972 assert!(released.trigger("deployment_status").unwrap().wants_type(Some("created")));
973 assert!(unsupported.iter().any(|m| m.contains("windows-latest")));
974 assert!(!unsupported.iter().any(|m| m.contains("services")));
975 assert!(!unsupported.iter().any(|m| m.contains("docker://alpine")));
976 assert!(workflow.notes.iter().any(|n| n.severity == Severity::Info && n.message.contains("own Docker Engine") && n.message.contains("localhost")));
977 assert!(workflow.notes.iter().any(|n| n.severity == Severity::Info && n.message.starts_with("`docker://alpine`")));
978 assert!(unsupported.iter().any(|m| m.contains("pwsh")));
979 assert!(workflow.notes.iter().any(|n| n.severity == Severity::Info && n.message.contains("actions/cache")));
980 assert!(workflow.notes.iter().any(|n| n.severity == Severity::Warning && n.message.contains("actions/setup-node")));
981 assert!(workflow.notes.iter().any(|n| n.message.contains("2 GiB an entry")));
982 }
983
984 #[test]
985 fn self_hosted_jobs_may_run_on_any_os() {
986 let workflow = parse(
987 "on: push
988jobs:
989 win:
990 runs-on: [self-hosted, windows]
991 steps:
992 - run: dir
993 shell: pwsh
994 mac:
995 runs-on: { group: Macs, labels: [macos] }
996 steps: [{ run: 'true' }]",
997 )
998 .unwrap();
999 assert!(!workflow.notes.iter().any(|n| n.severity == Severity::Unsupported), "{:?}", workflow.notes);
1000 let routed: Vec<&str> = workflow.notes.iter().filter(|n| n.message.starts_with("`self-hosted`")).map(|n| n.message.as_str()).collect();
1001 assert_eq!(routed.len(), 2);
1002 assert!(routed.iter().all(|m| m.contains("self-hosted runners") && !m.contains("Linux")));
1003 }
1004
1005 #[test]
1006 fn permissions_are_read_at_both_levels() {
1007 use crate::permissions::{Access, TokenDefault};
1008 let workflow = parse(
1009 "on: push
1010permissions:
1011 contents: read
1012 pull-requests: write
1013jobs:
1014 plain:
1015 runs-on: ubuntu-latest
1016 steps: [{ run: 'true' }]
1017 release:
1018 runs-on: ubuntu-latest
1019 permissions:
1020 contents: write
1021 steps: [{ run: 'true' }]
1022 quiet:
1023 runs-on: ubuntu-latest
1024 permissions: {}
1025 steps: [{ run: 'true' }]",
1026 )
1027 .unwrap();
1028 let plain = workflow.jobs[0].permissions(&workflow, TokenDefault::Restricted);
1029 assert_eq!(plain.get("pull-requests"), Access::Write);
1030 assert_eq!(plain.get("contents"), Access::Read);
1031 // A job's own permissions replace the workflow's whole.
1032 let release = workflow.jobs[1].permissions(&workflow, TokenDefault::Permissive);
1033 assert_eq!(release.get("contents"), Access::Write);
1034 assert_eq!(release.get("pull-requests"), Access::None);
1035 assert_eq!(workflow.jobs[2].permissions(&workflow, TokenDefault::Permissive).scopes(), ["repo:read"]);
1036 // Without any, the repository's default.
1037 let bare = parse("on: push\njobs:\n a:\n runs-on: ubuntu-latest\n steps: [{ run: 'true' }]").unwrap();
1038 assert_eq!(bare.jobs[0].permissions(&bare, TokenDefault::Restricted).get("contents"), Access::Read);
1039 assert_eq!(bare.jobs[0].permissions(&bare, TokenDefault::Restricted).get("issues"), Access::None);
1040 assert_eq!(bare.jobs[0].permissions(&bare, TokenDefault::Permissive).get("issues"), Access::Write);
1041 // What reads but grants nothing is said.
1042 let odd = parse("on: push\npermissions: { id-token: write, artifact-metadata: read }\njobs:\n a:\n runs-on: x\n steps: [{ run: 'true' }]").unwrap();
1043 assert!(!odd.notes.iter().any(|n| n.message.contains("id-token")), "OIDC tokens are issued");
1044 assert!(odd.notes.iter().any(|n| n.severity == Severity::Warning && n.message.contains("`permissions.artifact-metadata`")));
1045 // A name GitHub's token does not have is refused, as GitHub does;
1046 // `metadata` is always `read` and cannot be written.
1047 for name in ["wiki", "metadata"] {
1048 let problem = parse(&format!("on: push\npermissions: {{ {name}: read }}\njobs:\n a:\n runs-on: x\n steps: [{{ run: 'true' }}]")).unwrap_err();
1049 assert!(problem.contains(&format!("Unexpected `{name}` in `permissions`")), "{problem}");
1050 }
1051 assert!(parse("on: push\npermissions: read\njobs:\n a:\n runs-on: x\n steps: [{ run: 'true' }]").unwrap_err().contains("read-all"));
1052 assert!(
1053 parse("on: push\njobs:\n a:\n runs-on: x\n permissions: { contents: admin }\n steps: [{ run: 'true' }]")
1054 .unwrap_err()
1055 .contains("Job `a`")
1056 );
1057 }
1058
1059 #[test]
1060 fn a_job_has_its_own_concurrency() {
1061 let workflow = parse(
1062 "on: push
1063jobs:
1064 deploy:
1065 runs-on: ubuntu-latest
1066 concurrency:
1067 group: deploy-${{ github.ref }}
1068 cancel-in-progress: true
1069 steps: [{ run: 'true' }]
1070 named:
1071 runs-on: ubuntu-latest
1072 concurrency: just-one
1073 steps: [{ run: 'true' }]",
1074 )
1075 .unwrap();
1076 let deploy = workflow.jobs[0].concurrency.as_ref().unwrap();
1077 assert_eq!(deploy.group, "deploy-${{ github.ref }}");
1078 assert_eq!(deploy.cancel_in_progress, Value::Bool(true));
1079 assert_eq!(workflow.jobs[1].concurrency.as_ref().unwrap().group, "just-one");
1080 assert!(workflow.concurrency.is_none());
1081 }
1082
1083 #[test]
1084 fn events_g1t_never_sends_are_said_and_pull_request_target_is_the_base() {
1085 let workflow = parse("on: [create, delete, repository_dispatch, pull_request_target]\njobs:\n a:\n runs-on: x\n steps: [{ run: 'true' }]").unwrap();
1086 let unsupported: Vec<&str> = workflow.notes.iter().filter(|n| n.severity == Severity::Unsupported).map(|n| n.message.as_str()).collect();
1087 assert_eq!(unsupported.len(), 1, "{unsupported:?}");
1088 assert!(unsupported[0].contains("`delete`"));
1089 let target = workflow.notes.iter().find(|n| n.message.starts_with("`pull_request_target`")).unwrap();
1090 assert!(target.message.contains("default branch"));
1091 assert!(!target.message.contains("on the pull request's head"));
1092 }
1093
1094 #[test]
1095 fn mistakes_are_explained() {
1096 let problem = |yaml: &str| parse(yaml).unwrap_err();
1097 assert!(problem("jobs: {}").contains("`on` is missing"));
1098 assert!(problem("on: push").contains("`jobs` is missing"));
1099 assert!(problem("on: push\njobs:\n a:\n runs-on: x").contains("no `steps`"));
1100 assert!(problem("on: push\njobs:\n a:\n runs-on: x\n steps: [{ name: nothing }]").contains("`uses` or `run`"));
1101 assert!(problem("on: push\njobs:\n a:\n needs: b\n runs-on: x\n steps: [{ run: x }]").contains("no job called that"));
1102 assert!(
1103 problem("on: push\njobs:\n a:\n needs: b\n runs-on: x\n steps: [{ run: x }]\n b:\n needs: a\n runs-on: x\n steps: [{ run: x }]")
1104 .contains("circle")
1105 );
1106 assert!(problem("on: push\njobs: [1]").contains("`jobs`"));
1107 assert!(problem(": : :").contains("not valid YAML"));
1108 }
1109
1110 #[test]
1111 fn only_githubs_keys_and_g1ts_own() {
1112 let problem = |yaml: &str| parse(yaml).unwrap_err();
1113 let job = "\njobs:\n build:\n runs-on: x\n steps: [{ run: 'true' }]";
1114 assert!(problem(&format!("on: push\nrun_name: x{job}")).starts_with("Unexpected `run_name` in the workflow; it can have `on`, "));
1115 assert!(problem("on: push\njobs:\n build:\n runs-on: x\n step: []").starts_with("Job `build`: unexpected `step` in a job;"));
1116 let step = problem("on: push\njobs:\n build:\n runs-on: x\n steps:\n - run: 'true'\n - uses: actions/checkout@v5\n shell: bash");
1117 assert!(step.starts_with("Job `build`, step 2: unexpected `shell` in a step that uses an action;"), "{step}");
1118 assert!(problem("on: push\njobs:\n build:\n steps: [{ run: 'true' }]").contains("no `runs-on`"));
1119 assert!(problem("on: push\njobs:\n build:\n uses: ./.g1t/workflows/b.yml\n runs-on: x").contains("no `runs-on`"));
1120 assert!(problem("on: push\njobs:\n my.job:\n runs-on: x\n steps: [{ run: 'true' }]").contains("`my.job` is not a job id"));
1121 assert!(problem("on: pushh\njobs:\n a:\n runs-on: x\n steps: [{ run: 'true' }]").contains("no `pushh` event"));
1122
1123 // `g1t` is g1t's own, at each level, and kept as written.
1124 let workflow = parse(
1125 "on: push
1126g1t: { note: top }
1127jobs:
1128 deploy:
1129 runs-on: x
1130 environment: production
1131 g1t: { deployment: false }
1132 steps:
1133 - run: 'true'
1134 g1t: { anything: [1, 2] }",
1135 )
1136 .unwrap();
1137 assert_eq!(workflow.g1t, Some(serde_json::json!({ "note": "top" })));
1138 assert_eq!(workflow.jobs[0].g1t, Some(serde_json::json!({ "deployment": false })));
1139 assert_eq!(workflow.jobs[0].steps[0].g1t, Some(serde_json::json!({ "anything": [1, 2] })));
1140 assert!(problem(&format!("on: push\ng1t: yes{job}")).contains("`g1t` is a mapping"));
1141 assert!(!records_deployment(&workflow.jobs[0].raw));
1142 assert!(!records_deployment(&serde_json::json!({ "environment": { "name": "p", "deployment": false } })));
1143 assert!(records_deployment(&serde_json::json!({ "environment": { "name": "p", "deployment": true } })));
1144 assert!(records_deployment(&serde_json::json!({ "environment": "p" })));
1145 }
1146
1147 #[test]
1148 fn aliases_read_and_merge_keys_do_not() {
1149 let aliased = parse("on: push\njobs:\n a:\n runs-on: x\n steps: &steps\n - run: 'true'\n b:\n runs-on: x\n steps: *steps").unwrap();
1150 assert_eq!(aliased.jobs[1].steps.len(), 1);
1151 let merged = parse("on: push\njobs:\n a: &job\n runs-on: x\n steps: [{ run: 'true' }]\n b:\n <<: *job\n name: B").unwrap_err();
1152 assert!(merged.contains("merge key"), "{merged}");
1153 }
1154}