optify 0.10.1__tar.gz → 0.10.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. {optify-0.10.1 → optify-0.10.2}/PKG-INFO +1 -1
  2. {optify-0.10.1 → optify-0.10.2}/pyproject.toml +2 -2
  3. {optify-0.10.1 → optify-0.10.2}/python/optify/Cargo.lock +12 -13
  4. {optify-0.10.1 → optify-0.10.2}/python/optify/Cargo.toml +3 -3
  5. {optify-0.10.1 → optify-0.10.2}/rust/optify/Cargo.toml +1 -1
  6. {optify-0.10.1 → optify-0.10.2}/rust/optify/benches/loading_benchmark.rs +23 -1
  7. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/builder/builder_impl.rs +190 -166
  8. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/builder/loading_result.rs +13 -2
  9. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/configurable_values/locator.rs +0 -2
  10. optify-0.10.2/rust/optify/src/json/merge.rs +218 -0
  11. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/provider/provider_impl.rs +11 -4
  12. optify-0.10.1/rust/optify/src/json/merge.rs +0 -135
  13. {optify-0.10.1 → optify-0.10.2}/LICENSE.txt +0 -0
  14. {optify-0.10.1 → optify-0.10.2}/README.md +0 -0
  15. {optify-0.10.1 → optify-0.10.2}/optify/__init__.py +0 -0
  16. {optify-0.10.1 → optify-0.10.2}/optify/optify.pyi +0 -0
  17. {optify-0.10.1 → optify-0.10.2}/optify/py.typed +0 -0
  18. {optify-0.10.1 → optify-0.10.2}/python/optify/.gitignore +0 -0
  19. {optify-0.10.1 → optify-0.10.2}/python/optify/.vscode/settings.json +0 -0
  20. {optify-0.10.1 → optify-0.10.2}/python/optify/LICENSE.txt +0 -0
  21. {optify-0.10.1 → optify-0.10.2}/python/optify/README.md +0 -0
  22. {optify-0.10.1 → optify-0.10.2}/python/optify/src/lib.rs +0 -0
  23. {optify-0.10.1 → optify-0.10.2}/python/optify/src/preferences.rs +0 -0
  24. {optify-0.10.1 → optify-0.10.2}/python/optify/src/provider.rs +0 -0
  25. {optify-0.10.1 → optify-0.10.2}/python/optify/src/watcher.rs +0 -0
  26. {optify-0.10.1 → optify-0.10.2}/python/optify/tests/test_builder.py +0 -0
  27. {optify-0.10.1 → optify-0.10.2}/python/optify/tests/test_dacite.py +0 -0
  28. {optify-0.10.1 → optify-0.10.2}/python/optify/tests/test_optify.py +0 -0
  29. {optify-0.10.1 → optify-0.10.2}/python/optify/tests/test_provider.py +0 -0
  30. {optify-0.10.1 → optify-0.10.2}/python/optify/tests/test_pydantic.py +0 -0
  31. {optify-0.10.1 → optify-0.10.2}/rust/Cargo.toml +0 -0
  32. {optify-0.10.1 → optify-0.10.2}/rust/optify/README.md +0 -0
  33. {optify-0.10.1 → optify-0.10.2}/rust/optify/benches/caching_benchmark.rs +0 -0
  34. {optify-0.10.1 → optify-0.10.2}/rust/optify/benches/get_all_options_benchmark.rs +0 -0
  35. {optify-0.10.1 → optify-0.10.2}/rust/optify/benches/get_options_benchmark.rs +0 -0
  36. {optify-0.10.1 → optify-0.10.2}/rust/optify/build.rs +0 -0
  37. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/builder/builder_options.rs +0 -0
  38. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/builder/builder_trait.rs +0 -0
  39. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/builder/extract_configurable_string_files_from_config.rs +0 -0
  40. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/builder/extract_files_from_config.rs +0 -0
  41. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/builder/get_canonical_feature_name.rs +0 -0
  42. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/builder/get_supported_extensions.rs +0 -0
  43. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/builder/mod.rs +0 -0
  44. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/builder/watcher_builder.rs +0 -0
  45. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/configurable_string/configurable_string_impl.rs +0 -0
  46. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/configurable_string/mod.rs +0 -0
  47. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/configurable_values/configurable_list_impl.rs +0 -0
  48. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/configurable_values/mod.rs +0 -0
  49. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/json/escape_json_pointer.rs +0 -0
  50. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/json/mod.rs +0 -0
  51. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/json/reader.rs +0 -0
  52. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/lib.rs +0 -0
  53. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/provider/constraints.rs +0 -0
  54. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/provider/get_options_preferences.rs +0 -0
  55. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/provider/mod.rs +0 -0
  56. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/provider/provider_trait.rs +0 -0
  57. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/provider/watcher.rs +0 -0
  58. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/provider/watcher_options.rs +0 -0
  59. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/schema/conditions.rs +0 -0
  60. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/schema/feature.rs +0 -0
  61. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/schema/metadata.rs +0 -0
  62. {optify-0.10.1 → optify-0.10.2}/rust/optify/src/schema/mod.rs +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: optify
3
- Version: 0.10.1
3
+ Version: 0.10.2
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: Implementation :: CPython
6
6
  Classifier: Programming Language :: Python :: Implementation :: PyPy
@@ -26,11 +26,11 @@ build-backend = "maturin"
26
26
 
27
27
  [package]
28
28
  name = "optify"
29
- version = "0.10.1"
29
+ version = "0.10.2"
30
30
 
31
31
  [tool.poetry]
32
32
  name = "optify"
33
- version = "0.10.1"
33
+ version = "0.10.2"
34
34
  description = "Simplifies getting the right configuration options for a process using pre-loaded configurations from files to manage options for experiments or flights."
35
35
  authors = ["Justin D. Harris"]
36
36
  maintainers = ["Justin D. Harris"]
@@ -898,7 +898,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
898
898
 
899
899
  [[package]]
900
900
  name = "optify"
