44import sys
55from dataclasses import dataclass , field , replace as dataclass_replace
66from pathlib import Path
7- from typing import Optional
7+ from typing import Any , Optional , cast
88
99# Config file is searched in this order within the scan root.
1010CONFIG_FILENAMES = (".env-auditorrc" , "env-auditor.toml" , "pyproject.toml" )
@@ -48,10 +48,6 @@ class EnvAuditorConfig:
4848 """Keys that MUST be documented; always flagged if missing."""
4949
5050
51- # Keep old name as alias so existing imports don't break during transition
52- EnvCheckConfig = EnvAuditorConfig
53-
54-
5551def load_config (scan_root : Path ) -> EnvAuditorConfig :
5652 """Search for and parse a config file within *scan_root*.
5753
@@ -70,30 +66,15 @@ def load_config(scan_root: Path) -> EnvAuditorConfig:
7066 if not candidate .is_file ():
7167 continue
7268
73- # Guard: size limit — prevents memory exhaustion
74- try :
75- size = candidate .stat ().st_size
76- except OSError :
77- continue
78-
79- if size > CONFIG_FILE_SIZE_LIMIT :
80- print (
81- f"env-auditor: warning: config file { candidate } exceeds "
82- f"{ CONFIG_FILE_SIZE_LIMIT // 1024 } KB size limit, skipping" ,
83- file = sys .stderr ,
84- )
85- continue
86-
87- try :
88- raw = _parse_toml_file (candidate , filename == "pyproject.toml" )
89- except (OSError , ValueError , KeyError , TypeError ) as exc :
90- print (
91- f"env-auditor: warning: could not parse config { candidate } : { exc } " ,
92- file = sys .stderr ,
93- )
69+ raw , hard_error = _read_config_raw (candidate )
70+ if hard_error :
71+ # A candidate that exists but is broken (unreadable, unparseable)
72+ # stops the search here rather than silently falling through to
73+ # a different config file the user may not know exists.
9474 return EnvAuditorConfig ()
95-
9675 if raw is None :
76+ # File parsed fine but has no env-auditor section for us (e.g. a
77+ # pyproject.toml without [tool.env-auditor]), keep looking.
9778 continue
9879
9980 return _dict_to_config (raw , candidate )
@@ -105,7 +86,7 @@ def load_config_from_file(path: Path) -> EnvAuditorConfig:
10586 """Load config from an explicitly specified file path.
10687
10788 Unlike :func:`load_config`, which auto-discovers config files by name
108- within a directory, this function reads * exactly* the file given —
89+ within a directory, this function reads exactly the file given,
10990 regardless of its name. Used by the ``--config FILE`` CLI flag.
11091
11192 Args:
@@ -114,22 +95,53 @@ def load_config_from_file(path: Path) -> EnvAuditorConfig:
11495 Returns:
11596 Populated EnvAuditorConfig (defaults if the file cannot be parsed).
11697 """
98+ raw , _hard_error = _read_config_raw (path )
99+ if raw is None :
100+ print (
101+ f"env-auditor: warning: no [tool.env-auditor] section found in "
102+ f"{ path } , using defaults" ,
103+ file = sys .stderr ,
104+ )
105+ return EnvAuditorConfig ()
106+
107+ return _dict_to_config (raw , path )
108+
109+
110+ def _read_config_raw (path : Path ) -> tuple [Optional [dict [str , Any ]], bool ]:
111+ """Validate size, parse path as TOML, and return its env-auditor section.
112+
113+ Shared by :func:`load_config` (auto-discovery) and
114+ :func:`load_config_from_file` (explicit ``--config``) to avoid duplicating
115+ the size-limit check and parse-error handling in both places.
116+
117+ Args:
118+ path: Path to a config file that is known to exist.
119+
120+ Returns:
121+ ``(raw, hard_error)`` where:
122+ - ``raw`` is the parsed env-auditor section dict, or ``None`` if the
123+ file parsed cleanly but has no such section (e.g. pyproject.toml
124+ without ``[tool.env-auditor]``).
125+ - ``hard_error`` is ``True`` if the file could not be stat'd, exceeded
126+ the size limit, or failed to parse. Callers should not treat a
127+ hard error the same as "no section found".
128+ """
117129 try :
118130 size = path .stat ().st_size
119131 except OSError as exc :
120132 print (
121133 f"env-auditor: warning: cannot stat config file { path } : { exc } " ,
122134 file = sys .stderr ,
123135 )
124- return EnvAuditorConfig ()
136+ return None , True
125137
126138 if size > CONFIG_FILE_SIZE_LIMIT :
127139 print (
128140 f"env-auditor: warning: config file { path } exceeds "
129141 f"{ CONFIG_FILE_SIZE_LIMIT // 1024 } KB size limit, using defaults" ,
130142 file = sys .stderr ,
131143 )
132- return EnvAuditorConfig ()
144+ return None , True
133145
134146 try :
135147 raw = _parse_toml_file (path , is_pyproject = (path .name == "pyproject.toml" ))
@@ -138,20 +150,12 @@ def load_config_from_file(path: Path) -> EnvAuditorConfig:
138150 f"env-auditor: warning: could not parse config { path } : { exc } " ,
139151 file = sys .stderr ,
140152 )
141- return EnvAuditorConfig ()
153+ return None , True
142154
143- if raw is None :
144- print (
145- f"env-auditor: warning: no [tool.env-auditor] section found in "
146- f"{ path } , using defaults" ,
147- file = sys .stderr ,
148- )
149- return EnvAuditorConfig ()
150-
151- return _dict_to_config (raw , path )
155+ return raw , False
152156
153157
154- def _parse_toml_file (path : Path , is_pyproject : bool ) -> Optional [dict ]:
158+ def _parse_toml_file (path : Path , is_pyproject : bool ) -> Optional [dict [ str , Any ] ]:
155159 """Parse *path* as TOML and return the env-auditor section, or None.
156160
157161 Uses stdlib ``tomllib`` (Python 3.11+) with ``tomli`` fallback,
@@ -179,11 +183,11 @@ def _parse_toml_file(path: Path, is_pyproject: bool) -> Optional[dict]:
179183
180184 if is_pyproject :
181185 tool = data .get ("tool" , {})
182- return tool .get ("env-auditor" ) # None if not present
186+ return cast ( Optional [ dict [ str , Any ]], tool .get ("env-auditor" ) ) # None if not present
183187 return data or None
184188
185189
186- def _minimal_toml_parse (path : Path ) -> dict :
190+ def _minimal_toml_parse (path : Path ) -> dict [ str , Any ] :
187191 """Hand-rolled TOML subset parser for .env-auditorrc on Python 3.10.
188192
189193 Handles: string, bool, list of strings, comments, blank lines, and
@@ -200,8 +204,8 @@ def _minimal_toml_parse(path: Path) -> dict:
200204 Returns:
201205 Nested dict of parsed key/value pairs.
202206 """
203- result : dict = {}
204- current_node : dict = result # pointer into result at the current section
207+ result : dict [ str , Any ] = {}
208+ current_node : dict [ str , Any ] = result # pointer into result at the current section
205209 text = path .read_text (encoding = "utf-8" , errors = "replace" )
206210
207211 for raw_line in text .splitlines ():
@@ -244,7 +248,7 @@ def _minimal_toml_parse(path: Path) -> dict:
244248 return result
245249
246250
247- def _dict_to_config (raw : dict , source : Path ) -> EnvAuditorConfig :
251+ def _dict_to_config (raw : dict [ str , Any ] , source : Path ) -> EnvAuditorConfig :
248252 """Convert a raw dict from TOML into an EnvAuditorConfig.
249253
250254 Unknown keys are warned about but ignored. Type coercion is strict —
@@ -262,7 +266,7 @@ def _dict_to_config(raw: dict, source: Path) -> EnvAuditorConfig:
262266 raw = dict (raw )
263267 raw ["output_format" ] = raw .pop ("format" )
264268
265- known_keys = set (EnvAuditorConfig .__dataclass_fields__ .keys ()) # type: ignore[attr-defined]
269+ known_keys = set (EnvAuditorConfig .__dataclass_fields__ .keys ())
266270 cfg = EnvAuditorConfig ()
267271
268272 for key , value in raw .items ():
@@ -274,7 +278,7 @@ def _dict_to_config(raw: dict, source: Path) -> EnvAuditorConfig:
274278 continue
275279
276280 field_type = str (
277- EnvAuditorConfig .__dataclass_fields__ [key ].type # type: ignore[attr-defined]
281+ EnvAuditorConfig .__dataclass_fields__ [key ].type
278282 )
279283
280284 try :
@@ -339,7 +343,7 @@ def merge_cli_into_config(
339343 Returns:
340344 New EnvAuditorConfig with CLI overrides applied.
341345 """
342- overrides : dict = {}
346+ overrides : dict [ str , Any ] = {}
343347 if env_files is not None :
344348 overrides ["env_files" ] = env_files
345349 if exclude_dirs is not None :
@@ -361,4 +365,4 @@ def merge_cli_into_config(
361365 output_format = "text"
362366 overrides ["output_format" ] = output_format
363367
364- return dataclass_replace (cfg , ** overrides )
368+ return dataclass_replace (cfg , ** overrides )
0 commit comments