gh_workflow/
env.rs

1//!
2//! Environment variable types and implementations for GitHub workflows.
3
4use std::fmt::Display;
5
6use indexmap::IndexMap;
7use serde::{Deserialize, Serialize};
8use serde_json::Value;
9
10/// Represents environment variables in the workflow.
11#[derive(Default, Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
12#[serde(transparent)]
13pub struct Env(pub IndexMap<String, Value>);
14
15impl From<IndexMap<String, Value>> for Env {
16    /// Converts an `IndexMap` into an `Env`.
17    fn from(value: IndexMap<String, Value>) -> Self {
18        Env(value)
19    }
20}
21
22impl Env {
23    /// Sets the `GITHUB_TOKEN` environment variable.
24    pub fn github() -> Self {
25        let mut map = IndexMap::new();
26        map.insert(
27            "GITHUB_TOKEN".to_string(),
28            Value::from("${{ secrets.GITHUB_TOKEN }}"),
29        );
30        Env(map)
31    }
32
33    /// Creates a new `Env` with a specified key-value pair.
34    pub fn new<K: ToString, V: Into<Value>>(key: K, value: V) -> Self {
35        Env::default().add(key, value)
36    }
37
38    /// Adds an environment variable to the `Env`.
39    pub fn add<T1: ToString, T2: Into<Value>>(mut self, key: T1, value: T2) -> Self {
40        self.0.insert(key.to_string(), value.into());
41        self
42    }
43}
44
45/// Represents environment variables as key-value pairs.
46impl<S1: Display, S2: Display> From<(S1, S2)> for Env {
47    /// Converts a tuple into an `Env`.
48    fn from(value: (S1, S2)) -> Self {
49        let mut index_map: IndexMap<String, Value> = IndexMap::new();
50        index_map.insert(value.0.to_string(), Value::String(value.1.to_string()));
51        Env(index_map)
52    }
53}