901
- version = "1.3.1"
901
+ version = "1.3.2"
902
902
  dependencies = [
903
903
  "config",
904
904
  "cow-utils",
@@ -917,7 +917,7 @@ dependencies = [
917
917
 
918
918
  [[package]]
919
919
  name = "optify-python"
920
- version = "0.10.1"
920
+ version = "0.10.2"
921
921
  dependencies = [
922
922
  "optify",
923
923
  "pyo3",
@@ -1049,9 +1049,9 @@ dependencies = [
1049
1049
 
1050
1050
  [[package]]
1051
1051
  name = "pyo3"
1052
- version = "0.28.3"
1052
+ version = "0.29.0"
1053
1053
  source = "registry+https://github.com/rust-lang/crates.io-index"
1054
- checksum = "91fd8e38a3b50ed1167fb981cd6fd60147e091784c427b8f7183a7ee32c31c12"
1054
+ checksum = "cd274650b21d4bfc26a0a47587962c1edb425f69287324355cd040c3ea66071c"
1055
1055
  dependencies = [
1056
1056
  "libc",
1057
1057
  "once_cell",
@@ -1063,18 +1063,18 @@ dependencies = [
1063
1063
 
1064
1064
  [[package]]
1065
1065
  name = "pyo3-build-config"
1066
- version = "0.28.3"
1066
+ version = "0.29.0"
1067
1067
  source = "registry+https://github.com/rust-lang/crates.io-index"
1068
- checksum = "e368e7ddfdeb98c9bca7f8383be1648fd84ab466bf2bc015e94008db6d35611e"
1068
+ checksum = "c5e2a7d2f0d013342f295c048ad19237add5154a55b1c5a254c0ec93d4109078"
1069
1069
  dependencies = [
1070
1070
  "target-lexicon",
1071
1071
  ]
1072
1072
 
1073
1073
  [[package]]
1074
1074
  name = "pyo3-ffi"
1075
- version = "0.28.3"
1075
+ version = "0.29.0"
1076
1076
  source = "registry+https://github.com/rust-lang/crates.io-index"
1077
- checksum = "7f29e10af80b1f7ccaf7f69eace800a03ecd13e883acfacc1e5d0988605f651e"
1077
+ checksum = "ca85c467da1bbc8d866eea5deff9cf29ea5f7785054a17da36e65bda9c05845b"
1078
1078
  dependencies = [
1079
1079
  "libc",
1080
1080
  "pyo3-build-config",
@@ -1082,9 +1082,9 @@ dependencies = [
1082
1082
 
1083
1083
  [[package]]
1084
1084
  name = "pyo3-macros"
1085
- version = "0.28.3"
1085
+ version = "0.29.0"
1086
1086
  source = "registry+https://github.com/rust-lang/crates.io-index"
1087
- checksum = "df6e520eff47c45997d2fc7dd8214b25dd1310918bbb2642156ef66a67f29813"
1087
+ checksum = "9ac53762fd065daa3194dd09337a38bd793a188100fd1a9304c4ab312d901771"
1088
1088
  dependencies = [
1089
1089
  "proc-macro2",
1090
1090
  "pyo3-macros-backend",
@@ -1094,13 +1094,12 @@ dependencies = [
1094
1094
 
1095
1095
  [[package]]
1096
1096
  name = "pyo3-macros-backend"
1097
- version = "0.28.3"
1097
+ version = "0.29.0"
1098
1098
  source = "registry+https://github.com/rust-lang/crates.io-index"
1099
- checksum = "c4cdc218d835738f81c2338f822078af45b4afdf8b2e33cbb5916f108b813acb"
1099
+ checksum = "4ca3a1557399783172dc5bf39cfca835157732532cba56b71d2292161e53b362"
1100
1100
  dependencies = [
1101
1101
  "heck",
1102
1102
  "proc-macro2",
1103
- "pyo3-build-config",
1104
1103
  "quote",
1105
1104
  "syn",
1106
1105
  ]
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "optify-python"
3
- version = "0.10.1"
3
+ version = "0.10.2"
4
4
  edition = "2021"
5
5
 
6
6
  description = "Simplifies getting the right configuration options for a process using pre-loaded configurations from files (JSON, YAML, etc.) to manage options for experiments or flights. This library is mainly made to support building implementations for other languages such as Node.js, Python, and Ruby. It is not meant to be consumed directly yet."
@@ -15,5 +15,5 @@ name = "optify"
15
15
  crate-type = ["cdylib"]
16
16
 
17
17
  [dependencies]
18
- optify = { path = "../../rust/optify", version = "1.3.1" }
19
- pyo3 = "0.28.2"
18
+ optify = { path = "../../rust/optify", version = "1.3.2" }
19
+ pyo3 = "0.29.0"
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "optify"
3
- version = "1.3.1"
3
+ version = "1.3.2"
4
4
  edition = "2021"
5
5
  build = "build.rs"
6
6
 
@@ -1,4 +1,5 @@
1
1
  use criterion::{black_box, criterion_group, criterion_main, Criterion};
2
+ use optify::builder::BuilderOptions;
2
3
  use optify::builder::OptionsProviderBuilder;
3
4
  use optify::builder::OptionsRegistryBuilder;
4
5
  use optify::provider::OptionsRegistry;
@@ -55,6 +56,7 @@ fn create_test_files(dir: &Path, num_files: usize) {
55
56
  file.write_all(content.as_bytes()).unwrap();
56
57
  }
57
58
 
59
+ // Create features with imports.
58
60
  for i in num_files / 2..num_files {
59
61
  let file_path = dir.join(format!("test_{i}.yaml"));
60
62
  let mut file = fs::File::create(&file_path).unwrap();
@@ -90,6 +92,18 @@ options:
90
92
  );
91
93
  file.write_all(content.as_bytes()).unwrap();
92
94
  }
95
+
96
+ // Create raw files.
97
+ for i in 0..num_files / 2 {
98
+ let file_path = dir.join(format!("test_{i}.txt"));
99
+ let mut file = fs::File::create(&file_path).unwrap();
100
+
101
+ let content = format!(
102
+ r#"This is what goes in the file {i}
103
+ "#
104
+ );
105
+ file.write_all(content.as_bytes()).unwrap();
106
+ }
93
107
  }
94
108
 
95
109
  fn cleanup_test_files(dir: &Path) {
@@ -110,7 +124,15 @@ fn benchmark_loading(c: &mut Criterion) {
110
124
 
111
125
  group.bench_function("parallel loading", |b| {
112
126
  b.iter(|| {
113
- let mut builder = OptionsProviderBuilder::new();
127
+ let mut builder = black_box(OptionsProviderBuilder::new());
128
+ black_box(
129
+ builder
130
+ .with_options(BuilderOptions {
131
+ are_configurable_values_enabled: true,
132
+ ..Default::default()
133
+ })
134
+ .unwrap(),
135
+ );
114
136
  builder.add_directory(black_box(test_dir)).unwrap();
115
137
  })
116
138
  });
@@ -10,11 +10,11 @@ use crate::builder::extract_configurable_string_files_from_config::extract_confi
10
10
  use crate::builder::extract_files_from_config::extract_files_from_config;
11
11
  use crate::builder::get_canonical_feature_name::get_canonical_feature_name;
12
12
  use crate::builder::get_supported_extensions::get_supported_extensions;
13
- use crate::builder::loading_result::LoadingResult;
13
+ use crate::builder::loading_result::{FeatureLoadingResult, LoadingResult, RawLoadingResult};
14
14
  use crate::builder::OptionsRegistryBuilder;
15
15
  use crate::configurable_string::LoadedFiles;
16
16
  use crate::configurable_values::locator::{find_configurable_values, ConfigurableValuePointers};
17
- use crate::json::merge::merge_json_with_defaults;
17
+ use crate::json::merge::{merge_json_with_defaults, FrozenPaths};
18
18
  use crate::json::reader::read_json_from_file_as;
19
19
  use crate::provider::{
20
20
  Aliases, Conditions, Features, OptionsProvider, ReferencedFileToFeatureNames, Sources,
@@ -81,6 +81,7 @@ fn resolve_imports(
81
81
  ) -> Result<(), String> {
82
82
  // Build full configuration for the feature so that we don't need to traverse imports for the feature when configurations are requested from the provider.
83
83
  let mut merged_config = sources.get(canonical_feature_name).unwrap().clone();
84
+ let mut frozen_paths = FrozenPaths::new();
84
85
  for import in imports_for_feature.iter().rev() {
85
86
  // Validate imports.
86
87
  if features_in_resolution_path.contains(import) {
@@ -147,7 +148,7 @@ fn resolve_imports(
147
148
  }
148
149
  }
149
150
 
150
- merge_json_with_defaults(&mut merged_config, source);
151
+ merge_json_with_defaults(&mut merged_config, source, &mut frozen_paths);
151
152
  }
152
153
 
153
154
  sources.insert(canonical_feature_name.to_owned(), merged_config);
@@ -216,27 +217,6 @@ impl OptionsProviderBuilder {
216
217
  ))
217
218
  }
218
219
 
219
- fn validate_with_schema(&self, info: &LoadingResult) -> Result<(), String> {
220
- let validator = match &self.schema {
221
- Some(v) => v,
222
- None => return Ok(()),
223
- };
224
-
225
- let json_value = &info.original_config;
226
- if validator.is_valid(json_value) {
227
- Ok(())
228
- } else {
229
- let errors = validator.iter_errors(json_value);
230
- let error_messages: Vec<String> = errors.map(|e| format!("{e}")).collect();
231
- let path = info.metadata.path.as_ref().unwrap();
232
- Err(format!(
233
- "Schema validation failed for {:?} : {}",
234
- path,
235
- error_messages.join(", ")
236
- ))
237
- }
238
- }
239
-
240
220
  fn prepare_build(&mut self) -> Result<(), String> {
241
221
  let mut resolved_imports: HashSet<String> = HashSet::new();
242
222
  for (canonical_feature_name, imports_for_feature) in &self.imports {
@@ -270,115 +250,55 @@ impl OptionsProviderBuilder {
270
250
  Ok(())
271
251
  }
272
252
 
273
- fn process_entry(
253
+ fn process_path(
274
254
  path: &Path,
275
255
  directory: &Path,
276
256
  builder_options: &BuilderOptions,
257
+ supported_extensions: &HashSet<&str>,
258
+ feature_contents_validator: &Option<Arc<Validator>>,
277
259
  ) -> Result<LoadingResult, String> {
278
- let absolute_path = dunce::canonicalize(path).expect("path should be valid");
279
- // TODO Optimization: Find a more efficient way to build a more generic view of the file.
280
- // The `config` library is helpful because it handles many file types.
281
- // It would also be nice to support comments in .json files, even though it is not standard.
282
- // The `config` library does support .json5 which supports comments.
283
- let file = config::File::from(path);
284
- let config_for_path = match config::Config::builder().add_source(file).build() {
285
- Ok(conf) => conf,
286
- Err(e) => {
287
- return Err(format!(
288
- "Error loading file '{}': {e}",
289
- absolute_path.to_string_lossy(),
290
- ))
291
- }
292
- };
293
-
294
- // We need the raw JSON for validation.
295
- let raw_config: serde_json::Value = match config_for_path.try_deserialize() {
296
- Ok(v) => v,
297
- Err(e) => {
298
- return Err(format!(
299
- "Error deserializing configuration for file '{}': {e}",
300
- absolute_path.to_string_lossy(),
301
- ))
302
- }
303
- };
304
-
305
- let feature_config: FeatureConfiguration = match serde_json::from_value(raw_config.clone())
306
- {
307
- Ok(v) => v,
308
- Err(e) => {
309
- return Err(format!(
310
- "Error deserializing configuration for file '{}': {e}",
311
- absolute_path.to_string_lossy(),
312
- ))
313
- }
260
+ let is_config_file = match path.extension() {
261
+ Some(ext) => match ext.to_str() {
262
+ Some(ext_str) => supported_extensions.contains(ext_str),
263
+ None => false,
264
+ },
265
+ None => false,
314
266
  };
315
267
 
316
- let source = feature_config
317
- .options
318
- .unwrap_or(serde_json::Value::Object(serde_json::Map::new()));
319
-
320
- let canonical_feature_name = get_canonical_feature_name(path, directory);
321
-
322
- // Ensure the name is set in the metadata.
323
- let metadata = match feature_config.metadata {
324
- Some(mut metadata) => {
325
- metadata.name = Some(canonical_feature_name.clone());
326
- metadata.path = Some(absolute_path.to_string_lossy().to_string());
327
- metadata
268
+ if is_config_file {
269
+ process_config_file_entry(path, directory, builder_options, feature_contents_validator)
270
+ } else {
271
+ match std::fs::read_to_string(path) {
272
+ Ok(contents) => {
273
+ let relative_path = path
274
+ .strip_prefix(directory)
275
+ .unwrap()
276
+ .to_str()
277
+ .expect("path should be valid Unicode")
278
+ .replace(std::path::MAIN_SEPARATOR, "/");
279
+ Ok(LoadingResult::Raw(RawLoadingResult {
280
+ contents,
281
+ relative_path,
282
+ }))
283
+ }
284
+ Err(e) => Err(format!("Error reading file {}: {e}", path.display())),
328
285
  }
329
- None => OptionsMetadata::new(
330
- None,
331
- None,
332
- None,
333
- Some(canonical_feature_name.clone()),
334
- None,
335
- Some(absolute_path.to_string_lossy().to_string()),
336
- ),
337
- };
338
-
339
- let (configurable_value_pointers, configurable_string_files) =
340
- if builder_options.are_configurable_strings_enabled {
341
- let pointers = find_configurable_values(raw_config.get("options"));
342
-
343
- // Tracking file references is usually not enabled in production systems and is mainly for local development,
344
- // so we won't complicate `find_configurable_values` and make it also track referenced files.
345
- let files = match builder_options.track_file_references {
346
- TrackReferenceMode::None => Vec::new(),
347
- TrackReferenceMode::ConfigurableStrings => {
348
- extract_configurable_string_files_from_config(
349
- &raw_config,
350
- &pointers.configurable_string_pointers,
351
- )
352
- }
353
- TrackReferenceMode::KeyName => extract_files_from_config(&raw_config),
354
- };
355
- (pointers, files)
356
- } else {
357
- (ConfigurableValuePointers::default(), Vec::new())
358
- };
359
-
360
- Ok(LoadingResult {
361
- canonical_feature_name,
362
- conditions: feature_config.conditions,
363
- configurable_string_files,
364
- configurable_value_pointers,
365
- imports: feature_config.imports,
366
- metadata,
367
- original_config: raw_config,
368
- source,
369
- })
286
+ }
370
287
  }
371
288
 
372
289
  fn process_loading_result(
373
290
  &mut self,
374
291
  loading_result: Result<LoadingResult, String>,
375
292
  ) -> Result<(), String> {
376
- let info = loading_result?;
377
- let canonical_feature_name = &info.canonical_feature_name;
378
-
379
- if self.schema.is_some() {
380
- self.validate_with_schema(&info)?;
293
+ match loading_result? {
294
+ LoadingResult::Feature(feature) => self.process_feature_loading_result(feature),
295
+ LoadingResult::Raw(raw) => self.process_raw_loading_result(raw),
381
296
  }
297
+ }
298
+
299
+ fn process_feature_loading_result(&mut self, info: FeatureLoadingResult) -> Result<(), String> {
300
+ let canonical_feature_name = info.canonical_feature_name;
301
+
382
302
  if self
383
303
  .sources
384
304
  .insert(canonical_feature_name.clone(), info.source)
@@ -404,16 +324,32 @@ impl OptionsProviderBuilder {
404
324
  }
405
325
  add_alias(
406
326
  &mut self.aliases,
407
- canonical_feature_name,
408
- canonical_feature_name,
327
+ &canonical_feature_name,
328
+ &canonical_feature_name,
409
329
  )?;
410
330
  if let Some(aliases) = &info.metadata.aliases {
411
331
  for alias in aliases {
412
- add_alias(&mut self.aliases, alias, canonical_feature_name)?;
332
+ add_alias(&mut self.aliases, alias, &canonical_feature_name)?;
333
+ }
334
+ }
335
+ self.features.insert(canonical_feature_name, info.metadata);
336
+ Ok(())
337
+ }
338
+
339
+ fn process_raw_loading_result(&mut self, raw_result: RawLoadingResult) -> Result<(), String> {
340
+ match self.loaded_files.entry(raw_result.relative_path) {
341
+ std::collections::hash_map::Entry::Occupied(entry) => {
342
+ // Since the files are loaded from a directory,
343
+ // this should only happen when two directories have files with the same path relative to the given directory.
344
+ return Err(format!(
345
+ "File '{}' is already loaded from another directory.",
346
+ entry.key()
347
+ ));
348
+ }
349
+ std::collections::hash_map::Entry::Vacant(entry) => {
350
+ entry.insert(raw_result.contents);
413
351
  }
414
352
  }
415
- self.features
416
- .insert(canonical_feature_name.clone(), info.metadata);
417
353
  Ok(())
418
354
  }
419
355
 
@@ -445,6 +381,127 @@ impl OptionsProviderBuilder {
445
381
  }
446
382
  }
447
383
 
384
+ fn validate_with_schema(
385
+ validator: &Option<Arc<Validator>>,
386
+ original_config: &serde_json::Value,
387
+ path: &String,
388
+ ) -> Result<(), String> {
389
+ match validator {
390
+ Some(validator) => {
391
+ if validator.is_valid(original_config) {
392
+ Ok(())
393
+ } else {
394
+ let errors = validator.iter_errors(original_config);
395
+ let error_messages: Vec<String> = errors.map(|e| format!("{e}")).collect();
396
+ Err(format!(
397
+ "Schema validation failed for {:?} : {}",
398
+ path,
399
+ error_messages.join(", ")
400
+ ))
401
+ }
402
+ }
403
+ None => Ok(()),
404
+ }
405
+ }
406
+
407
+ fn process_config_file_entry(
408
+ path: &Path,
409
+ directory: &Path,
410
+ builder_options: &BuilderOptions,
411
+ feature_contents_validator: &Option<Arc<Validator>>,
412
+ ) -> Result<LoadingResult, String> {
413
+ let absolute_path = dunce::canonicalize(path)
414
+ .expect("path should be valid")
415
+ .to_string_lossy()
416
+ .to_string();
417
+ // TODO Optimization: Find a more efficient way to build a more generic view of the file.
418
+ // The `config` library is helpful because it handles many file types.
419
+ // It would also be nice to support comments in .json files, even though it is not standard.
420
+ // The `config` library does support .json5 which supports comments.
421
+ let file = config::File::from(path);
422
+ let config_for_path = match config::Config::builder().add_source(file).build() {
423
+ Ok(conf) => conf,
424
+ Err(e) => return Err(format!("Error loading file '{}': {e}", absolute_path)),
425
+ };
426
+
427
+ // We need the raw JSON for validation.
428
+ let raw_config: serde_json::Value = match config_for_path.try_deserialize() {
429
+ Ok(v) => v,
430
+ Err(e) => {
431
+ return Err(format!(
432
+ "Error deserializing configuration for file '{}': {e}",
433
+ absolute_path,
434
+ ))
435
+ }
436
+ };
437
+
438
+ validate_with_schema(feature_contents_validator, &raw_config, &absolute_path)?;
439
+
440
+ let feature_config: FeatureConfiguration = match serde_json::from_value(raw_config.clone()) {
441
+ Ok(v) => v,
442
+ Err(e) => {
443
+ return Err(format!(
444
+ "Error deserializing configuration for file '{}': {e}",
445
+ absolute_path,
446
+ ))
447
+ }
448
+ };
449
+
450
+ let source = feature_config
451
+ .options
452
+ .unwrap_or(serde_json::Value::Object(serde_json::Map::new()));
453
+
454
+ let canonical_feature_name = get_canonical_feature_name(path, directory);
455
+
456
+ // Ensure the name is set in the metadata.
457
+ let metadata = match feature_config.metadata {
458
+ Some(mut metadata) => {
459
+ metadata.name = Some(canonical_feature_name.clone());
460
+ metadata.path = Some(absolute_path);
461
+ metadata
462
+ }
463
+ None => OptionsMetadata::new(
464
+ None,
465
+ None,
466
+ None,
467
+ Some(canonical_feature_name.clone()),
468
+ None,
469
+ Some(absolute_path),
470
+ ),
471
+ };
472
+
473
+ let (configurable_value_pointers, configurable_string_files) =
474
+ if builder_options.are_configurable_strings_enabled {
475
+ let pointers = find_configurable_values(raw_config.get("options"));
476
+
477
+ // Tracking file references is usually not enabled in production systems and is mainly for local development,
478
+ // so we won't complicate `find_configurable_values` and make it also track referenced files.
479
+ let files = match builder_options.track_file_references {
480
+ TrackReferenceMode::None => Vec::new(),
481
+ TrackReferenceMode::ConfigurableStrings => {
482
+ extract_configurable_string_files_from_config(
483
+ &raw_config,
484
+ &pointers.configurable_string_pointers,
485
+ )
486
+ }
487
+ TrackReferenceMode::KeyName => extract_files_from_config(&raw_config),
488
+ };
489
+ (pointers, files)
490
+ } else {
491
+ (ConfigurableValuePointers::default(), Vec::new())
492
+ };
493
+
494
+ Ok(LoadingResult::Feature(FeatureLoadingResult {
495
+ canonical_feature_name,
496
+ conditions: feature_config.conditions,
497
+ configurable_string_files,
498
+ configurable_value_pointers,
499
+ imports: feature_config.imports,
500
+ metadata,
501
+ source,
502
+ }))
503
+ }
504
+
448
505
  impl OptionsRegistryBuilder<OptionsProvider> for OptionsProviderBuilder {
449
506
  fn add_directories(&mut self, directories: &[impl AsRef<Path>]) -> Result<&Self, String> {
450
507
  for directory in directories {
@@ -478,6 +535,7 @@ impl OptionsRegistryBuilder<OptionsProvider> for OptionsProviderBuilder {
478
535
  };
479
536
 
480
537
  let supported_extensions = get_supported_extensions();
538
+
481
539
  let loading_results: Vec<Result<LoadingResult, String>> = walkdir::WalkDir::new(directory)
482
540
  .into_iter()
483
541
  .filter_map(|entry| {
@@ -498,52 +556,18 @@ impl OptionsRegistryBuilder<OptionsProvider> for OptionsProviderBuilder {
498
556
  return None;
499
557
  }
500
558
 
501
- let is_config_file = match path.extension() {
502
- Some(ext) => match ext.to_str() {
503
- Some(ext_str) => supported_extensions.contains(ext_str),
504
- None => false,
505
- },
506
- None => false,
507
- };
508
-
509
- if is_config_file {
510
- Some(Ok(path.to_path_buf()))
511
- } else {
512
- // Load the file content
513
- match std::fs::read_to_string(path) {
514
- Ok(contents) => {
515
- let relative_path = path
516
- .strip_prefix(directory)
517
- .unwrap()
518
- .to_str()
519
- .expect("path should be valid Unicode")
520
- .replace(std::path::MAIN_SEPARATOR, "/");
521
- match self.loaded_files.entry(relative_path) {
522
- std::collections::hash_map::Entry::Occupied(entry) => {
523
- return Some(Err(format!(
524
- "File '{}' is already loaded from another directory.",
525
- entry.key()
526
- )));
527
- }
528
- std::collections::hash_map::Entry::Vacant(entry) => {
529
- entry.insert(contents);
530
- }
531
- }
532
- }
533
- Err(e) => {
534
- return Some(Err(format!(
535
- "Error reading file {}: {e}",
536
- path.display()
537
- )));
538
- }
539
- }
540
- None
541
- }
559
+ Some(Ok(path.to_path_buf()))
542
560
  })
543
561
  .collect::<Vec<_>>()
544
562
  .into_par_iter()
545
563
  .map(|path_result| match path_result {
546
- Ok(path) => Self::process_entry(&path, directory, &builder_options),
564
+ Ok(path) => Self::process_path(
565
+ &path,
566
+ directory,
567
+ &builder_options,
568
+ &supported_extensions,
569
+ &self.schema,
570
+ ),
547
571
  Err(e) => Err(e),
548
572
  })
549
573
  .collect();
@@ -4,8 +4,14 @@ use crate::{
4
4
  schema::{conditions::ConditionExpression, metadata::OptionsMetadata},
5
5
  };
6
6
 
7
+ #[allow(clippy::large_enum_variant)]
8
+ pub(crate) enum LoadingResult {
9
+ Feature(FeatureLoadingResult),
10
+ Raw(RawLoadingResult),
11
+ }
12
+
7
13
  /// The result of loading a feature configuration file.
8
- pub(crate) struct LoadingResult {
14
+ pub(crate) struct FeatureLoadingResult {
9
15
  pub canonical_feature_name: String,
10
16
  pub conditions: Option<ConditionExpression>,
11
17
  /// A list of file paths that are explicitly referenced within this feature's ConfigurableStrings.
@@ -14,6 +20,11 @@ pub(crate) struct LoadingResult {
14
20
  pub configurable_value_pointers: ConfigurableValuePointers,
15
21
  pub imports: Option<Vec<String>>,
16
22
  pub metadata: OptionsMetadata,
17
- pub original_config: serde_json::Value,
18
23
  pub source: SourceValue,
19
24
  }
25
+
26
+ /// The result of loading a feature configuration file.
27
+ pub(crate) struct RawLoadingResult {
28
+ pub contents: String,
29
+ pub relative_path: String,
30
+ }
@@ -146,8 +146,6 @@ mod tests {
146
146
  use super::*;
147
147
  use serde_json::json;
148
148
 
149
- // TODO Add tests for finding configurable lists.
150
-
151
149
  #[test]
152
150
  fn test_configurable_string_at_root() {
153
151
  let json_value = json!({
@@ -0,0 +1,218 @@
1
+ use std::collections::HashSet;
2
+
3
+ pub(crate) type FrozenPaths = HashSet<String>;
4
+
5
+ /// Merges objects recursively while remembering paths where lower-priority defaults are blocked.
6
+ /// Merges objects recursively with a target for the correct information
7
+ /// and defaults to use if the target is missing a value.
8
+ /// The `target` is the final value after many merges.
9
+ /// `defaults` has values to use if the `target` is missing a value.
10
+ /// I.e., values in `target` override values in `defaults`.
11
+ /// If a key is missing from `target`, it is copied from `defaults`.
12
+ /// If the key is present in both `target` and `defaults` and the value is an object, the objects are merged recursively.
13
+ #[inline]
14
+ pub(crate) fn merge_json_with_defaults(
15
+ target: &mut serde_json::Value,
16
+ defaults: &serde_json::Value,
17
+ frozen_paths: &mut FrozenPaths,
18
+ ) {
19
+ if frozen_paths.contains("") {
20
+ return;
21
+ }
22
+
23
+ let mut path = String::new();
24
+ merge_json_with_defaults_at_path(target, defaults, frozen_paths, &mut path);
25
+ }
26
+
27
+ #[inline]
28
+ fn merge_json_with_defaults_at_path(
29
+ target: &mut serde_json::Value,
30
+ defaults: &serde_json::Value,
31
+ frozen_paths: &mut FrozenPaths,
32
+ path: &mut String,
33
+ ) {
34
+ match (target, defaults) {
35
+ (serde_json::Value::Object(target_map), serde_json::Value::Object(defaults_map)) => {
36
+ for (key, defaults_value) in defaults_map {
37
+ let previous_path_len = path.len();
38
+ push_json_pointer_segment(path, key);
39
+
40
+ if !frozen_paths.contains(path) {
41
+ match target_map.get_mut(key) {
42
+ Some(target_value) => {
43
+ // They both have a value for this key.
44
+ merge_json_with_defaults_at_path(
45
+ target_value,
46
+ defaults_value,
47
+ frozen_paths,
48
+ path,
49
+ );
50
+ }
51
+ None => {
52
+ // Default value is missing from target.
53
+ target_map.insert(key.clone(), defaults_value.clone());
54
+ }
55
+ }
56
+ }
57
+
58
+ path.truncate(previous_path_len);
59
+ }
60
+ }
61
+ (serde_json::Value::Object(_), _) => {
62
+ // `defaults` is not an object.
63
+ // A lower-priority primitive would have stopped deeper defaults if it had been the target.
64
+ // Remember that lower-priority objects cannot add children at this path later
65
+ // because the default would have overwritten them if we were merge for low to high,
66
+ // but we merge from high priority to low priority to attempt to copy less.
67
+ frozen_paths.insert(path.clone());
68
+ }
69
+ _ => {
70
+ // `target` is not an object.
71
+ // The target already has the winning value at this path.
72
+ // Defaults only merge through this path when both values are objects.
73
+ }
74
+ }
75
+ }
76
+
77
+ fn push_json_pointer_segment(path: &mut String, key: &str) {
78
+ path.push('/');
79
+ for character in key.chars() {
80
+ match character {
81
+ '~' => path.push_str("~0"),
82
+ '/' => path.push_str("~1"),
83
+ _ => path.push(character),
84
+ }
85
+ }
86
+ }
87
+
88
+ #[cfg(test)]
89
+ mod tests {
90
+ use super::*;
91
+ use serde_json::json;
92
+
93
+ fn merge_json(target: &mut serde_json::Value, defaults: &serde_json::Value) {
94
+ let mut frozen_paths = FrozenPaths::new();
95
+ merge_json_with_defaults(target, defaults, &mut frozen_paths);
96
+ }
97
+
98
+ #[test]
99
+ fn test_merge_with_defaults() {
100
+ let mut target = json!({"a": 1, "b": 2});
101
+ let defaults = json!({"b": 3, "c": 4});
102
+ merge_json(&mut target, &defaults);
103
+ assert_eq!(target, json!({"a": 1, "b": 2, "c": 4}));
104
+ }
105
+
106
+ #[test]
107
+ fn test_merge_with_defaults_nested() {
108
+ let mut target = json!({
109
+ "level1": {
110
+ "a": 1,
111
+ "b": 2
112
+ }
113
+ });
114
+ let defaults = json!({
115
+ "level1": {
116
+ "b": 3,
117
+ "c": 4
118
+ }
119
+ });
120
+ merge_json(&mut target, &defaults);
121
+ assert_eq!(
122
+ target,
123
+ json!({
124
+ "level1": {
125
+ "a": 1,
126
+ "b": 2,
127
+ "c": 4
128
+ }
129
+ })
130
+ );
131
+ }
132
+
133
+ #[test]
134
+ fn test_merge_with_defaults_deeply_nested() {
135
+ let mut target = json!({
136
+ "l1": {
137
+ "l2": {
138
+ "l3": {
139
+ "a": 1
140
+ }
141
+ }
142
+ }
143
+ });
144
+ let defaults = json!({
145
+ "l1": {
146
+ "l2": {
147
+ "l3": {
148
+ "a": 57,
149
+ "b": 2
150
+ },
151
+ "new": "value"
152
+ }
153
+ }
154
+ });
155
+ merge_json(&mut target, &defaults);
156
+ assert_eq!(
157
+ target,
158
+ json!({
159
+ "l1": {
160
+ "l2": {
161
+ "l3": {
162
+ "a": 1,
163
+ "b": 2
164
+ },
165
+ "new": "value"
166
+ }
167
+ }
168
+ })
169
+ );
170
+ }
171
+
172
+ #[test]
173
+ fn test_merge_with_defaults_type_override() {
174
+ let mut target = json!({"key": {"nested": 1}});
175
+ let defaults = json!({"key": "string"});
176
+ merge_json(&mut target, &defaults);
177
+ assert_eq!(target, json!({"key": {"nested": 1}}));
178
+ }
179
+
180
+ #[test]
181
+ fn test_merge_with_defaults_using_frozen_paths_blocks_lower_priority_object_defaults() {
182
+ let mut target = json!({
183
+ "key/with~special": {
184
+ "high": true
185
+ }
186
+ });
187
+ let middle_priority_defaults = json!({"key/with~special": false});
188
+ let low_priority_defaults = json!({
189
+ "key/with~special": {
190
+ "low": true
191
+ }
192
+ });
193
+ let mut frozen_paths = FrozenPaths::new();
194
+
195
+ merge_json_with_defaults(&mut target, &middle_priority_defaults, &mut frozen_paths);
196
+ merge_json_with_defaults(&mut target, &low_priority_defaults, &mut frozen_paths);
197
+
198
+ assert_eq!(target, json!({"key/with~special": {"high": true}}));
199
+ assert!(frozen_paths.contains("/key~1with~0special"));
200
+ }
201
+
202
+ #[test]
203
+ fn test_merge_with_defaults_missing_key() {
204
+ let mut target = json!({"a": 1});
205
+ let defaults = json!({"b": 2});
206
+ merge_json(&mut target, &defaults);
207
+ assert_eq!(target, json!({"a": 1, "b": 2}));
208
+ }
209
+
210
+ #[test]
211
+ fn test_merge_with_defaults_arrays_not_merged() {
212
+ let mut target = json!({"arr": [1, 2, 3]});
213
+ let defaults = json!({"arr": [4, 5]});
214
+ merge_json(&mut target, &defaults);
215
+ // Target array is preserved, not replaced or merged.
216
+ assert_eq!(target, json!({"arr": [1, 2, 3]}));
217
+ }
218
+ }
@@ -6,7 +6,7 @@ use crate::configurable_values::configurable_list_impl::ConfigurableList;
6
6
  use crate::{
7
7
  builder::{OptionsProviderBuilder, OptionsRegistryBuilder},
8
8
  configurable_string::LoadedFiles,
9
- json::merge::merge_json_with_defaults,
9
+ json::merge::{merge_json_with_defaults, FrozenPaths},
10
10
  provider::GetOptionsPreferences,
11
11
  schema::{conditions::ConditionExpression, metadata::OptionsMetadata},
12
12
  };
@@ -133,6 +133,7 @@ impl OptionsProvider {
133
133
 
134
134
  // Merge sources as defaults in reverse (highest to lowest priority).
135
135
  // Skip last source if no overrides (already used as base).
136
+ let mut frozen_paths = FrozenPaths::new();
136
137
  let skip_count = if overrides.is_some() { 0 } else { 1 };
137
138
  for canonical_feature_name in feature_names.iter().rev().skip(skip_count) {
138
139
  let source = self.sources.get(canonical_feature_name).ok_or_else(|| {
@@ -141,7 +142,7 @@ impl OptionsProvider {
141
142
  // It could happen in the future if we allow aliases to be added directly, but we should try to validate them when the provider is built.
142
143
  format!("Feature name {canonical_feature_name:?} is not a known feature.")
143
144
  })?;
144
- merge_json_with_defaults(&mut result, source);
145
+ merge_json_with_defaults(&mut result, source, &mut frozen_paths);
145
146
  }
146
147
 
147
148
  result
@@ -186,6 +187,7 @@ impl OptionsProvider {
186
187
  // No override. Find first source with key (iterating in reverse = highest priority first).
187
188
  // Use the last source with the key to avoid merging to an empty object.
188
189
  let mut result = None;
190
+ let mut frozen_paths = FrozenPaths::new();
189
191
  for canonical_feature_name in filtered_feature_names.iter().rev() {
190
192
  let source = self.sources.get(canonical_feature_name).ok_or_else(|| {
191
193
  format!(
@@ -195,7 +197,11 @@ impl OptionsProvider {
195
197
 
196
198
  if let Some(source_value) = source.get(key) {
197
199
  match &mut result {
198
- Some(existing) => merge_json_with_defaults(existing, source_value),
200
+ Some(existing) => merge_json_with_defaults(
201
+ existing,
202
+ source_value,
203
+ &mut frozen_paths,
204
+ ),
199
205
  None => result = Some(source_value.clone()),
200
206
  }
201
207
  }
@@ -207,6 +213,7 @@ impl OptionsProvider {
207
213
  // Start with override as base (highest priority).
208
214
  // Sources are ordered from lowest to highest priority, so we iterate in reverse.
209
215
  let mut result = override_value.clone();
216
+ let mut frozen_paths = FrozenPaths::new();
210
217
  for canonical_feature_name in filtered_feature_names.iter().rev() {
211
218
  let source = self.sources.get(canonical_feature_name).ok_or_else(|| {
212
219
  format!(
@@ -215,7 +222,7 @@ impl OptionsProvider {
215
222
  })?;
216
223
 
217
224
  if let Some(source_value) = source.get(key) {
218
- merge_json_with_defaults(&mut result, source_value);
225
+ merge_json_with_defaults(&mut result, source_value, &mut frozen_paths);
219
226
  }
220
227
  }
221
228
  Some(result)
@@ -1,135 +0,0 @@
1
- /// Merges objects recursively with a target for the right information and defaults to use if the target is missing a value.
2
- /// The `target` is the final value after many merges.
3
- /// `defaults` has values to use if the `target` is missing a value.
4
- /// I.e., values in `target` override values in `defaults`.
5
- /// If a key is missing from `target`, it is copied from `defaults`.
6
- /// If the key is present in both `target` and `defaults` and the value is an object, the objects are merged recursively.
7
- #[inline]
8
- pub fn merge_json_with_defaults(target: &mut serde_json::Value, defaults: &serde_json::Value) {
9
- match (target, defaults) {
10
- (serde_json::Value::Object(target_map), serde_json::Value::Object(defaults_map)) => {
11
- for (key, defaults_value) in defaults_map {
12
- match target_map.get_mut(key) {
13
- Some(target_value) => {
14
- // They both have a value for this key.
15
- merge_json_with_defaults(target_value, defaults_value);
16
- }
17
- None => {
18
- // Default value is missing from target.
19
- target_map.insert(key.clone(), defaults_value.clone());
20
- }
21
- }
22
- }
23
- }
24
- _ => {
25
- // Either:
26
- // defaults is not an object, but target is already defined so use the target.
27
- // target is not an object, so use it as is.
28
- }
29
- }
30
- }
31
-
32
- #[cfg(test)]
33
- mod tests {
34
- use super::*;
35
- use serde_json::json;
36
-
37
- #[test]
38
- fn test_merge_with_defaults() {
39
- let mut target = json!({"a": 1, "b": 2});
40
- let defaults = json!({"b": 3, "c": 4});
41
- merge_json_with_defaults(&mut target, &defaults);
42
- assert_eq!(target, json!({"a": 1, "b": 2, "c": 4}));
43
- }
44
-
45
- #[test]
46
- fn test_merge_with_defaults_nested() {
47
- let mut target = json!({
48
- "level1": {
49
- "a": 1,
50
- "b": 2
51
- }
52
- });
53
- let defaults = json!({
54
- "level1": {
55
- "b": 3,
56
- "c": 4
57
- }
58
- });
59
- merge_json_with_defaults(&mut target, &defaults);
60
- assert_eq!(
61
- target,
62
- json!({
63
- "level1": {
64
- "a": 1,
65
- "b": 2,
66
- "c": 4
67
- }
68
- })
69
- );
70
- }
71
-
72
- #[test]
73
- fn test_merge_with_defaults_deeply_nested() {
74
- let mut target = json!({
75
- "l1": {
76
- "l2": {
77
- "l3": {
78
- "a": 1
79
- }
80
- }
81
- }
82
- });
83
- let defaults = json!({
84
- "l1": {
85
- "l2": {
86
- "l3": {
87
- "a": 57,
88
- "b": 2
89
- },
90
- "new": "value"
91
- }
92
- }
93
- });
94
- merge_json_with_defaults(&mut target, &defaults);
95
- assert_eq!(
96
- target,
97
- json!({
98
- "l1": {
99
- "l2": {
100
- "l3": {
101
- "a": 1,
102
- "b": 2
103
- },
104
- "new": "value"
105
- }
106
- }
107
- })
108
- );
109
- }
110
-
111
- #[test]
112
- fn test_merge_with_defaults_type_override() {
113
- let mut target = json!({"key": {"nested": 1}});
114
- let defaults = json!({"key": "string"});
115
- merge_json_with_defaults(&mut target, &defaults);
116
- assert_eq!(target, json!({"key": {"nested": 1}}));
117
- }
118
-
119
- #[test]
120
- fn test_merge_with_defaults_missing_key() {
121
- let mut target = json!({"a": 1});
122
- let defaults = json!({"b": 2});
123
- merge_json_with_defaults(&mut target, &defaults);
124
- assert_eq!(target, json!({"a": 1, "b": 2}));
125
- }
126
-
127
- #[test]
128
- fn test_merge_with_defaults_arrays_not_merged() {
129
- let mut target = json!({"arr": [1, 2, 3]});
130
- let defaults = json!({"arr": [4, 5]});
131
- merge_json_with_defaults(&mut target, &defaults);
132
- // Target array is preserved, not replaced or merged.
133
- assert_eq!(target, json!({"arr": [1, 2, 3]}));
134
- }
135
- }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes