envkeep 0.1.1__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.
envkeep/interpolate.py ADDED
@@ -0,0 +1,142 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from collections.abc import Iterator, Mapping
5
+ from dataclasses import dataclass
6
+ from typing import Literal
7
+
8
+ _NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
9
+
10
+ Kind = Literal["plain", "default", "required", "alternate"]
11
+
12
+ # operator -> (kind, whether an empty value counts as unset)
13
+ _OPERATORS: dict[str, tuple[Kind, bool]] = {
14
+ ":-": ("default", True),
15
+ "-": ("default", False),
16
+ ":?": ("required", True),
17
+ "?": ("required", False),
18
+ ":+": ("alternate", True),
19
+ "+": ("alternate", False),
20
+ }
21
+
22
+ _MAX_DEPTH = 32 # deeper nesting is treated as unresolvable
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class Reference:
27
+ """One variable reference found in a string."""
28
+
29
+ name: str
30
+ kind: Kind
31
+ treat_empty_as_unset: bool = False
32
+ body: str = "" # the text after the operator; may contain nested references
33
+
34
+
35
+ def _closing_brace(text: str, start: int) -> int:
36
+ """Index of the "}" that closes a "${" (nested "${...}" allowed), or -1."""
37
+ depth = 1
38
+ index = start
39
+ while index < len(text):
40
+ if text.startswith("${", index):
41
+ depth += 1
42
+ index += 2
43
+ continue
44
+ if text[index] == "}":
45
+ depth -= 1
46
+ if depth == 0:
47
+ return index
48
+ index += 1
49
+ return -1
50
+
51
+
52
+ def _scan(text: str) -> Iterator[tuple[int, int, Reference]]:
53
+ """Yield (start, end, reference) for each top-level reference in the text.
54
+
55
+ "$$" is an escaped literal dollar sign and is skipped. Malformed syntax is ignored.
56
+ """
57
+ index = 0
58
+ while index < len(text):
59
+ if text[index] != "$":
60
+ index += 1
61
+ continue
62
+
63
+ following = text[index + 1 : index + 2]
64
+ if following == "$": # escaped dollar sign
65
+ index += 2
66
+ elif following == "{":
67
+ match = _NAME.match(text, index + 2)
68
+ if not match:
69
+ index += 2
70
+ continue
71
+ name, pos = match.group(), match.end()
72
+ if text[pos : pos + 1] == "}":
73
+ yield index, pos + 1, Reference(name, "plain")
74
+ index = pos + 1
75
+ continue
76
+ operator = text[pos : pos + 2]
77
+ if operator not in _OPERATORS:
78
+ operator = text[pos : pos + 1]
79
+ if operator not in _OPERATORS:
80
+ index = pos # malformed: skip it
81
+ continue
82
+ body_start = pos + len(operator)
83
+ end = _closing_brace(text, body_start)
84
+ if end == -1:
85
+ index = pos # unterminated: skip it
86
+ continue
87
+ kind, treat_empty = _OPERATORS[operator]
88
+ yield index, end + 1, Reference(name, kind, treat_empty, text[body_start:end])
89
+ index = end + 1
90
+ else:
91
+ match = _NAME.match(text, index + 1)
92
+ if match:
93
+ yield index, match.end(), Reference(match.group(), "plain")
94
+ index = match.end()
95
+ else:
96
+ index += 1
97
+
98
+
99
+ def find_references(text: str) -> list[Reference]:
100
+ """Find the variables a compose string refers to, at the top level only.
101
+
102
+ A reference nested inside another one ("${A:-${B}}") is not returned here: it stays
103
+ in the outer reference's body, because whether it matters depends on the outer
104
+ variable's value. Run find_references on the body to get it.
105
+ """
106
+ return [reference for _, _, reference in _scan(text)]
107
+
108
+
109
+ def _expand_reference(ref: Reference, values: Mapping[str, str], depth: int) -> str | None:
110
+ value = values.get(ref.name)
111
+ unset = value is None or (ref.treat_empty_as_unset and value == "")
112
+
113
+ if ref.kind == "plain":
114
+ return value # None when the variable is undefined
115
+ if ref.kind == "required":
116
+ return None if unset else value
117
+ if ref.kind == "default":
118
+ return expand(ref.body, values, depth + 1) if unset else value
119
+ # alternate: the body replaces a set value, and an unset one becomes empty
120
+ return "" if unset else expand(ref.body, values, depth + 1)
121
+
122
+
123
+ def expand(text: str, values: Mapping[str, str], _depth: int = 0) -> str | None:
124
+ """Expand the variables in text the way Compose would, or None if it can't be done.
125
+
126
+ None means a variable the text needs is undefined (or blank where ":?" demands a
127
+ value), so the real result isn't known. "$$" becomes a literal "$".
128
+ """
129
+ if _depth > _MAX_DEPTH:
130
+ return None
131
+
132
+ parts: list[str] = []
133
+ last = 0
134
+ for start, end, ref in _scan(text):
135
+ parts.append(text[last:start].replace("$$", "$"))
136
+ piece = _expand_reference(ref, values, _depth)
137
+ if piece is None:
138
+ return None
139
+ parts.append(piece)
140
+ last = end
141
+ parts.append(text[last:].replace("$$", "$"))
142
+ return "".join(parts)
envkeep/models.py ADDED
@@ -0,0 +1,15 @@
1
+ from dataclasses import dataclass, field
2
+
3
+
4
+ @dataclass
5
+ class CheckResult:
6
+ """The outcome of comparing an env file against an example file."""
7
+
8
+ missing: list[str] = field(default_factory=list) # in example, not in env
9
+ extra: list[str] = field(default_factory=list) # in env, not in example
10
+ empty: list[str] = field(default_factory=list) # in both, but env value is ""
11
+ invalid: dict[str, str] = field(default_factory=dict) # name -> problem (never the value)
12
+
13
+ @property
14
+ def ok(self) -> bool:
15
+ return not (self.missing or self.empty or self.invalid)
envkeep/output.py ADDED
@@ -0,0 +1,179 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ from rich.console import Console
6
+ from rich.markup import escape
7
+ from rich.table import Table
8
+
9
+ from envkeep.compose import ComposeResult
10
+ from envkeep.differ import DiffResult
11
+ from envkeep.models import CheckResult
12
+
13
+ console = Console()
14
+ err_console = Console(stderr=True)
15
+
16
+ _STYLES = {"missing": "red", "empty": "yellow", "invalid": "magenta", "extra": "blue"}
17
+
18
+
19
+ def print_check_result(result: CheckResult, env: Path, source: Path) -> None:
20
+ """Print a check result as a colored table plus a one-line summary."""
21
+ env_label = escape(str(env))
22
+ source_label = escape(str(source))
23
+
24
+ rows = (
25
+ [("missing", key, "") for key in result.missing]
26
+ + [("empty", key, "") for key in result.empty]
27
+ + [("invalid", key, problem) for key, problem in result.invalid.items()]
28
+ + [("extra", key, "") for key in result.extra]
29
+ )
30
+
31
+ if not rows:
32
+ console.print(f"[green]OK[/green] {env_label} matches {source_label}")
33
+ return
34
+
35
+ table = Table(title=f"{env_label} vs {source_label}")
36
+ table.add_column("Status")
37
+ table.add_column("Variable")
38
+ if result.invalid:
39
+ table.add_column("Problem")
40
+ for status, key, problem in rows:
41
+ style = _STYLES[status]
42
+ cells = [f"[{style}]{status}[/{style}]", escape(key)]
43
+ if result.invalid:
44
+ cells.append(escape(problem))
45
+ table.add_row(*cells)
46
+ console.print(table)
47
+
48
+ summary = f"{len(result.missing)} missing, {len(result.empty)} empty, "
49
+ if result.invalid:
50
+ summary += f"{len(result.invalid)} invalid, "
51
+ summary += f"{len(result.extra)} extra"
52
+
53
+ if result.ok:
54
+ console.print(f"[green]OK[/green] {summary} (extra variables are only warnings)")
55
+ else:
56
+ console.print(f"[red]FAILED[/red] {summary}")
57
+
58
+
59
+ def print_error(message: str) -> None:
60
+ """Print an error to stderr, so it doesn't mix with normal output."""
61
+ err_console.print(f"[red]error:[/red] {escape(message)}")
62
+
63
+
64
+ def print_success(message: str) -> None:
65
+ """Print a green OK line."""
66
+ console.print(f"[green]OK[/green] {escape(message)}")
67
+
68
+
69
+ def print_sync_result(added: list[str], env: Path, dry_run: bool) -> None:
70
+ """Print which variables were (or would be) added to the env file."""
71
+ env_label = escape(str(env))
72
+ if not added:
73
+ console.print(f"[green]OK[/green] {env_label} already has every variable")
74
+ return
75
+
76
+ verb = "Would add" if dry_run else "Added"
77
+ console.print(f"[green]{verb}[/green] {len(added)} variable(s) to {env_label}:")
78
+ for key in added:
79
+ console.print(f" + {escape(key)}")
80
+
81
+
82
+ def _show(value: str | None) -> str:
83
+ """Render one value cell. Escaped, because values come from the user's files."""
84
+ if value is None:
85
+ return "[dim]-[/dim]"
86
+ if value == "":
87
+ return "[dim](empty)[/dim]"
88
+ return escape(value)
89
+
90
+
91
+ def print_diff_result(
92
+ result: DiffResult,
93
+ first: Path,
94
+ second: Path,
95
+ first_values: dict[str, str],
96
+ second_values: dict[str, str],
97
+ *,
98
+ show_values: bool = False,
99
+ keys_only: bool = False,
100
+ ) -> None:
101
+ """Print the differences between two env files. Values are hidden unless asked for."""
102
+ first_label = escape(str(first))
103
+ second_label = escape(str(second))
104
+
105
+ if result.identical:
106
+ what = "have the same variables" if keys_only else "are identical"
107
+ console.print(f"[green]OK[/green] {first_label} and {second_label} {what}")
108
+ return
109
+
110
+ rows = (
111
+ [(key, "only in A", "red") for key in result.only_in_a]
112
+ + [(key, "only in B", "blue") for key in result.only_in_b]
113
+ + [(key, "changed", "yellow") for key in result.changed]
114
+ )
115
+
116
+ table = Table(title=f"A: {first_label}\nB: {second_label}")
117
+ table.add_column("Variable")
118
+ table.add_column("Status")
119
+ if show_values:
120
+ table.add_column("A value")
121
+ table.add_column("B value")
122
+
123
+ for key, status, style in sorted(rows):
124
+ cells = [escape(key), f"[{style}]{status}[/{style}]"]
125
+ if show_values:
126
+ cells.append(_show(first_values.get(key)))
127
+ cells.append(_show(second_values.get(key)))
128
+ table.add_row(*cells)
129
+ console.print(table)
130
+
131
+ console.print(
132
+ f"[yellow]DIFFERENT[/yellow] {len(result.only_in_a)} only in A, "
133
+ f"{len(result.only_in_b)} only in B, {len(result.changed)} changed"
134
+ )
135
+
136
+
137
+ def _where(locations: list[str], limit: int = 3) -> str:
138
+ """Join the first few locations, escaped, and say how many were left out."""
139
+ shown = ", ".join(escape(location) for location in locations[:limit])
140
+ hidden = len(locations) - limit
141
+ return f"{shown} (+{hidden} more)" if hidden > 0 else shown
142
+
143
+
144
+ def print_compose_result(result: ComposeResult, compose_file: Path) -> None:
145
+ """Print undefined variables and missing env_file entries. Never prints values."""
146
+ label = escape(str(compose_file))
147
+ note = f" ({len(result.optional)} with defaults)" if result.optional else ""
148
+
149
+ rows = (
150
+ [("undefined", name, _where(locs), "red") for name, locs in result.undefined.items()]
151
+ + [("empty", name, _where(locs), "yellow") for name, locs in result.empty.items()]
152
+ + [
153
+ (
154
+ "missing file",
155
+ ref.path,
156
+ escape(f"services.{ref.service}.env_file"),
157
+ "red",
158
+ )
159
+ for ref in result.missing_env_files
160
+ ]
161
+ )
162
+
163
+ if not rows:
164
+ console.print(f"[green]OK[/green] {label}: nothing undefined{note}")
165
+ return
166
+
167
+ table = Table(title=label)
168
+ table.add_column("Status")
169
+ table.add_column("Name")
170
+ table.add_column("Where")
171
+ for status, name, where, style in rows:
172
+ table.add_row(f"[{style}]{status}[/{style}]", escape(name), where)
173
+ console.print(table)
174
+
175
+ console.print(
176
+ f"[red]FAILED[/red] {len(result.undefined)} undefined, "
177
+ f"{len(result.empty)} empty, "
178
+ f"{len(result.missing_env_files)} missing env_file{note}"
179
+ )
envkeep/parser.py ADDED
@@ -0,0 +1,127 @@
1
+ import codecs
2
+ import re
3
+ from collections.abc import Iterator
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import Literal
7
+
8
+
9
+ class EnvSyntaxError(ValueError):
10
+ """Raised when an env file can't be read safely (e.g. an unterminated quote)."""
11
+
12
+ def __init__(self, message: str, line_number: int) -> None:
13
+ super().__init__(f"line {line_number}: {message}")
14
+ self.line_number = line_number
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Entry:
19
+ """One logical item in an env file."""
20
+
21
+ kind: Literal["raw", "ignored", "assignment"]
22
+ line: str = "" # raw: the original line (blank lines and real comments)
23
+ prefix: str = "" # assignment: "export " or ""
24
+ key: str = "" # assignment
25
+ value: str = "" # assignment: the value, without quotes or inline comment
26
+
27
+
28
+ _DOUBLE_QUOTE_ESCAPES = re.compile(r"\\[\\'\"abfnrtv]")
29
+ _SINGLE_QUOTE_ESCAPES = re.compile(r"\\[\\']")
30
+
31
+
32
+ def _decode_escapes(value: str, quote: str) -> str:
33
+ """Decode backslash escapes in a quoted value, following python-dotenv's rules."""
34
+ pattern = _DOUBLE_QUOTE_ESCAPES if quote == '"' else _SINGLE_QUOTE_ESCAPES
35
+ return pattern.sub(lambda m: codecs.decode(m.group(0), "unicode-escape"), value)
36
+
37
+
38
+ def _find_closing_quote(chunk: str, quote: str) -> int:
39
+ """Index of the first unescaped closing quote in chunk, or -1."""
40
+ escaped = False
41
+ for index, char in enumerate(chunk):
42
+ if escaped:
43
+ escaped = False
44
+ elif char == "\\":
45
+ escaped = True
46
+ elif char == quote:
47
+ return index
48
+ return -1
49
+
50
+
51
+ def _read_quoted(lines: list[str], start: int, first_chunk: str, key: str) -> tuple[str, int]:
52
+ """Read a quoted value that may continue over several lines.
53
+
54
+ Returns (value, index of the next unread line).
55
+ """
56
+ quote = first_chunk[0]
57
+ chunk = first_chunk[1:]
58
+ collected: list[str] = []
59
+ index = start
60
+ while True:
61
+ end = _find_closing_quote(chunk, quote)
62
+ if end != -1:
63
+ collected.append(chunk[:end]) # anything after the closing quote is ignored
64
+ return _decode_escapes("\n".join(collected), quote), index + 1
65
+ collected.append(chunk)
66
+ index += 1
67
+ if index >= len(lines):
68
+ raise EnvSyntaxError(f"unterminated quoted value for {key}", start + 1)
69
+ chunk = lines[index]
70
+
71
+
72
+ def scan(text: str) -> Iterator[Entry]:
73
+ """Split env file text into logical entries.
74
+
75
+ A quoted value that spans several lines is ONE assignment, so the lines inside
76
+ it are never mistaken for comments or other variables.
77
+ """
78
+ lines = text.splitlines()
79
+ index = 0
80
+ while index < len(lines):
81
+ raw = lines[index]
82
+ stripped = raw.strip()
83
+
84
+ if not stripped or stripped.startswith("#"):
85
+ yield Entry("raw", line=raw)
86
+ index += 1
87
+ continue
88
+
89
+ body = raw.lstrip()
90
+ prefix = ""
91
+ if body.startswith("export "):
92
+ prefix = "export "
93
+ body = body[len(prefix) :]
94
+
95
+ if "=" not in body:
96
+ yield Entry("ignored")
97
+ index += 1
98
+ continue
99
+
100
+ key, _, rest = body.partition("=") # splits on the FIRST "=" only
101
+ key = key.strip()
102
+ rest = rest.lstrip()
103
+
104
+ if rest[:1] in ('"', "'"):
105
+ value, index = _read_quoted(lines, index, rest, key)
106
+ else:
107
+ value = rest.split(" #", 1)[0].strip() # drop inline comment
108
+ index += 1
109
+
110
+ yield Entry("assignment", prefix=prefix, key=key, value=value)
111
+
112
+
113
+ def parse_env_text(text: str) -> dict[str, str]:
114
+ """Parse env file text into {KEY: value}."""
115
+ return {entry.key: entry.value for entry in scan(text) if entry.kind == "assignment"}
116
+
117
+
118
+ def parse_env_file(path: Path) -> dict[str, str]:
119
+ """Read a .env file and return {KEY: value}."""
120
+ return parse_env_text(path.read_text(encoding="utf-8"))
121
+
122
+
123
+ if __name__ == "__main__":
124
+ import sys
125
+
126
+ for key, value in parse_env_file(Path(sys.argv[1])).items():
127
+ print(f"{key!r} -> {value!r}")
envkeep/schema.py ADDED
@@ -0,0 +1,125 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ from envkeep.checks import TYPES, check_type
8
+ from envkeep.yamlutil import YamlSyntaxError, load_yaml
9
+
10
+ _RULE_KEYS = {"type", "required", "default"}
11
+
12
+
13
+ class SchemaError(ValueError):
14
+ """Raised when a schema file is unreadable or invalid. Carries every problem found."""
15
+
16
+ def __init__(self, problems: list[str]) -> None:
17
+ super().__init__("; ".join(problems))
18
+ self.problems = problems
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class VarRule:
23
+ type: str = "str"
24
+ required: bool = True
25
+ default: str | None = None # always stored as text, like an env value
26
+
27
+
28
+ def _parse_rule(name: str, spec: Any, problems: list[str]) -> VarRule | None:
29
+ """Turn one variable's YAML into a VarRule, or record what is wrong with it."""
30
+ if spec is None:
31
+ return VarRule() # a bare "NAME:" means a required string
32
+ if not isinstance(spec, dict):
33
+ problems.append(f"{name}: expected rules (type/required/default), not a plain value")
34
+ return None
35
+
36
+ unknown = sorted(str(key) for key in spec if key not in _RULE_KEYS)
37
+ if unknown:
38
+ problems.append(
39
+ f"{name}: unknown key(s) {', '.join(unknown)} (allowed: default, required, type)"
40
+ )
41
+ return None
42
+
43
+ var_type = spec.get("type", "str")
44
+ if var_type not in TYPES:
45
+ problems.append(f"{name}: unknown type {var_type!r} (choose one of: {', '.join(TYPES)})")
46
+ return None
47
+
48
+ required = spec.get("required")
49
+ if required is not None and not isinstance(required, bool):
50
+ problems.append(f"{name}: 'required' must be true or false")
51
+ return None
52
+
53
+ raw_default = spec.get("default")
54
+ default: str | None = None
55
+ if raw_default is not None:
56
+ if isinstance(raw_default, bool): # check bool first: bool is a subclass of int
57
+ default = "true" if raw_default else "false"
58
+ elif isinstance(raw_default, (int, float, str)):
59
+ default = str(raw_default)
60
+ else:
61
+ problems.append(f"{name}: 'default' must be a single plain value")
62
+ return None
63
+ message = check_type(var_type, default)
64
+ if message is not None:
65
+ problems.append(f"{name}: the default is not a valid {var_type} ({message})")
66
+ return None
67
+
68
+ if required is True and default is not None:
69
+ problems.append(f"{name}: 'required: true' can't be combined with a default")
70
+ return None
71
+
72
+ return VarRule(
73
+ type=var_type,
74
+ required=(default is None) if required is None else required,
75
+ default=default,
76
+ )
77
+
78
+
79
+ def load_schema_text(text: str) -> dict[str, VarRule]:
80
+ """Parse schema text into {variable name: rule}. Raises SchemaError if it's invalid."""
81
+ try:
82
+ data = load_yaml(text)
83
+ except YamlSyntaxError as exc:
84
+ raise SchemaError([str(exc)]) from None
85
+
86
+ if not isinstance(data, dict):
87
+ raise SchemaError(["expected a mapping with a top-level 'variables' key"])
88
+ unknown = sorted(str(key) for key in data if key != "variables")
89
+ if unknown:
90
+ raise SchemaError(
91
+ [f"unknown top-level key(s): {', '.join(unknown)} (only 'variables' is allowed)"]
92
+ )
93
+
94
+ variables = data.get("variables")
95
+ if not isinstance(variables, dict) or not variables:
96
+ raise SchemaError(["'variables' must be a non-empty mapping of NAME to rules"])
97
+
98
+ problems: list[str] = []
99
+ rules: dict[str, VarRule] = {}
100
+ for name, spec in variables.items():
101
+ if not isinstance(name, str):
102
+ problems.append(
103
+ f'variable name {name!r} was read as a non-text value; put it in quotes, e.g. "NO":'
104
+ )
105
+ continue
106
+ rule = _parse_rule(name, spec, problems)
107
+ if rule is not None:
108
+ rules[name] = rule
109
+
110
+ if problems:
111
+ raise SchemaError(problems)
112
+ return rules
113
+
114
+
115
+ def load_schema(path: Path) -> dict[str, VarRule]:
116
+ """Read and parse a schema file."""
117
+ try:
118
+ text = path.read_text(encoding="utf-8")
119
+ except UnicodeDecodeError as exc:
120
+ raise SchemaError(["the file is not valid UTF-8"]) from exc
121
+ except OSError as exc:
122
+ # Permission denied, the path is a directory, a disk error, and so on.
123
+ reason = exc.strerror or "unknown error"
124
+ raise SchemaError([f"could not read the file: {reason}"]) from exc
125
+ return load_schema_text(text)
envkeep/syncer.py ADDED
@@ -0,0 +1,45 @@
1
+ HEADER = "# Added by envkeep sync"
2
+
3
+
4
+ _ESCAPES = str.maketrans({"\\": "\\\\", '"': '\\"', "\n": "\\n", "\r": "\\r"})
5
+
6
+
7
+ def _needs_quotes(value: str) -> bool:
8
+ """Whitespace, '#', or a quote character would be misread in an unquoted value."""
9
+ return any(char.isspace() or char in "#'\"" for char in value)
10
+
11
+
12
+ def _format_value(value: str) -> str:
13
+ """Serialize a value so both envkeep and python-dotenv read back the same string."""
14
+ if not _needs_quotes(value):
15
+ return value
16
+ return '"' + value.translate(_ESCAPES) + '"'
17
+
18
+
19
+ def _detect_newline(text: str) -> str:
20
+ """Return the line ending the text already uses (the first one found), default LF."""
21
+ index = text.find("\n")
22
+ if index > 0 and text[index - 1] == "\r":
23
+ return "\r\n"
24
+ return "\n"
25
+
26
+
27
+ def sync_env(example: dict[str, str], env_text: str, env: dict[str, str]) -> tuple[str, list[str]]:
28
+ """Append variables that exist in the example but not in the env file.
29
+
30
+ Returns (new_text, added_keys). Existing content is never modified:
31
+ the new text always starts with the old text.
32
+ """
33
+
34
+ added = [key for key in example if key not in env] # keeps the example's order
35
+ if not added:
36
+ return env_text, added
37
+
38
+ newline = _detect_newline(env_text)
39
+ lines = [HEADER] + [f"{key}={_format_value(example[key])}" for key in added]
40
+
41
+ separator = ""
42
+ if env_text:
43
+ separator = newline if env_text.endswith("\n") else newline * 2
44
+
45
+ return env_text + separator + newline.join(lines) + newline, added
envkeep/validate.py ADDED
@@ -0,0 +1,39 @@
1
+ from envkeep.checks import check_type
2
+ from envkeep.models import CheckResult
3
+ from envkeep.schema import VarRule
4
+
5
+
6
+ def validate_env(rules: dict[str, VarRule], env: dict[str, str]) -> CheckResult:
7
+ """Check parsed env values against schema rules.
8
+
9
+ - a required variable that is absent is "missing"; if it is blank, "empty"
10
+ - an optional variable (required: false, or one with a default) may be absent or blank
11
+ - any non-blank value must pass its type check, otherwise it is "invalid"
12
+ - variables the schema doesn't mention are reported as "extra" (a warning)
13
+ """
14
+ missing: list[str] = []
15
+ empty: list[str] = []
16
+ invalid: dict[str, str] = {}
17
+
18
+ for name, rule in rules.items():
19
+ if name not in env:
20
+ if rule.required:
21
+ missing.append(name)
22
+ continue
23
+
24
+ value = env[name]
25
+ if value == "":
26
+ if rule.required:
27
+ empty.append(name)
28
+ continue
29
+
30
+ problem = check_type(rule.type, value)
31
+ if problem is not None:
32
+ invalid[name] = problem
33
+
34
+ return CheckResult(
35
+ missing=sorted(missing),
36
+ extra=sorted(set(env) - set(rules)),
37
+ empty=sorted(empty),
38
+ invalid=dict(sorted(invalid.items())),
39
+ )