1use crate::{Config, extend, utils};
2use figment::{
3 Error, Figment, Metadata, Profile, Provider,
4 providers::{Env, Format, Toml},
5 value::{Dict, Map, Value},
6};
7use foundry_compilers::ProjectPathsConfig;
8use heck::ToSnakeCase;
9use std::{
10 cell::OnceCell,
11 path::{Path, PathBuf},
12};
13
14pub(crate) trait ProviderExt: Provider + Sized {
15 fn rename(
16 self,
17 from: impl Into<Profile>,
18 to: impl Into<Profile>,
19 ) -> RenameProfileProvider<Self> {
20 RenameProfileProvider::new(self, from, to)
21 }
22
23 fn wrap(
24 self,
25 wrapping_key: impl Into<Profile>,
26 profile: impl Into<Profile>,
27 ) -> WrapProfileProvider<Self> {
28 WrapProfileProvider::new(self, wrapping_key, profile)
29 }
30
31 fn strict_select(
32 self,
33 profiles: impl IntoIterator<Item = impl Into<Profile>>,
34 ) -> OptionalStrictProfileProvider<Self> {
35 OptionalStrictProfileProvider::new(self, profiles)
36 }
37
38 fn fallback(
39 self,
40 profile: impl Into<Profile>,
41 fallback: impl Into<Profile>,
42 ) -> FallbackProfileProvider<Self> {
43 FallbackProfileProvider::new(self, profile, fallback)
44 }
45
46 fn legacy_labels(self) -> LegacyLabelsProvider<Self> {
47 LegacyLabelsProvider(self)
48 }
49}
50
51impl<P: Provider> ProviderExt for P {}
52
53pub(crate) struct TomlFileProvider {
56 env_var: Option<&'static str>,
57 env_val: OnceCell<Option<String>>,
58 default: PathBuf,
59 cache: OnceCell<Result<Map<Profile, Dict>, Error>>,
60}
61
62impl TomlFileProvider {
63 pub(crate) const fn new(env_var: Option<&'static str>, default: PathBuf) -> Self {
64 Self { env_var, env_val: OnceCell::new(), default, cache: OnceCell::new() }
65 }
66
67 fn env_val(&self) -> Option<&str> {
68 self.env_val.get_or_init(|| self.env_var.and_then(Env::var)).as_deref()
69 }
70
71 fn file(&self) -> PathBuf {
72 self.env_val().map(PathBuf::from).unwrap_or_else(|| self.default.clone())
73 }
74
75 fn is_missing(&self) -> bool {
76 if let Some(file) = self.env_val() {
77 let path = Path::new(&file);
78 if !path.exists() {
79 return true;
80 }
81 }
82 false
83 }
84
85 fn read(&self) -> Result<Map<Profile, Dict>, Error> {
87 use serde::de::Error as _;
88
89 let local_path = self.file();
91 if !local_path.exists() {
92 if let Some(file) = self.env_val() {
93 return Err(Error::custom(format!(
94 "Config file `{}` set in env var `{}` does not exist",
95 file,
96 self.env_var.unwrap()
97 )));
98 }
99 return Ok(Map::new());
100 }
101
102 let local_provider = Toml::file(local_path.clone()).nested();
104
105 let local_path_str = local_path.to_string_lossy();
107 let local_content = std::fs::read_to_string(&local_path)
108 .map_err(|e| Error::custom(e.to_string()).with_path(&local_path_str))?;
109 let partial_config: extend::ExtendsPartialConfig = toml::from_str(&local_content)
110 .map_err(|e| Error::custom(e.to_string()).with_path(&local_path_str))?;
111
112 let selected_profile = Config::selected_profile();
114 let extends_config = partial_config.profile.as_ref().and_then(|profiles| {
115 let profile_str = selected_profile.to_string();
116 profiles.get(&profile_str).and_then(|cfg| cfg.extends.as_ref())
117 });
118
119 if let Some(extends_config) = extends_config {
121 let extends_path = extends_config.path();
122 let extends_strategy = extends_config.strategy();
123 let relative_base_path = PathBuf::from(extends_path);
124 let local_dir = local_path.parent().ok_or_else(|| {
125 Error::custom(format!(
126 "Could not determine parent directory of config file: {}",
127 local_path.display()
128 ))
129 })?;
130
131 let base_path =
132 foundry_compilers::utils::canonicalize(local_dir.join(&relative_base_path))
133 .map_err(|e| {
134 Error::custom(format!(
135 "Failed to resolve inherited config path: {}: {e}",
136 relative_base_path.display()
137 ))
138 })?;
139
140 if !base_path.is_file() {
142 return Err(Error::custom(format!(
143 "Inherited config file does not exist or is not a file: {}",
144 base_path.display()
145 )));
146 }
147
148 if foundry_compilers::utils::canonicalize(&local_path).ok().as_ref() == Some(&base_path)
150 {
151 return Err(Error::custom(format!(
152 "Config file {} cannot inherit from itself.",
153 local_path.display()
154 )));
155 }
156
157 let base_path_str = base_path.to_string_lossy();
159 let base_content = std::fs::read_to_string(&base_path)
160 .map_err(|e| Error::custom(e.to_string()).with_path(&base_path_str))?;
161 let base_partial: extend::ExtendsPartialConfig = toml::from_str(&base_content)
162 .map_err(|e| Error::custom(e.to_string()).with_path(&base_path_str))?;
163
164 let base_extends = base_partial
166 .profile
167 .as_ref()
168 .and_then(|profiles| {
169 let profile_str = selected_profile.to_string();
170 profiles.get(&profile_str)
171 })
172 .and_then(|profile| profile.extends.as_ref());
173
174 if base_extends.is_some() {
176 return Err(Error::custom(format!(
177 "Nested inheritance is not allowed. Base file '{}' cannot have an 'extends' field in profile '{selected_profile}'.",
178 base_path.display()
179 )));
180 }
181
182 let base_provider = NormalizeSymbolicProvider::new(
185 NormalizeTracingProvider::new(
186 Toml::file(base_path).nested().legacy_labels(),
187 selected_profile.clone(),
188 ),
189 selected_profile.clone(),
190 );
191 let local_provider = NormalizeSymbolicProvider::new(
192 NormalizeTracingProvider::new(
193 local_provider.legacy_labels(),
194 selected_profile.clone(),
195 ),
196 selected_profile.clone(),
197 );
198
199 match extends_strategy {
201 extend::ExtendStrategy::ExtendArrays => {
202 Figment::new().merge(base_provider).admerge(local_provider).data()
207 }
208 extend::ExtendStrategy::ReplaceArrays => {
209 Figment::new().merge(base_provider).merge(local_provider).data()
213 }
214 extend::ExtendStrategy::NoCollision => {
215 let base_data = base_provider.data()?;
217 let local_data = local_provider.data()?;
218
219 let profile_key = Profile::new("profile");
220 if let (Some(local_profiles), Some(base_profiles)) =
221 (local_data.get(&profile_key), base_data.get(&profile_key))
222 {
223 let profile_str = selected_profile.to_string();
225 let base_dict = base_profiles.get(&profile_str).and_then(|v| v.as_dict());
226 let local_dict = local_profiles.get(&profile_str).and_then(|v| v.as_dict());
227
228 if let (Some(local_dict), Some(base_dict)) = (local_dict, base_dict) {
230 let collisions: Vec<&String> = local_dict
231 .keys()
232 .filter(|key| {
233 *key != "extends" && base_dict.contains_key(*key)
235 })
236 .collect();
237
238 if !collisions.is_empty() {
239 return Err(Error::custom(format!(
240 "Key collision detected in profile '{profile_str}' when extending '{extends_path}'. \
241 Conflicting keys: {collisions:?}. Use 'extends.strategy' or 'extends_strategy' to specify how to handle conflicts."
242 )));
243 }
244 }
245 }
246
247 Figment::new().merge(base_provider).merge(local_provider).data()
249 }
250 }
251 } else {
252 local_provider.data()
254 }
255 }
256}
257
258struct NormalizeSymbolicProvider<P> {
259 provider: P,
260 selected_profile: Profile,
261}
262
263impl<P> NormalizeSymbolicProvider<P> {
264 const fn new(provider: P, selected_profile: Profile) -> Self {
265 Self { provider, selected_profile }
266 }
267}
268
269struct NormalizeTracingProvider<P> {
270 provider: P,
271 selected_profile: Profile,
272}
273
274impl<P> NormalizeTracingProvider<P> {
275 const fn new(provider: P, selected_profile: Profile) -> Self {
276 Self { provider, selected_profile }
277 }
278}
279
280impl<P: Provider> Provider for NormalizeTracingProvider<P> {
281 fn metadata(&self) -> Metadata {
282 self.provider.metadata()
283 }
284
285 fn data(&self) -> Result<Map<Profile, Dict>, Error> {
286 let mut data = self.provider.data()?;
287 normalize_tracing_section(&mut data, &self.selected_profile);
288 Ok(data)
289 }
290
291 fn profile(&self) -> Option<Profile> {
292 self.provider.profile()
293 }
294}
295
296fn normalize_tracing_section(data: &mut Map<Profile, Dict>, selected_profile: &Profile) {
300 let Some(tracing) = data.remove(&Profile::new("tracing")) else { return };
301
302 let profiles = data.entry(Profile::new(Config::PROFILE_SECTION)).or_default();
303 let profile =
304 profiles.entry(selected_profile.to_string()).or_insert_with(|| Value::from(Dict::new()));
305 let Value::Dict(_, profile) = profile else { return };
306
307 match (profile.get_mut("tracing"), tracing) {
308 (Some(Value::Dict(_, profile_tracing)), tracing) => {
309 merge_missing(profile_tracing, tracing);
310 }
311 (None, tracing) => {
312 profile.insert("tracing".to_string(), Value::from(tracing));
313 }
314 _ => {}
315 }
316}
317
318impl<P: Provider> Provider for NormalizeSymbolicProvider<P> {
319 fn metadata(&self) -> Metadata {
320 self.provider.metadata()
321 }
322
323 fn data(&self) -> Result<Map<Profile, Dict>, Error> {
324 let mut data = self.provider.data()?;
325 normalize_symbolic_section(&mut data, &self.selected_profile);
326 Ok(data)
327 }
328
329 fn profile(&self) -> Option<Profile> {
330 self.provider.profile()
331 }
332}
333
334fn normalize_symbolic_section(data: &mut Map<Profile, Dict>, selected_profile: &Profile) {
340 let Some(symbolic) = data.remove(&Profile::new("symbolic")) else { return };
341
342 let profiles = data.entry(Profile::new(Config::PROFILE_SECTION)).or_default();
343 let profile =
344 profiles.entry(selected_profile.to_string()).or_insert_with(|| Value::from(Dict::new()));
345 let Value::Dict(_, profile) = profile else { return };
346
347 match (profile.get_mut("symbolic"), symbolic) {
348 (Some(Value::Dict(_, profile_symbolic)), symbolic) => {
349 merge_missing(profile_symbolic, symbolic);
350 }
351 (None, symbolic) => {
352 profile.insert("symbolic".to_string(), Value::from(symbolic));
353 }
354 _ => {}
355 }
356}
357
358fn merge_missing(target: &mut Dict, fallback: Dict) {
360 for (key, value) in fallback {
361 match (target.get_mut(&key), value) {
362 (Some(Value::Dict(_, target)), Value::Dict(_, fallback)) => {
363 merge_missing(target, fallback);
364 }
365 (None, value) => {
366 target.insert(key, value);
367 }
368 _ => {}
369 }
370 }
371}
372
373impl Provider for TomlFileProvider {
374 fn metadata(&self) -> Metadata {
375 if self.is_missing() {
376 Metadata::named("TOML file provider")
377 } else {
378 Toml::file(self.file()).nested().metadata()
379 }
380 }
381
382 fn data(&self) -> Result<Map<Profile, Dict>, Error> {
383 self.cache.get_or_init(|| self.read()).clone()
384 }
385}
386
387pub(crate) struct ForcedSnakeCaseData<P>(pub(crate) P);
393
394impl<P: Provider> Provider for ForcedSnakeCaseData<P> {
395 fn metadata(&self) -> Metadata {
396 self.0.metadata()
397 }
398
399 fn data(&self) -> Result<Map<Profile, Dict>, Error> {
400 let mut map = self.0.data()?;
401 for (profile, dict) in &mut map {
402 if Config::STANDALONE_SECTIONS.contains(&profile.as_ref()) {
403 continue;
405 }
406
407 if profile.as_str().as_str() == Config::PROFILE_SECTION {
408 let dict2 = std::mem::take(dict);
411 *dict = dict2
412 .into_iter()
413 .map(|(profile_name, v)| {
414 let v = snake_case_profile_keys(v);
416 (profile_name, v)
417 })
418 .collect();
419 continue;
420 }
421
422 let dict2 = std::mem::take(dict);
423 *dict = dict2.into_iter().map(|(k, v)| (k.to_snake_case(), v)).collect();
424 }
425 Ok(map)
426 }
427
428 fn profile(&self) -> Option<Profile> {
429 self.0.profile()
430 }
431}
432
433fn snake_case_profile_keys(value: Value) -> Value {
435 match value {
436 Value::Dict(tag, dict) => {
437 let new_dict = dict.into_iter().map(|(k, v)| (k.to_snake_case(), v)).collect();
438 Value::Dict(tag, new_dict)
439 }
440 other => other,
441 }
442}
443
444pub(crate) struct BackwardsCompatTomlProvider<P>(pub(crate) P);
446
447impl<P: Provider> Provider for BackwardsCompatTomlProvider<P> {
448 fn metadata(&self) -> Metadata {
449 self.0.metadata()
450 }
451
452 fn data(&self) -> Result<Map<Profile, Dict>, Error> {
453 let mut map = Map::new();
454 let solc_env = std::env::var("FOUNDRY_SOLC_VERSION")
455 .or_else(|_| std::env::var("DAPP_SOLC_VERSION"))
456 .map(Value::from)
457 .ok();
458 for (profile, mut dict) in self.0.data()? {
459 if let Some(v) = solc_env.clone() {
460 dict.insert("solc".to_string(), v);
462 } else if let Some(v) = dict.remove("solc_version") {
463 if !dict.contains_key("solc") {
465 dict.insert("solc".to_string(), v);
466 }
467 }
468 if let Some(v) = dict.remove("deny_warnings")
469 && !dict.contains_key("deny")
470 {
471 dict.insert("deny".to_string(), v);
472 }
473
474 map.insert(profile, dict);
475 }
476 normalize_legacy_labels(&mut map);
477 Ok(map)
478 }
479
480 fn profile(&self) -> Option<Profile> {
481 self.0.profile()
482 }
483}
484
485pub(crate) struct LegacyLabelsProvider<P>(pub(crate) P);
487
488impl<P: Provider> Provider for LegacyLabelsProvider<P> {
489 fn metadata(&self) -> Metadata {
490 self.0.metadata()
491 }
492
493 fn data(&self) -> Result<Map<Profile, Dict>, Error> {
494 let mut map = self.0.data()?;
495 normalize_legacy_labels(&mut map);
496 Ok(map)
497 }
498
499 fn profile(&self) -> Option<Profile> {
500 self.0.profile()
501 }
502}
503
504pub(crate) fn normalize_legacy_labels(map: &mut Map<Profile, Dict>) {
505 if let Some(labels) = map.get(&Profile::new("labels")).cloned() {
506 merge_tracing_labels(&labels, map.entry(Profile::new("tracing")).or_default());
507 }
508
509 for (profile, dict) in map {
510 if profile.as_str().as_str() == Config::PROFILE_SECTION {
511 for value in dict.values_mut() {
512 if let Value::Dict(_, profile) = value {
513 normalize_legacy_labels_in_profile(profile);
514 }
515 }
516 } else if !Config::STANDALONE_SECTIONS.contains(&profile.as_ref()) {
517 normalize_legacy_labels_in_profile(dict);
518 }
519 }
520}
521
522pub(crate) fn normalize_legacy_labels_in_profile(dict: &mut Dict) {
523 let Some(Value::Dict(_, labels)) = dict.get("labels").cloned() else { return };
524 let tracing = dict.entry("tracing".to_string()).or_insert_with(|| Dict::new().into());
525 if let Value::Dict(_, tracing) = tracing {
526 merge_tracing_labels(&labels, tracing);
527 }
528}
529
530fn merge_tracing_labels(legacy: &Dict, tracing: &mut Dict) {
531 match tracing.get("labels") {
532 Some(Value::Dict(_, configured)) => {
533 let mut labels = legacy.clone();
534 labels.extend(configured.clone());
535 tracing.insert("labels".to_string(), labels.into());
536 }
537 Some(_) => {}
538 None => {
539 tracing.insert("labels".to_string(), legacy.clone().into());
540 }
541 }
542}
543
544pub(crate) struct DappHardhatDirProvider<'a>(pub(crate) &'a Path);
546
547impl Provider for DappHardhatDirProvider<'_> {
548 fn metadata(&self) -> Metadata {
549 Metadata::named("Dapp Hardhat dir compat")
550 }
551
552 fn data(&self) -> Result<Map<Profile, Dict>, Error> {
553 let mut dict = Dict::new();
554 dict.insert(
555 "src".to_string(),
556 ProjectPathsConfig::find_source_dir(self.0)
557 .file_name()
558 .unwrap()
559 .to_string_lossy()
560 .to_string()
561 .into(),
562 );
563 dict.insert(
564 "out".to_string(),
565 ProjectPathsConfig::find_artifacts_dir(self.0)
566 .file_name()
567 .unwrap()
568 .to_string_lossy()
569 .to_string()
570 .into(),
571 );
572
573 let mut libs = vec![];
578 let node_modules = self.0.join("node_modules");
579 let lib = self.0.join("lib");
580 if node_modules.exists() {
581 if lib.exists() {
582 libs.push(lib.file_name().unwrap().to_string_lossy().to_string());
583 }
584 libs.push(node_modules.file_name().unwrap().to_string_lossy().to_string());
585 } else {
586 libs.push(lib.file_name().unwrap().to_string_lossy().to_string());
587 }
588
589 dict.insert("libs".to_string(), libs.into());
590
591 Ok(Map::from([(Config::selected_profile(), dict)]))
592 }
593}
594
595pub(crate) struct DappEnvCompatProvider;
597
598impl Provider for DappEnvCompatProvider {
599 fn metadata(&self) -> Metadata {
600 Metadata::named("Dapp env compat")
601 }
602
603 fn data(&self) -> Result<Map<Profile, Dict>, Error> {
604 use serde::de::Error as _;
605 use std::env;
606
607 let mut dict = Dict::new();
608 if let Ok(val) = env::var("DAPP_TEST_NUMBER") {
609 dict.insert(
610 "block_number".to_string(),
611 val.parse::<u64>().map_err(figment::Error::custom)?.into(),
612 );
613 }
614 if let Ok(val) = env::var("DAPP_TEST_ADDRESS") {
615 dict.insert("sender".to_string(), val.into());
616 }
617 if let Ok(val) = env::var("DAPP_FORK_BLOCK") {
618 dict.insert(
619 "fork_block_number".to_string(),
620 val.parse::<u64>().map_err(figment::Error::custom)?.into(),
621 );
622 } else if let Ok(val) = env::var("DAPP_TEST_NUMBER") {
623 dict.insert(
624 "fork_block_number".to_string(),
625 val.parse::<u64>().map_err(figment::Error::custom)?.into(),
626 );
627 }
628 if let Ok(val) = env::var("DAPP_TEST_TIMESTAMP") {
629 dict.insert(
630 "block_timestamp".to_string(),
631 val.parse::<u64>().map_err(figment::Error::custom)?.into(),
632 );
633 }
634 if let Ok(val) = env::var("DAPP_BUILD_OPTIMIZE_RUNS") {
635 dict.insert(
636 "optimizer_runs".to_string(),
637 val.parse::<u64>().map_err(figment::Error::custom)?.into(),
638 );
639 }
640 if let Ok(val) = env::var("DAPP_BUILD_OPTIMIZE") {
641 let val = val.parse::<u8>().map_err(figment::Error::custom)?;
643 if val > 1 {
644 return Err(
645 format!("Invalid $DAPP_BUILD_OPTIMIZE value `{val}`, expected 0 or 1").into()
646 );
647 }
648 dict.insert("optimizer".to_string(), (val == 1).into());
649 }
650
651 if let Ok(val) = env::var("DAPP_LIBRARIES").or_else(|_| env::var("FOUNDRY_LIBRARIES")) {
653 dict.insert("libraries".to_string(), utils::to_array_value(&val)?);
654 }
655
656 let mut fuzz_dict = Dict::new();
657 if let Ok(val) = env::var("DAPP_TEST_FUZZ_RUNS") {
658 fuzz_dict.insert(
659 "runs".to_string(),
660 val.parse::<u32>().map_err(figment::Error::custom)?.into(),
661 );
662 }
663 dict.insert("fuzz".to_string(), fuzz_dict.into());
664
665 let mut invariant_dict = Dict::new();
666 if let Ok(val) = env::var("DAPP_TEST_DEPTH") {
667 invariant_dict.insert(
668 "depth".to_string(),
669 val.parse::<u32>().map_err(figment::Error::custom)?.into(),
670 );
671 }
672 dict.insert("invariant".to_string(), invariant_dict.into());
673
674 Ok(Map::from([(Config::selected_profile(), dict)]))
675 }
676}
677
678pub(crate) struct RenameProfileProvider<P> {
694 provider: P,
695 from: Profile,
696 to: Profile,
697}
698
699impl<P> RenameProfileProvider<P> {
700 pub(crate) fn new(provider: P, from: impl Into<Profile>, to: impl Into<Profile>) -> Self {
701 Self { provider, from: from.into(), to: to.into() }
702 }
703}
704
705impl<P: Provider> Provider for RenameProfileProvider<P> {
706 fn metadata(&self) -> Metadata {
707 self.provider.metadata()
708 }
709
710 fn data(&self) -> Result<Map<Profile, Dict>, Error> {
711 let mut data = self.provider.data()?;
712 if let Some(data) = data.remove(&self.from) {
713 return Ok(Map::from([(self.to.clone(), data)]));
714 }
715 Ok(Default::default())
716 }
717
718 fn profile(&self) -> Option<Profile> {
719 Some(self.to.clone())
720 }
721}
722
723struct UnwrapProfileProvider<P> {
739 provider: P,
740 wrapping_key: Profile,
741 profile: Profile,
742}
743
744impl<P> UnwrapProfileProvider<P> {
745 pub fn new(provider: P, wrapping_key: impl Into<Profile>, profile: impl Into<Profile>) -> Self {
746 Self { provider, wrapping_key: wrapping_key.into(), profile: profile.into() }
747 }
748}
749
750impl<P: Provider> Provider for UnwrapProfileProvider<P> {
751 fn metadata(&self) -> Metadata {
752 self.provider.metadata()
753 }
754
755 fn data(&self) -> Result<Map<Profile, Dict>, Error> {
756 let mut data = self.provider.data()?;
757 if let Some(profiles) = data.remove(&self.wrapping_key) {
758 for (profile_str, profile_val) in profiles {
759 let profile = Profile::new(&profile_str);
760 if profile != self.profile {
761 continue;
762 }
763 match profile_val {
764 Value::Dict(_, dict) => return Ok(profile.collect(dict)),
765 bad_val => {
766 let mut err = Error::from(figment::error::Kind::InvalidType(
767 bad_val.to_actual(),
768 "dict".into(),
769 ));
770 err.metadata = Some(self.provider.metadata());
771 err.profile = Some(self.profile.clone());
772 return Err(err);
773 }
774 }
775 }
776 }
777 Ok(Default::default())
778 }
779
780 fn profile(&self) -> Option<Profile> {
781 Some(self.profile.clone())
782 }
783}
784
785pub(crate) struct WrapProfileProvider<P> {
801 provider: P,
802 wrapping_key: Profile,
803 profile: Profile,
804}
805
806impl<P> WrapProfileProvider<P> {
807 pub fn new(provider: P, wrapping_key: impl Into<Profile>, profile: impl Into<Profile>) -> Self {
808 Self { provider, wrapping_key: wrapping_key.into(), profile: profile.into() }
809 }
810}
811
812impl<P: Provider> Provider for WrapProfileProvider<P> {
813 fn metadata(&self) -> Metadata {
814 self.provider.metadata()
815 }
816
817 fn data(&self) -> Result<Map<Profile, Dict>, Error> {
818 if let Some(inner) = self.provider.data()?.remove(&self.profile) {
819 let value = Value::from(inner);
820 let mut dict = Dict::new();
821 dict.insert(self.profile.as_str().as_str().to_snake_case(), value);
822 Ok(self.wrapping_key.collect(dict))
823 } else {
824 Ok(Default::default())
825 }
826 }
827
828 fn profile(&self) -> Option<Profile> {
829 Some(self.profile.clone())
830 }
831}
832
833pub(crate) struct OptionalStrictProfileProvider<P> {
856 provider: P,
857 profiles: Vec<Profile>,
858}
859
860impl<P> OptionalStrictProfileProvider<P> {
861 pub const PROFILE_PROFILE: Profile = Profile::const_new("profile");
862
863 pub fn new(provider: P, profiles: impl IntoIterator<Item = impl Into<Profile>>) -> Self {
864 Self { provider, profiles: profiles.into_iter().map(|profile| profile.into()).collect() }
865 }
866}
867
868impl<P: Provider> Provider for OptionalStrictProfileProvider<P> {
869 fn metadata(&self) -> Metadata {
870 self.provider.metadata()
871 }
872
873 fn data(&self) -> Result<Map<Profile, Dict>, Error> {
874 let mut figment = Figment::from(&self.provider);
875 for profile in &self.profiles {
876 figment = figment.merge(UnwrapProfileProvider::new(
877 &self.provider,
878 Self::PROFILE_PROFILE,
879 profile.clone(),
880 ));
881 }
882 figment.data().map_err(|err| {
883 if let Err(root_err) = self.provider.data() {
888 return root_err;
889 }
890 err
891 })
892 }
893
894 fn profile(&self) -> Option<Profile> {
895 self.profiles.last().cloned()
896 }
897}
898
899pub struct FallbackProfileProvider<P> {
902 provider: P,
903 profile: Profile,
904 fallback: Profile,
905}
906
907impl<P> FallbackProfileProvider<P> {
908 pub fn new(provider: P, profile: impl Into<Profile>, fallback: impl Into<Profile>) -> Self {
910 Self { provider, profile: profile.into(), fallback: fallback.into() }
911 }
912}
913
914impl<P: Provider> Provider for FallbackProfileProvider<P> {
915 fn metadata(&self) -> Metadata {
916 self.provider.metadata()
917 }
918
919 fn data(&self) -> Result<Map<Profile, Dict>, Error> {
920 let mut data = self.provider.data()?;
921 let invariant_corpus_random_sequence_weight_configured = self.profile == "invariant"
922 && data
923 .get(&self.profile)
924 .is_some_and(|inner| inner.contains_key("corpus_random_sequence_weight"));
925 let mark_invariant_corpus_random_sequence_weight_configured =
926 |inner: &mut Dict| -> Result<(), Error> {
927 if invariant_corpus_random_sequence_weight_configured {
928 inner.insert(
929 "corpus_random_sequence_weight_configured".to_string(),
930 Value::serialize(true)?,
931 );
932 }
933 Ok(())
934 };
935
936 if let Some(fallback) = data.remove(&self.fallback) {
937 let mut inner = data.remove(&self.profile).unwrap_or_default();
938 for (k, v) in fallback {
939 inner.entry(k).or_insert(v);
940 }
941 mark_invariant_corpus_random_sequence_weight_configured(&mut inner)?;
942 Ok(self.profile.collect(inner))
943 } else {
944 if let Some(inner) = data.get_mut(&self.profile) {
945 mark_invariant_corpus_random_sequence_weight_configured(inner)?;
946 }
947 Ok(data)
948 }
949 }
950
951 fn profile(&self) -> Option<Profile> {
952 Some(self.profile.clone())
953 }
954}