zombienet_provider/shared/
helpers.rs1use std::{
2 env,
3 path::{Path, PathBuf},
4};
5
6use anyhow::anyhow;
7use support::fs::FileSystem;
8use tracing::warn;
9
10use crate::{
11 types::{RunCommandOptions, TransferedFile},
12 DynNode, ProviderError,
13};
14
15pub(crate) async fn namespace_base_dir<FS: FileSystem>(
20 filesystem: &FS,
21 tmp_dir: &Path,
22 name: &str,
23 custom: Option<&Path>,
24) -> Result<PathBuf, ProviderError> {
25 let base_dir = custom.map_or_else(|| tmp_dir.join(name), Path::to_path_buf);
26 if filesystem.exists(&base_dir).await {
27 warn!(
28 "⚠️ Using an existing directory {} as base dir",
29 base_dir.display()
30 );
31 } else {
32 filesystem.create_dir_all(&base_dir).await.map_err(|err| {
33 ProviderError::CreateNamespaceFailed(
34 name.to_string(),
35 anyhow!("can't create base dir {}: {err}", base_dir.display()),
36 )
37 })?;
38 }
39 std::path::absolute(&base_dir)
40 .map_err(|err| ProviderError::CreateNamespaceFailed(name.to_string(), err.into()))
41}
42
43pub fn running_in_ci() -> bool {
45 env::var("RUN_IN_CI").unwrap_or_default() == "1"
46}
47
48pub(crate) fn default_true() -> bool {
50 true
51}
52
53pub(crate) fn ensure_wrapper(
57 name: &str,
58 wrapper: bool,
59 action: &str,
60 failed: fn(String, anyhow::Error) -> ProviderError,
61) -> Result<(), ProviderError> {
62 if wrapper {
63 Ok(())
64 } else {
65 Err(failed(
66 name.to_string(),
67 anyhow!("runs without the zombie wrapper, {action} is not available"),
68 ))
69 }
70}
71
72pub async fn extract_execution_result(
75 temp_node: &DynNode,
76 options: RunCommandOptions,
77 expected_path: Option<&PathBuf>,
78) -> Result<String, ProviderError> {
79 let output_contents = temp_node
80 .run_command(options)
81 .await?
82 .map_err(|(_, msg)| ProviderError::FileGenerationFailed(anyhow!("{msg}")))?;
83
84 if let Some(expected_path) = expected_path.as_ref() {
86 Ok(temp_node
87 .run_command(
88 RunCommandOptions::new("cat")
89 .args(vec![expected_path.to_string_lossy().to_string()]),
90 )
91 .await?
92 .map_err(|(_, msg)| {
93 ProviderError::FileGenerationFailed(anyhow!(format!(
94 "failed reading expected_path {}: {}",
95 expected_path.display(),
96 msg
97 )))
98 })?)
99 } else {
100 Ok(output_contents)
101 }
102}
103
104pub fn extract_namespace_info(
105 json_value: &serde_json::Value,
106) -> Result<(PathBuf, String), ProviderError> {
107 let base_dir = json_value
108 .get("local_base_dir")
109 .and_then(|v| v.as_str())
110 .map(PathBuf::from)
111 .ok_or(ProviderError::InvalidConfig(
112 "`field local_base_dir` is missing from zombie.json".to_string(),
113 ))?;
114
115 let name =
116 json_value
117 .get("ns")
118 .and_then(|v| v.as_str())
119 .ok_or(ProviderError::InvalidConfig(
120 "field `ns` is missing from zombie.json".to_string(),
121 ))?;
122
123 Ok((base_dir, name.to_string()))
124}
125
126pub(crate) fn injected_file_name(index: usize, file: &TransferedFile) -> String {
130 let name: String = file
131 .remote_path
132 .file_name()
133 .map(|name| name.to_string_lossy().into_owned())
134 .unwrap_or_default()
135 .chars()
136 .map(|c| {
137 if c.is_ascii_alphanumeric() || "-_.".contains(c) {
138 c
139 } else {
140 '-'
141 }
142 })
143 .collect();
144 format!("{index}-{name}")
145}
146
147#[cfg(test)]
148mod tests {
149 use super::*;
150
151 #[test]
152 fn check_runing_in_ci_env_var() {
153 assert!(!running_in_ci());
154 env::set_var("RUN_IN_CI", "1");
156 assert!(running_in_ci());
157 env::set_var("RUN_IN_CI", "");
159 }
160}