release_utils/
env.rs

1// Copyright 2024 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use std::env;
10use std::fmt::{self, Display, Formatter};
11
12/// Error getting an environment variable
13///
14/// Wrapper around [`std::env::VarError`] that adds the name of the
15/// variable. This provides a more useful error message.
16#[derive(Debug, PartialEq)]
17pub struct VarError {
18    /// Name of the environment variable.
19    pub name: String,
20
21    /// The underlying error.
22    pub err: env::VarError,
23}
24
25impl Display for VarError {
26    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
27        write!(f, r#"failed to read "{}" from the env"#, self.name)
28    }
29}
30
31impl std::error::Error for VarError {
32    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
33        Some(&self.err)
34    }
35}
36
37/// Get the commit to operate on from the `GITHUB_SHA` env var. When
38/// running in Github Actions, this will be set to the SHA of the commit
39/// that triggered the workflow.
40///
41/// See Github Actions' [Variables] documentation for details.
42///
43/// [Variables]: https://docs.github.com/en/actions/learn-github-actions/variables
44pub fn get_github_sha() -> Result<String, VarError> {
45    let commit_var_name = "GITHUB_SHA";
46    env::var(commit_var_name).map_err(|err| VarError {
47        name: commit_var_name.to_owned(),
48        err,
49    })
50}