optify 0.1.1__tar.gz → 0.1.3__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: optify
3
- Version: 0.1.1
3
+ Version: 0.1.3
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: Implementation :: CPython
6
6
  Classifier: Programming Language :: Python :: Implementation :: PyPy
@@ -27,6 +27,9 @@ This is just meant to be minimal to get started and help build a Python library.
27
27
 
28
28
  See the [homepage] for details.
29
29
 
30
+ ## Usage
31
+ See the [tests directory](./tests/) for examples.
32
+
30
33
  ## Development
31
34
 
32
35
  ### Setup
@@ -51,6 +54,12 @@ maturin develop
51
54
  pytest
52
55
  ```
53
56
 
57
+ ### Formatting
58
+ To automatically change the Rust code, run:
59
+ ```shell
60
+ cargo fmt && cargo clippy --fix --allow-dirty --allow-staged
61
+ ```
62
+
54
63
  # Publishing
55
64
  A GitHub Action will automatically publish new versions: https://github.com/juharris/optify/actions/workflows/python_publish.yml
56
65
 
@@ -9,6 +9,9 @@ This is just meant to be minimal to get started and help build a Python library.
9
9
 
10
10
  See the [homepage] for details.
11
11
 
12
+ ## Usage
13
+ See the [tests directory](./tests/) for examples.
14
+
12
15
  ## Development
13
16
 
14
17
  ### Setup
@@ -33,6 +36,12 @@ maturin develop
33
36
  pytest
34
37
  ```
35
38
 
39
+ ### Formatting
40
+ To automatically change the Rust code, run:
41
+ ```shell
42
+ cargo fmt && cargo clippy --fix --allow-dirty --allow-staged
43
+ ```
44
+
36
45
  # Publishing
37
46
  A GitHub Action will automatically publish new versions: https://github.com/juharris/optify/actions/workflows/python_publish.yml
38
47
 
@@ -26,11 +26,11 @@ build-backend = "maturin"
26
26
 
27
27
  [package]
28
28
  name = "optify"
29
- version = "0.1.1"
29
+ version = "0.1.3"
30
30
 
31
31
  [tool.poetry]
32
32
  name = "optify"
33
- version = "0.1.1"
33
+ version = "0.1.3"
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"]
@@ -124,6 +124,31 @@ dependencies = [
124
124
  "libc",
125
125
  ]
126
126
 
127
+ [[package]]
128
+ name = "crossbeam-deque"
129
+ version = "0.8.6"
130
+ source = "registry+https://github.com/rust-lang/crates.io-index"
131
+ checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51"
132
+ dependencies = [
133
+ "crossbeam-epoch",
134
+ "crossbeam-utils",
135
+ ]
136
+
137
+ [[package]]
138
+ name = "crossbeam-epoch"
139
+ version = "0.9.18"
140
+ source = "registry+https://github.com/rust-lang/crates.io-index"
141
+ checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
142
+ dependencies = [
143
+ "crossbeam-utils",
144
+ ]
145
+
146
+ [[package]]
147
+ name = "crossbeam-utils"
148
+ version = "0.8.21"
149
+ source = "registry+https://github.com/rust-lang/crates.io-index"
150
+ checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
151
+
127
152
  [[package]]
128
153
  name = "crunchy"
129
154
  version = "0.2.3"
@@ -159,6 +184,12 @@ dependencies = [
159
184
  "const-random",
160
185
  ]
161
186
 
187
+ [[package]]
188
+ name = "either"
189
+ version = "1.15.0"
190
+ source = "registry+https://github.com/rust-lang/crates.io-index"
191
+ checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
192
+
162
193
  [[package]]
163
194
  name = "encoding_rs"
164
195
  version = "0.8.35"
@@ -287,9 +318,10 @@ checksum = "945462a4b81e43c4e3ba96bd7b49d834c6f61198356aa858733bc4acf3cbe62e"
287
318
 
288
319
  [[package]]
289
320
  name = "optify"
