Skip to content
1,188 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)
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 } else if lower.contains("arm") {
522 note(
523 Severity::Warning,
524 Some(id),
525 format!("`runs-on: {label}`: g1t's own runners are x64, so this job runs on x64, not Arm. A self-hosted Arm runner runs it as asked: `runs-on: [self-hosted, ARM64]`."),
526 );
527 }
528 }
529 if let Some(minutes) = spec.get("timeout-minutes").and_then(Value::as_f64)
530 && minutes > f64::from(HOSTED_MAX_TIMEOUT_MINUTES)
531 {
532 note(
533 Severity::Warning,
534 Some(id),
535 format!("`timeout-minutes: {minutes}`: a job on g1t's own machines is stopped at {HOSTED_MAX_TIMEOUT_MINUTES} minutes. A self-hosted runner runs it for as long as it asks, up to 24 hours."),
536 );
537 }
538 }
539 if spec.contains_key("services") {
540 note(
541 Severity::Info,
542 Some(id),
543 "`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(),
544 );
545 }
546 if spec.contains_key("container") {
547 note(
548 Severity::Info,
549 Some(id),
550 "`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(),
551 );
552 }
553 if spec.contains_key("environment") {
554 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());
555 }
556 let job_permissions = match spec.get("permissions") {
557 None => None,
558 Some(value) => {
559 if let Value::Object(map) = value {
560 check_keys(map, syntax::PERMISSIONS, false, &place, "`permissions`")?;
561 }
562 let (permissions, unknown) = permissions::parse(value).map_err(|problem| format!("Job `{id}`: {problem}"))?;
563 permission_notes(&unknown, Some(id), &mut note);
564 Some(permissions)
565 }
566 };
567 let (matrix, fail_fast, max_parallel) = match spec.get("strategy") {
568 Some(Value::Object(strategy)) => (
569 strategy.get("matrix").cloned(),
570 strategy.get("fail-fast").and_then(Value::as_bool).unwrap_or(true),
571 strategy.get("max-parallel").and_then(Value::as_u64).map(|n| n as u32),
572 ),
573 _ => (None, true, None),
574 };
575 if let Some(called) = uses.as_deref().filter(|uses| !uses.starts_with("./")) {
576 note(
577 Severity::Info,
578 Some(id),
579 format!(
580 "`{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."
581 ),
582 );
583 }
584 jobs.push(Job {
585 id: id.clone(),
586 name: text(spec.get("name")),
587 needs: texts(spec.get("needs")),
588 condition: text(spec.get("if")),
589 runs_on,
590 matrix,
591 fail_fast,
592 max_parallel,
593 uses,
594 permissions: job_permissions,
595 concurrency: concurrency_of(spec.get("concurrency")),
596 steps,
597 g1t: spec.get(syntax::EXTENSION).cloned(),
598 raw: Value::Object(spec.clone()),
599 });
600 }
601 for job in &jobs {
602 for need in &job.needs {
603 if !jobs.iter().any(|other| &other.id == need) {
604 return Err(format!("Job `{}` needs `{need}`, and there is no job called that.", job.id));
605 }
606 }
607 }
608 let workflow = Workflow {
609 name: text(root.get("name")),
610 run_name: text(root.get("run-name")),
611 triggers,
612 env,
613 concurrency,
614 permissions,
615 jobs,
616 notes,
617 g1t: root.get(syntax::EXTENSION).cloned(),
618 raw,
619 };
620 if workflow.job_order().len() < workflow.jobs.len() {
621 return Err("The jobs' `needs` go round in a circle.".to_owned());
622 }
623 Ok(workflow)
624}
625
626/// Whether a job (as written) records a deployment to its environment:
627/// unless it says `deployment: false`, in its `environment` as on GitHub,
628/// or in its `g1t` settings.
629pub fn records_deployment(job: &Value) -> bool {
630 let off = |value: Option<&Value>| match value {
631 Some(Value::Bool(flag)) => !flag,
632 Some(Value::String(text)) => text.trim() == "false",
633 _ => false,
634 };
635 !off(job.get("environment").and_then(|environment| environment.get("deployment")))
636 && !off(job.get(syntax::EXTENSION).and_then(|settings| settings.get("deployment")))
637}
638
639/// GitHub's rule for job and step ids, as said when one breaks it.
640const ID_RULE: &str = "it starts with a letter or `_`, has only letters, digits, `-` and `_`, is under 100 characters, and does not start with `__`.";
641
642/// Whether a YAML merge key (`<<`) is anywhere in it.
643fn has_merge_key(value: &serde_yaml::Value) -> bool {
644 match value {
645 serde_yaml::Value::Mapping(map) => map.iter().any(|(key, value)| key.as_str() == Some("<<") || has_merge_key(value)),
646 serde_yaml::Value::Sequence(items) => items.iter().any(has_merge_key),
647 serde_yaml::Value::Tagged(tagged) => has_merge_key(&tagged.value),
648 _ => false,
649 }
650}
651
652/// Keys as a sentence: `a`, `b` or `c`.
653fn listed(keys: &[&str]) -> String {
654 let quoted: Vec<String> = keys.iter().map(|key| format!("`{key}`")).collect();
655 match quoted.split_last() {
656 None => String::new(),
657 Some((last, [])) => last.clone(),
658 Some((last, rest)) => format!("{} or {last}", rest.join(", ")),
659 }
660}
661
662/// `message`, said of `place` ("Job `build`, step 2"), or on its own for
663/// the workflow's top level.
664fn at(place: &str, message: &str) -> String {
665 if place.is_empty() {
666 let mut chars = message.chars();
667 chars.next().map(|first| first.to_uppercase().chain(chars).collect()).unwrap_or_default()
668 } else {
669 format!("{place}: {message}")
670 }
671}
672
673/// Refuses any key of `map` that is not `allowed`, as GitHub does
674/// ("Unexpected value"). With `extension`, `g1t` is allowed too, as a
675/// mapping of anything. `what` names the mapping in the message.
676fn check_keys(map: &Map<String, Value>, allowed: &[&str], extension: bool, place: &str, what: &str) -> Result<(), String> {
677 for (key, value) in map {
678 if extension && key == syntax::EXTENSION {
679 if !value.is_object() {
680 return Err(at(place, "`g1t` is a mapping of g1t's own settings."));
681 }
682 continue;
683 }
684 if !allowed.contains(&key.as_str()) {
685 return Err(at(place, &format!("unexpected `{key}` in {what}; it can have {}.", listed(allowed))));
686 }
687 }
688 Ok(())
689}
690
691/// Refuses a mapping without `key`.
692fn require(map: &Map<String, Value>, key: &str, place: &str, what: &str) -> Result<(), String> {
693 if map.contains_key(key) { Ok(()) } else { Err(at(place, &format!("{what} needs `{key}`."))) }
694}
695
696/// One event under `on` and what it is given.
697fn check_event(event: &str, kind: syntax::EventSpec, spec: &Value, note: &mut impl FnMut(Severity, Option<&str>, String)) -> Result<(), String> {
698 let what = format!("`on.{event}`");
699 match (kind, spec) {
700 (syntax::EventSpec::Schedule, Value::Array(entries)) => {
701 for entry in entries {
702 let Value::Object(entry) = entry else { return Err("`on.schedule` is a list of `cron:` entries.".to_owned()) };
703 check_keys(entry, syntax::CRON, false, "", "an entry of `on.schedule`")?;
704 require(entry, "cron", "", "Each entry of `on.schedule`")?;
705 if entry.contains_key("timezone") {
706 note(
707 Severity::Warning,
708 None,
709 "`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(),
710 );
711 }
712 }
713 Ok(())
714 }
715 (syntax::EventSpec::Schedule, _) => Err("`on.schedule` is a list of `cron:` entries.".to_owned()),
716 (_, Value::Null) => Ok(()),
717 (syntax::EventSpec::Bare, _) => Err(format!("{what} takes no settings: write `{event}:` with nothing after it.")),
718 (syntax::EventSpec::Filters(keys), Value::Object(map)) => {
719 check_keys(map, keys, false, "", &what)?;
720 for only in ["branches", "tags", "paths"] {
721 let ignore = format!("{only}-ignore");
722 if map.contains_key(only) && map.contains_key(&ignore) {
723 return Err(format!(
724 "{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 `!`."
725 ));
726 }
727 }
728 let definitions = |key: &str| -> Result<Vec<(&String, &Value)>, String> {
729 match map.get(key) {
730 None | Some(Value::Null) => Ok(Vec::new()),
731 Some(Value::Object(entries)) => Ok(entries.iter().collect()),
732 Some(_) => Err(format!("`on.{event}.{key}` is a mapping of names to their definitions.")),
733 }
734 };
735 if event == "workflow_dispatch" {
736 for (name, input) in definitions("inputs")? {
737 match input {
738 Value::Null => {}
739 Value::Object(input) => check_keys(input, syntax::DISPATCH_INPUT, false, "", &format!("input `{name}` of {what}"))?,
740 _ => return Err(format!("Input `{name}` of {what} is a mapping.")),
741 }
742 }
743 }
744 if event == "workflow_call" {
745 for (name, input) in definitions("inputs")? {
746 let Value::Object(input) = input else { return Err(format!("Input `{name}` of {what} is a mapping with its `type`.")) };
747 let place = format!("input `{name}` of {what}");
748 check_keys(input, syntax::CALL_INPUT, false, "", &place)?;
749 require(input, "type", "", &format!("Input `{name}` of {what}"))?;
750 }
751 for (name, output) in definitions("outputs")? {
752 let Value::Object(output) = output else { return Err(format!("Output `{name}` of {what} is a mapping with its `value`.")) };
753 check_keys(output, syntax::CALL_OUTPUT, false, "", &format!("output `{name}` of {what}"))?;
754 require(output, "value", "", &format!("Output `{name}` of {what}"))?;
755 }
756 for (name, secret) in definitions("secrets")? {
757 match secret {
758 Value::Null => {}
759 Value::Object(secret) => check_keys(secret, syntax::CALL_SECRET, false, "", &format!("secret `{name}` of {what}"))?,
760 _ => return Err(format!("Secret `{name}` of {what} is a mapping, or nothing.")),
761 }
762 }
763 }
764 Ok(())
765 }
766 (syntax::EventSpec::Filters(_), _) => Err(format!("{what} is a mapping of its filters, or nothing.")),
767 }
768}
769
770/// `defaults`, at the top level or on a job.
771fn check_defaults(value: &Value, place: &str) -> Result<(), String> {
772 let Value::Object(defaults) = value else { return Err(at(place, "`defaults` is a mapping with `run`.")) };
773 check_keys(defaults, syntax::DEFAULTS, false, place, "`defaults`")?;
774 match defaults.get("run") {
775 None | Some(Value::Null) => Ok(()),
776 Some(Value::Object(run)) => check_keys(run, syntax::DEFAULTS_RUN, false, place, "`defaults.run`"),
777 Some(_) => Err(at(place, "`defaults.run` is a mapping with `shell` or `working-directory`.")),
778 }
779}
780
781/// `concurrency`, at the top level or on a job (`job`).
782fn check_concurrency(value: &Value, place: &str, job: Option<&str>, note: &mut impl FnMut(Severity, Option<&str>, String)) -> Result<(), String> {
783 let Value::Object(concurrency) = value else { return Ok(()) };
784 check_keys(concurrency, syntax::CONCURRENCY, false, place, "`concurrency`")?;
785 require(concurrency, "group", place, "`concurrency`")?;
786 if let Some(queue) = concurrency.get("queue")
787 && text(Some(queue)).as_deref() != Some("single")
788 {
789 note(
790 Severity::Warning,
791 job,
792 "`concurrency.queue`: g1t keeps one run or job waiting in a group, as `queue: single` does, and does not read `queue` yet.".to_owned(),
793 );
794 }
795 Ok(())
796}
797
798/// A job's mappings other than its steps: each has only GitHub's keys.
799fn check_job_parts(id: &str, spec: &Map<String, Value>, note: &mut impl FnMut(Severity, Option<&str>, String)) -> Result<(), String> {
800 let place = format!("Job `{id}`");
801 let credentials = |container: &Map<String, Value>, what: &str| -> Result<(), String> {
802 match container.get("credentials") {
803 Some(Value::Object(credentials)) => check_keys(credentials, syntax::CREDENTIALS, false, &place, &format!("the `credentials` of {what}")),
804 _ => Ok(()),
805 }
806 };
807 if let Some(Value::Object(runs_on)) = spec.get("runs-on") {
808 check_keys(runs_on, syntax::RUNS_ON, false, &place, "`runs-on`")?;
809 }
810 if let Some(Value::Object(strategy)) = spec.get("strategy") {
811 check_keys(strategy, syntax::STRATEGY, false, &place, "`strategy`")?;
812 }
813 if let Some(Value::Object(container)) = spec.get("container") {
814 check_keys(container, syntax::CONTAINER, false, &place, "`container`")?;
815 credentials(container, "`container`")?;
816 }
817 if let Some(Value::Object(services)) = spec.get("services") {
818 for (name, service) in services {
819 if let Value::Object(service) = service {
820 let what = format!("service `{name}`");
821 check_keys(service, syntax::SERVICE, false, &place, &what)?;
822 credentials(service, &what)?;
823 }
824 }
825 }
826 if let Some(Value::Object(environment)) = spec.get("environment") {
827 check_keys(environment, syntax::ENVIRONMENT, false, &place, "`environment`")?;
828 require(environment, "name", &place, "`environment`")?;
829 }
830 if let Some(concurrency) = spec.get("concurrency") {
831 check_concurrency(concurrency, &place, Some(id), note)?;
832 }
833 if let Some(defaults) = spec.get("defaults") {
834 check_defaults(defaults, &place)?;
835 }
836 if spec.contains_key("snapshot") {
837 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());
838 }
839 if spec.contains_key("cancel-timeout-minutes") {
840 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());
841 }
842 Ok(())
843}
844
845/// `concurrency`, as a group's name or a mapping with `group` and
846/// `cancel-in-progress`.
847fn concurrency_of(value: Option<&Value>) -> Option<Concurrency> {
848 match value {
849 Some(Value::String(group)) => Some(Concurrency { group: group.clone(), cancel_in_progress: Value::Bool(false) }),
850 Some(Value::Object(spec)) => text(spec.get("group")).map(|group| Concurrency {
851 group,
852 cancel_in_progress: spec.get("cancel-in-progress").cloned().unwrap_or(Value::Bool(false)),
853 }),
854 _ => None,
855 }
856}
857
858/// The longest a job on g1t's own machines may run, whatever its
859/// `timeout-minutes`.
860pub const HOSTED_MAX_TIMEOUT_MINUTES: u32 = 60;
861/// How long a job may run when it names no `timeout-minutes`, as on GitHub.
862pub const DEFAULT_TIMEOUT_MINUTES: u32 = 360;
863
864/// What to say about `permissions` names GitHub has that g1t's token has
865/// nothing behind.
866fn permission_notes(unknown: &[String], job: Option<&str>, note: &mut impl FnMut(Severity, Option<&str>, String)) {
867 for name in unknown {
868 note(Severity::Warning, job, format!("`permissions.{name}`: g1t's token has nothing behind that permission yet, so it grants nothing."));
869 }
870}
871
872/// What to say about an action g1t runs differently, if anything.
873fn action_note(uses: &str) -> Option<(Severity, String)> {
874 if uses.starts_with("docker://") {
875 return Some((Severity::Info, format!("`{uses}` runs in Docker (on g1t's machines, the job's own Engine).")));
876 }
877 let name = uses.split('@').next().unwrap_or(uses).to_ascii_lowercase();
878 match name.as_str() {
879 "actions/checkout" => Some((Severity::Info, "`actions/checkout` checks out from g1t.".to_owned())),
880 "actions/cache" | "actions/cache/restore" | "actions/cache/save" => Some((
881 Severity::Info,
882 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."),
883 )),
884 "actions/upload-artifact" | "actions/download-artifact" => Some((
885 Severity::Info,
886 format!("`{name}`: g1t keeps artifacts with the run for 14 days unless the repository says otherwise, up to 5 GiB each."),
887 )),
888 _ => None,
889 }
890}
891
892#[cfg(test)]
893mod tests {
894 use super::*;
895
896 const CI: &str = r#"
897name: CI
898on:
899 push:
900 branches: [main]
901 paths-ignore: ["docs/**"]
902 pull_request:
903 workflow_dispatch:
904 inputs:
905 debug:
906 type: boolean
907 default: false
908 schedule:
909 - cron: "0 3 * * *"
910concurrency:
911 group: ci-${{ github.ref }}
912 cancel-in-progress: true
913env:
914 CARGO_TERM_COLOR: always
915jobs:
916 test:
917 runs-on: ${{ matrix.os }}
918 strategy:
919 matrix:
920 os: [ubuntu-latest, windows-latest]
921 node: [22, 24]
922 steps:
923 - uses: actions/checkout@v7
924 - uses: actions/setup-node@v7
925 with:
926 node-version: ${{ matrix.node }}
927 - run: npm ci
928 - name: Test
929 run: npm test
930 deploy:
931 needs: test
932 if: github.ref == 'refs/heads/main'
933 runs-on: ubuntu-latest
934 steps:
935 - run: echo deploy
936"#;
937
938 #[test]
939 fn a_whole_workflow_reads() {
940 let workflow = parse(CI).unwrap();
941 assert_eq!(workflow.name.as_deref(), Some("CI"));
942 assert_eq!(workflow.triggers.iter().map(|t| t.event.as_str()).collect::<Vec<_>>(), ["push", "pull_request", "workflow_dispatch", "schedule"]);
943 let push = workflow.trigger("push").unwrap();
944 assert!(push.branches.allows("main"));
945 assert!(!push.branches.allows("dev"));
946 assert!(!push.paths.allows_paths(&["docs/a.md".into()]));
947 assert_eq!(workflow.trigger("schedule").unwrap().crons, ["0 3 * * *"]);
948 assert!(workflow.trigger("workflow_dispatch").unwrap().inputs.contains_key("debug"));
949 assert_eq!(workflow.concurrency.as_ref().unwrap().group, "ci-${{ github.ref }}");
950 assert_eq!(workflow.jobs.len(), 2);
951 assert_eq!(workflow.jobs[1].needs, ["test"]);
952 assert_eq!(workflow.jobs[0].steps[0].title(), "Run actions/checkout@v7");
953 assert_eq!(workflow.jobs[0].steps[2].title(), "Run npm ci");
954 assert_eq!(workflow.jobs[0].steps[3].title(), "Test");
955 assert_eq!(workflow.job_order(), ["test", "deploy"]);
956 assert_eq!(workflow.env["CARGO_TERM_COLOR"], "always");
957 }
958
959 #[test]
960 fn short_forms_of_on() {
961 let one = parse("on: push\njobs:\n a:\n runs-on: ubuntu-latest\n steps: [{ run: 'true' }]").unwrap();
962 assert_eq!(one.triggers[0].event, "push");
963 let list = parse("on: [push, pull_request]\njobs:\n a:\n runs-on: ubuntu-latest\n steps: [{ run: 'true' }]").unwrap();
964 assert_eq!(list.triggers.len(), 2);
965 let pr = list.trigger("pull_request").unwrap();
966 assert!(pr.wants_type(Some("opened")));
967 assert!(pr.wants_type(Some("synchronize")));
968 assert!(!pr.wants_type(Some("closed")));
969 assert!(pr.wants_type(Some("ready_for_review")));
970 let typed = parse("on:\n pull_request:\n types: [closed]\njobs:\n a:\n runs-on: ubuntu-latest\n steps: [{ run: 'true' }]").unwrap();
971 assert!(typed.trigger("pull_request").unwrap().wants_type(Some("closed")));
972 assert!(!typed.trigger("pull_request").unwrap().wants_type(Some("opened")));
973 }
974
975 #[test]
976 fn notes_say_what_runs_differently() {
977 let workflow = parse(
978 "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",
979 )
980 .unwrap();
981 let unsupported: Vec<&str> =
982 workflow.notes.iter().filter(|n| n.severity == Severity::Unsupported).map(|n| n.message.as_str()).collect();
983 assert!(unsupported.iter().any(|m| m.contains("`watch`")));
984 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();
985 assert!(!released.notes.iter().any(|n| n.severity == Severity::Unsupported));
986 assert!(released.trigger("release").unwrap().wants_type(Some("published")));
987 assert!(!released.trigger("release").unwrap().wants_type(Some("created")));
988 assert!(released.trigger("deployment_status").unwrap().wants_type(Some("created")));
989 assert!(unsupported.iter().any(|m| m.contains("windows-latest")));
990 assert!(!unsupported.iter().any(|m| m.contains("services")));
991 assert!(!unsupported.iter().any(|m| m.contains("docker://alpine")));
992 assert!(workflow.notes.iter().any(|n| n.severity == Severity::Info && n.message.contains("own Docker Engine") && n.message.contains("localhost")));
993 assert!(workflow.notes.iter().any(|n| n.severity == Severity::Info && n.message.starts_with("`docker://alpine`")));
994 assert!(unsupported.iter().any(|m| m.contains("pwsh")));
995 assert!(workflow.notes.iter().any(|n| n.severity == Severity::Info && n.message.contains("actions/cache")));
996 // Toolkit caches work on g1t, so `setup-node` with `cache:` says nothing.
997 assert!(!workflow.notes.iter().any(|n| n.message.contains("actions/setup-node")));
998 assert!(workflow.notes.iter().any(|n| n.message.contains("2 GiB an entry")));
999 }
1000
1001 #[test]
1002 fn notes_say_what_g1ts_machines_change_about_a_job() {
1003 let workflow = parse(
1004 "on: push\njobs:\n arm:\n runs-on: ubuntu-24.04-arm\n timeout-minutes: 90\n steps: [{ run: 'true' }]\n call:\n uses: ./.g1t/workflows/build.yml\n strategy:\n matrix: { os: [a, b] }\n short:\n runs-on: ubuntu-latest\n timeout-minutes: 30\n steps: [{ run: 'true' }]\n mine:\n runs-on: [self-hosted, arm64]\n timeout-minutes: 300\n steps: [{ run: 'true' }]",
1005 )
1006 .unwrap();
1007 let warned = |job: &str, text: &str| {
1008 workflow.notes.iter().any(|n| n.severity == Severity::Warning && n.job.as_deref() == Some(job) && n.message.contains(text))
1009 };
1010 assert!(warned("arm", "runs on x64"));
1011 assert!(warned("arm", "stopped at 60 minutes"));
1012 assert!(!workflow.notes.iter().any(|n| n.job.as_deref() == Some("call") && n.severity == Severity::Warning));
1013 assert!(!workflow.notes.iter().any(|n| matches!(n.job.as_deref(), Some("short" | "mine")) && n.severity == Severity::Warning));
1014 let artifacts = parse("on: push\njobs:\n a:\n runs-on: ubuntu-latest\n steps: [{ uses: actions/upload-artifact@v4 }]").unwrap();
1015 assert!(artifacts.notes.iter().any(|n| n.message.contains("5 GiB each")));
1016 }
1017
1018 #[test]
1019 fn self_hosted_jobs_may_run_on_any_os() {
1020 let workflow = parse(
1021 "on: push
1022jobs:
1023 win:
1024 runs-on: [self-hosted, windows]
1025 steps:
1026 - run: dir
1027 shell: pwsh
1028 mac:
1029 runs-on: { group: Macs, labels: [macos] }
1030 steps: [{ run: 'true' }]",
1031 )
1032 .unwrap();
1033 assert!(!workflow.notes.iter().any(|n| n.severity == Severity::Unsupported), "{:?}", workflow.notes);
1034 let routed: Vec<&str> = workflow.notes.iter().filter(|n| n.message.starts_with("`self-hosted`")).map(|n| n.message.as_str()).collect();
1035 assert_eq!(routed.len(), 2);
1036 assert!(routed.iter().all(|m| m.contains("self-hosted runners") && !m.contains("Linux")));
1037 }
1038
1039 #[test]
1040 fn permissions_are_read_at_both_levels() {
1041 use crate::permissions::{Access, TokenDefault};
1042 let workflow = parse(
1043 "on: push
1044permissions:
1045 contents: read
1046 pull-requests: write
1047jobs:
1048 plain:
1049 runs-on: ubuntu-latest
1050 steps: [{ run: 'true' }]
1051 release:
1052 runs-on: ubuntu-latest
1053 permissions:
1054 contents: write
1055 steps: [{ run: 'true' }]
1056 quiet:
1057 runs-on: ubuntu-latest
1058 permissions: {}
1059 steps: [{ run: 'true' }]",
1060 )
1061 .unwrap();
1062 let plain = workflow.jobs[0].permissions(&workflow, TokenDefault::Restricted);
1063 assert_eq!(plain.get("pull-requests"), Access::Write);
1064 assert_eq!(plain.get("contents"), Access::Read);
1065 // A job's own permissions replace the workflow's whole.
1066 let release = workflow.jobs[1].permissions(&workflow, TokenDefault::Permissive);
1067 assert_eq!(release.get("contents"), Access::Write);
1068 assert_eq!(release.get("pull-requests"), Access::None);
1069 assert_eq!(workflow.jobs[2].permissions(&workflow, TokenDefault::Permissive).scopes(), ["repo:read"]);
1070 // Without any, the repository's default.
1071 let bare = parse("on: push\njobs:\n a:\n runs-on: ubuntu-latest\n steps: [{ run: 'true' }]").unwrap();
1072 assert_eq!(bare.jobs[0].permissions(&bare, TokenDefault::Restricted).get("contents"), Access::Read);
1073 assert_eq!(bare.jobs[0].permissions(&bare, TokenDefault::Restricted).get("issues"), Access::None);
1074 assert_eq!(bare.jobs[0].permissions(&bare, TokenDefault::Permissive).get("issues"), Access::Write);
1075 // What reads but grants nothing is said.
1076 let odd = parse("on: push\npermissions: { id-token: write, artifact-metadata: read }\njobs:\n a:\n runs-on: x\n steps: [{ run: 'true' }]").unwrap();
1077 assert!(!odd.notes.iter().any(|n| n.message.contains("id-token")), "OIDC tokens are issued");
1078 assert!(odd.notes.iter().any(|n| n.severity == Severity::Warning && n.message.contains("`permissions.artifact-metadata`")));
1079 // A name GitHub's token does not have is refused, as GitHub does;
1080 // `metadata` is always `read` and cannot be written.
1081 for name in ["wiki", "metadata"] {
1082 let problem = parse(&format!("on: push\npermissions: {{ {name}: read }}\njobs:\n a:\n runs-on: x\n steps: [{{ run: 'true' }}]")).unwrap_err();
1083 assert!(problem.contains(&format!("Unexpected `{name}` in `permissions`")), "{problem}");
1084 }
1085 assert!(parse("on: push\npermissions: read\njobs:\n a:\n runs-on: x\n steps: [{ run: 'true' }]").unwrap_err().contains("read-all"));
1086 assert!(
1087 parse("on: push\njobs:\n a:\n runs-on: x\n permissions: { contents: admin }\n steps: [{ run: 'true' }]")
1088 .unwrap_err()
1089 .contains("Job `a`")
1090 );
1091 }
1092
1093 #[test]
1094 fn a_job_has_its_own_concurrency() {
1095 let workflow = parse(
1096 "on: push
1097jobs:
1098 deploy:
1099 runs-on: ubuntu-latest
1100 concurrency:
1101 group: deploy-${{ github.ref }}
1102 cancel-in-progress: true
1103 steps: [{ run: 'true' }]
1104 named:
1105 runs-on: ubuntu-latest
1106 concurrency: just-one
1107 steps: [{ run: 'true' }]",
1108 )
1109 .unwrap();
1110 let deploy = workflow.jobs[0].concurrency.as_ref().unwrap();
1111 assert_eq!(deploy.group, "deploy-${{ github.ref }}");
1112 assert_eq!(deploy.cancel_in_progress, Value::Bool(true));
1113 assert_eq!(workflow.jobs[1].concurrency.as_ref().unwrap().group, "just-one");
1114 assert!(workflow.concurrency.is_none());
1115 }
1116
1117 #[test]
1118 fn events_g1t_never_sends_are_said_and_pull_request_target_is_the_base() {
1119 let workflow = parse("on: [create, delete, repository_dispatch, pull_request_target]\njobs:\n a:\n runs-on: x\n steps: [{ run: 'true' }]").unwrap();
1120 let unsupported: Vec<&str> = workflow.notes.iter().filter(|n| n.severity == Severity::Unsupported).map(|n| n.message.as_str()).collect();
1121 assert_eq!(unsupported.len(), 1, "{unsupported:?}");
1122 assert!(unsupported[0].contains("`delete`"));
1123 let target = workflow.notes.iter().find(|n| n.message.starts_with("`pull_request_target`")).unwrap();
1124 assert!(target.message.contains("default branch"));
1125 assert!(!target.message.contains("on the pull request's head"));
1126 }
1127
1128 #[test]
1129 fn mistakes_are_explained() {
1130 let problem = |yaml: &str| parse(yaml).unwrap_err();
1131 assert!(problem("jobs: {}").contains("`on` is missing"));
1132 assert!(problem("on: push").contains("`jobs` is missing"));
1133 assert!(problem("on: push\njobs:\n a:\n runs-on: x").contains("no `steps`"));
1134 assert!(problem("on: push\njobs:\n a:\n runs-on: x\n steps: [{ name: nothing }]").contains("`uses` or `run`"));
1135 assert!(problem("on: push\njobs:\n a:\n needs: b\n runs-on: x\n steps: [{ run: x }]").contains("no job called that"));
1136 assert!(
1137 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 }]")
1138 .contains("circle")
1139 );
1140 assert!(problem("on: push\njobs: [1]").contains("`jobs`"));
1141 assert!(problem(": : :").contains("not valid YAML"));
1142 }
1143
1144 #[test]
1145 fn only_githubs_keys_and_g1ts_own() {
1146 let problem = |yaml: &str| parse(yaml).unwrap_err();
1147 let job = "\njobs:\n build:\n runs-on: x\n steps: [{ run: 'true' }]";
1148 assert!(problem(&format!("on: push\nrun_name: x{job}")).starts_with("Unexpected `run_name` in the workflow; it can have `on`, "));
1149 assert!(problem("on: push\njobs:\n build:\n runs-on: x\n step: []").starts_with("Job `build`: unexpected `step` in a job;"));
1150 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");
1151 assert!(step.starts_with("Job `build`, step 2: unexpected `shell` in a step that uses an action;"), "{step}");
1152 assert!(problem("on: push\njobs:\n build:\n steps: [{ run: 'true' }]").contains("no `runs-on`"));
1153 assert!(problem("on: push\njobs:\n build:\n uses: ./.g1t/workflows/b.yml\n runs-on: x").contains("no `runs-on`"));
1154 assert!(problem("on: push\njobs:\n my.job:\n runs-on: x\n steps: [{ run: 'true' }]").contains("`my.job` is not a job id"));
1155 assert!(problem("on: pushh\njobs:\n a:\n runs-on: x\n steps: [{ run: 'true' }]").contains("no `pushh` event"));
1156
1157 // `g1t` is g1t's own, at each level, and kept as written.
1158 let workflow = parse(
1159 "on: push
1160g1t: { note: top }
1161jobs:
1162 deploy:
1163 runs-on: x
1164 environment: production
1165 g1t: { deployment: false }
1166 steps:
1167 - run: 'true'
1168 g1t: { anything: [1, 2] }",
1169 )
1170 .unwrap();
1171 assert_eq!(workflow.g1t, Some(serde_json::json!({ "note": "top" })));
1172 assert_eq!(workflow.jobs[0].g1t, Some(serde_json::json!({ "deployment": false })));
1173 assert_eq!(workflow.jobs[0].steps[0].g1t, Some(serde_json::json!({ "anything": [1, 2] })));
1174 assert!(problem(&format!("on: push\ng1t: yes{job}")).contains("`g1t` is a mapping"));
1175 assert!(!records_deployment(&workflow.jobs[0].raw));
1176 assert!(!records_deployment(&serde_json::json!({ "environment": { "name": "p", "deployment": false } })));
1177 assert!(records_deployment(&serde_json::json!({ "environment": { "name": "p", "deployment": true } })));
1178 assert!(records_deployment(&serde_json::json!({ "environment": "p" })));
1179 }
1180
1181 #[test]
1182 fn aliases_read_and_merge_keys_do_not() {
1183 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();
1184 assert_eq!(aliased.jobs[1].steps.len(), 1);
1185 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();
1186 assert!(merged.contains("merge key"), "{merged}");
1187 }
1188}