1use crate::Config;
4use alloy_primitives::U256;
5use figment::value::Value;
6use foundry_compilers::artifacts::remappings::{Remapping, RemappingError};
7use serde::{
8 Deserialize, Deserializer, Serializer,
9 de::{DeserializeOwned, Error, IgnoredAny, MapAccess, Visitor},
10};
11use std::{
12 fmt, fs,
13 io::{self, BufReader},
14 path::{Path, PathBuf},
15 str::FromStr,
16};
17
18pub fn load_config() -> eyre::Result<Config> {
22 load_config_with_root(None)
23}
24
25pub fn load_config_with_root(root: Option<&Path>) -> eyre::Result<Config> {
27 let root = match root {
28 Some(root) => root,
29 None => &find_project_root(None)?,
30 };
31 Ok(Config::load_with_root(root)?.sanitized())
32}
33
34pub fn find_git_root(relative_to: &Path) -> io::Result<Option<PathBuf>> {
36 let root =
37 if relative_to.is_absolute() { relative_to } else { &dunce::canonicalize(relative_to)? };
38 Ok(root.ancestors().find(|p| p.join(".git").exists()).map(Path::to_path_buf))
39}
40
41pub fn find_project_root(cwd: Option<&Path>) -> io::Result<PathBuf> {
63 let cwd = match cwd {
64 Some(path) => path,
65 None => &std::env::current_dir()?,
66 };
67 let boundary = find_git_root(cwd)?;
68 let found = cwd
69 .ancestors()
70 .take_while(|p| boundary.as_ref().is_none_or(|boundary| p.starts_with(boundary)))
72 .find(|p| p.join(Config::FILE_NAME).is_file())
73 .map(Path::to_path_buf);
74 Ok(found.or(boundary).unwrap_or_else(|| cwd.to_path_buf()))
75}
76
77pub fn remappings_from_newline(
92 remappings: &str,
93) -> impl Iterator<Item = Result<Remapping, RemappingError>> + '_ {
94 remappings.lines().map(|x| x.trim()).filter(|x| !x.is_empty()).map(Remapping::from_str)
95}
96
97pub fn remappings_from_env_var(env_var: &str) -> Option<Result<Vec<Remapping>, RemappingError>> {
102 let val = std::env::var(env_var).ok()?;
103 Some(remappings_from_newline(&val).collect())
104}
105
106pub fn to_array_value(val: &str) -> Result<Value, figment::Error> {
110 Ok(val
111 .trim()
112 .trim_start_matches('[')
113 .trim_end_matches(']')
114 .split(',')
115 .map(str::trim)
116 .filter(|s| !s.is_empty())
117 .map(String::from)
118 .collect::<Vec<_>>()
119 .into())
120}
121
122pub fn foundry_toml_dirs(root: impl AsRef<Path>) -> Vec<PathBuf> {
144 walkdir::WalkDir::new(root)
145 .max_depth(1)
146 .into_iter()
147 .filter_map(Result::ok)
148 .filter(|entry| entry.file_type().is_dir())
149 .filter_map(|entry| dunce::canonicalize(entry.path()).ok())
150 .filter(|path| path.join(Config::FILE_NAME).exists())
151 .collect()
152}
153
154#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
156pub(crate) struct FoundryTomlDir {
157 pub canonical: PathBuf,
159 pub path: PathBuf,
161}
162
163pub(crate) fn foundry_toml_dir_entries(root: impl AsRef<Path>) -> Vec<FoundryTomlDir> {
165 let mut dirs = walkdir::WalkDir::new(root)
166 .max_depth(1)
167 .into_iter()
168 .filter_map(Result::ok)
169 .filter_map(|entry| {
170 let canonical = dunce::canonicalize(entry.path()).ok()?;
171 (canonical.is_dir() && canonical.join(Config::FILE_NAME).exists())
172 .then(|| FoundryTomlDir { path: entry.path().to_path_buf(), canonical })
173 })
174 .collect::<Vec<_>>();
175 dirs.sort_unstable_by(|a, b| a.canonical.cmp(&b.canonical).then_with(|| a.path.cmp(&b.path)));
176 dirs.dedup();
177 dirs
178}
179
180pub(crate) fn get_dir_remapping(dir: impl AsRef<Path>) -> Option<Remapping> {
182 let dir = dir.as_ref();
183 dir.file_name().and_then(|s| s.to_str()).filter(|s| !s.is_empty()).map(|dir_name| {
184 let mut r = Remapping {
185 context: None,
186 name: format!("{dir_name}/"),
187 path: format!("{}", dir.display()),
188 };
189 if !r.path.ends_with('/') {
190 r.path.push('/')
191 }
192 r
193 })
194}
195
196pub(crate) fn deserialize_stringified_percent<'de, D>(deserializer: D) -> Result<u32, D::Error>
198where
199 D: Deserializer<'de>,
200{
201 let num: U256 = Numeric::deserialize(deserializer)?.into();
202 let num: u64 = num.try_into().map_err(serde::de::Error::custom)?;
203 if num <= 100 {
204 num.try_into().map_err(serde::de::Error::custom)
205 } else {
206 Err(serde::de::Error::custom("percent must be lte 100"))
207 }
208}
209
210pub(crate) fn deserialize_u64_or_max<'de, D>(deserializer: D) -> Result<u64, D::Error>
212where
213 D: Deserializer<'de>,
214{
215 #[derive(Deserialize)]
216 #[serde(untagged)]
217 enum Val {
218 Number(u64),
219 String(String),
220 }
221
222 match Val::deserialize(deserializer)? {
223 Val::Number(num) => Ok(num),
224 Val::String(s) if s.eq_ignore_ascii_case("max") => Ok(u64::MAX),
225 Val::String(s) => s.parse::<u64>().map_err(D::Error::custom),
226 }
227}
228
229pub(crate) fn deserialize_usize_or_max<'de, D>(deserializer: D) -> Result<usize, D::Error>
231where
232 D: Deserializer<'de>,
233{
234 deserialize_u64_or_max(deserializer)?.try_into().map_err(D::Error::custom)
235}
236
237pub(crate) fn serialize_usize_or_max<S>(value: &usize, serializer: S) -> Result<S::Ok, S::Error>
240where
241 S: Serializer,
242{
243 if *value == usize::MAX {
244 serializer.serialize_str("max")
245 } else if *value > i64::MAX as usize {
246 serializer.serialize_str(&value.to_string())
247 } else {
248 serializer.serialize_u64(*value as u64)
249 }
250}
251
252pub fn deserialize_u64_to_u256<'de, D>(deserializer: D) -> Result<U256, D::Error>
254where
255 D: Deserializer<'de>,
256{
257 #[derive(Deserialize)]
258 #[serde(untagged)]
259 enum NumericValue {
260 U256(U256),
261 U64(u64),
262 String(String),
263 }
264
265 match NumericValue::deserialize(deserializer)? {
266 NumericValue::U64(n) => Ok(U256::from(n)),
267 NumericValue::U256(n) => Ok(n),
268 NumericValue::String(s) => {
269 U256::from_str(&s).map_err(D::Error::custom)
271 }
272 }
273}
274
275pub fn serialize_u64_or_u256<S>(n: &U256, serializer: S) -> Result<S::Ok, S::Error>
280where
281 S: Serializer,
282{
283 if let Ok(n_i64) = i64::try_from(*n) {
287 serializer.serialize_i64(n_i64)
288 } else if let Ok(n_u64) = u64::try_from(*n) {
289 serializer.serialize_str(&n_u64.to_string())
290 } else {
291 serializer.serialize_str(&format!("{n:#x}"))
292 }
293}
294
295#[derive(Clone, Copy, Deserialize)]
297#[serde(untagged)]
298pub enum Numeric {
299 U256(U256),
301 Num(u64),
303}
304
305impl From<Numeric> for U256 {
306 fn from(n: Numeric) -> Self {
307 match n {
308 Numeric::U256(n) => n,
309 Numeric::Num(n) => Self::from(n),
310 }
311 }
312}
313
314impl FromStr for Numeric {
315 type Err = String;
316
317 fn from_str(s: &str) -> Result<Self, Self::Err> {
318 if s.starts_with("0x") {
319 U256::from_str_radix(s, 16).map(Numeric::U256).map_err(|err| err.to_string())
320 } else {
321 U256::from_str(s).map(Numeric::U256).map_err(|err| err.to_string())
322 }
323 }
324}
325
326pub fn read_build_info_input<T: DeserializeOwned>(path: &Path) -> eyre::Result<Option<T>> {
332 let mut input = None;
333 let reader = BufReader::new(fs::File::open(path)?);
334 let read =
335 serde_json::Deserializer::from_reader(reader).deserialize_map(BuildInfoInput(&mut input));
336 match (input, read) {
337 (Some(input), _) => Ok(Some(input)),
338 (None, Ok(())) => Ok(None),
339 (None, Err(error)) => Err(error.into()),
340 }
341}
342
343struct BuildInfoInput<'a, T>(&'a mut Option<T>);
345
346impl<'de, T: Deserialize<'de>> Visitor<'de> for BuildInfoInput<'_, T> {
347 type Value = ();
348
349 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
350 formatter.write_str("a build info")
351 }
352
353 fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<(), A::Error> {
354 let mut id = false;
355 while let Some(key) = map.next_key::<String>()? {
356 if key == "input" {
357 *self.0 = Some(map.next_value()?);
358 return Err(A::Error::custom("stopped after the input"));
360 }
361 id |= key == "id";
362 map.next_value::<IgnoredAny>()?;
363 }
364 if id { Ok(()) } else { Err(A::Error::custom("not a build info")) }
365 }
366}
367
368pub(crate) struct Present;
371
372impl<'de> Deserialize<'de> for Present {
373 fn deserialize<D: Deserializer<'de>>(_deserializer: D) -> Result<Self, D::Error> {
374 Ok(Self)
375 }
376}
377
378#[cfg(all(test, unix))]
379mod tests {
380 use super::{FoundryTomlDir, foundry_toml_dir_entries, foundry_toml_dirs};
381 use std::{fs, os::unix::fs::symlink};
382 use tempfile::tempdir;
383
384 #[test]
385 fn finds_physical_foundry_toml_dirs_without_recursing() {
386 let temp = tempdir().unwrap();
387 let root = temp.path().join("lib");
388 let dependency = root.join("dependency");
389 let nested = dependency.join("nested");
390 fs::create_dir_all(&nested).unwrap();
391 fs::write(dependency.join("foundry.toml"), "").unwrap();
392 fs::write(nested.join("foundry.toml"), "").unwrap();
393
394 assert_eq!(foundry_toml_dirs(&root), vec![dunce::canonicalize(dependency).unwrap()]);
395 }
396
397 #[test]
398 fn preserves_sorted_aliases_for_the_same_canonical_dependency() {
399 let temp = tempdir().unwrap();
400 let root = temp.path().join("lib");
401 let dependency = temp.path().join("dependency");
402 fs::create_dir_all(&root).unwrap();
403 fs::create_dir_all(&dependency).unwrap();
404 fs::write(dependency.join("foundry.toml"), "").unwrap();
405 symlink(&dependency, root.join("z-alias")).unwrap();
406 symlink(&dependency, root.join("a-alias")).unwrap();
407
408 let canonical = dunce::canonicalize(dependency).unwrap();
409 assert_eq!(
410 foundry_toml_dir_entries(&root),
411 vec![
412 FoundryTomlDir { path: root.join("a-alias"), canonical: canonical.clone() },
413 FoundryTomlDir { path: root.join("z-alias"), canonical },
414 ]
415 );
416 }
417
418 #[test]
419 fn sorts_distinct_dependencies_by_canonical_path() {
420 let temp = tempdir().unwrap();
421 let root = temp.path().join("lib");
422 let dependency_a = temp.path().join("dependency-a");
423 let dependency_z = temp.path().join("dependency-z");
424 fs::create_dir_all(&root).unwrap();
425 for dependency in [&dependency_z, &dependency_a] {
426 fs::create_dir_all(dependency).unwrap();
427 fs::write(dependency.join("foundry.toml"), "").unwrap();
428 }
429 symlink(&dependency_z, root.join("a-alias")).unwrap();
430 symlink(&dependency_a, root.join("z-alias")).unwrap();
431
432 let canonical = foundry_toml_dir_entries(&root)
433 .into_iter()
434 .map(|entry| entry.canonical)
435 .collect::<Vec<_>>();
436 assert_eq!(
437 canonical,
438 vec![
439 dunce::canonicalize(dependency_a).unwrap(),
440 dunce::canonicalize(dependency_z).unwrap(),
441 ]
442 );
443 }
444
445 #[test]
446 fn ignores_broken_and_cyclic_symlinks() {
447 let temp = tempdir().unwrap();
448 let root = temp.path().join("lib");
449 fs::create_dir_all(&root).unwrap();
450 symlink("missing", root.join("broken")).unwrap();
451 symlink("cycle-b", root.join("cycle-a")).unwrap();
452 symlink("cycle-a", root.join("cycle-b")).unwrap();
453
454 assert!(foundry_toml_dir_entries(&root).is_empty());
455 }
456}