Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/iniconfig/__init__.py: 63%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""brain-dead simple parser for ini-style files.
2(C) Ronny Pfannschmidt, Holger Krekel -- MIT licensed
3"""
5import os
6from collections.abc import Callable
7from collections.abc import Iterator
8from collections.abc import Mapping
9from typing import Final
10from typing import TypeVar
11from typing import overload
13__all__ = ["COMMENTCHARS", "IniConfig", "ParseError", "iscommentline"]
15from . import _parse
16from ._parse import COMMENTCHARS
17from ._parse import iscommentline
18from .exceptions import ParseError
20_D = TypeVar("_D")
21_T = TypeVar("_T")
24class SectionWrapper:
25 config: Final["IniConfig"]
26 name: Final[str]
28 def __init__(self, config: "IniConfig", name: str) -> None:
29 self.config = config
30 self.name = name
32 def lineof(self, name: str) -> int | None:
33 return self.config.lineof(self.name, name)
35 @overload
36 def get(self, key: str) -> str | None: ...
38 @overload
39 def get(
40 self,
41 key: str,
42 *,
43 convert: Callable[[str], _T],
44 ) -> _T | None: ...
46 @overload
47 def get(
48 self,
49 key: str,
50 default: None,
51 convert: Callable[[str], _T],
52 ) -> _T | None: ...
54 @overload
55 def get(self, key: str, default: _D, convert: None = None) -> str | _D: ...
57 @overload
58 def get(
59 self,
60 key: str,
61 default: _D,
62 convert: Callable[[str], _T],
63 ) -> _T | _D: ...
65 def get(
66 self,
67 key: str,
68 default: _D | None = None,
69 convert: Callable[[str], _T] | None = None,
70 ) -> _D | _T | str | None:
71 return self.config.get(self.name, key, convert=convert, default=default)
73 def __getitem__(self, key: str) -> str:
74 return self.config.sections[self.name][key]
76 def __iter__(self) -> Iterator[str]:
77 section: Mapping[str, str] = self.config.sections.get(self.name, {})
79 def lineof(key: str) -> int:
80 return self.config.lineof(self.name, key) # type: ignore[return-value]
82 yield from sorted(section, key=lineof)
84 def items(self) -> Iterator[tuple[str, str]]:
85 for name in self:
86 yield name, self[name]
89class IniConfig:
90 path: Final[str]
91 sections: Final[Mapping[str, Mapping[str, str]]]
92 _sources: Final[Mapping[tuple[str, str | None], int]]
94 def __init__(
95 self,
96 path: str | os.PathLike[str],
97 data: str | None = None,
98 encoding: str = "utf-8",
99 *,
100 _sections: Mapping[str, Mapping[str, str]] | None = None,
101 _sources: Mapping[tuple[str, str | None], int] | None = None,
102 ) -> None:
103 self.path = os.fspath(path)
105 # Determine sections and sources
106 if _sections is not None and _sources is not None:
107 # Use provided pre-parsed data (called from parse())
108 sections_data = _sections
109 sources = _sources
110 else:
111 # Parse the data (backward compatible path)
112 if data is None:
113 with open(self.path, encoding=encoding) as fp:
114 data = fp.read()
116 # Use old behavior (no stripping) for backward compatibility
117 sections_data, sources = _parse.parse_ini_data(
118 self.path, data, strip_inline_comments=False
119 )
121 # Assign once to Final attributes
122 self._sources = sources
123 self.sections = sections_data
125 @classmethod
126 def parse(
127 cls,
128 path: str | os.PathLike[str],
129 data: str | None = None,
130 encoding: str = "utf-8",
131 *,
132 strip_inline_comments: bool = True,
133 strip_section_whitespace: bool = False,
134 ) -> "IniConfig":
135 """Parse an INI file.
137 Args:
138 path: Path to the INI file (used for error messages)
139 data: Optional INI content as string. If None, reads from path.
140 encoding: Encoding to use when reading the file (default: utf-8)
141 strip_inline_comments: Whether to strip inline comments from values
142 (default: True). When True, comments starting with # or ; are
143 removed from values, matching the behavior for section comments.
144 strip_section_whitespace: Whether to strip whitespace from section and key names
145 (default: False). When True, strips Unicode whitespace from section and key names,
146 addressing issue #4. When False, preserves existing behavior for backward compatibility.
148 Returns:
149 IniConfig instance with parsed configuration
151 Example:
152 # With comment stripping (default):
153 config = IniConfig.parse("setup.cfg")
154 # value = "foo" instead of "foo # comment"
156 # Without comment stripping (old behavior):
157 config = IniConfig.parse("setup.cfg", strip_inline_comments=False)
158 # value = "foo # comment"
160 # With section name stripping (opt-in for issue #4):
161 config = IniConfig.parse("setup.cfg", strip_section_whitespace=True)
162 # section names and keys have Unicode whitespace stripped
163 """
164 fspath = os.fspath(path)
166 if data is None:
167 with open(fspath, encoding=encoding) as fp:
168 data = fp.read()
170 sections_data, sources = _parse.parse_ini_data(
171 fspath,
172 data,
173 strip_inline_comments=strip_inline_comments,
174 strip_section_whitespace=strip_section_whitespace,
175 )
177 # Call constructor with pre-parsed sections and sources
178 return cls(path=fspath, _sections=sections_data, _sources=sources)
180 def lineof(self, section: str, name: str | None = None) -> int | None:
181 lineno = self._sources.get((section, name))
182 return None if lineno is None else lineno + 1
184 @overload
185 def get(
186 self,
187 section: str,
188 name: str,
189 ) -> str | None: ...
191 @overload
192 def get(
193 self,
194 section: str,
195 name: str,
196 *,
197 convert: Callable[[str], _T],
198 ) -> _T | None: ...
200 @overload
201 def get(
202 self,
203 section: str,
204 name: str,
205 default: None,
206 convert: Callable[[str], _T],
207 ) -> _T | None: ...
209 @overload
210 def get(
211 self, section: str, name: str, default: _D, convert: None = None
212 ) -> str | _D: ...
214 @overload
215 def get(
216 self,
217 section: str,
218 name: str,
219 default: _D,
220 convert: Callable[[str], _T],
221 ) -> _T | _D: ...
223 def get(
224 self,
225 section: str,
226 name: str,
227 default: _D | None = None,
228 convert: Callable[[str], _T] | None = None,
229 ) -> _D | _T | str | None:
230 try:
231 value: str = self.sections[section][name]
232 except KeyError:
233 return default
234 else:
235 if convert is not None:
236 return convert(value)
237 else:
238 return value
240 def __getitem__(self, name: str) -> SectionWrapper:
241 if name not in self.sections:
242 raise KeyError(name)
243 return SectionWrapper(self, name)
245 def __iter__(self) -> Iterator[SectionWrapper]:
246 for name in sorted(self.sections, key=self.lineof): # type: ignore
247 yield SectionWrapper(self, name)
249 def __contains__(self, arg: str) -> bool:
250 return arg in self.sections