foundry_test_utils/
util.rs1use foundry_compilers::{Project, ProjectCompileOutput, Vyper, utils::RuntimeOrHandle};
2use foundry_config::Config;
3use std::{
4 env,
5 fs::{self, File},
6 io::{Read, Seek, Write},
7 path::{Path, PathBuf},
8 process::Command,
9 sync::LazyLock,
10};
11
12const SKIP_DIRS: &[&str] = &["out", "cache", "broadcast"];
16
17pub use crate::{ext::*, prj::*};
18
19pub const FORGE_STD_REVISION: &str = include_str!("../../../testdata/forge-std-rev");
21
22static TEMPLATE_PATH: LazyLock<PathBuf> =
25 LazyLock::new(|| env::temp_dir().join("foundry-forge-test-template"));
26
27static TEMPLATE_LOCK: LazyLock<PathBuf> =
30 LazyLock::new(|| env::temp_dir().join("foundry-forge-test-template.lock"));
31
32pub const SOLC_VERSION: &str = "0.8.33";
34
35pub const OTHER_SOLC_VERSION: &str = "0.8.26";
39
40pub fn initialize(target: &Path) {
56 test_debug!("initializing {}", target.display());
57
58 let tpath = TEMPLATE_PATH.as_path();
59 pretty_err(tpath, fs::create_dir_all(tpath));
60
61 let mut lock = crate::fd_lock::new_lock(TEMPLATE_LOCK.as_path());
63 let mut _read = lock.read().unwrap();
64 if !crate::fd_lock::lock_exists(TEMPLATE_LOCK.as_path()) {
65 drop(_read);
75 let mut write = lock.write().unwrap();
76
77 let mut data = Vec::new();
78 write.read_to_end(&mut data).unwrap();
79 if data != crate::fd_lock::LOCK_TOKEN {
80 let (prj, mut cmd) = setup_forge("template", foundry_compilers::PathStyle::Dapptools);
82 test_debug!("- initializing template dir in {}", prj.root().display());
83
84 cmd.args(["init", "--force", "--empty"]).assert_success();
85 prj.write_config(Config {
86 solc: Some(foundry_config::SolcReq::Version(SOLC_VERSION.parse().unwrap())),
87 ..Default::default()
88 });
89
90 let output = Command::new("git")
92 .current_dir(prj.root().join("lib/forge-std"))
93 .args(["checkout", FORGE_STD_REVISION])
94 .output()
95 .expect("failed to checkout forge-std");
96 assert!(output.status.success(), "{output:#?}");
97
98 cmd.forge_fuse().arg("build").assert_success();
100
101 let _ = fs::remove_dir_all(tpath);
103
104 pretty_err(tpath, copy_dir_filtered(prj.root(), tpath));
106
107 write.set_len(0).unwrap();
109 write.seek(std::io::SeekFrom::Start(0)).unwrap();
110 write.write_all(crate::fd_lock::LOCK_TOKEN).unwrap();
111 }
112
113 drop(write);
115 _read = lock.read().unwrap();
116 }
117
118 test_debug!("- copying template dir from {}", tpath.display());
119 pretty_err(target, fs::create_dir_all(target));
120 pretty_err(target, copy_dir_filtered(tpath, target));
121}
122
123pub fn get_compiled(project: &mut Project) -> ProjectCompileOutput {
125 let lock_file_path = project.sources_path().join(".lock");
126 let mut lock = crate::fd_lock::new_lock(&lock_file_path);
129 let read = lock.read().unwrap();
130 let out;
131
132 let mut write = None;
133 if !project.cache_path().exists() || !crate::fd_lock::lock_exists(&lock_file_path) {
134 drop(read);
135 write = Some(lock.write().unwrap());
136 test_debug!("cache miss for {}", lock_file_path.display());
137 } else {
138 test_debug!("cache hit for {}", lock_file_path.display());
139 }
140
141 if project.compiler.vyper.is_none() {
142 project.compiler.vyper = Some(get_vyper());
143 }
144
145 test_debug!("compiling {}", lock_file_path.display());
146 out = project.compile().unwrap();
147 test_debug!("compiled {}", lock_file_path.display());
148
149 assert!(!out.has_compiler_errors(), "Compiled with errors:\n{out}");
150
151 if let Some(write) = &mut write {
152 write.write_all(crate::fd_lock::LOCK_TOKEN).unwrap();
153 }
154
155 out
156}
157
158pub fn get_vyper() -> Vyper {
160 static VYPER: LazyLock<PathBuf> = LazyLock::new(|| std::env::temp_dir().join("vyper"));
161
162 if let Ok(vyper) = Vyper::new("vyper") {
163 return vyper;
164 }
165 if let Ok(vyper) = Vyper::new(&*VYPER) {
166 return vyper;
167 }
168 return RuntimeOrHandle::new().block_on(install());
169
170 async fn install() -> Vyper {
171 #[cfg(target_family = "unix")]
172 use std::{fs::Permissions, os::unix::fs::PermissionsExt};
173
174 let path = VYPER.as_path();
175 let mut file = File::create(path).unwrap();
176 if let Err(e) = file.try_lock() {
177 if let fs::TryLockError::WouldBlock = e {
178 file.lock().unwrap();
179 assert!(path.exists());
180 return Vyper::new(path).unwrap();
181 }
182 file.lock().unwrap();
183 }
184
185 let suffix = match svm::platform() {
186 svm::Platform::MacOsAarch64 => "darwin",
187 svm::Platform::LinuxAmd64 => "linux",
188 svm::Platform::WindowsAmd64 => "windows.exe",
189 platform => panic!(
190 "unsupported platform {platform:?} for installing vyper, \
191 install it manually and add it to $PATH"
192 ),
193 };
194 let url = format!(
195 "https://github.com/vyperlang/vyper/releases/download/v0.4.3/vyper.0.4.3+commit.bff19ea2.{suffix}"
196 );
197
198 test_debug!("downloading vyper from {url}");
199 let res = reqwest::Client::builder().build().unwrap().get(url).send().await.unwrap();
200
201 assert!(res.status().is_success());
202
203 let bytes = res.bytes().await.unwrap();
204
205 file.write_all(&bytes).unwrap();
206
207 #[cfg(target_family = "unix")]
208 file.set_permissions(Permissions::from_mode(0o755)).unwrap();
209
210 Vyper::new(path).unwrap()
211 }
212}
213
214#[track_caller]
215pub fn pretty_err<T, E: std::error::Error>(path: impl AsRef<Path>, res: Result<T, E>) -> T {
216 match res {
217 Ok(t) => t,
218 Err(err) => panic!("{}: {err}", path.as_ref().display()),
219 }
220}
221
222pub fn read_string(path: impl AsRef<Path>) -> String {
223 let path = path.as_ref();
224 pretty_err(path, std::fs::read_to_string(path))
225}
226
227pub fn copy_dir_filtered(src: &Path, dst: &Path) -> std::io::Result<()> {
233 fs::create_dir_all(dst)?;
234 copy_dir_filtered_inner(src, dst, true)
235}
236
237fn copy_dir_filtered_inner(src: &Path, dst: &Path, is_root: bool) -> std::io::Result<()> {
238 for entry in fs::read_dir(src)? {
239 let entry = entry?;
240 let ty = entry.file_type()?;
241 let src_path = entry.path();
242 let dst_path = dst.join(entry.file_name());
243
244 if ty.is_dir() {
245 if is_root
247 && let Some(name) = entry.file_name().to_str()
248 && SKIP_DIRS.contains(&name)
249 {
250 continue;
251 }
252 fs::create_dir_all(&dst_path)?;
253 copy_dir_filtered_inner(&src_path, &dst_path, false)?;
254 } else {
255 fs::copy(&src_path, &dst_path)?;
256 }
257 }
258 Ok(())
259}