Skip to main content

nerdbank_gitversioning/
cloud.rs

1// Copyright (c) .NET Foundation and Contributors. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
4//! Cloud-build provider discovery and common functionality.
5
6use std::collections::HashMap;
7use std::io::{self, Write};
8
9use crate::cloud_build_services::{
10    AppVeyor, AtlassianBamboo, BitbucketCloud, GitHubActions, GitLab, Jenkins, SpaceAutomation,
11    TeamCity, Travis, VisualStudioTeamServices,
12};
13
14/// Environment changes that should be applied by the caller.
15pub type EnvironmentVariables = HashMap<String, String>;
16
17/// Describes a supported cloud-build service.
18pub trait CloudBuild: Send + Sync {
19    /// Returns the stable name of this provider.
20    fn name(&self) -> &'static str;
21
22    /// Returns whether this provider recognizes the current environment.
23    fn is_applicable(&self) -> bool;
24
25    /// Returns whether the current build validates a pull request.
26    fn is_pull_request(&self) -> bool;
27
28    /// Returns the fully qualified branch ref being built, when known.
29    fn building_branch(&self) -> Option<String>;
30
31    /// Returns the fully qualified tag ref being built, when known.
32    fn building_tag(&self) -> Option<String>;
33
34    /// Returns the Git commit ID being built, when supplied by the provider.
35    fn git_commit_id(&self) -> Option<String>;
36
37    /// Updates the provider's build number and returns environment changes for the caller.
38    fn set_cloud_build_number(
39        &self,
40        build_number: &str,
41        stdout: &mut dyn Write,
42        stderr: &mut dyn Write,
43    ) -> io::Result<EnvironmentVariables>;
44
45    /// Sets a provider variable and returns environment changes for the caller.
46    fn set_cloud_build_variable(
47        &self,
48        name: &str,
49        value: &str,
50        stdout: &mut dyn Write,
51        stderr: &mut dyn Write,
52    ) -> io::Result<EnvironmentVariables>;
53}
54
55/// Creates the supported providers in detection-priority order.
56pub fn supported_cloud_builds() -> Vec<Box<dyn CloudBuild>> {
57    vec![
58        Box::new(AppVeyor),
59        Box::new(VisualStudioTeamServices),
60        Box::new(GitHubActions),
61        Box::new(TeamCity),
62        Box::new(AtlassianBamboo),
63        Box::new(Jenkins),
64        Box::new(GitLab),
65        Box::new(Travis),
66        Box::new(SpaceAutomation),
67        Box::new(BitbucketCloud),
68    ]
69}
70
71/// Returns the first provider that recognizes the current environment.
72pub fn active() -> Option<Box<dyn CloudBuild>> {
73    supported_cloud_builds()
74        .into_iter()
75        .find(|provider| provider.is_applicable())
76}
77
78/// Adds `prefix` to a nonempty value unless it is already present.
79pub(crate) fn should_start_with(value: Option<String>, prefix: &str) -> Option<String> {
80    value.map(|value| {
81        if value.is_empty() || value.starts_with(prefix) {
82            value
83        } else {
84            format!("{prefix}{value}")
85        }
86    })
87}
88
89/// Retains a value only when it starts with `prefix`.
90pub(crate) fn if_starts_with(value: Option<String>, prefix: &str) -> Option<String> {
91    value.filter(|value| value.starts_with(prefix))
92}
93
94pub(crate) fn env(name: &str) -> Option<String> {
95    std::env::var_os(name).map(|value| value.to_string_lossy().into_owned())
96}
97
98pub(crate) fn is_nonempty(value: Option<&str>) -> bool {
99    value.is_some_and(|value| !value.is_empty())
100}
101
102pub(crate) fn empty_variables() -> EnvironmentVariables {
103    EnvironmentVariables::new()
104}
105
106pub(crate) fn variable_for_environment(name: &str, value: &str) -> EnvironmentVariables {
107    EnvironmentVariables::from([(name.to_uppercase().replace('.', "_"), value.to_owned())])
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113
114    #[test]
115    fn ref_helpers_match_cloud_build_conventions() {
116        assert_eq!(
117            should_start_with(Some("main".into()), "refs/heads/").as_deref(),
118            Some("refs/heads/main")
119        );
120        assert_eq!(
121            should_start_with(Some("refs/heads/main".into()), "refs/heads/").as_deref(),
122            Some("refs/heads/main")
123        );
124        assert_eq!(should_start_with(None, "refs/heads/"), None);
125        assert_eq!(
126            if_starts_with(Some("refs/tags/v1".into()), "refs/tags/").as_deref(),
127            Some("refs/tags/v1")
128        );
129        assert_eq!(if_starts_with(Some("main".into()), "refs/heads/"), None);
130    }
131
132    #[test]
133    fn provider_order_matches_managed_library() {
134        let names: Vec<_> = supported_cloud_builds()
135            .iter()
136            .map(|provider| provider.name())
137            .collect();
138        assert_eq!(
139            names,
140            [
141                "AppVeyor",
142                "VisualStudioTeamServices",
143                "GitHubActions",
144                "TeamCity",
145                "AtlassianBamboo",
146                "Jenkins",
147                "GitLab",
148                "Travis",
149                "SpaceAutomation",
150                "BitbucketCloud",
151            ]
152        );
153    }
154}