zombienet_provider/shared/
helpers.rs

1use std::{env, path::PathBuf};
2
3use anyhow::anyhow;
4
5use crate::{types::RunCommandOptions, DynNode, ProviderError};
6
7/// Check if we are running in `CI` by checking the 'RUN_IN_CI' env var
8pub fn running_in_ci() -> bool {
9    env::var("RUN_IN_CI").unwrap_or_default() == "1"
10}
11
12/// Executes a command on a temporary node and extracts the execution result either from the
13/// standard output or a file.
14pub async fn extract_execution_result(
15    temp_node: &DynNode,
16    options: RunCommandOptions,
17    expected_path: Option<&PathBuf>,
18) -> Result<String, ProviderError> {
19    let output_contents = temp_node
20        .run_command(options)
21        .await?
22        .map_err(|(_, msg)| ProviderError::FileGenerationFailed(anyhow!("{msg}")))?;
23
24    // If an expected_path is provided, read the file contents from inside the container
25    if let Some(expected_path) = expected_path.as_ref() {
26        Ok(temp_node
27            .run_command(
28                RunCommandOptions::new("cat")
29                    .args(vec![expected_path.to_string_lossy().to_string()]),
30            )
31            .await?
32            .map_err(|(_, msg)| {
33                ProviderError::FileGenerationFailed(anyhow!(format!(
34                    "failed reading expected_path {}: {}",
35                    expected_path.display(),
36                    msg
37                )))
38            })?)
39    } else {
40        Ok(output_contents)
41    }
42}
43
44pub fn extract_namespace_info(
45    json_value: &serde_json::Value,
46) -> Result<(PathBuf, String), ProviderError> {
47    let base_dir = json_value
48        .get("local_base_dir")
49        .and_then(|v| v.as_str())
50        .map(PathBuf::from)
51        .ok_or(ProviderError::InvalidConfig(
52            "`field local_base_dir` is missing from zombie.json".to_string(),
53        ))?;
54
55    let name =
56        json_value
57            .get("ns")
58            .and_then(|v| v.as_str())
59            .ok_or(ProviderError::InvalidConfig(
60                "field `ns` is missing from zombie.json".to_string(),
61            ))?;
62
63    Ok((base_dir, name.to_string()))
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69
70    #[test]
71    fn check_runing_in_ci_env_var() {
72        assert!(!running_in_ci());
73        // now set the env var
74        env::set_var("RUN_IN_CI", "1");
75        assert!(running_in_ci());
76        // reset
77        env::set_var("RUN_IN_CI", "");
78    }
79}