290
- version = "0.4.0"
321
+ version = "0.6.2"
291
322
  dependencies = [
292
323
  "config",
324
+ "rayon",
293
325
  "serde",
294
326
  "serde_derive",
295
327
  "serde_json",
@@ -299,7 +331,7 @@ dependencies = [
299
331
 
300
332
  [[package]]
301
333
  name = "optify-python"
302
- version = "0.1.1"
334
+ version = "0.1.3"
303
335
  dependencies = [
304
336
  "optify",
305
337
  "pyo3",
@@ -383,9 +415,9 @@ dependencies = [
383
415
 
384
416
  [[package]]
385
417
  name = "pyo3"
386
- version = "0.23.4"
418
+ version = "0.24.1"
387
419
  source = "registry+https://github.com/rust-lang/crates.io-index"
388
- checksum = "57fe09249128b3173d092de9523eaa75136bf7ba85e0d69eca241c7939c933cc"
420
+ checksum = "17da310086b068fbdcefbba30aeb3721d5bb9af8db4987d6735b2183ca567229"
389
421
  dependencies = [
390
422
  "cfg-if",
391
423
  "indoc",
@@ -401,9 +433,9 @@ dependencies = [
401
433
 
402
434
  [[package]]
403
435
  name = "pyo3-build-config"
404
- version = "0.23.4"
436
+ version = "0.24.1"
405
437
  source = "registry+https://github.com/rust-lang/crates.io-index"
406
- checksum = "1cd3927b5a78757a0d71aa9dff669f903b1eb64b54142a9bd9f757f8fde65fd7"
438
+ checksum = "e27165889bd793000a098bb966adc4300c312497ea25cf7a690a9f0ac5aa5fc1"
407
439
  dependencies = [
408
440
  "once_cell",
409
441
  "target-lexicon",
@@ -411,9 +443,9 @@ dependencies = [
411
443
 
412
444
  [[package]]
413
445
  name = "pyo3-ffi"
414
- version = "0.23.4"
446
+ version = "0.24.1"
415
447
  source = "registry+https://github.com/rust-lang/crates.io-index"
416
- checksum = "dab6bb2102bd8f991e7749f130a70d05dd557613e39ed2deeee8e9ca0c4d548d"
448
+ checksum = "05280526e1dbf6b420062f3ef228b78c0c54ba94e157f5cb724a609d0f2faabc"
417
449
  dependencies = [
418
450
  "libc",
419
451
  "pyo3-build-config",
@@ -421,9 +453,9 @@ dependencies = [
421
453
 
422
454
  [[package]]
423
455
  name = "pyo3-macros"
424
- version = "0.23.4"
456
+ version = "0.24.1"
425
457
  source = "registry+https://github.com/rust-lang/crates.io-index"
426
- checksum = "91871864b353fd5ffcb3f91f2f703a22a9797c91b9ab497b1acac7b07ae509c7"
458
+ checksum = "5c3ce5686aa4d3f63359a5100c62a127c9f15e8398e5fdeb5deef1fed5cd5f44"
427
459
  dependencies = [
428
460
  "proc-macro2",
429
461
  "pyo3-macros-backend",
@@ -433,9 +465,9 @@ dependencies = [
433
465
 
434
466
  [[package]]
435
467
  name = "pyo3-macros-backend"
436
- version = "0.23.4"
468
+ version = "0.24.1"
437
469
  source = "registry+https://github.com/rust-lang/crates.io-index"
438
- checksum = "43abc3b80bc20f3facd86cd3c60beed58c3e2aa26213f3cda368de39c60a27e4"
470
+ checksum = "f4cf6faa0cbfb0ed08e89beb8103ae9724eb4750e3a78084ba4017cbe94f3855"
439
471
  dependencies = [
440
472
  "heck",
441
473
  "proc-macro2",
@@ -453,6 +485,26 @@ dependencies = [
453
485
  "proc-macro2",
454
486
  ]
455
487
 
488
+ [[package]]
489
+ name = "rayon"
490
+ version = "1.10.0"
491
+ source = "registry+https://github.com/rust-lang/crates.io-index"
492
+ checksum = "b418a60154510ca1a002a752ca9714984e21e4241e804d32555251faf8b78ffa"
493
+ dependencies = [
494
+ "either",
495
+ "rayon-core",
496
+ ]
497
+
498
+ [[package]]
499
+ name = "rayon-core"
500
+ version = "1.12.1"
501
+ source = "registry+https://github.com/rust-lang/crates.io-index"
502
+ checksum = "1465873a3dfdaa8ae7cb14b4383657caab0b3e8a0aa9ae8e04b044854c8dfce2"
503
+ dependencies = [
504
+ "crossbeam-deque",
505
+ "crossbeam-utils",
506
+ ]
507
+
456
508
  [[package]]
457
509
  name = "ron"
458
510
  version = "0.8.1"
@@ -513,9 +565,9 @@ dependencies = [
513
565
 
514
566
  [[package]]
515
567
  name = "serde_json"
516
- version = "1.0.138"
568
+ version = "1.0.140"
517
569
  source = "registry+https://github.com/rust-lang/crates.io-index"
518
- checksum = "d434192e7da787e94a6ea7e9670b26a036d0ca41e0b7efb2676dd32bae872949"
570
+ checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373"
519
571
  dependencies = [
520
572
  "itoa",
521
573
  "memchr",
@@ -556,9 +608,9 @@ dependencies = [
556
608
 
557
609
  [[package]]
558
610
  name = "target-lexicon"
559
- version = "0.12.16"
611
+ version = "0.13.2"
560
612
  source = "registry+https://github.com/rust-lang/crates.io-index"
561
- checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"
613
+ checksum = "e502f78cdbb8ba4718f566c418c52bc729126ffd16baee5baa718cf25dd5a69a"
562
614
 
563
615
  [[package]]
564
616
  name = "thiserror"
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "optify-python"
3
- version = "0.1.1"
3
+ version = "0.1.3"
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."
@@ -14,5 +14,5 @@ name = "optify"
14
14
  crate-type = ["cdylib"]
15
15
 
16
16
  [dependencies]
17
- optify = { path = "../../rust/optify", version = "0.4.0" }
18
- pyo3 = "0.23.3"
17
+ optify = { path = "../../rust/optify", version = "0.6.2" }
18
+ pyo3 = "0.24.1"
@@ -9,6 +9,9 @@ This is just meant to be minimal to get started and help build a Python library.
9
9
 
10
10
  See the [homepage] for details.
11
11
 
12
+ ## Usage
13
+ See the [tests directory](./tests/) for examples.
14
+
12
15
  ## Development
13
16
 
14
17
  ### Setup
@@ -33,6 +36,12 @@ maturin develop
33
36
  pytest
34
37
  ```
35
38
 
39
+ ### Formatting
40
+ To automatically change the Rust code, run:
41
+ ```shell
42
+ cargo fmt && cargo clippy --fix --allow-dirty --allow-staged
43
+ ```
44
+
36
45
  # Publishing
37
46
  A GitHub Action will automatically publish new versions: https://github.com/juharris/optify/actions/workflows/python_publish.yml
38
47
 
@@ -11,14 +11,21 @@ struct PyOptionsProviderBuilder(OptionsProviderBuilder);
11
11
  struct PyOptionsProvider(OptionsProvider);
12
12
 
13
13
  #[pymethods]
14
- impl PyOptionsProvider{
14
+ impl PyOptionsProvider {
15
+ fn features(&self) -> Vec<String> {
16
+ self.0.get_features()
17
+ }
18
+
15
19
  fn get_options_json(&self, key: &str, feature_names: Vec<String>) -> String {
16
- self.0.get_options(&key, &feature_names).unwrap().to_string()
20
+ self.0
21
+ .get_options(key, &feature_names)
22
+ .expect("key and feature names should be valid")
23
+ .to_string()
17
24
  }
18
25
  }
19
26
 
20
27
  #[pymethods]
21
- impl PyOptionsProviderBuilder{
28
+ impl PyOptionsProviderBuilder {
22
29
  #[new]
23
30
  fn new() -> Self {
24
31
  Self(OptionsProviderBuilder::new())
@@ -26,17 +33,23 @@ impl PyOptionsProviderBuilder{
26
33
 
27
34
  fn add_directory(&mut self, directory: &str) -> Self {
28
35
  let path = std::path::Path::new(&directory);
29
- self.0.add_directory(path).unwrap();
36
+ self.0
37
+ .add_directory(path)
38
+ .expect("directory contents should be valid");
30
39
  // TODO Try to avoid cloning
31
40
  Self(self.0.clone())
32
41
  }
33
42
 
34
43
  fn build(&mut self) -> PyOptionsProvider {
35
- PyOptionsProvider(self.0.build().unwrap())
44
+ PyOptionsProvider(
45
+ self.0
46
+ .build()
47
+ .expect("OptionsProvider should be built successfully"),
48
+ )
36
49
  }
37
50
  }
38
51
 
39
- #[pymodule(name="optify")]
52
+ #[pymodule(name = "optify")]
40
53
  mod optify_python {
41
54
  #[pymodule_export]
42
55
  use super::PyOptionsProviderBuilder;
@@ -0,0 +1,19 @@
1
+ from pathlib import Path
2
+
3
+ from optify import OptionsProviderBuilder
4
+
5
+
6
+ def test_features():
7
+ test_suites_dir = (Path(__file__) / '../../../../tests/test_suites').resolve()
8
+ builder = OptionsProviderBuilder()
9
+ builder.add_directory(str(test_suites_dir / 'simple/configs'))
10
+ provider = builder.build()
11
+ features = provider.features()
12
+ features.sort()
13
+ assert features == ['A_with_comments', 'feature_A', 'feature_B/initial']
14
+
15
+ try:
16
+ provider.get_options_json('key', ['A'])
17
+ assert False, "Should have raised an error"
18
+ except BaseException as e:
19
+ assert str(e) == "key and feature names should be valid: \"configuration property \\\"key\\\" not found\""
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "optify"
3
- version = "0.4.0"
3
+ version = "0.6.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."
@@ -18,11 +18,17 @@ exclude = [
18
18
 
19
19
  [dependencies]
20
20
  config = "0.15.6"
21
+ rayon = "1.10.0"
21
22
  serde = "1.0.217"
22
23
  serde_derive = "1.0.217"
23
- serde_json = "1.0.137"
24
+ serde_json = "1.0.140"
24
25
  unicase = "2.8.1"
25
26
  walkdir = "2.5.0"
26
27
 
27
28
  [dev-dependencies]
28
29
  regex = "1.11.1"
30
+ criterion = "0.5.1"
31
+
32
+ [[bench]]
33
+ name = "loading_benchmark"
34
+ harness = false
@@ -24,8 +24,7 @@ cargo test
24
24
  ## Formatting
25
25
  To automatically change code, run:
26
26
  ```shell
27
- cargo fmt
28
- cargo clippy --fix --allow-dirty --allow-staged
27
+ cargo fmt && cargo clippy --fix --allow-dirty --allow-staged
29
28
  ```
30
29
 
31
30
  ## Publishing
@@ -0,0 +1,105 @@
1
+ use criterion::{black_box, criterion_group, criterion_main, Criterion};
2
+ use optify::builder::OptionsProviderBuilder;
3
+ use std::fs;
4
+ use std::io::Write;
5
+ use std::path::Path;
6
+
7
+ struct TestDirGuard {
8
+ dir: &'static Path,
9
+ }
10
+
11
+ impl TestDirGuard {
12
+ fn new(dir: &'static Path) -> Self {
13
+ Self { dir }
14
+ }
15
+ }
16
+
17
+ impl Drop for TestDirGuard {
18
+ fn drop(&mut self) {
19
+ cleanup_test_files(self.dir);
20
+ }
21
+ }
22
+
23
+ fn create_test_files(dir: &Path, num_files: usize) {
24
+ cleanup_test_files(dir);
25
+ fs::create_dir_all(dir).unwrap();
26
+
27
+ for i in 0..num_files / 2 {
28
+ let file_path = dir.join(format!("test_{}.json", i));
29
+ let mut file = fs::File::create(&file_path).unwrap();
30
+
31
+ // Create a test configuration file with some realistic content
32
+ let content = format!(
33
+ r#"{{
34
+ "metadata": {{
35
+ "aliases": ["alias_{}_1", "alias_{}_2"]
36
+ }},
37
+ "options": {{
38
+ "setting1": "value1",
39
+ "setting2": 42,
40
+ "setting3": true,
41
+ "nested": {{
42
+ "field1": "nested_value",
43
+ "field2": [1, 2, 3]
44
+ }}
45
+ }}
46
+ }}"#,
47
+ i, i,
48
+ );
49
+
50
+ file.write_all(content.as_bytes()).unwrap();
51
+ }
52
+
53
+ for i in num_files / 2..num_files {
54
+ let file_path = dir.join(format!("test_{}.yaml", i));
55
+ let mut file = fs::File::create(&file_path).unwrap();
56
+
57
+ let content = format!(
58
+ r#"metadata:
59
+ aliases:
60
+ - alias_y_{}_1
61
+ - alias_y_{}_2
62
+ options:
63
+ setting1: value1
64
+ setting2: 42
65
+ setting3: true
66
+ nested:
67
+ field1: nested_value
68
+ field2: [1, 2, 3]
69
+ "#,
70
+ i, i,
71
+ );
72
+ file.write_all(content.as_bytes()).unwrap();
73
+ }
74
+ }
75
+
76
+ fn cleanup_test_files(dir: &Path) {
77
+ fs::remove_dir_all(dir).unwrap_or_default();
78
+ }
79
+
80
+ fn benchmark_loading(c: &mut Criterion) {
81
+ let test_dir = Path::new("bench_test_files");
82
+ let num_files = 100;
83
+ let _guard = TestDirGuard::new(test_dir);
84
+ let test_build = false;
85
+
86
+ create_test_files(test_dir, num_files);
87
+
88
+ let mut group = c.benchmark_group(format!("file_loading-{}", num_files));
89
+
90
+ group.bench_function("parallel loading", |b| {
91
+ b.iter(|| {
92
+ let mut builder = OptionsProviderBuilder::new();
93
+ builder.add_directory(black_box(test_dir)).unwrap();
94
+ if test_build {
95
+ // Ensure that there are no errors in the builder.
96
+ builder.build().unwrap();
97
+ }
98
+ })
99
+ });
100
+
101
+ group.finish();
102
+ }
103
+
104
+ criterion_group!(benches, benchmark_loading);
105
+ criterion_main!(benches);
@@ -1,10 +1,11 @@
1
1
  use config;
2
+ use rayon::prelude::*;
2
3
  use std::collections::{HashMap, HashSet};
3
4
  use std::path::Path;
4
- use walkdir::WalkDir;
5
5
 
6
- use crate::provider::{Aliases, OptionsProvider, Sources};
6
+ use crate::provider::{Aliases, Features, OptionsProvider, Sources};
7
7
  use crate::schema::feature::FeatureConfiguration;
8
+ use crate::schema::metadata::OptionsMetadata;
8
9
 
9
10
  type Imports = HashMap<String, Vec<String>>;
10
11
 
@@ -13,6 +14,7 @@ type Imports = HashMap<String, Vec<String>>;
13
14
  #[derive(Clone)]
14
15
  pub struct OptionsProviderBuilder {
15
16
  aliases: Aliases,
17
+ features: Features,
16
18
  imports: Imports,
17
19
  sources: Sources,
18
20
  }
@@ -29,7 +31,7 @@ fn add_alias(
29
31
  canonical_feature_name: &String,
30
32
  ) -> Result<(), String> {
31
33
  let uni_case_alias = unicase::UniCase::new(alias.clone());
32
- if let Some(res) = aliases.insert(uni_case_alias, canonical_feature_name.clone()) {
34
+ if let Some(ref res) = aliases.insert(uni_case_alias, canonical_feature_name.clone()) {
33
35
  return Err(format!(
34
36
  "The alias '{alias}' for canonical feature name '{canonical_feature_name}' is already mapped to '{res}'."
35
37
  ));
@@ -89,7 +91,7 @@ fn resolve_imports(
89
91
  _features_in_resolution_path.insert(import.clone());
90
92
  resolve_imports(
91
93
  import,
92
- &imports_for_import.clone(),
94
+ imports_for_import,
93
95
  resolved_imports,
94
96
  &mut _features_in_resolution_path,
95
97
  aliases,
@@ -109,7 +111,7 @@ fn resolve_imports(
109
111
  let source = sources.get(canonical_feature_name).unwrap();
110
112
  config_builder = config_builder.add_source(source.clone());
111
113
 
112
- // We have the configuration, build it and store it.
114
+ // Build the configuration and store it.
113
115
  match config_builder.build() {
114
116
  Ok(new_config) => {
115
117
  // Convert to something that can be inserted as a source.
@@ -121,8 +123,9 @@ fn resolve_imports(
121
123
  ))
122
124
  }
123
125
  };
124
- let options_as_json: serde_json::Value =
125
- options_as_config_value.try_deserialize().unwrap();
126
+ let options_as_json: serde_json::Value = options_as_config_value
127
+ .try_deserialize()
128
+ .expect("configuration should be deserializable to JSON");
126
129
  let options_as_json_str = serde_json::to_string(&options_as_json).unwrap();
127
130
  let source = config::File::from_str(&options_as_json_str, config::FileFormat::Json);
128
131
  sources.insert(canonical_feature_name.to_owned(), source);
@@ -138,97 +141,41 @@ fn resolve_imports(
138
141
  Ok(())
139
142
  }
140
143
 
144
+ /// The result of loading a feature configuration file.
145
+ struct LoadingResult {
146
+ canonical_feature_name: String,
147
+ source: config::File<config::FileSourceString, config::FileFormat>,
148
+ imports: Option<Vec<String>>,
149
+ metadata: OptionsMetadata,
150
+ }
151
+
141
152
  impl OptionsProviderBuilder {
142
153
  pub fn new() -> Self {
143
154
  OptionsProviderBuilder {
144
155
  aliases: Aliases::new(),
156
+ features: Features::new(),
145
157
  imports: HashMap::new(),
146
158
  sources: Sources::new(),
147
159
  }
148
160
  }
149
161
 
150
162
  pub fn add_directory(&mut self, directory: &Path) -> Result<&Self, String> {
151
- for entry in WalkDir::new(directory) {
152
- let entry = entry.unwrap();
153
- let path = entry.path();
154
- if !path.is_file() {
155
- continue;
156
- }
157
- // Skip .md files because they are not handled by the `config` library and we may have README.md files in the directory.
158
- if path.extension().and_then(|s| s.to_str()) == Some("md") {
159
- continue;
160
- }
161
-
162
- // TODO Optimization: Find a more efficient way to build a more generic view of the file.
163
- // The `config` library is helpful because it handles many file types.
164
- // It would also be nice to support comments in .json files, even though it is not standard.
165
- // The `config` library does support .json5 which supports comments.
166
- let file = config::File::from(path);
167
- let config_for_path = match config::Config::builder().add_source(file).build() {
168
- Ok(conf) => conf,
169
- Err(e) => {
170
- return Err(format!(
171
- "Error loading file '{}': {e}",
172
- path.to_string_lossy(),
173
- ))
174
- }
175
- };
176
-
177
- let feature_config: FeatureConfiguration = match config_for_path.try_deserialize() {
178
- Ok(v) => v,
179
- Err(e) => {
180
- return Err(format!(
181
- "Error deserializing configuration for file '{}': {e}",
182
- path.to_string_lossy(),
183
- ))
184
- }
185
- };
186
-
187
- let options_as_json_str = match feature_config.options {
188
- None => "{}".to_owned(),
189
- Some(options) => {
190
- let options_as_json: serde_json::Value =
191
- options.try_deserialize().map_err(|e| {
192
- format!(
193
- "Error deserializing options for '{:?}': {e}",
194
- path.to_string_lossy()
195
- )
196
- })?;
197
- serde_json::to_string(&options_as_json).unwrap()
198
- }
199
- };
200
- let source = config::File::from_str(&options_as_json_str, config::FileFormat::Json);
201
- let canonical_feature_name = get_canonical_feature_name(path, directory);
202
-
203
- if self
204
- .sources
205
- .insert(canonical_feature_name.clone(), source)
206
- .is_some()
207
- {
208
- return Err(format!(
209
- "Error when loading '{}'. The canonical feature name for the file, '{canonical_feature_name}', was already added. It may be an alias for another feature.",
210
- path.to_string_lossy()
211
- ));
212
- }
213
-
214
- if let Some(imports) = feature_config.imports {
215
- self.imports.insert(canonical_feature_name.clone(), imports);
216
- }
217
-
218
- add_alias(
219
- &mut self.aliases,
220
- &canonical_feature_name,
221
- &canonical_feature_name,
222
- )?;
223
-
224
- // Add aliases.
225
- if let Some(metadata) = feature_config.metadata {
226
- if let Some(aliases) = metadata.aliases {
227
- for alias in aliases {
228
- add_alias(&mut self.aliases, &alias, &canonical_feature_name)?;
229
- }
230
- }
231
- }
163
+ let loading_results: Vec<Result<LoadingResult, String>> = walkdir::WalkDir::new(directory)
164
+ .into_iter()
165
+ .par_bridge()
166
+ .filter_map(|entry| {
167
+ Self::process_entry(
168
+ entry
169
+ .unwrap_or_else(|_| {
170
+ panic!("Error walking directory: {}", directory.display())
171
+ })
172
+ .path(),
173
+ directory,
174
+ )
175
+ })
176
+ .collect();
177
+ for loading_result in loading_results {
178
+ self.process_loading_result(&loading_result)?;
232
179
  }
233
180
 
234
181
  Ok(self)
@@ -253,6 +200,107 @@ impl OptionsProviderBuilder {
253
200
  }
254
201
  }
255
202
 
256
- Ok(OptionsProvider::new(&self.aliases, &self.sources))
203
+ Ok(OptionsProvider::new(
204
+ &self.aliases,
205
+ &self.features,
206
+ &self.sources,
207
+ ))
208
+ }
209
+
210
+ fn process_entry(path: &Path, directory: &Path) -> Option<Result<LoadingResult, String>> {
211
+ // Skip .md files because they are not handled by the `config` library and we may have README.md files in the directory.
212
+ if !path.is_file() || path.extension().filter(|e| *e == "md").is_some() {
213
+ return None;
214
+ }
215
+
216
+ // TODO Optimization: Find a more efficient way to build a more generic view of the file.
217
+ // The `config` library is helpful because it handles many file types.
218
+ // It would also be nice to support comments in .json files, even though it is not standard.
219
+ // The `config` library does support .json5 which supports comments.
220
+ let file = config::File::from(path);
221
+ let config_for_path = match config::Config::builder().add_source(file).build() {
222
+ Ok(conf) => conf,
223
+ Err(e) => {
224
+ return Some(Err(format!(
225
+ "Error loading file '{}': {e}",
226
+ path.to_string_lossy(),
227
+ )))
228
+ }
229
+ };
230
+
231
+ let feature_config: FeatureConfiguration = match config_for_path.try_deserialize() {
232
+ Ok(v) => v,
233
+ Err(e) => {
234
+ return Some(Err(format!(
235
+ "Error deserializing configuration for file '{:?}': {e}",
236
+ path.to_string_lossy(),
237
+ )))
238
+ }
239
+ };
240
+
241
+ let options_as_json_str = match feature_config.options {
242
+ Some(options) => match options.try_deserialize::<serde_json::Value>() {
243
+ Ok(options_as_json) => serde_json::to_string(&options_as_json).unwrap(),
244
+ Err(e) => {
245
+ return Some(Err(format!(
246
+ "Error deserializing options for '{:?}': {e}",
247
+ path.to_string_lossy()
248
+ )))
249
+ }
250
+ },
251
+ None => "{}".to_owned(),
252
+ };
253
+ let source = config::File::from_str(&options_as_json_str, config::FileFormat::Json);
254
+ let canonical_feature_name = get_canonical_feature_name(path, directory);
255
+
256
+ // Ensure the name is set in the metadata.
257
+ let metadata = match feature_config.metadata {
258
+ Some(mut metadata) => {
259
+ metadata.name = Some(canonical_feature_name.clone());
260
+ metadata
261
+ }
262
+ None => OptionsMetadata::new(None, None, Some(canonical_feature_name.clone()), None),
263
+ };
264
+
265
+ Some(Ok(LoadingResult {
266
+ canonical_feature_name,
267
+ source,
268
+ imports: feature_config.imports,
269
+ metadata,
270
+ }))
271
+ }
272
+
273
+ fn process_loading_result(
274
+ &mut self,
275
+ loading_result: &Result<LoadingResult, String>,
276
+ ) -> Result<(), String> {
277
+ let info = loading_result.as_ref().expect("the file should be loaded");
278
+ let canonical_feature_name = &info.canonical_feature_name;
279
+ if self
280
+ .sources
281
+ .insert(canonical_feature_name.clone(), info.source.clone())
282
+ .is_some()
283
+ {
284
+ return Err(format!(
285
+ "Error when loading feature. The canonical feature name '{canonical_feature_name}' was already added. It may be an alias for another feature."
286
+ ));
287
+ }
288
+ if let Some(imports) = &info.imports {
289
+ self.imports
290
+ .insert(canonical_feature_name.clone(), imports.clone());
291
+ }
292
+ add_alias(
293
+ &mut self.aliases,
294
+ canonical_feature_name,
295
+ canonical_feature_name,
296
+ )?;
297
+ if let Some(ref aliases) = info.metadata.aliases {
298
+ for alias in aliases {
299
+ add_alias(&mut self.aliases, alias, canonical_feature_name)?;
300
+ }
301
+ }
302
+ self.features
303
+ .insert(canonical_feature_name.clone(), info.metadata.clone());
304
+ Ok(())
257
305
  }
258
306
  }
@@ -1,3 +1,3 @@
1
1
  pub mod builder;
2
2
  pub mod provider;
3
- pub(crate) mod schema;
3
+ pub mod schema;
@@ -1,6 +1,8 @@
1
1
  use config::{self};
2
2
  use std::collections::HashMap;
3
3
 
4
+ use crate::schema::metadata::OptionsMetadata;
5
+
4
6
  // Replicating https://github.com/juharris/dotnet-OptionsProvider/blob/main/src/OptionsProvider/OptionsProvider/IOptionsProvider.cs
5
7
  // and https://github.com/juharris/dotnet-OptionsProvider/blob/main/src/OptionsProvider/OptionsProvider/OptionsProviderWithDefaults.cs
6
8
 
@@ -8,27 +10,49 @@ use std::collections::HashMap;
8
10
  pub(crate) type SourceValue = config::File<config::FileSourceString, config::FileFormat>;
9
11
 
10
12
  pub(crate) type Aliases = HashMap<unicase::UniCase<String>, String>;
13
+ pub(crate) type Features = HashMap<String, OptionsMetadata>;
11
14
  pub(crate) type Sources = HashMap<String, SourceValue>;
12
15
 
13
16
  pub struct GetOptionsPreferences {
14
17
  pub skip_feature_name_conversion: bool,
15
18
  }
16
19
 
20
+ pub struct CacheOptions {}
21
+
17
22
  /// ⚠️ Development in progress ⚠️\
18
23
  /// Not truly considered public and mainly available to support bindings for other languages.
19
24
  pub struct OptionsProvider {
20
25
  aliases: Aliases,
26
+ features: Features,
21
27
  sources: Sources,
22
28
  }
23
29
 
24
30
  impl OptionsProvider {
25
- pub(crate) fn new(aliases: &Aliases, sources: &Sources) -> Self {
31
+ pub(crate) fn new(aliases: &Aliases, features: &Features, sources: &Sources) -> Self {
26
32
  OptionsProvider {
27
33
  aliases: aliases.clone(),
34
+ features: features.clone(),
28
35
  sources: sources.clone(),
29
36
  }
30
37
  }
31
38
 
39
+ pub fn get_all_options(
40
+ &self,
41
+ feature_names: &Vec<String>,
42
+ cache_options: &Option<CacheOptions>,
43
+ preferences: &Option<GetOptionsPreferences>,
44
+ ) -> Result<serde_json::Value, String> {
45
+ let config = self._get_entire_config(feature_names, cache_options, preferences)?;
46
+
47
+ match config {
48
+ Ok(cfg) => match cfg.try_deserialize() {
49
+ Ok(value) => Ok(value),
50
+ Err(e) => Err(e.to_string()),
51
+ },
52
+ Err(e) => Err(e.to_string()),
53
+ }
54
+ }
55
+
32
56
  // Map an alias or canonical feature name (perhaps derived from a file name) to a canonical feature name.
33
57
  // Canonical feature names map to themselves.
34
58
  //
@@ -46,23 +70,53 @@ impl OptionsProvider {
46
70
  }
47
71
  }
48
72
 
73
+ pub fn get_feature_metadata(&self, canonical_feature_name: &str) -> Option<&OptionsMetadata> {
74
+ self.features.get(canonical_feature_name)
75
+ }
76
+
77
+ pub fn get_features(&self) -> Vec<String> {
78
+ self.sources.keys().map(|s| s.to_owned()).collect()
79
+ }
80
+
81
+ pub fn get_features_with_metadata(&self) -> &Features {
82
+ &self.features
83
+ }
84
+
49
85
  pub fn get_options(
50
86
  &self,
51
87
  key: &str,
52
88
  feature_names: &Vec<String>,
53
89
  ) -> Result<serde_json::Value, String> {
54
- self.get_option_with_preferences(key, feature_names, &None)
90
+ self.get_options_with_preferences(key, feature_names, &None, &None)
55
91
  }
56
92
 
57
- // TODO Add another method with caching
58
- // with an option to disable because we will not want to use the cache when calling from other languages because they should use their own caching
59
- // in order to avoid possible overhead and conversion.
60
- pub fn get_option_with_preferences(
93
+ pub fn get_options_with_preferences(
61
94
  &self,
62
95
  key: &str,
63
96
  feature_names: &Vec<String>,
97
+ cache_options: &Option<CacheOptions>,
64
98
  preferences: &Option<GetOptionsPreferences>,
65
99
  ) -> Result<serde_json::Value, String> {
100
+ let config = self._get_entire_config(feature_names, cache_options, preferences)?;
101
+
102
+ match config {
103
+ Ok(cfg) => match cfg.get(key) {
104
+ Ok(value) => Ok(value),
105
+ Err(e) => Err(e.to_string()),
106
+ },
107
+ Err(e) => Err(e.to_string()),
108
+ }
109
+ }
110
+
111
+ fn _get_entire_config(
112
+ &self,
113
+ feature_names: &Vec<String>,
114
+ cache_options: &Option<CacheOptions>,
115
+ preferences: &Option<GetOptionsPreferences>,
116
+ ) -> Result<Result<config::Config, config::ConfigError>, String> {
117
+ if let Some(_cache_options) = cache_options {
118
+ return Err("Caching is not supported yet.".to_owned());
119
+ };
66
120
  let mut config_builder = config::Config::builder();
67
121
  let mut skip_feature_name_conversion = false;
68
122
  if let Some(_preferences) = preferences {
@@ -90,14 +144,6 @@ impl OptionsProvider {
90
144
  };
91
145
  config_builder = config_builder.add_source(source.clone());
92
146
  }
93
- let config = config_builder.build();
94
-
95
- match config {
96
- Ok(cfg) => match cfg.get(key) {
97
- Ok(value) => Ok(value),
98
- Err(e) => Err(e.to_string()),
99
- },
100
- Err(e) => Err(e.to_string()),
101
- }
147
+ Ok(config_builder.build())
102
148
  }
103
149
  }
@@ -6,7 +6,7 @@ use super::metadata::OptionsMetadata;
6
6
 
7
7
  pub(crate) type ConfigurationOptions = config::Value;
8
8
 
9
- #[derive(Debug, Deserialize)]
9
+ #[derive(Clone, Debug, Deserialize)]
10
10
  #[allow(unused)]
11
11
  pub(crate) struct FeatureConfiguration {
12
12
  pub imports: Option<Vec<String>>,
@@ -0,0 +1,51 @@
1
+ // Similar to https://github.com/juharris/dotnet-OptionsProvider/blob/main/src/OptionsProvider/OptionsProvider/OptionsMetadata.cs
2
+
3
+ use serde::{Deserialize, Serialize};
4
+
5
+ type Details = serde_json::Value;
6
+
7
+ /// Information about a group of options.
8
+ #[derive(Clone, Debug, Deserialize, Serialize)]
9
+ #[allow(unused)]
10
+ pub struct OptionsMetadata {
11
+ // TODO Add more props.
12
+ /// Alternative names for the group of options.
13
+ ///
14
+ /// This is helpful for using custom short names for the group of options.
15
+ pub aliases: Option<Vec<String>>,
16
+
17
+ /// Other metadata that may be custom and application specific.
18
+ ///
19
+ /// This is a good place for documentation that should be available to the application.
20
+ /// Comments that are not parsed are still great to have in files, when supported,
21
+ /// but some comments are useful to have here because they can be accessed programmatically.
22
+ pub details: Option<Details>,
23
+
24
+ /// The name of the group of options.
25
+ ///
26
+ /// This may be derived from the file name including subdirectories.
27
+ /// Should never be <tt>None</tt> or an empty string.
28
+ /// When loading the options from a file, the name is automatically derived from the file name.
29
+ pub name: Option<String>,
30
+
31
+ /// The creators or maintainers of this group of options.
32
+ ///
33
+ /// For example, emails separated by ";".
34
+ pub owners: Option<String>,
35
+ }
36
+
37
+ impl OptionsMetadata {
38
+ pub fn new(
39
+ aliases: Option<Vec<String>>,
40
+ details: Option<Details>,
41
+ name: Option<String>,
42
+ owners: Option<String>,
43
+ ) -> Self {
44
+ Self {
45
+ aliases,
46
+ details,
47
+ name,
48
+ owners,
49
+ }
50
+ }
51
+ }
@@ -1,15 +0,0 @@
1
- // Similar to https://github.com/juharris/dotnet-OptionsProvider/blob/main/src/OptionsProvider/OptionsProvider/OptionsMetadata.cs
2
-
3
- use serde::Deserialize;
4
-
5
- #[derive(Clone, Debug, Deserialize)]
6
- #[allow(unused)]
7
- pub struct OptionsMetadata {
8
- // TODO Add more props.
9
- /// Alternative names for the group of options.
10
- /// This is helpful for using custom short names for the group of options.
11
- pub aliases: Option<Vec<String>>,
12
- /// The creators or maintainers of this group of options.
13
- /// For example, emails separated by ";".
14
- pub owners: Option<String>,
15
- }
File without changes
File without changes