Skip to main content

nerdbank_gitversioning/cloud_build_services/
visual_studio_team_services.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//! [Azure DevOps](https://learn.microsoft.com/azure/devops/pipelines/build/variables) support.
5
6use std::io::{self, Write};
7
8use crate::cloud::{
9    CloudBuild, EnvironmentVariables, env, if_starts_with, is_nonempty, variable_for_environment,
10};
11
12/// Azure DevOps (formerly Visual Studio Team Services) integration.
13pub struct VisualStudioTeamServices;
14
15impl CloudBuild for VisualStudioTeamServices {
16    fn name(&self) -> &'static str {
17        "VisualStudioTeamServices"
18    }
19
20    fn is_applicable(&self) -> bool {
21        is_nonempty(env("SYSTEM_TEAMPROJECTID").as_deref())
22    }
23
24    fn is_pull_request(&self) -> bool {
25        env("BUILD_SOURCEBRANCH").is_some_and(|value| value.starts_with("refs/pull/"))
26    }
27
28    fn building_branch(&self) -> Option<String> {
29        if_starts_with(env("BUILD_SOURCEBRANCH"), "refs/heads/")
30    }
31
32    fn building_tag(&self) -> Option<String> {
33        if_starts_with(env("BUILD_SOURCEBRANCH"), "refs/tags/")
34    }
35
36    fn git_commit_id(&self) -> Option<String> {
37        None
38    }
39
40    fn set_cloud_build_number(
41        &self,
42        build_number: &str,
43        stdout: &mut dyn Write,
44        _stderr: &mut dyn Write,
45    ) -> io::Result<EnvironmentVariables> {
46        writeln!(
47            stdout,
48            "##vso[build.updatebuildnumber]{}",
49            escape_data(build_number)
50        )?;
51        Ok(variable_for_environment("Build.BuildNumber", build_number))
52    }
53
54    fn set_cloud_build_variable(
55        &self,
56        name: &str,
57        value: &str,
58        stdout: &mut dyn Write,
59        _stderr: &mut dyn Write,
60    ) -> io::Result<EnvironmentVariables> {
61        let escaped_name = escape_property(name);
62        let escaped_value = escape_data(value);
63        writeln!(
64            stdout,
65            "##vso[task.setvariable variable={escaped_name};]{escaped_value}"
66        )?;
67        writeln!(
68            stdout,
69            "##vso[task.setvariable variable={escaped_name};isOutput=true;]{escaped_value}"
70        )?;
71        Ok(variable_for_environment(name, value))
72    }
73}
74
75fn escape_data(value: &str) -> String {
76    value
77        .replace('%', "%AZP25")
78        .replace('\r', "%0D")
79        .replace('\n', "%0A")
80}
81
82fn escape_property(value: &str) -> String {
83    escape_data(value).replace(']', "%5D").replace(';', "%3B")
84}