toml-combine 0.5.0__py3-none-any.whl → 0.6.0__py3-none-any.whl

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.
toml_combine/combiner.py CHANGED
@@ -2,9 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  import copy
4
4
  import dataclasses
5
- import itertools
6
5
  from collections.abc import Iterable, Mapping, Sequence
7
- from functools import partial
8
6
  from typing import Any, TypeVar
9
7
 
10
8
  from . import exceptions
@@ -60,48 +58,6 @@ def clean_dimensions_dict(
60
58
  return result
61
59
 
62
60
 
63
- def override_sort_key(
64
- override: Override, dimensions: dict[str, list[str]]
65
- ) -> tuple[int, ...]:
66
- """
67
- We sort overrides before applying them, and they are applied in the order of the
68
- sorted list, each override replacing the common values of the previous overrides.
69
-
70
- override_sort_key defines the sort key for overrides that ensures less specific
71
- overrides come first:
72
- - Overrides with fewer dimensions come first (will be overridden
73
- by more specific ones)
74
- - If two overrides have the same number of dimensions but define different
75
- dimensions, we sort by the definition order of the dimensions.
76
-
77
- Example:
78
- dimensions = {"env": ["dev", "prod"], "region": ["us", "eu"]}
79
-
80
- - Override with {"env": "dev"} comes before override with
81
- {"env": "dev", "region": "us"} (less specific)
82
- - Override with {"env": "dev"} comes before override with {"region": "us"} ("env"
83
- is defined before "region" in the dimensions list)
84
-
85
- Parameters:
86
- -----------
87
- override: An Override object that defines the condition when it applies
88
- (override.when)
89
- dimensions: The dict of all existing dimensions and their values, in order of
90
- definition
91
-
92
- Returns:
93
- --------
94
- A tuple that supports comparisons. Less specific Overrides should return smaller
95
- values and vice versa.
96
- """
97
- result = [len(override.when)]
98
- for i, dimension in enumerate(dimensions):
99
- if dimension in override.when:
100
- result.append(i)
101
-
102
- return tuple(result)
103
-
104
-
105
61
  T = TypeVar("T", dict, list, str, int, float, bool)
106
62
 
107
63
 
@@ -136,21 +92,27 @@ def extract_keys(config: Any) -> Iterable[tuple[str, ...]]:
136
92
  yield tuple()
137
93
 
138
94
 
139
- def extract_conditions_and_keys(
140
- when: dict[str, list[str]], config: dict[str, Any]
141
- ) -> Iterable[tuple[Any, ...]]:
95
+ def are_conditions_compatible(
96
+ a: Mapping[str, list[str]], b: Mapping[str, list[str]], /
97
+ ) -> bool:
142
98
  """
143
- Extract the definitions from an override.
99
+ `a` and `b` are dictionaries representing override conditions (`when`). Return
100
+ `True` if the conditions represented by `a` are compatible. Conditions are
101
+ compatible if one is stricly more specific than the other or if they're mutually
102
+ exclusive.
144
103
  """
145
- when_definitions = []
146
- for key, values in when.items():
147
- when_definitions.append([(key, value) for value in values])
104
+ # Subset
105
+ if set(a) < set(b) or set(b) < set(a):
106
+ return True
107
+
108
+ # Disjoint or overlapping sets
109
+ if set(a) != set(b):
110
+ return False
148
111
 
149
- when_combined_definitions = list(itertools.product(*when_definitions))
150
- config_keys = extract_keys(config)
151
- for config_key in config_keys:
152
- for when_definition in when_combined_definitions:
153
- yield (when_definition, *config_key)
112
+ # Equal sets: it's only compatible if the values are disjoint
113
+ if any(set(a[key]) & set(b[key]) for key in a.keys()):
114
+ return False
115
+ return True
154
116
 
155
117
 
156
118
  def build_config(config: dict[str, Any]) -> Config:
@@ -161,9 +123,6 @@ def build_config(config: dict[str, Any]) -> Config:
161
123
  # Parse template
162
124
  default = config.pop("default", {})
163
125
 
164
- # The rule is: the same exact set of conditions cannot be used twice to define
165
- # the same values (on the same or different overrides)
166
- seen_conditions_and_keys = set()
167
126
  overrides = []
168
127
  for override in config.pop("override", []):
169
128
  try:
@@ -176,22 +135,10 @@ def build_config(config: dict[str, Any]) -> Config:
176
135
  type="override",
177
136
  )
