Skip to main content

nerdbank_gitversioning/cloud_build_services/
github_actions.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//! [GitHub Actions](https://docs.github.com/actions/learn-github-actions/variables) support.
5
6use std::fs::OpenOptions;
7use std::io::{self, Read, Seek, SeekFrom, Write};
8use std::path::Path;
9use std::sync::atomic::{AtomicU64, Ordering};
10use std::time::{SystemTime, UNIX_EPOCH};
11
12use crate::cloud::{
13    CloudBuild, EnvironmentVariables, empty_variables, env, if_starts_with,
14    variable_for_environment,
15};
16
17static DELIMITER_SEQUENCE: AtomicU64 = AtomicU64::new(0);
18
19/// GitHub Actions cloud-build integration.
20pub struct GitHubActions;
21
22impl GitHubActions {
23    fn ignore_github_ref() -> bool {
24        env("IGNORE_GITHUB_REF").is_some_and(|value| value.eq_ignore_ascii_case("true"))
25    }
26
27    fn building_ref() -> Option<String> {
28        (!Self::ignore_github_ref())
29            .then(|| env("GITHUB_REF"))
30            .flatten()
31    }
32
33    /// Formats an assignment for the UTF-8 `GITHUB_ENV` environment file.
34    ///
35    /// Single-line values use `name=value`. Multiline values use GitHub's heredoc
36    /// syntax with a unique delimiter, and their line endings are normalized to LF.
37    pub fn format_variable(name: &str, value: &str) -> String {
38        if !value.contains(['\n', '\r']) {
39            return format!("{name}={value}\n");
40        }
41
42        let delimiter = loop {
43            let sequence = DELIMITER_SEQUENCE.fetch_add(1, Ordering::Relaxed);
44            let nanos = SystemTime::now()
45                .duration_since(UNIX_EPOCH)
46                .unwrap_or_default()
47                .as_nanos();
48            let candidate = format!(
49                "NBGV_EOF_{:032x}",
50                nanos ^ ((std::process::id() as u128) << 64) ^ sequence as u128
51            );
52            if !value.contains(&candidate) {
53                break candidate;
54            }
55        };
56
57        let normalized_value = value.replace("\r\n", "\n").replace('\r', "\n");
58        format!("{name}<<{delimiter}\n{normalized_value}\n{delimiter}\n")
59    }
60
61    /// Atomically appends an assignment to a GitHub Actions environment file.
62    ///
63    /// An exclusive file lock covers the seek and complete write so parallel build
64    /// processes cannot overwrite or interleave assignments. UTF-8 is written
65    /// without a byte-order mark. An unterminated pre-existing line is terminated.
66    pub fn append_variable(
67        environment_file_path: impl AsRef<Path>,
68        name: &str,
69        value: Option<&str>,
70    ) -> io::Result<()> {
71        let path = environment_file_path.as_ref();
72        if path.as_os_str().is_empty() {
73            return Err(io::Error::new(
74                io::ErrorKind::InvalidInput,
75                "environment file path must not be empty",
76            ));
77        }
78        if name.is_empty() {
79            return Err(io::Error::new(
80                io::ErrorKind::InvalidInput,
81                "variable name must not be empty",
82            ));
83        }
84        if name.contains(['\n', '\r']) {
85            return Err(io::Error::new(
86                io::ErrorKind::InvalidInput,
87                "variable names must not contain newlines",
88            ));
89        }
90
91        let bytes = Self::format_variable(name, value.unwrap_or_default()).into_bytes();
92        let mut file = OpenOptions::new()
93            .create(true)
94            .read(true)
95            .write(true)
96            .truncate(false)
97            .open(path)?;
98        file.lock()?;
99
100        let result = (|| {
101            let length = file.seek(SeekFrom::End(0))?;
102            if length > 0 {
103                file.seek(SeekFrom::End(-1))?;
104                let mut last = [0];
105                file.read_exact(&mut last)?;
106                if last[0] != b'\n' {
107                    file.seek(SeekFrom::End(0))?;
108                    file.write_all(b"\n")?;
109                }
110            }
111            file.seek(SeekFrom::End(0))?;
112            file.write_all(&bytes)?;
113            file.flush()
114        })();
115
116        let unlock_result = file.unlock();
117        result.and(unlock_result)
118    }
119}
120
121impl CloudBuild for GitHubActions {
122    fn name(&self) -> &'static str {
123        "GitHubActions"
124    }
125
126    fn is_applicable(&self) -> bool {
127        env("GITHUB_ACTIONS").as_deref() == Some("true")
128    }
129
130    fn is_pull_request(&self) -> bool {
131        matches!(
132            env("GITHUB_EVENT_NAME").as_deref(),
133            Some("pull_request" | "pull_request_target")
134        )
135    }
136
137    fn building_branch(&self) -> Option<String> {
138        if_starts_with(Self::building_ref(), "refs/heads/")
139    }
140
141    fn building_tag(&self) -> Option<String> {
142        if_starts_with(Self::building_ref(), "refs/tags/")
143    }
144
145    fn git_commit_id(&self) -> Option<String> {
146        (!Self::ignore_github_ref())
147            .then(|| env("GITHUB_SHA"))
148            .flatten()
149    }
150
151    fn set_cloud_build_number(
152        &self,
153        _build_number: &str,
154        _stdout: &mut dyn Write,
155        _stderr: &mut dyn Write,
156    ) -> io::Result<EnvironmentVariables> {
157        Ok(empty_variables())
158    }
159
160    fn set_cloud_build_variable(
161        &self,
162        name: &str,
163        value: &str,
164        _stdout: &mut dyn Write,
165        _stderr: &mut dyn Write,
166    ) -> io::Result<EnvironmentVariables> {
167        let environment_file = env("GITHUB_ENV").ok_or_else(|| {
168            io::Error::new(io::ErrorKind::InvalidInput, "GITHUB_ENV is not defined")
169        })?;
170        Self::append_variable(environment_file, name, Some(value))?;
171        Ok(variable_for_environment(name, value))
172    }
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178    use std::collections::HashSet;
179    use std::fs;
180    use std::sync::Arc;
181    use std::thread;
182
183    fn test_file() -> std::path::PathBuf {
184        std::env::current_dir()
185            .unwrap()
186            .join(format!("nbgv-github-env-{}.txt", unique_number()))
187    }
188
189    fn unique_number() -> u128 {
190        SystemTime::now()
191            .duration_since(UNIX_EPOCH)
192            .unwrap()
193            .as_nanos()
194            ^ DELIMITER_SEQUENCE.fetch_add(1, Ordering::Relaxed) as u128
195    }
196
197    #[test]
198    fn formats_single_line_values() {
199        assert_eq!(
200            GitHubActions::format_variable("Name", "Value"),
201            "Name=Value\n"
202        );
203        assert_eq!(GitHubActions::format_variable("Name", ""), "Name=\n");
204        assert_eq!(GitHubActions::format_variable("Name", "a=b"), "Name=a=b\n");
205    }
206
207    #[test]
208    fn formats_multiline_values_as_heredocs() {
209        for value in ["first\nsecond", "first\r\nsecond", "first\rsecond"] {
210            let actual = GitHubActions::format_variable("Name", value);
211            let lines: Vec<_> = actual.split('\n').collect();
212            let delimiter = lines[0].strip_prefix("Name<<").unwrap();
213            assert!(!delimiter.is_empty());
214            assert_eq!(&lines[1..3], ["first", "second"]);
215            assert_eq!(lines[3], delimiter);
216            assert_eq!(lines[4], "");
217            assert!(!actual.contains('\r'));
218            assert!(!value.contains(delimiter));
219        }
220
221        assert_ne!(
222            GitHubActions::format_variable("Name", "a\nb"),
223            GitHubActions::format_variable("Name", "a\nb")
224        );
225    }
226
227    #[test]
228    fn appends_utf8_and_terminates_existing_line() {
229        let path = test_file();
230        fs::write(&path, "Existing=1").unwrap();
231        GitHubActions::append_variable(&path, "Name", Some("é")).unwrap();
232        assert_eq!(fs::read(&path).unwrap(), b"Existing=1\nName=\xc3\xa9\n");
233        fs::remove_file(path).unwrap();
234    }
235
236    #[test]
237    fn rejects_invalid_arguments() {
238        let path = test_file();
239        assert_eq!(
240            GitHubActions::append_variable("", "Name", Some("Value"))
241                .unwrap_err()
242                .kind(),
243            io::ErrorKind::InvalidInput
244        );
245        assert!(GitHubActions::append_variable(&path, "", Some("Value")).is_err());
246        assert!(GitHubActions::append_variable(&path, "Na\nme", Some("Value")).is_err());
247    }
248
249    #[test]
250    fn concurrent_appends_are_complete_and_distinct() {
251        const WRITERS: usize = 16;
252        const WRITES_PER_WRITER: usize = 100;
253        let path = Arc::new(test_file());
254        let handles: Vec<_> = (0..WRITERS)
255            .map(|writer| {
256                let path = Arc::clone(&path);
257                thread::spawn(move || {
258                    for index in 0..WRITES_PER_WRITER {
259                        let name = format!("NBGV_{writer}_{index}");
260                        let value = format!(
261                            "{}{index}",
262                            ((b'a' + writer as u8) as char).to_string().repeat(100)
263                        );
264                        GitHubActions::append_variable(path.as_ref(), &name, Some(&value)).unwrap();
265                    }
266                })
267            })
268            .collect();
269        for handle in handles {
270            handle.join().unwrap();
271        }
272
273        let expected: HashSet<_> = (0..WRITERS)
274            .flat_map(|writer| {
275                (0..WRITES_PER_WRITER).map(move |index| {
276                    format!(
277                        "NBGV_{writer}_{index}={}{index}",
278                        ((b'a' + writer as u8) as char).to_string().repeat(100)
279                    )
280                })
281            })
282            .collect();
283        let actual: HashSet<_> = fs::read_to_string(path.as_ref())
284            .unwrap()
285            .lines()
286            .map(str::to_owned)
287            .collect();
288        assert_eq!(actual, expected);
289        fs::remove_file(path.as_ref()).unwrap();
290    }
291}