Skip to main content

nerdbank_gitversioning/
cloud_command.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//! Reusable implementation of the `nbgv cloud` command.
5
6use std::collections::{HashMap, HashSet};
7use std::fmt;
8use std::io::Write;
9use std::path::Path;
10
11use crate::cloud::{CloudBuild, EnvironmentVariables, active, supported_cloud_builds};
12use crate::{GitContext, GitEngine, VersionOracle, effective_git_engine};
13
14/// The classified failures produced by [`CloudCommand`].
15#[derive(Clone, Copy, Debug, Eq, PartialEq)]
16pub enum CloudCommandError {
17    /// The explicitly named provider was not found.
18    NoCloudBuildProviderMatch,
19    /// A variable was specified more than once.
20    DuplicateCloudVariable,
21    /// No supported provider could be detected.
22    NoCloudBuildEnvDetected,
23    /// Version calculation or provider output failed.
24    OperationFailed,
25}
26
27/// An error from [`CloudCommand`].
28#[derive(Debug)]
29pub struct CloudCommandException {
30    /// The stable error classification.
31    pub error: CloudCommandError,
32    message: String,
33}
34
35impl CloudCommandException {
36    fn new(error: CloudCommandError, message: impl Into<String>) -> Self {
37        Self {
38            error,
39            message: message.into(),
40        }
41    }
42}
43
44impl fmt::Display for CloudCommandException {
45    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
46        formatter.write_str(&self.message)
47    }
48}
49
50impl std::error::Error for CloudCommandException {}
51
52/// Arguments accepted by [`CloudCommand::set_build_variables`].
53#[derive(Clone, Debug, Default)]
54pub struct CloudCommandOptions {
55    /// Build metadata identifiers to append.
56    pub metadata: Vec<String>,
57    /// An explicit cloud build number; an empty value uses the calculated number.
58    pub version: Option<String>,
59    /// An explicit provider name, matched case-insensitively.
60    pub ci_system: Option<String>,
61    /// Whether all oracle variables should be defined.
62    pub all_vars: bool,
63    /// Whether the three common version variables should be defined.
64    pub common_vars: bool,
65    /// Whether the cloud build number should be changed.
66    pub cloud_build_number: bool,
67    /// Additional variables to define.
68    pub additional_variables: Vec<(String, String)>,
69    /// Whether a read-write Git engine should be requested.
70    pub always_use_libgit2: bool,
71}
72
73/// Applies calculated version values to a cloud-build provider.
74pub struct CloudCommand<'a> {
75    stdout: &'a mut dyn Write,
76    stderr: &'a mut dyn Write,
77}
78
79impl<'a> CloudCommand<'a> {
80    /// Creates a command writing provider messages to the supplied streams.
81    pub fn new(stdout: &'a mut dyn Write, stderr: &'a mut dyn Write) -> Self {
82        Self { stdout, stderr }
83    }
84
85    /// Calculates and sets cloud variables, returning environment changes requested by providers.
86    pub fn set_build_variables(
87        &mut self,
88        project_directory: impl AsRef<Path>,
89        options: &CloudCommandOptions,
90    ) -> std::result::Result<EnvironmentVariables, CloudCommandException> {
91        let provider: Option<Box<dyn CloudBuild>> =
92            if let Some(name) = options.ci_system.as_deref().filter(|name| !name.is_empty()) {
93                Some(
94                    supported_cloud_builds()
95                        .into_iter()
96                        .find(|provider| provider.name().eq_ignore_ascii_case(name))
97                        .ok_or_else(|| {
98                            CloudCommandException::new(
99                                CloudCommandError::NoCloudBuildProviderMatch,
100                                format!("No cloud provider found by the name: \"{name}\""),
101                            )
102                        })?,
103                )
104            } else {
105                active()
106            };
107
108        let engine = effective_git_engine(if options.always_use_libgit2 {
109            GitEngine::ReadWrite
110        } else {
111            GitEngine::ReadOnly
112        });
113        let context =
114            GitContext::create(project_directory, None, engine).map_err(operation_failed)?;
115        let mut oracle =
116            VersionOracle::new(&context, provider.as_deref()).map_err(operation_failed)?;
117        oracle
118            .build_metadata
119            .extend(options.metadata.iter().cloned());
120
121        let mut variables = Vec::new();
122        if options.all_vars {
123            variables.extend(oracle.cloud_build_all_vars());
124        }
125        if options.common_vars {
126            variables.extend(oracle.cloud_build_version_vars());
127        }
128        let mut names: HashSet<String> = variables.iter().map(|(name, _)| name.clone()).collect();
129        for (name, value) in &options.additional_variables {
130            if !names.insert(name.clone()) {
131                return Err(CloudCommandException::new(
132                    CloudCommandError::DuplicateCloudVariable,
133                    format!("Cloud build variable \"{name}\" specified more than once."),
134                ));
135            }
136            variables.push((name.clone(), value.clone()));
137        }
138
139        let mut changes = HashMap::new();
140        let provider = provider.ok_or_else(|| {
141            CloudCommandException::new(
142                CloudCommandError::NoCloudBuildEnvDetected,
143                "No cloud build detected.",
144            )
145        })?;
146        if options.cloud_build_number {
147            let build_number = options
148                .version
149                .as_deref()
150                .filter(|version| !version.is_empty())
151                .map(str::to_owned)
152                .unwrap_or_else(|| oracle.cloud_build_number());
153            changes.extend(
154                provider
155                    .set_cloud_build_number(&build_number, self.stdout, self.stderr)
156                    .map_err(operation_failed)?,
157            );
158        }
159        for (name, value) in variables {
160            changes.extend(
161                provider
162                    .set_cloud_build_variable(&name, &value, self.stdout, self.stderr)
163                    .map_err(operation_failed)?,
164            );
165        }
166        Ok(changes)
167    }
168}
169
170fn operation_failed(error: impl fmt::Display) -> CloudCommandException {
171    CloudCommandException::new(CloudCommandError::OperationFailed, error.to_string())
172}
173
174#[cfg(test)]
175mod tests {
176    use std::fs;
177    use std::path::PathBuf;
178    use std::sync::atomic::{AtomicU64, Ordering};
179
180    use git2::{IndexAddOption, Repository, Signature};
181
182    use super::*;
183
184    static NEXT_REPOSITORY: AtomicU64 = AtomicU64::new(0);
185
186    fn repository() -> PathBuf {
187        let id = NEXT_REPOSITORY.fetch_add(1, Ordering::Relaxed);
188        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
189            .join("target")
190            .join("test-repositories")
191            .join(format!("cloud-command-{}-{id}", std::process::id()));
192        let _ = fs::remove_dir_all(&path);
193        fs::create_dir_all(&path).unwrap();
194        let repository = Repository::init(&path).unwrap();
195        fs::write(path.join("version.json"), r#"{"version":"1.2"}"#).unwrap();
196        let mut index = repository.index().unwrap();
197        index.add_all(["*"], IndexAddOption::DEFAULT, None).unwrap();
198        let tree_id = index.write_tree().unwrap();
199        let tree = repository.find_tree(tree_id).unwrap();
200        let signature = Signature::now("Test", "test@example.com").unwrap();
201        repository
202            .commit(Some("HEAD"), &signature, &signature, "version", &tree, &[])
203            .unwrap();
204        path
205    }
206
207    #[test]
208    fn explicit_provider_sets_number_variables_and_returns_environment() {
209        let path = repository();
210        let mut stdout = Vec::new();
211        let mut stderr = Vec::new();
212        let changes = CloudCommand::new(&mut stdout, &mut stderr)
213            .set_build_variables(
214                &path,
215                &CloudCommandOptions {
216                    version: Some("1.2.3.4".into()),
217                    ci_system: Some("visualstudioteamservices".into()),
218                    cloud_build_number: true,
219                    common_vars: true,
220                    additional_variables: vec![("Custom".into(), "Value".into())],
221                    ..Default::default()
222                },
223            )
224            .unwrap();
225        let output = String::from_utf8(stdout).unwrap();
226        assert!(output.contains("##vso[build.updatebuildnumber]1.2.3.4"));
227        assert!(output.contains("variable=GitBuildVersion;"));
228        assert!(output.contains("variable=Custom;"));
229        assert_eq!(changes["BUILD_BUILDNUMBER"], "1.2.3.4");
230        assert!(stderr.is_empty());
231        fs::remove_dir_all(path).unwrap();
232    }
233
234    #[test]
235    fn reports_unknown_provider_and_exact_duplicates() {
236        let path = repository();
237        let mut stdout = Vec::new();
238        let mut stderr = Vec::new();
239        let error = CloudCommand::new(&mut stdout, &mut stderr)
240            .set_build_variables(
241                &path,
242                &CloudCommandOptions {
243                    ci_system: Some("missing".into()),
244                    ..Default::default()
245                },
246            )
247            .unwrap_err();
248        assert_eq!(error.error, CloudCommandError::NoCloudBuildProviderMatch);
249        assert_eq!(
250            error.to_string(),
251            "No cloud provider found by the name: \"missing\""
252        );
253
254        CloudCommand::new(&mut stdout, &mut stderr)
255            .set_build_variables(
256                &path,
257                &CloudCommandOptions {
258                    ci_system: Some("VisualStudioTeamServices".into()),
259                    additional_variables: vec![
260                        ("Name".into(), "one".into()),
261                        ("name".into(), "two".into()),
262                    ],
263                    ..Default::default()
264                },
265            )
266            .unwrap();
267
268        let error = CloudCommand::new(&mut stdout, &mut stderr)
269            .set_build_variables(
270                &path,
271                &CloudCommandOptions {
272                    ci_system: Some("VisualStudioTeamServices".into()),
273                    additional_variables: vec![
274                        ("Name".into(), "one".into()),
275                        ("Name".into(), "two".into()),
276                    ],
277                    ..Default::default()
278                },
279            )
280            .unwrap_err();
281        assert_eq!(error.error, CloudCommandError::DuplicateCloudVariable);
282        assert_eq!(
283            error.to_string(),
284            "Cloud build variable \"Name\" specified more than once."
285        );
286        fs::remove_dir_all(path).unwrap();
287    }
288}