178
137
 
179
- conditions_and_keys = set(
180
- extract_conditions_and_keys(when=when, config=override)
181
- )
182
- if duplicates := (conditions_and_keys & seen_conditions_and_keys):
183
- duplicate_str = ", ".join(sorted(key for *_, key in duplicates))
184
- raise exceptions.DuplicateError(id=when, details=duplicate_str)
185
-
186
- seen_conditions_and_keys |= conditions_and_keys
187
-
188
138
  overrides.append(Override(when=when, config=override))
189
139
 
190
140
  # Sort overrides by increasing specificity
191
- overrides = sorted(
192
- overrides,
193
- key=partial(override_sort_key, dimensions=dimensions),
194
- )
141
+ overrides = sorted(overrides, key=lambda override: len(override.when))
195
142
 
196
143
  return Config(
197
144
  dimensions=dimensions,
@@ -219,11 +166,28 @@ def generate_for_mapping(
219
166
  mapping: Mapping[str, str],
220
167
  ) -> Mapping[str, Any]:
221
168
  result = copy.deepcopy(config.default)
169
+ keys_to_conditions: dict[tuple[str, ...], list[dict[str, list[str]]]] = {}
222
170
  # Apply each matching override
223
171
  for override in config.overrides:
224
172
  # Check if all dimension values in the override match
225
173
 
226
174
  if mapping_matches_override(mapping=mapping, override=override):
175
+ # Check that all applicableoverrides are compatible
176
+ keys = extract_keys(override.config)
177
+
178
+ for key in keys:
179
+ previous_conditions = keys_to_conditions.setdefault(key, [])
180
+
181
+ for previous_condition in previous_conditions:
182
+ if not are_conditions_compatible(previous_condition, override.when):
183
+ raise exceptions.DuplicateError(
184
+ id=override.when,
185
+ key=".".join(key),
186
+ other_override=previous_condition,
187
+ )
188
+
189
+ keys_to_conditions[key].append(override.when)
190
+
227
191
  result = merge_configs(result, override.config)
228
192
 
229
193
  return result
@@ -20,7 +20,7 @@ class TomlEncodeError(TomlCombineError):
20
20
 
21
21
 
22
22
  class DuplicateError(TomlCombineError):
23
- """In override {id}: Overrides with the same dimensions cannot define the same configuration keys: {details}"""
23
+ """In override {id}: Overrides defining the same configuration keys must be included in one another or mutually exclusive.\nKey defined multiple times: {key}\nOther override: {other_override}"""
24
24
 
25
25
 
26
26
  class DimensionNotFound(TomlCombineError):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: toml-combine
3
- Version: 0.5.0
3
+ Version: 0.6.0
4
4
  Summary: A tool for combining complex configurations in TOML format.
5
5
  Author-email: Joachim Jablon <ewjoachim@gmail.com>
6
6
  License-Expression: MIT
@@ -62,17 +62,19 @@ The common configuration to start from, before we start overlaying overrides on
62
62
  ### Overrides
63
63
 
64
64
  Overrides define a set of condition where they apply (`when.<dimension> =
65
- "<value>"`) and the values that are overriden. Overrides are applied in order from less
66
- specific to more specific, each one overriding the values of the previous ones:
67
-
68
- - In case 2 overrides are applicable, the more specific one (the one with more
69
- dimensions defined) has greater priority
70
- - In case 2 overrides use the same number of dimensions, then it depends on how the
71
- dimensions are defined at the top of the file: dimensions defined last have a greater
72
- priority
73
- - In case 2 overrides use the same dimensions, if they define the same configuration
74
- values, an error will be raised. If they define different configuation values, then
75
- the priority is irrelevant.
65
+ "<value>"`) and the values that are overridden when they're applicable.
66
+
67
+ - In case 2 overrides are applicable and define a value for the same key, if one is more
68
+ specific than the other (e.g. env=prod,region=us is more specific than env=prod) then
69
+ its values will have precedence.
70
+ - If they are mutually exclusive, (env=prod vs env=staging) precedence is irrelevant.
71
+ - If you try to generate the configuration and 2 applicable overrides define a value for
72
+ the same key, an error will be raised (e.g. env=staging and region=eu). In that case,
73
+ you should add dimensions to either override to make them mutually exclusive or make
74
+ one more specific than the other.
75
+
76
+ Note that it's not a problem if incompatible overrides exist in your configuration, as
77
+ long as they are not both applicable in the same call.
76
78
 
77
79
  > [!Note]
78
80
  > Defining a list as the value of one or more conditions in an override
@@ -80,14 +82,11 @@ specific to more specific, each one overriding the values of the previous ones:
80
82
 
81
83
  ### The configuration itself
82
84
 
83
- Under the layer of `dimensions/default/override/mapping` system, what you actually define
84
- in the configuration is completely up to you. That said, only nested
85
+ Under the layer of `dimensions/default/override/mapping` system, what you actually
86
+ define in the configuration is completely up to you. That said, only nested
85
87
  "dictionnaries"/"objects"/"tables"/"mapping" (those are all the same things in
86
- Python/JS/Toml lingo) will be merged between the default and the overrides, while
87
- arrays will just replace one another. See `Arrays` below.
88
-
89
- In the generated configuration, the dimensions of the output will appear in the generated
90
- object as an object under the `dimensions` key.
88
+ Python/JS/Toml lingo) will be merged between the default and the applicable overrides,
89
+ while arrays will just replace one another. See `Arrays` below.
91
90
 
92
91
  ### Arrays
93
92
 
@@ -191,8 +190,9 @@ container.image_name = "my-image-backend"
191
190
  container.port = 8080
192
191
 
193
192
  [[override]]
194
- name = "service-dev"
193
+ when.service = "backend"
195
194
  when.environment = "dev"
195
+ name = "service-dev"
196
196
  container.env.DEBUG = true
197
197
 
198
198
  [[override]]
@@ -1,11 +1,11 @@
1
1
  toml_combine/__init__.py,sha256=TDkOwwEM-nS6hOh79u9Qae6g2Q6VfANpPpnKGfSgu80,84
2
2
  toml_combine/__main__.py,sha256=hmF8N8xX6UEApzbKTVZ-4E1HU5-rjgUkdXNLO-mF6vo,100
3
3
  toml_combine/cli.py,sha256=hG03eDKz7xU-ydJIa1kDuu6WlFzNS3GTMJ6zals9M9c,2843
4
- toml_combine/combiner.py,sha256=BCsZOm7Cr2_JxttsKzjJH_HYQkD2XPjylXKlkxvi1EY,6974
5
- toml_combine/exceptions.py,sha256=Qg_gGIdXcwTmWDlIfJOidXkViBOVSPdLx0WOELxFPp0,1026
4
+ toml_combine/combiner.py,sha256=nwq3q06UhXZkM2Nch_gEnn7K8WUlKbbYxFk1myH63CE,5649
5
+ toml_combine/exceptions.py,sha256=2b-EkmSoe6bbuE7txDVjEDuix_9bfLQrapkNhy8i-lU,1109
6
6
  toml_combine/lib.py,sha256=jh6OG57JefpGa-WE-mLSIK6KjyJ0-1yGBynr_kiVTww,1634
7
7
  toml_combine/toml.py,sha256=iBV8xj0qWcvGp2AZaML8FCT3i2X9DL7iA6jd-wcP5Bc,814
8
- toml_combine-0.5.0.dist-info/METADATA,sha256=XRrnb4YkB_wwoGdoZBDQBGoXi4qY9FmjBhKGQVAJjc4,7585
9
- toml_combine-0.5.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
10
- toml_combine-0.5.0.dist-info/entry_points.txt,sha256=dXUQNom54uZt_7ylEG81iNYMamYpaFo9-ItcZJU6Uzc,58
11
- toml_combine-0.5.0.dist-info/RECORD,,
8
+ toml_combine-0.6.0.dist-info/METADATA,sha256=1TbVtui8W4B4zumo-rCpPnnuxx83GD5Xkyk-rRqCE5E,7625
9
+ toml_combine-0.6.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
10
+ toml_combine-0.6.0.dist-info/entry_points.txt,sha256=dXUQNom54uZt_7ylEG81iNYMamYpaFo9-ItcZJU6Uzc,58
11
+ toml_combine-0.6.0.dist-info/RECORD,,