flowey_core/pipeline.rs
1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Core types and traits used to create and work with flowey pipelines.
5
6mod artifact;
7
8pub use artifact::Artifact;
9pub use artifact::ArtifactType;
10pub use artifact::resolve;
11
12use self::internal::*;
13use crate::node::FlowArch;
14use crate::node::FlowNodeBase;
15use crate::node::FlowPlatform;
16use crate::node::FlowPlatformLinuxDistro;
17use crate::node::GhUserSecretVar;
18use crate::node::IntoConfig;
19use crate::node::IntoRequest;
20use crate::node::NodeHandle;
21use crate::node::ReadVar;
22use crate::node::WriteVar;
23use crate::node::steps::ado::AdoResourcesRepositoryId;
24use crate::node::user_facing::AdoRuntimeVar;
25use crate::node::user_facing::GhPermission;
26use crate::node::user_facing::GhPermissionValue;
27use crate::patch::PatchResolver;
28use crate::patch::ResolvedPatches;
29use serde::Serialize;
30use serde::de::DeserializeOwned;
31use std::collections::BTreeMap;
32use std::collections::BTreeSet;
33use std::path::PathBuf;
34
35/// Pipeline types which are considered "user facing", and included in the
36/// `flowey` prelude.
37pub mod user_facing {
38 pub use super::AdoCiTriggers;
39 pub use super::AdoPool;
40 pub use super::AdoPrTriggers;
41 pub use super::AdoResourcesRepository;
42 pub use super::AdoResourcesRepositoryRef;
43 pub use super::AdoResourcesRepositoryType;
44 pub use super::AdoScheduleTriggers;
45 pub use super::GhCiTriggers;
46 pub use super::GhConcurrencyGroup;
47 pub use super::GhPrTriggers;
48 pub use super::GhRunner;
49 pub use super::GhRunnerOsLabel;
50 pub use super::GhScheduleTriggers;
51 pub use super::HostExt;
52 pub use super::IntoPipeline;
53 pub use super::ParameterKind;
54 pub use super::Pipeline;
55 pub use super::PipelineBackendHint;
56 pub use super::PipelineJob;
57 pub use super::PipelineJobCtx;
58 pub use super::PipelineJobHandle;
59 pub use super::PublishArtifact;
60 pub use super::PublishTypedArtifact;
61 pub use super::UseArtifact;
62 pub use super::UseParameter;
63 pub use super::UseTypedArtifact;
64 pub use crate::node::FlowArch;
65 pub use crate::node::FlowPlatform;
66}
67
68fn linux_distro() -> FlowPlatformLinuxDistro {
69 // Check for nix environment first - takes precedence over distro detection
70 if std::env::var("IN_NIX_SHELL").is_ok() {
71 return FlowPlatformLinuxDistro::Nix;
72 }
73
74 // A `nix develop` shell doesn't set `IN_NIX_SHELL`, but the PATH should include a nix store path
75 if std::env::var("PATH").is_ok_and(|path| path.contains("/nix/store")) {
76 return FlowPlatformLinuxDistro::Nix;
77 }
78
79 if let Ok(etc_os_release) = fs_err::read_to_string("/etc/os-release") {
80 if etc_os_release.contains("ID=ubuntu") {
81 FlowPlatformLinuxDistro::Ubuntu
82 } else if etc_os_release.contains("ID=fedora") {
83 FlowPlatformLinuxDistro::Fedora
84 } else if etc_os_release.contains("ID=azurelinux") || etc_os_release.contains("ID=mariner")
85 {
86 FlowPlatformLinuxDistro::AzureLinux
87 } else if etc_os_release.contains("ID=arch") {
88 FlowPlatformLinuxDistro::Arch
89 } else if etc_os_release
90 .lines()
91 .find_map(|line| line.strip_prefix("ID="))
92 .is_some_and(|id| id.trim_matches(['"', '\'']).starts_with("opensuse"))
93 {
94 FlowPlatformLinuxDistro::OpenSuse
95 } else {
96 FlowPlatformLinuxDistro::Unknown
97 }
98 } else {
99 FlowPlatformLinuxDistro::Unknown
100 }
101}
102
103pub trait HostExt: Sized {
104 /// Return the value for the current host machine.
105 ///
106 /// Will panic on non-local backends.
107 fn host(backend_hint: PipelineBackendHint) -> Self;
108}
109
110impl HostExt for FlowPlatform {
111 /// Return the platform of the current host machine.
112 ///
113 /// Will panic on non-local backends.
114 fn host(backend_hint: PipelineBackendHint) -> Self {
115 if !matches!(backend_hint, PipelineBackendHint::Local) {
116 panic!("can only use `FlowPlatform::host` when defining a local-only pipeline");
117 }
118
119 if cfg!(target_os = "windows") {
120 Self::Windows
121 } else if cfg!(target_os = "linux") {
122 Self::Linux(linux_distro())
123 } else if cfg!(target_os = "macos") {
124 Self::MacOs
125 } else {
126 panic!("no valid host-os")
127 }
128 }
129}
130
131impl HostExt for FlowArch {
132 /// Return the arch of the current host machine.
133 ///
134 /// Will panic on non-local backends.
135 fn host(backend_hint: PipelineBackendHint) -> Self {
136 if !matches!(backend_hint, PipelineBackendHint::Local) {
137 panic!("can only use `FlowArch::host` when defining a local-only pipeline");
138 }
139
140 cfg_select! {
141 // xtask-fmt allow-target-arch oneoff-flowey
142 target_arch = "x86_64" => Self::X86_64,
143 // xtask-fmt allow-target-arch oneoff-flowey
144 target_arch = "aarch64" => Self::Aarch64,
145 }
146 }
147}
148
149/// Trigger ADO pipelines via Continuous Integration
150#[derive(Default, Debug)]
151pub struct AdoScheduleTriggers {
152 /// Friendly name for the scheduled run
153 pub display_name: String,
154 /// Run the pipeline whenever there is a commit on these specified branches
155 /// (supports glob syntax)
156 pub branches: Vec<String>,
157 /// Specify any branches which should be filtered out from the list of
158 /// `branches` (supports glob syntax)
159 pub exclude_branches: Vec<String>,
160 /// Run the pipeline in a schedule, as specified by a cron string
161 pub cron: String,
162}
163
164/// Trigger ADO pipelines per PR
165#[derive(Debug)]
166pub struct AdoPrTriggers {
167 /// Run the pipeline whenever there is a PR to these specified branches
168 /// (supports glob syntax)
169 pub branches: Vec<String>,
170 /// Specify any branches which should be filtered out from the list of
171 /// `branches` (supports glob syntax)
172 pub exclude_branches: Vec<String>,
173 /// Run the pipeline even if the PR is a draft PR. Defaults to `false`.
174 pub run_on_draft: bool,
175 /// Automatically cancel the pipeline run if a new commit lands in the
176 /// branch. Defaults to `true`.
177 pub auto_cancel: bool,
178 /// Only run the pipeline when files matching these paths are changed
179 /// (supports glob syntax)
180 pub paths: Vec<String>,
181 /// Specify any paths which should be filtered out from the list of
182 /// `paths` (supports glob syntax)
183 pub exclude_paths: Vec<String>,
184}
185
186/// Trigger ADO pipelines per CI
187#[derive(Debug, Default)]
188pub struct AdoCiTriggers {
189 /// Run the pipeline whenever there is a change to these specified branches
190 /// (supports glob syntax)
191 pub branches: Vec<String>,
192 /// Specify any branches which should be filtered out from the list of
193 /// `branches` (supports glob syntax)
194 pub exclude_branches: Vec<String>,
195 /// Run the pipeline whenever a matching tag is created (supports glob
196 /// syntax)
197 pub tags: Vec<String>,
198 /// Specify any tags which should be filtered out from the list of `tags`
199 /// (supports glob syntax)
200 pub exclude_tags: Vec<String>,
201 /// Whether to batch changes per branch.
202 pub batch: bool,
203 /// Only run the pipeline when files matching these paths are changed
204 /// (supports glob syntax)
205 pub paths: Vec<String>,
206 /// Specify any paths which should be filtered out from the list of
207 /// `paths` (supports glob syntax)
208 pub exclude_paths: Vec<String>,
209}
210
211impl Default for AdoPrTriggers {
212 fn default() -> Self {
213 Self {
214 branches: Vec::new(),
215 exclude_branches: Vec::new(),
216 run_on_draft: false,
217 auto_cancel: true,
218 paths: Vec::new(),
219 exclude_paths: Vec::new(),
220 }
221 }
222}
223
224/// ADO repository resource.
225#[derive(Debug)]
226pub struct AdoResourcesRepository {
227 /// Type of repo that is being connected to.
228 pub repo_type: AdoResourcesRepositoryType,
229 /// Repository name. Format depends on `repo_type`.
230 pub name: String,
231 /// git ref to checkout.
232 pub git_ref: AdoResourcesRepositoryRef,
233 /// (optional) ID of the service endpoint connecting to this repository.
234 pub endpoint: Option<String>,
235}
236
237/// ADO repository resource type
238#[derive(Debug)]
239pub enum AdoResourcesRepositoryType {
240 /// Azure Repos Git repository
241 AzureReposGit,
242 /// Github repository
243 GitHub,
244}
245
246/// ADO repository ref
247#[derive(Debug)]
248pub enum AdoResourcesRepositoryRef<P = UseParameter<String>> {
249 /// Hard-coded ref (e.g: refs/heads/main)
250 Fixed(String),
251 /// Connected to pipeline-level parameter
252 Parameter(P),
253}
254
255/// Trigger Github Actions pipelines via Continuous Integration
256///
257/// NOTE: Github Actions doesn't support specifying the branch when triggered by `schedule`.
258/// To run on a specific branch, modify the branch checked out in the pipeline.
259#[derive(Default, Debug)]
260pub struct GhScheduleTriggers {
261 /// Run the pipeline in a schedule, as specified by a cron string
262 pub cron: String,
263 /// IANA timezone string
264 pub timezone: Option<String>,
265}
266
267/// Trigger Github Actions pipelines per PR
268#[derive(Debug)]
269pub struct GhPrTriggers {
270 /// Run the pipeline whenever there is a PR to these specified branches
271 /// (supports glob syntax)
272 pub branches: Vec<String>,
273 /// Specify any branches which should be filtered out from the list of
274 /// `branches` (supports glob syntax)
275 pub exclude_branches: Vec<String>,
276 /// Automatically cancel the pipeline run if a new commit lands in the
277 /// branch. Defaults to `true`.
278 pub auto_cancel: bool,
279 /// Run the pipeline whenever the PR trigger matches the specified types
280 pub types: Vec<String>,
281 /// Only run the pipeline when files matching these paths are changed
282 /// (supports glob syntax)
283 pub paths: Vec<String>,
284 /// Specify any paths which should be filtered out from the list of
285 /// `paths` (supports glob syntax)
286 pub paths_ignore: Vec<String>,
287}
288
289/// Trigger Github Actions pipelines per PR
290#[derive(Debug, Default)]
291pub struct GhCiTriggers {
292 /// Run the pipeline whenever there is a change to these specified branches
293 /// (supports glob syntax)
294 pub branches: Vec<String>,
295 /// Specify any branches which should be filtered out from the list of
296 /// `branches` (supports glob syntax)
297 pub exclude_branches: Vec<String>,
298 /// Run the pipeline whenever a matching tag is created (supports glob
299 /// syntax)
300 pub tags: Vec<String>,
301 /// Specify any tags which should be filtered out from the list of `tags`
302 /// (supports glob syntax)
303 pub exclude_tags: Vec<String>,
304 /// Only run the pipeline when files matching these paths are changed
305 /// (supports glob syntax)
306 pub paths: Vec<String>,
307 /// Specify any paths which should be filtered out from the list of
308 /// `paths` (supports glob syntax)
309 pub paths_ignore: Vec<String>,
310 /// If set, only one pipeline run in this concurrency group runs at a time.
311 pub concurrency_group: Option<GhConcurrencyGroup>,
312}
313
314/// Settings for a Github concurrency group.
315#[derive(Debug, Default, Clone)]
316pub struct GhConcurrencyGroup {
317 /// The name of the concurrency group.
318 pub name: String,
319 /// Cancel the active run when a new run joins the concurrency group.
320 /// Defaults to `false`.
321 pub cancel_in_progress: bool,
322}
323
324impl GhPrTriggers {
325 /// Triggers the pipeline on the default PR events plus when a draft is marked as ready for review.
326 pub fn new_draftable() -> Self {
327 Self {
328 branches: Vec::new(),
329 exclude_branches: Vec::new(),
330 types: vec![
331 "opened".into(),
332 "synchronize".into(),
333 "reopened".into(),
334 "ready_for_review".into(),
335 ],
336 auto_cancel: true,
337 paths: Vec::new(),
338 paths_ignore: Vec::new(),
339 }
340 }
341}
342
343#[derive(Debug, Clone, PartialEq)]
344pub enum GhRunnerOsLabel {
345 UbuntuLatest,
346 Ubuntu2404,
347 Ubuntu2204,
348 WindowsLatest,
349 Windows2025,
350 Windows2022,
351 Ubuntu2404Arm,
352 Ubuntu2204Arm,
353 Windows11Arm,
354 Custom(String),
355}
356
357/// GitHub runner type
358#[derive(Debug, Clone, PartialEq)]
359pub enum GhRunner {
360 // See <https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#choosing-github-hosted-runners>
361 // for more details.
362 GhHosted(GhRunnerOsLabel),
363 // Self hosted runners are selected by matching runner labels to <labels>.
364 // 'self-hosted' is a common label for self hosted runners, but is not required.
365 // Labels are case-insensitive and can take the form of arbitrary strings.
366 // See <https://docs.github.com/en/actions/hosting-your-own-runners> for more details.
367 SelfHosted(Vec<String>),
368 // This uses a runner belonging to <group> that matches all labels in <labels>.
369 // See <https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#choosing-github-hosted-runners>
370 // for more details.
371 RunnerGroup { group: String, labels: Vec<String> },
372}
373
374impl GhRunner {
375 /// Whether this is a self-hosted runner with the provided label
376 pub fn is_self_hosted_with_label(&self, label: &str) -> bool {
377 matches!(self, GhRunner::SelfHosted(labels) if labels.iter().any(|s| s.as_str() == label))
378 }
379}
380
381// TODO: support a more structured format for demands
382// See https://learn.microsoft.com/en-us/azure/devops/pipelines/yaml-schema/pool-demands
383#[derive(Debug, Clone)]
384pub struct AdoPool {
385 pub name: String,
386 pub demands: Vec<String>,
387}
388
389/// Parameter type (unstable / stable).
390#[derive(Debug, Clone)]
391pub enum ParameterKind {
392 // The parameter is considered an unstable API, and should not be
393 // taken as a dependency.
394 Unstable,
395 // The parameter is considered a stable API, and can be used by
396 // external pipelines to control behavior of the pipeline.
397 Stable,
398}
399
400#[derive(Clone, Debug)]
401#[must_use]
402pub struct UseParameter<T> {
403 idx: usize,
404 _kind: std::marker::PhantomData<T>,
405}
406
407/// Opaque handle to an artifact which must be published by a single job.
408#[must_use]
409pub struct PublishArtifact {
410 idx: usize,
411}
412
413/// Opaque handle to an artifact which can be used by one or more jobs.
414#[derive(Clone)]
415#[must_use]
416pub struct UseArtifact {
417 idx: usize,
418}
419
420/// Opaque handle to an artifact of type `T` which must be published by a single job.
421#[must_use]
422pub struct PublishTypedArtifact<T>(PublishArtifact, std::marker::PhantomData<fn() -> T>);
423
424/// Opaque handle to an artifact of type `T` which can be used by one or more
425/// jobs.
426#[must_use]
427pub struct UseTypedArtifact<T>(UseArtifact, std::marker::PhantomData<fn(T)>);
428
429impl<T> Clone for UseTypedArtifact<T> {
430 fn clone(&self) -> Self {
431 UseTypedArtifact(self.0.clone(), std::marker::PhantomData)
432 }
433}
434
435#[derive(Default)]
436pub struct Pipeline {
437 jobs: Vec<PipelineJobMetadata>,
438 artifacts: Vec<ArtifactMeta>,
439 parameters: Vec<ParameterMeta>,
440 extra_deps: BTreeSet<(usize, usize)>,
441 // builder internal
442 artifact_names: BTreeSet<String>,
443 dummy_done_idx: usize,
444 artifact_map_idx: usize,
445 global_patchfns: Vec<crate::patch::PatchFn>,
446 inject_all_jobs_with: Option<Box<dyn for<'a> Fn(PipelineJob<'a>) -> PipelineJob<'a>>>,
447 // backend specific
448 ado_name: Option<String>,
449 ado_job_id_overrides: BTreeMap<usize, String>,
450 ado_schedule_triggers: Vec<AdoScheduleTriggers>,
451 ado_ci_triggers: Option<AdoCiTriggers>,
452 ado_pr_triggers: Option<AdoPrTriggers>,
453 ado_resources_repository: Vec<InternalAdoResourcesRepository>,
454 ado_bootstrap_template: Option<Box<AdoBootstrapTemplate>>,
455 ado_variables: BTreeMap<String, String>,
456 ado_post_process_yaml_cb: Option<Box<dyn FnOnce(serde_yaml::Value) -> serde_yaml::Value>>,
457 gh_name: Option<String>,
458 gh_schedule_triggers: Vec<GhScheduleTriggers>,
459 gh_ci_triggers: Option<GhCiTriggers>,
460 gh_pr_triggers: Option<GhPrTriggers>,
461 gh_bootstrap_template: Option<Box<GhBootstrapTemplate>>,
462}
463
464impl Pipeline {
465 pub fn new() -> Pipeline {
466 Pipeline::default()
467 }
468
469 /// Inject all pipeline jobs with some common logic. (e.g: to resolve common
470 /// configuration requirements shared by all jobs).
471 ///
472 /// Can only be invoked once per pipeline.
473 #[track_caller]
474 pub fn inject_all_jobs_with(
475 &mut self,
476 cb: impl for<'a> Fn(PipelineJob<'a>) -> PipelineJob<'a> + 'static,
477 ) -> &mut Self {
478 if self.inject_all_jobs_with.is_some() {
479 panic!("can only call inject_all_jobs_with once!")
480 }
481 self.inject_all_jobs_with = Some(Box::new(cb));
482 self
483 }
484
485 /// (ADO only) Provide a callback to provide a job-specific YAML template used to bootstrap flowey at the start
486 /// of an ADO pipeline.
487 ///
488 /// The callback receives the job's platform and architecture and is invoked
489 /// for each job that builds flowey, but not jobs that consume a prebuilt
490 /// binary.
491 ///
492 /// The template has access to the following vars, which will be statically
493 /// interpolated into the template's text:
494 ///
495 /// - `{{FLOWEY_OUTDIR}}`
496 /// - Directory to copy artifacts into.
497 /// - NOTE: this var will include `\` on Windows, and `/` on linux!
498 /// - `{{FLOWEY_BIN_EXTENSION}}`
499 /// - Extension of the expected flowey bin (either "", or ".exe")
500 /// - `{{FLOWEY_CRATE}}`
501 /// - Name of the project-specific flowey crate to be built
502 /// - `{{FLOWEY_TARGET}}`
503 /// - The target-triple flowey is being built for
504 /// - `{{FLOWEY_PIPELINE_PATH}}`
505 /// - Repo-root relative path to the pipeline (as provided when
506 /// generating the pipeline via the flowey CLI)
507 ///
508 /// The template's sole responsibility is to copy 3 files into the
509 /// `{{FLOWEY_OUTDIR}}`:
510 ///
511 /// 1. The bootstrapped flowey binary, with the file name
512 /// `flowey{{FLOWEY_BIN_EXTENSION}}`
513 /// 2. Two files called `pipeline.yaml` and `pipeline.json`, which are
514 /// copied of the pipeline YAML and pipeline JSON currently being run.
515 /// `{{FLOWEY_PIPELINE_PATH}}` is provided as a way to disambiguate in
516 /// cases where the same template is being for multiple pipelines (e.g: a
517 /// debug vs. release pipeline).
518 pub fn ado_set_flowey_bootstrap_template_fn(
519 &mut self,
520 template: impl Fn(FlowPlatform, FlowArch) -> anyhow::Result<String> + 'static,
521 ) -> &mut Self {
522 self.ado_bootstrap_template = Some(Box::new(template));
523 self
524 }
525
526 /// (ADO only) Provide a callback function which will be used to
527 /// post-process any YAML flowey generates for the pipeline.
528 ///
529 /// Until flowey defines a stable API for maintaining out-of-tree backends,
530 /// this method can be used to integrate the output from the generic ADO
531 /// backend with any organization-specific templates that one may be
532 /// required to use (e.g: for compliance reasons).
533 pub fn ado_post_process_yaml(
534 &mut self,
535 cb: impl FnOnce(serde_yaml::Value) -> serde_yaml::Value + 'static,
536 ) -> &mut Self {
537 self.ado_post_process_yaml_cb = Some(Box::new(cb));
538 self
539 }
540
541 /// (ADO only) Add a new scheduled CI trigger. Can be called multiple times
542 /// to set up multiple schedules runs.
543 pub fn ado_add_schedule_trigger(&mut self, triggers: AdoScheduleTriggers) -> &mut Self {
544 self.ado_schedule_triggers.push(triggers);
545 self
546 }
547
548 /// (ADO only) Set a PR trigger. Calling this method multiple times will
549 /// overwrite any previously set triggers.
550 pub fn ado_set_pr_triggers(&mut self, triggers: AdoPrTriggers) -> &mut Self {
551 self.ado_pr_triggers = Some(triggers);
552 self
553 }
554
555 /// (ADO only) Set a CI trigger. Calling this method multiple times will
556 /// overwrite any previously set triggers.
557 pub fn ado_set_ci_triggers(&mut self, triggers: AdoCiTriggers) -> &mut Self {
558 self.ado_ci_triggers = Some(triggers);
559 self
560 }
561
562 /// (ADO only) Declare a new repository resource, returning a type-safe
563 /// handle which downstream ADO steps are able to consume via
564 /// [`AdoStepServices::resolve_repository_id`](crate::node::user_facing::AdoStepServices::resolve_repository_id).
565 pub fn ado_add_resources_repository(
566 &mut self,
567 repo: AdoResourcesRepository,
568 ) -> AdoResourcesRepositoryId {
569 let AdoResourcesRepository {
570 repo_type,
571 name,
572 git_ref,
573 endpoint,
574 } = repo;
575
576 let repo_id = format!("repo{}", self.ado_resources_repository.len());
577
578 self.ado_resources_repository
579 .push(InternalAdoResourcesRepository {
580 repo_id: repo_id.clone(),
581 repo_type,
582 name,
583 git_ref: match git_ref {
584 AdoResourcesRepositoryRef::Fixed(s) => AdoResourcesRepositoryRef::Fixed(s),
585 AdoResourcesRepositoryRef::Parameter(p) => {
586 AdoResourcesRepositoryRef::Parameter(p.idx)
587 }
588 },
589 endpoint,
590 });
591 AdoResourcesRepositoryId { repo_id }
592 }
593
594 /// (GitHub Actions only) Set the pipeline-level name.
595 ///
596 /// <https://docs.github.com/en/actions/writing-workflows/workflow-syntax-for-github-actions#name>
597 pub fn gh_set_name(&mut self, name: impl AsRef<str>) -> &mut Self {
598 self.gh_name = Some(name.as_ref().into());
599 self
600 }
601
602 /// Provide a callback that provides a job-specific YAML template used to
603 /// bootstrap flowey at the start of a GitHub Actions pipeline.
604 ///
605 /// The callback receives the job's platform and architecture and is invoked
606 /// for each job that builds flowey, but not jobs that consume a prebuilt
607 /// binary.
608 ///
609 /// The template has access to the following vars, which will be statically
610 /// interpolated into the template's text:
611 ///
612 /// - `{{FLOWEY_OUTDIR}}`
613 /// - Directory to copy artifacts into.
614 /// - NOTE: this var will include `\` on Windows, and `/` on linux!
615 /// - `{{FLOWEY_BIN_EXTENSION}}`
616 /// - Extension of the expected flowey bin (either "", or ".exe")
617 /// - `{{FLOWEY_CRATE}}`
618 /// - Name of the project-specific flowey crate to be built
619 /// - `{{FLOWEY_TARGET}}`
620 /// - The target-triple flowey is being built for
621 /// - `{{FLOWEY_PIPELINE_PATH}}`
622 /// - Repo-root relative path to the pipeline (as provided when
623 /// generating the pipeline via the flowey CLI)
624 ///
625 /// The template's sole responsibility is to copy 3 files into the
626 /// `{{FLOWEY_OUTDIR}}`:
627 ///
628 /// 1. The bootstrapped flowey binary, with the file name
629 /// `flowey{{FLOWEY_BIN_EXTENSION}}`
630 /// 2. Two files called `pipeline.yaml` and `pipeline.json`, which are
631 /// copied of the pipeline YAML and pipeline JSON currently being run.
632 /// `{{FLOWEY_PIPELINE_PATH}}` is provided as a way to disambiguate in
633 /// cases where the same template is being for multiple pipelines (e.g: a
634 /// debug vs. release pipeline).
635 pub fn gh_set_flowey_bootstrap_template_fn(
636 &mut self,
637 template: impl Fn(FlowPlatform, FlowArch) -> anyhow::Result<String> + 'static,
638 ) -> &mut Self {
639 self.gh_bootstrap_template = Some(Box::new(template));
640 self
641 }
642
643 /// (GitHub Actions only) Add a new scheduled CI trigger. Can be called multiple times
644 /// to set up multiple schedules runs.
645 pub fn gh_add_schedule_trigger(&mut self, triggers: GhScheduleTriggers) -> &mut Self {
646 self.gh_schedule_triggers.push(triggers);
647 self
648 }
649
650 /// (GitHub Actions only) Set a PR trigger. Calling this method multiple times will
651 /// overwrite any previously set triggers.
652 pub fn gh_set_pr_triggers(&mut self, triggers: GhPrTriggers) -> &mut Self {
653 self.gh_pr_triggers = Some(triggers);
654 self
655 }
656
657 /// (GitHub Actions only) Set a CI trigger. Calling this method multiple times will
658 /// overwrite any previously set triggers.
659 pub fn gh_set_ci_triggers(&mut self, triggers: GhCiTriggers) -> &mut Self {
660 self.gh_ci_triggers = Some(triggers);
661 self
662 }
663
664 /// (GitHub Actions only) Use a pre-defined GitHub Actions secret variable.
665 ///
666 /// For more information on defining secrets for use in GitHub Actions, see
667 /// <https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions>
668 pub fn gh_use_secret(&mut self, secret_name: impl AsRef<str>) -> GhUserSecretVar {
669 GhUserSecretVar(secret_name.as_ref().to_string())
670 }
671
672 pub fn new_job(
673 &mut self,
674 platform: FlowPlatform,
675 arch: FlowArch,
676 label: impl AsRef<str>,
677 ) -> PipelineJob<'_> {
678 let idx = self.jobs.len();
679 self.jobs.push(PipelineJobMetadata {
680 root_nodes: BTreeMap::new(),
681 root_configs: BTreeMap::new(),
682 patches: ResolvedPatches::build(),
683 label: label.as_ref().into(),
684 platform,
685 arch,
686 cond_param_idx: None,
687 timeout_minutes: None,
688 command_wrapper: None,
689 ado_pool: None,
690 ado_variables: BTreeMap::new(),
691 gh_override_if: None,
692 gh_global_env: BTreeMap::new(),
693 gh_pool: None,
694 gh_concurrency_group: None,
695 gh_permissions: BTreeMap::new(),
696 });
697
698 PipelineJob {
699 pipeline: self,
700 job_idx: idx,
701 }
702 }
703
704 /// Declare a dependency between two jobs that does is not a result of an
705 /// artifact.
706 pub fn non_artifact_dep(
707 &mut self,
708 job: &PipelineJobHandle,
709 depends_on_job: &PipelineJobHandle,
710 ) -> &mut Self {
711 self.extra_deps
712 .insert((depends_on_job.job_idx, job.job_idx));
713 self
714 }
715
716 #[track_caller]
717 pub fn new_artifact(&mut self, name: impl AsRef<str>) -> (PublishArtifact, UseArtifact) {
718 let name = name.as_ref();
719 let owned_name = name.to_string();
720
721 let not_exists = self.artifact_names.insert(owned_name.clone());
722 if !not_exists {
723 panic!("duplicate artifact name: {}", name)
724 }
725
726 let idx = self.artifacts.len();
727 self.artifacts.push(ArtifactMeta {
728 name: owned_name,
729 published_by_job: None,
730 used_by_jobs: BTreeSet::new(),
731 });
732
733 (PublishArtifact { idx }, UseArtifact { idx })
734 }
735
736 /// Returns a pair of opaque handles to a new artifact for use across jobs
737 /// in the pipeline.
738 #[track_caller]
739 pub fn new_typed_artifact<T: Artifact>(
740 &mut self,
741 name: impl AsRef<str>,
742 ) -> (PublishTypedArtifact<T>, UseTypedArtifact<T>) {
743 let (publish, use_artifact) = self.new_artifact(name);
744 (
745 PublishTypedArtifact(publish, std::marker::PhantomData),
746 UseTypedArtifact(use_artifact, std::marker::PhantomData),
747 )
748 }
749
750 /// Returns a pair of sets of opaque handles to a new artifact for use
751 /// across jobs in the pipeline. The artifact names are derived by the impl
752 /// of [`ArtifactType::name`] using common prefixes and suffixes if
753 /// specified (although the implementor can choose to use those values
754 /// differently).
755 #[track_caller]
756 pub fn new_typed_artifact_collection<T: Artifact, U: ArtifactType>(
757 &mut self,
758 artifact_types: impl IntoIterator<Item = U>,
759 prefix: Option<&str>,
760 suffix: Option<&str>,
761 ) -> (
762 BTreeMap<U, PublishTypedArtifact<T>>,
763 BTreeMap<U, UseTypedArtifact<T>>,
764 ) {
765 artifact_types
766 .into_iter()
767 .map(|artifact_type| {
768 let (pub_artifact, use_artifact) =
769 self.new_typed_artifact(artifact_type.name(prefix, suffix));
770 (
771 (artifact_type.clone(), pub_artifact),
772 (artifact_type, use_artifact),
773 )
774 })
775 .unzip()
776 }
777
778 /// (ADO only) Set the pipeline-level name.
779 ///
780 /// <https://learn.microsoft.com/en-us/azure/devops/pipelines/process/run-number?view=azure-devops&tabs=yaml>
781 pub fn ado_add_name(&mut self, name: String) -> &mut Self {
782 self.ado_name = Some(name);
783 self
784 }
785
786 /// (ADO only) Declare a pipeline-level, named, read-only ADO variable.
787 ///
788 /// `name` and `value` are both arbitrary strings.
789 ///
790 /// Returns an instance of [`AdoRuntimeVar`], which, if need be, can be
791 /// converted into a [`ReadVar<String>`] using
792 /// [`NodeCtx::get_ado_variable`].
793 ///
794 /// NOTE: Unless required by some particular third-party task, it's strongly
795 /// recommended to _avoid_ using this method, and to simply use
796 /// [`ReadVar::from_static`] to get a obtain a static variable.
797 ///
798 /// [`NodeCtx::get_ado_variable`]: crate::node::NodeCtx::get_ado_variable
799 pub fn ado_new_named_variable(
800 &mut self,
801 name: impl AsRef<str>,
802 value: impl AsRef<str>,
803 ) -> AdoRuntimeVar {
804 let name = name.as_ref();
805 let value = value.as_ref();
806
807 self.ado_variables.insert(name.into(), value.into());
808
809 // safe, since we'll ensure that the global exists in the ADO backend
810 AdoRuntimeVar::dangerous_from_global(name, false)
811 }
812
813 /// (ADO only) Declare multiple pipeline-level, named, read-only ADO
814 /// variables at once.
815 ///
816 /// This is a convenience method to streamline invoking
817 /// [`Self::ado_new_named_variable`] multiple times.
818 ///
819 /// NOTE: Unless required by some particular third-party task, it's strongly
820 /// recommended to _avoid_ using this method, and to simply use
821 /// [`ReadVar::from_static`] to get a obtain a static variable.
822 ///
823 /// DEVNOTE: In the future, this API may be updated to return a handle that
824 /// will allow resolving the resulting `AdoRuntimeVar`, but for
825 /// implementation expediency, this API does not currently do this. If you
826 /// need to read the value of this variable at runtime, you may need to
827 /// invoke [`AdoRuntimeVar::dangerous_from_global`] manually.
828 ///
829 /// [`NodeCtx::get_ado_variable`]: crate::node::NodeCtx::get_ado_variable
830 pub fn ado_new_named_variables<K, V>(
831 &mut self,
832 vars: impl IntoIterator<Item = (K, V)>,
833 ) -> &mut Self
834 where
835 K: AsRef<str>,
836 V: AsRef<str>,
837 {
838 self.ado_variables.extend(
839 vars.into_iter()
840 .map(|(k, v)| (k.as_ref().into(), v.as_ref().into())),
841 );
842 self
843 }
844
845 /// Declare a pipeline-level runtime parameter with type `bool`.
846 ///
847 /// To obtain a [`ReadVar<bool>`] that can be used within a node, use the
848 /// [`PipelineJobCtx::use_parameter`] method.
849 ///
850 /// `name` is the name of the parameter.
851 ///
852 /// `description` is an arbitrary string, which will be be shown to users.
853 ///
854 /// `kind` is the type of parameter and if it should be treated as a stable
855 /// external API to callers of the pipeline.
856 ///
857 /// `default` is the default value for the parameter. If none is provided,
858 /// the parameter _must_ be specified in order for the pipeline to run.
859 ///
860 /// `possible_values` can be used to limit the set of valid values the
861 /// parameter accepts.
862 pub fn new_parameter_bool(
863 &mut self,
864 name: impl AsRef<str>,
865 description: impl AsRef<str>,
866 kind: ParameterKind,
867 default: Option<bool>,
868 ) -> UseParameter<bool> {
869 let idx = self.parameters.len();
870 let name = new_parameter_name(name, kind.clone());
871 self.parameters.push(ParameterMeta {
872 parameter: Parameter::Bool {
873 name,
874 description: description.as_ref().into(),
875 kind,
876 default,
877 },
878 used_by_jobs: BTreeSet::new(),
879 });
880
881 UseParameter {
882 idx,
883 _kind: std::marker::PhantomData,
884 }
885 }
886
887 /// Declare a pipeline-level runtime parameter with type `i64`.
888 ///
889 /// To obtain a [`ReadVar<i64>`] that can be used within a node, use the
890 /// [`PipelineJobCtx::use_parameter`] method.
891 ///
892 /// `name` is the name of the parameter.
893 ///
894 /// `description` is an arbitrary string, which will be be shown to users.
895 ///
896 /// `kind` is the type of parameter and if it should be treated as a stable
897 /// external API to callers of the pipeline.
898 ///
899 /// `default` is the default value for the parameter. If none is provided,
900 /// the parameter _must_ be specified in order for the pipeline to run.
901 ///
902 /// `possible_values` can be used to limit the set of valid values the
903 /// parameter accepts.
904 pub fn new_parameter_num(
905 &mut self,
906 name: impl AsRef<str>,
907 description: impl AsRef<str>,
908 kind: ParameterKind,
909 default: Option<i64>,
910 possible_values: Option<Vec<i64>>,
911 ) -> UseParameter<i64> {
912 let idx = self.parameters.len();
913 let name = new_parameter_name(name, kind.clone());
914 self.parameters.push(ParameterMeta {
915 parameter: Parameter::Num {
916 name,
917 description: description.as_ref().into(),
918 kind,
919 default,
920 possible_values,
921 },
922 used_by_jobs: BTreeSet::new(),
923 });
924
925 UseParameter {
926 idx,
927 _kind: std::marker::PhantomData,
928 }
929 }
930
931 /// Declare a pipeline-level runtime parameter with type `String`.
932 ///
933 /// To obtain a [`ReadVar<String>`] that can be used within a node, use the
934 /// [`PipelineJobCtx::use_parameter`] method.
935 ///
936 /// `name` is the name of the parameter.
937 ///
938 /// `description` is an arbitrary string, which will be be shown to users.
939 ///
940 /// `kind` is the type of parameter and if it should be treated as a stable
941 /// external API to callers of the pipeline.
942 ///
943 /// `default` is the default value for the parameter. If none is provided,
944 /// the parameter _must_ be specified in order for the pipeline to run.
945 ///
946 /// `possible_values` allows restricting inputs to a set of possible values.
947 /// Depending on the backend, these options may be presented as a set of
948 /// radio buttons, a dropdown menu, or something in that vein. If `None`,
949 /// then any string is allowed.
950 pub fn new_parameter_string(
951 &mut self,
952 name: impl AsRef<str>,
953 description: impl AsRef<str>,
954 kind: ParameterKind,
955 default: Option<impl AsRef<str>>,
956 possible_values: Option<Vec<String>>,
957 ) -> UseParameter<String> {
958 let idx = self.parameters.len();
959 let name = new_parameter_name(name, kind.clone());
960 self.parameters.push(ParameterMeta {
961 parameter: Parameter::String {
962 name,
963 description: description.as_ref().into(),
964 kind,
965 default: default.map(|x| x.as_ref().into()),
966 possible_values,
967 },
968 used_by_jobs: BTreeSet::new(),
969 });
970
971 UseParameter {
972 idx,
973 _kind: std::marker::PhantomData,
974 }
975 }
976}
977
978pub struct PipelineJobCtx<'a> {
979 pipeline: &'a mut Pipeline,
980 job_idx: usize,
981}
982
983impl PipelineJobCtx<'_> {
984 /// Create a new `WriteVar<SideEffect>` anchored to the pipeline job.
985 pub fn new_done_handle(&mut self) -> WriteVar<crate::node::SideEffect> {
986 self.pipeline.dummy_done_idx += 1;
987 crate::node::thin_air_write_runtime_var(format!("start{}", self.pipeline.dummy_done_idx))
988 }
989
990 /// Claim that this job will use this artifact, obtaining a path to a folder
991 /// with the artifact's contents.
992 pub fn use_artifact(&mut self, artifact: &UseArtifact) -> ReadVar<PathBuf> {
993 self.pipeline.artifacts[artifact.idx]
994 .used_by_jobs
995 .insert(self.job_idx);
996
997 crate::node::thin_air_read_runtime_var(consistent_artifact_runtime_var_name(
998 &self.pipeline.artifacts[artifact.idx].name,
999 true,
1000 ))
1001 }
1002
1003 /// Claim that this job will publish this artifact, obtaining a path to a
1004 /// fresh, empty folder which will be published as the specific artifact at
1005 /// the end of the job.
1006 pub fn publish_artifact(&mut self, artifact: PublishArtifact) -> ReadVar<PathBuf> {
1007 let existing = self.pipeline.artifacts[artifact.idx]
1008 .published_by_job
1009 .replace(self.job_idx);
1010 assert!(existing.is_none()); // PublishArtifact isn't cloneable
1011
1012 crate::node::thin_air_read_runtime_var(consistent_artifact_runtime_var_name(
1013 &self.pipeline.artifacts[artifact.idx].name,
1014 false,
1015 ))
1016 }
1017
1018 fn helper_request<R: IntoRequest>(&mut self, req: R)
1019 where
1020 R::Node: 'static,
1021 {
1022 self.pipeline.jobs[self.job_idx]
1023 .root_nodes
1024 .entry(NodeHandle::from_type::<R::Node>())
1025 .or_default()
1026 .push(serde_json::to_vec(&req.into_request()).unwrap().into());
1027 }
1028
1029 fn new_artifact_map_vars<T: Artifact>(&mut self) -> (ReadVar<T>, WriteVar<T>) {
1030 let artifact_map_idx = self.pipeline.artifact_map_idx;
1031 self.pipeline.artifact_map_idx += 1;
1032
1033 let backing_var = format!("artifact_map{}", artifact_map_idx);
1034 let read_var = crate::node::thin_air_read_runtime_var(backing_var.clone());
1035 let write_var = crate::node::thin_air_write_runtime_var(backing_var);
1036 (read_var, write_var)
1037 }
1038
1039 /// Claim that this job will use this artifact, obtaining the resolved
1040 /// contents of the artifact.
1041 pub fn use_typed_artifact<T: Artifact>(
1042 &mut self,
1043 artifact: &UseTypedArtifact<T>,
1044 ) -> ReadVar<T> {
1045 let artifact_path = self.use_artifact(&artifact.0);
1046 let (read, write) = self.new_artifact_map_vars::<T>();
1047 self.helper_request(resolve::Request::new(artifact_path, write));
1048 read
1049 }
1050
1051 /// Claim that this job will publish this artifact, obtaining a variable to
1052 /// write the artifact's contents to. The artifact will be published at
1053 /// the end of the job.
1054 pub fn publish_typed_artifact<T: Artifact>(
1055 &mut self,
1056 artifact: PublishTypedArtifact<T>,
1057 ) -> WriteVar<T> {
1058 let artifact_path = self.publish_artifact(artifact.0);
1059 let (read, write) = self.new_artifact_map_vars::<T>();
1060 let done = self.new_done_handle();
1061 self.helper_request(artifact::publish::Request::new(read, artifact_path, done));
1062 write
1063 }
1064
1065 /// Obtain a `ReadVar<T>` corresponding to a pipeline parameter which is
1066 /// specified at runtime.
1067 pub fn use_parameter<T>(&mut self, param: UseParameter<T>) -> ReadVar<T>
1068 where
1069 T: Serialize + DeserializeOwned,
1070 {
1071 self.pipeline.parameters[param.idx]
1072 .used_by_jobs
1073 .insert(self.job_idx);
1074
1075 crate::node::thin_air_read_runtime_var(
1076 self.pipeline.parameters[param.idx]
1077 .parameter
1078 .name()
1079 .to_string(),
1080 )
1081 }
1082
1083 /// Shortcut which allows defining a bool pipeline parameter within a Job.
1084 ///
1085 /// To share a single parameter between multiple jobs, don't use this method
1086 /// - use [`Pipeline::new_parameter_bool`] + [`Self::use_parameter`] instead.
1087 pub fn new_parameter_bool(
1088 &mut self,
1089 name: impl AsRef<str>,
1090 description: impl AsRef<str>,
1091 kind: ParameterKind,
1092 default: Option<bool>,
1093 ) -> ReadVar<bool> {
1094 let param = self
1095 .pipeline
1096 .new_parameter_bool(name, description, kind, default);
1097 self.use_parameter(param)
1098 }
1099
1100 /// Shortcut which allows defining a number pipeline parameter within a Job.
1101 ///
1102 /// To share a single parameter between multiple jobs, don't use this method
1103 /// - use [`Pipeline::new_parameter_num`] + [`Self::use_parameter`] instead.
1104 pub fn new_parameter_num(
1105 &mut self,
1106 name: impl AsRef<str>,
1107 description: impl AsRef<str>,
1108 kind: ParameterKind,
1109 default: Option<i64>,
1110 possible_values: Option<Vec<i64>>,
1111 ) -> ReadVar<i64> {
1112 let param =
1113 self.pipeline
1114 .new_parameter_num(name, description, kind, default, possible_values);
1115 self.use_parameter(param)
1116 }
1117
1118 /// Shortcut which allows defining a string pipeline parameter within a Job.
1119 ///
1120 /// To share a single parameter between multiple jobs, don't use this method
1121 /// - use [`Pipeline::new_parameter_string`] + [`Self::use_parameter`] instead.
1122 pub fn new_parameter_string(
1123 &mut self,
1124 name: impl AsRef<str>,
1125 description: impl AsRef<str>,
1126 kind: ParameterKind,
1127 default: Option<String>,
1128 possible_values: Option<Vec<String>>,
1129 ) -> ReadVar<String> {
1130 let param =
1131 self.pipeline
1132 .new_parameter_string(name, description, kind, default, possible_values);
1133 self.use_parameter(param)
1134 }
1135}
1136
1137#[must_use]
1138pub struct PipelineJob<'a> {
1139 pipeline: &'a mut Pipeline,
1140 job_idx: usize,
1141}
1142
1143impl PipelineJob<'_> {
1144 /// (ADO only) specify which agent pool this job will be run on.
1145 pub fn ado_set_pool(self, pool: AdoPool) -> Self {
1146 self.pipeline.jobs[self.job_idx].ado_pool = Some(pool);
1147 self
1148 }
1149
1150 /// (ADO only) specify which agent pool this job will be run on, with
1151 /// additional special runner demands.
1152 pub fn ado_set_pool_with_demands(self, pool: impl AsRef<str>, demands: Vec<String>) -> Self {
1153 self.pipeline.jobs[self.job_idx].ado_pool = Some(AdoPool {
1154 name: pool.as_ref().into(),
1155 demands,
1156 });
1157 self
1158 }
1159
1160 /// (ADO only) Declare a job-level, named, read-only ADO variable.
1161 ///
1162 /// `name` and `value` are both arbitrary strings, which may include ADO
1163 /// template expressions.
1164 ///
1165 /// NOTE: Unless required by some particular third-party task, it's strongly
1166 /// recommended to _avoid_ using this method, and to simply use
1167 /// [`ReadVar::from_static`] to get a obtain a static variable.
1168 ///
1169 /// DEVNOTE: In the future, this API may be updated to return a handle that
1170 /// will allow resolving the resulting `AdoRuntimeVar`, but for
1171 /// implementation expediency, this API does not currently do this. If you
1172 /// need to read the value of this variable at runtime, you may need to
1173 /// invoke [`AdoRuntimeVar::dangerous_from_global`] manually.
1174 ///
1175 /// [`NodeCtx::get_ado_variable`]: crate::node::NodeCtx::get_ado_variable
1176 pub fn ado_new_named_variable(self, name: impl AsRef<str>, value: impl AsRef<str>) -> Self {
1177 let name = name.as_ref();
1178 let value = value.as_ref();
1179 self.pipeline.jobs[self.job_idx]
1180 .ado_variables
1181 .insert(name.into(), value.into());
1182 self
1183 }
1184
1185 /// (ADO only) Declare multiple job-level, named, read-only ADO variables at
1186 /// once.
1187 ///
1188 /// This is a convenience method to streamline invoking
1189 /// [`Self::ado_new_named_variable`] multiple times.
1190 ///
1191 /// NOTE: Unless required by some particular third-party task, it's strongly
1192 /// recommended to _avoid_ using this method, and to simply use
1193 /// [`ReadVar::from_static`] to get a obtain a static variable.
1194 ///
1195 /// DEVNOTE: In the future, this API may be updated to return a handle that
1196 /// will allow resolving the resulting `AdoRuntimeVar`, but for
1197 /// implementation expediency, this API does not currently do this. If you
1198 /// need to read the value of this variable at runtime, you may need to
1199 /// invoke [`AdoRuntimeVar::dangerous_from_global`] manually.
1200 ///
1201 /// [`NodeCtx::get_ado_variable`]: crate::node::NodeCtx::get_ado_variable
1202 pub fn ado_new_named_variables<K, V>(self, vars: impl IntoIterator<Item = (K, V)>) -> Self
1203 where
1204 K: AsRef<str>,
1205 V: AsRef<str>,
1206 {
1207 self.pipeline.jobs[self.job_idx].ado_variables.extend(
1208 vars.into_iter()
1209 .map(|(k, v)| (k.as_ref().into(), v.as_ref().into())),
1210 );
1211 self
1212 }
1213
1214 /// Overrides the id of the job.
1215 ///
1216 /// Flowey typically generates a reasonable job ID but some use cases that depend
1217 /// on the ID may find it useful to override it to something custom.
1218 pub fn ado_override_job_id(self, name: impl AsRef<str>) -> Self {
1219 self.pipeline
1220 .ado_job_id_overrides
1221 .insert(self.job_idx, name.as_ref().into());
1222 self
1223 }
1224
1225 /// (GitHub Actions only) specify which Github runner this job will be run on.
1226 pub fn gh_set_pool(self, pool: GhRunner) -> Self {
1227 self.pipeline.jobs[self.job_idx].gh_pool = Some(pool);
1228 self
1229 }
1230
1231 /// (GitHub Actions only) Set the concurrency group for this job.
1232 pub fn gh_set_concurrency_group(self, group: GhConcurrencyGroup) -> Self {
1233 self.pipeline.jobs[self.job_idx].gh_concurrency_group = Some(group);
1234 self
1235 }
1236
1237 /// (GitHub Actions only) Manually override the `if:` condition for this
1238 /// particular job.
1239 ///
1240 /// **This is dangerous**, as an improperly set `if` condition may break
1241 /// downstream flowey jobs which assume flowey is in control of the job's
1242 /// scheduling logic.
1243 ///
1244 /// See
1245 /// <https://docs.github.com/en/actions/writing-workflows/workflow-syntax-for-github-actions#jobsjob_idif>
1246 /// for more info.
1247 pub fn gh_dangerous_override_if(self, condition: impl AsRef<str>) -> Self {
1248 self.pipeline.jobs[self.job_idx].gh_override_if = Some(condition.as_ref().into());
1249 self
1250 }
1251
1252 /// (GitHub Actions only) Declare a global job-level environment variable,
1253 /// visible to all downstream steps.
1254 ///
1255 /// `name` and `value` are both arbitrary strings, which may include GitHub
1256 /// Actions template expressions.
1257 ///
1258 /// **This is dangerous**, as it is easy to misuse this API in order to
1259 /// write a node which takes an implicit dependency on there being a global
1260 /// variable set on its behalf by the top-level pipeline code, making it
1261 /// difficult to "locally reason" about the behavior of a node simply by
1262 /// reading its code.
1263 ///
1264 /// Whenever possible, nodes should "late bind" environment variables:
1265 /// accepting a compile-time / runtime flowey parameter, and then setting it
1266 /// prior to executing a child command that requires it.
1267 ///
1268 /// Only use this API in exceptional cases, such as obtaining an environment
1269 /// variable whose value is determined by a job-level GitHub Actions
1270 /// expression evaluation.
1271 pub fn gh_dangerous_global_env_var(
1272 self,
1273 name: impl AsRef<str>,
1274 value: impl AsRef<str>,
1275 ) -> Self {
1276 let name = name.as_ref();
1277 let value = value.as_ref();
1278 self.pipeline.jobs[self.job_idx]
1279 .gh_global_env
1280 .insert(name.into(), value.into());
1281 self
1282 }
1283
1284 /// (GitHub Actions only) Grant permissions required by nodes in the job.
1285 ///
1286 /// For a given node handle, grant the specified permissions.
1287 /// The list provided must match the permissions specified within the node
1288 /// using `requires_permission`.
1289 ///
1290 /// NOTE: While this method is called at a node-level for auditability, the emitted
1291 /// yaml grants permissions at the job-level.
1292 ///
1293 /// This can lead to weird situations where node 1 might not specify a permission
1294 /// required according to Github Actions, but due to job-level granting of the permission
1295 /// by another node 2, the pipeline executes even though it wouldn't if node 2 was removed.
1296 ///
1297 /// For available permission scopes and their descriptions, see
1298 /// <https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#permissions>.
1299 pub fn gh_grant_permissions<N: FlowNodeBase + 'static>(
1300 self,
1301 permissions: impl IntoIterator<Item = (GhPermission, GhPermissionValue)>,
1302 ) -> Self {
1303 let node_handle = NodeHandle::from_type::<N>();
1304 for (permission, value) in permissions {
1305 self.pipeline.jobs[self.job_idx]
1306 .gh_permissions
1307 .entry(node_handle)
1308 .or_default()
1309 .insert(permission, value);
1310 }
1311 self
1312 }
1313
1314 pub fn apply_patchfn(self, patchfn: crate::patch::PatchFn) -> Self {
1315 self.pipeline.jobs[self.job_idx]
1316 .patches
1317 .apply_patchfn(patchfn);
1318 self
1319 }
1320
1321 /// Set a timeout for the job, in minutes.
1322 ///
1323 /// Not calling this will result in the platform's default timeout being used,
1324 /// which is typically 60 minutes, but may vary.
1325 pub fn with_timeout_in_minutes(self, timeout: u32) -> Self {
1326 self.pipeline.jobs[self.job_idx].timeout_minutes = Some(timeout);
1327 self
1328 }
1329
1330 /// (ADO+Local Only) Only run the job if the specified condition is true.
1331 pub fn with_condition(self, cond: UseParameter<bool>) -> Self {
1332 self.pipeline.jobs[self.job_idx].cond_param_idx = Some(cond.idx);
1333 self.pipeline.parameters[cond.idx]
1334 .used_by_jobs
1335 .insert(self.job_idx);
1336 self
1337 }
1338
1339 /// Set a [`CommandWrapperKind`] that will be applied to all shell
1340 /// commands executed in this job's steps.
1341 ///
1342 /// The wrapper is applied both when running locally (via direct run)
1343 /// and when running in CI (the kind is serialized into
1344 /// `pipeline.json` and reconstructed at runtime).
1345 ///
1346 /// [`CommandWrapperKind`]: crate::shell::CommandWrapperKind
1347 pub fn set_command_wrapper(self, wrapper: crate::shell::CommandWrapperKind) -> Self {
1348 self.pipeline.jobs[self.job_idx].command_wrapper = Some(wrapper);
1349 self
1350 }
1351
1352 /// Add a flow node which will be run as part of the job.
1353 pub fn dep_on<R: IntoRequest + 'static>(
1354 self,
1355 f: impl FnOnce(&mut PipelineJobCtx<'_>) -> R,
1356 ) -> Self {
1357 // JobToNodeCtx will ensure artifact deps are taken care of
1358 let req = f(&mut PipelineJobCtx {
1359 pipeline: self.pipeline,
1360 job_idx: self.job_idx,
1361 });
1362
1363 self.pipeline.jobs[self.job_idx]
1364 .root_nodes
1365 .entry(NodeHandle::from_type::<R::Node>())
1366 .or_default()
1367 .push(serde_json::to_vec(&req.into_request()).unwrap().into());
1368
1369 self
1370 }
1371
1372 /// Add a flow node whose request publishes a typed artifact.
1373 ///
1374 /// This is a shortcut for the common pattern of calling
1375 /// [`PipelineJobCtx::publish_typed_artifact`] inside a [`Self::dep_on`]
1376 /// closure and passing the resulting [`WriteVar`] into a request.
1377 pub fn publish<T: Artifact, R: IntoRequest + 'static>(
1378 self,
1379 artifact: PublishTypedArtifact<T>,
1380 f: impl FnOnce(WriteVar<T>) -> R,
1381 ) -> Self {
1382 self.dep_on(|ctx| f(ctx.publish_typed_artifact(artifact)))
1383 }
1384
1385 /// Add a flow node whose request is run purely for its side effect.
1386 ///
1387 /// This is a shortcut for the common pattern of calling
1388 /// [`PipelineJobCtx::new_done_handle`] inside a [`Self::dep_on`]
1389 /// closure and passing the resulting [`WriteVar`] into a request.
1390 pub fn side_effect<R: IntoRequest + 'static>(
1391 self,
1392 f: impl FnOnce(WriteVar<crate::node::SideEffect>) -> R,
1393 ) -> Self {
1394 self.dep_on(|ctx| f(ctx.new_done_handle()))
1395 }
1396
1397 /// Set config on a node for this job.
1398 ///
1399 /// This is the pipeline-level equivalent of [`NodeCtx::config`]. Config
1400 /// set here is merged with any config set by nodes within the job.
1401 ///
1402 /// [`NodeCtx::config`]: crate::node::NodeCtx::config
1403 pub fn config<C: IntoConfig + 'static>(self, config: C) -> Self {
1404 self.pipeline.jobs[self.job_idx]
1405 .root_configs
1406 .entry(NodeHandle::from_type::<C::Node>())
1407 .or_default()
1408 .push(serde_json::to_vec(&config).unwrap().into());
1409
1410 self
1411 }
1412
1413 /// Finish describing the pipeline job.
1414 pub fn finish(self) -> PipelineJobHandle {
1415 PipelineJobHandle {
1416 job_idx: self.job_idx,
1417 }
1418 }
1419
1420 /// Return the job's platform.
1421 pub fn get_platform(&self) -> FlowPlatform {
1422 self.pipeline.jobs[self.job_idx].platform
1423 }
1424
1425 /// Return the job's architecture.
1426 pub fn get_arch(&self) -> FlowArch {
1427 self.pipeline.jobs[self.job_idx].arch
1428 }
1429}
1430
1431#[derive(Clone)]
1432pub struct PipelineJobHandle {
1433 job_idx: usize,
1434}
1435
1436impl PipelineJobHandle {
1437 pub fn is_handle_for(&self, job: &PipelineJob<'_>) -> bool {
1438 self.job_idx == job.job_idx
1439 }
1440}
1441
1442#[derive(Clone, Copy)]
1443pub enum PipelineBackendHint {
1444 /// Pipeline is being run on the user's dev machine (via bash / direct run)
1445 Local,
1446 /// Pipeline is run on ADO
1447 Ado,
1448 /// Pipeline is run on GitHub Actions
1449 Github,
1450}
1451
1452/// Trait for types that can be converted into a [`Pipeline`].
1453///
1454/// This is the primary entry point for defining flowey pipelines. Implement this trait
1455/// to create a pipeline definition that can be executed locally or converted to CI YAML.
1456///
1457/// # Example
1458///
1459/// ```rust,no_run
1460/// use flowey_core::pipeline::{IntoPipeline, Pipeline, PipelineBackendHint};
1461/// use flowey_core::node::{FlowPlatform, FlowPlatformLinuxDistro, FlowArch};
1462///
1463/// struct MyPipeline;
1464///
1465/// impl IntoPipeline for MyPipeline {
1466/// fn into_pipeline(self, backend_hint: PipelineBackendHint) -> anyhow::Result<Pipeline> {
1467/// let mut pipeline = Pipeline::new();
1468///
1469/// // Define a job that runs on Linux x86_64
1470/// let _job = pipeline
1471/// .new_job(
1472/// FlowPlatform::Linux(FlowPlatformLinuxDistro::Ubuntu),
1473/// FlowArch::X86_64,
1474/// "build"
1475/// )
1476/// .finish();
1477///
1478/// Ok(pipeline)
1479/// }
1480/// }
1481/// ```
1482///
1483/// # Complex Example with Parameters and Artifacts
1484///
1485/// ```rust,ignore
1486/// use flowey_core::pipeline::{IntoPipeline, Pipeline, PipelineBackendHint, ParameterKind};
1487/// use flowey_core::node::{FlowPlatform, FlowPlatformLinuxDistro, FlowArch};
1488///
1489/// struct BuildPipeline;
1490///
1491/// impl IntoPipeline for BuildPipeline {
1492/// fn into_pipeline(self, backend_hint: PipelineBackendHint) -> anyhow::Result<Pipeline> {
1493/// let mut pipeline = Pipeline::new();
1494///
1495/// // Define a runtime parameter
1496/// let enable_tests = pipeline.new_parameter_bool(
1497/// "enable_tests",
1498/// "Whether to run tests",
1499/// ParameterKind::Stable,
1500/// Some(true) // default value
1501/// );
1502///
1503/// // Create an artifact for passing data between jobs
1504/// let (publish_build, use_build) = pipeline.new_artifact("build-output");
1505///
1506/// // Job 1: Build
1507/// let build_job = pipeline
1508/// .new_job(
1509/// FlowPlatform::Linux(FlowPlatformLinuxDistro::Ubuntu),
1510/// FlowArch::X86_64,
1511/// "build"
1512/// )
1513/// .with_timeout_in_minutes(30)
1514/// .dep_on(|ctx| flowey_lib_hvlite::_jobs::example_node::Request {
1515/// output_dir: ctx.publish_artifact(publish_build),
1516/// })
1517/// .finish();
1518///
1519/// // Job 2: Test (conditionally run based on parameter)
1520/// let _test_job = pipeline
1521/// .new_job(
1522/// FlowPlatform::Linux(FlowPlatformLinuxDistro::Ubuntu),
1523/// FlowArch::X86_64,
1524/// "test"
1525/// )
1526/// .with_condition(enable_tests)
1527/// .dep_on(|ctx| flowey_lib_hvlite::_jobs::example_node2::Request {
1528/// input_dir: ctx.use_artifact(&use_build),
1529/// })
1530/// .finish();
1531///
1532/// Ok(pipeline)
1533/// }
1534/// }
1535/// ```
1536pub trait IntoPipeline {
1537 fn into_pipeline(self, backend_hint: PipelineBackendHint) -> anyhow::Result<Pipeline>;
1538}
1539
1540fn new_parameter_name(name: impl AsRef<str>, kind: ParameterKind) -> String {
1541 match kind {
1542 ParameterKind::Unstable => format!("__unstable_{}", name.as_ref()),
1543 ParameterKind::Stable => name.as_ref().into(),
1544 }
1545}
1546
1547/// Structs which should only be used by top-level flowey emitters. If you're a
1548/// pipeline author, these are not types you need to care about!
1549pub mod internal {
1550 use super::*;
1551 use std::collections::BTreeMap;
1552
1553 /// Generate an ADO bootstrap template for a job's platform and architecture.
1554 pub type AdoBootstrapTemplate = dyn Fn(FlowPlatform, FlowArch) -> anyhow::Result<String>;
1555
1556 /// Generate a GitHub bootstrap template for a job's platform and architecture.
1557 pub type GhBootstrapTemplate = dyn Fn(FlowPlatform, FlowArch) -> anyhow::Result<String>;
1558
1559 pub fn consistent_artifact_runtime_var_name(artifact: impl AsRef<str>, is_use: bool) -> String {
1560 format!(
1561 "artifact_{}_{}",
1562 if is_use { "use_from" } else { "publish_from" },
1563 artifact.as_ref()
1564 )
1565 }
1566
1567 #[derive(Debug)]
1568 pub struct InternalAdoResourcesRepository {
1569 /// flowey-generated unique repo identifier
1570 pub repo_id: String,
1571 /// Type of repo that is being connected to.
1572 pub repo_type: AdoResourcesRepositoryType,
1573 /// Repository name. Format depends on `repo_type`.
1574 pub name: String,
1575 /// git ref to checkout.
1576 pub git_ref: AdoResourcesRepositoryRef<usize>,
1577 /// (optional) ID of the service endpoint connecting to this repository.
1578 pub endpoint: Option<String>,
1579 }
1580
1581 pub struct PipelineJobMetadata {
1582 pub root_nodes: BTreeMap<NodeHandle, Vec<Box<[u8]>>>,
1583 pub root_configs: BTreeMap<NodeHandle, Vec<Box<[u8]>>>,
1584 pub patches: PatchResolver,
1585 pub label: String,
1586 pub platform: FlowPlatform,
1587 pub arch: FlowArch,
1588 pub cond_param_idx: Option<usize>,
1589 pub timeout_minutes: Option<u32>,
1590 pub command_wrapper: Option<crate::shell::CommandWrapperKind>,
1591 // backend specific
1592 pub ado_pool: Option<AdoPool>,
1593 pub ado_variables: BTreeMap<String, String>,
1594 pub gh_override_if: Option<String>,
1595 pub gh_pool: Option<GhRunner>,
1596 pub gh_concurrency_group: Option<GhConcurrencyGroup>,
1597 pub gh_global_env: BTreeMap<String, String>,
1598 pub gh_permissions: BTreeMap<NodeHandle, BTreeMap<GhPermission, GhPermissionValue>>,
1599 }
1600
1601 #[derive(Debug)]
1602 pub struct ArtifactMeta {
1603 pub name: String,
1604 pub published_by_job: Option<usize>,
1605 pub used_by_jobs: BTreeSet<usize>,
1606 }
1607
1608 #[derive(Debug)]
1609 pub struct ParameterMeta {
1610 pub parameter: Parameter,
1611 pub used_by_jobs: BTreeSet<usize>,
1612 }
1613
1614 /// Mirror of [`Pipeline`], except with all field marked as `pub`.
1615 pub struct PipelineFinalized {
1616 pub jobs: Vec<PipelineJobMetadata>,
1617 pub artifacts: Vec<ArtifactMeta>,
1618 pub parameters: Vec<ParameterMeta>,
1619 pub extra_deps: BTreeSet<(usize, usize)>,
1620 // backend specific
1621 pub ado_name: Option<String>,
1622 pub ado_schedule_triggers: Vec<AdoScheduleTriggers>,
1623 pub ado_ci_triggers: Option<AdoCiTriggers>,
1624 pub ado_pr_triggers: Option<AdoPrTriggers>,
1625 pub ado_bootstrap_template: Option<Box<AdoBootstrapTemplate>>,
1626 pub ado_resources_repository: Vec<InternalAdoResourcesRepository>,
1627 pub ado_post_process_yaml_cb:
1628 Option<Box<dyn FnOnce(serde_yaml::Value) -> serde_yaml::Value>>,
1629 pub ado_variables: BTreeMap<String, String>,
1630 pub ado_job_id_overrides: BTreeMap<usize, String>,
1631 pub gh_name: Option<String>,
1632 pub gh_schedule_triggers: Vec<GhScheduleTriggers>,
1633 pub gh_ci_triggers: Option<GhCiTriggers>,
1634 pub gh_pr_triggers: Option<GhPrTriggers>,
1635 pub gh_bootstrap_template: Option<Box<GhBootstrapTemplate>>,
1636 }
1637
1638 impl PipelineFinalized {
1639 pub fn from_pipeline(mut pipeline: Pipeline) -> Self {
1640 if let Some(cb) = pipeline.inject_all_jobs_with.take() {
1641 for job_idx in 0..pipeline.jobs.len() {
1642 let _ = cb(PipelineJob {
1643 pipeline: &mut pipeline,
1644 job_idx,
1645 });
1646 }
1647 }
1648
1649 let Pipeline {
1650 mut jobs,
1651 artifacts,
1652 parameters,
1653 extra_deps,
1654 ado_name,
1655 ado_bootstrap_template,
1656 ado_schedule_triggers,
1657 ado_ci_triggers,
1658 ado_pr_triggers,
1659 ado_resources_repository,
1660 ado_post_process_yaml_cb,
1661 ado_variables,
1662 ado_job_id_overrides,
1663 gh_name,
1664 gh_schedule_triggers,
1665 gh_ci_triggers,
1666 gh_pr_triggers,
1667 gh_bootstrap_template,
1668 // not relevant to consumer code
1669 dummy_done_idx: _,
1670 artifact_map_idx: _,
1671 artifact_names: _,
1672 global_patchfns,
1673 inject_all_jobs_with: _, // processed above
1674 } = pipeline;
1675
1676 for patchfn in global_patchfns {
1677 for job in &mut jobs {
1678 job.patches.apply_patchfn(patchfn)
1679 }
1680 }
1681
1682 Self {
1683 jobs,
1684 artifacts,
1685 parameters,
1686 extra_deps,
1687 ado_name,
1688 ado_schedule_triggers,
1689 ado_ci_triggers,
1690 ado_pr_triggers,
1691 ado_bootstrap_template,
1692 ado_resources_repository,
1693 ado_post_process_yaml_cb,
1694 ado_variables,
1695 ado_job_id_overrides,
1696 gh_name,
1697 gh_schedule_triggers,
1698 gh_ci_triggers,
1699 gh_pr_triggers,
1700 gh_bootstrap_template,
1701 }
1702 }
1703 }
1704
1705 #[derive(Debug, Clone)]
1706 pub enum Parameter {
1707 Bool {
1708 name: String,
1709 description: String,
1710 kind: ParameterKind,
1711 default: Option<bool>,
1712 },
1713 String {
1714 name: String,
1715 description: String,
1716 default: Option<String>,
1717 kind: ParameterKind,
1718 possible_values: Option<Vec<String>>,
1719 },
1720 Num {
1721 name: String,
1722 description: String,
1723 default: Option<i64>,
1724 kind: ParameterKind,
1725 possible_values: Option<Vec<i64>>,
1726 },
1727 }
1728
1729 impl Parameter {
1730 pub fn name(&self) -> &str {
1731 match self {
1732 Parameter::Bool { name, .. } => name,
1733 Parameter::String { name, .. } => name,
1734 Parameter::Num { name, .. } => name,
1735 }
1736 }
1737 }
1738}