Skip to main content

nerdbank_gitversioning/cloud_build_services/
jenkins.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//! [Jenkins Git plugin](https://plugins.jenkins.io/git/#plugin-content-environment-variables) support.
5
6use std::fs;
7use std::io::{self, Write};
8use std::path::Path;
9
10use crate::cloud::{CloudBuild, EnvironmentVariables, env, is_nonempty, should_start_with};
11
12/// Jenkins cloud-build integration.
13pub struct Jenkins;
14
15impl CloudBuild for Jenkins {
16    fn name(&self) -> &'static str {
17        "Jenkins"
18    }
19
20    fn is_applicable(&self) -> bool {
21        is_nonempty(env("JENKINS_URL").as_deref())
22    }
23
24    fn is_pull_request(&self) -> bool {
25        false
26    }
27
28    fn building_branch(&self) -> Option<String> {
29        should_start_with(
30            env("GIT_LOCAL_BRANCH").or_else(|| env("GIT_BRANCH")),
31            "refs/heads/",
32        )
33    }
34
35    fn building_tag(&self) -> Option<String> {
36        None
37    }
38
39    fn git_commit_id(&self) -> Option<String> {
40        env("GIT_COMMIT")
41    }
42
43    fn set_cloud_build_number(
44        &self,
45        build_number: &str,
46        stdout: &mut dyn Write,
47        _stderr: &mut dyn Write,
48    ) -> io::Result<EnvironmentVariables> {
49        if let Some(workspace) = env("WORKSPACE").filter(|value| !value.is_empty()) {
50            fs::write(
51                Path::new(&workspace).join("jenkins_build_number.txt"),
52                build_number.as_bytes(),
53            )?;
54        }
55        writeln!(stdout, "## GIT_VERSION: {build_number}")?;
56        Ok(EnvironmentVariables::from([(
57            "GIT_VERSION".into(),
58            build_number.into(),
59        )]))
60    }
61
62    fn set_cloud_build_variable(
63        &self,
64        name: &str,
65        value: &str,
66        _stdout: &mut dyn Write,
67        _stderr: &mut dyn Write,
68    ) -> io::Result<EnvironmentVariables> {
69        Ok(EnvironmentVariables::from([(name.into(), value.into())]))
70    }
71}