|
1 | 1 | """Load configuration.""" |
2 | 2 |
|
| 3 | +from __future__ import annotations |
| 4 | + |
3 | 5 | import logging |
4 | | -import pathlib |
5 | | -from typing import Optional |
| 6 | +import sys |
| 7 | +from pathlib import Path |
| 8 | +from typing import Any |
6 | 9 |
|
7 | | -import tomllib |
| 10 | +# YORE: EOL 3.10: Replace block with line 2. |
| 11 | +if sys.version_info >= (3, 11): |
| 12 | + import tomllib |
| 13 | +else: |
| 14 | + import tomli as tomllib |
8 | 15 |
|
9 | 16 | logger = logging.getLogger(__name__) |
10 | 17 |
|
11 | | -PATHS = ( |
12 | | - ".config/griffe2md.toml", |
13 | | - "config/griffe2md.toml", |
| 18 | +CONFIG_FILE_PATHS = ( |
| 19 | + Path(".config/griffe2md.toml"), |
| 20 | + Path("config/griffe2md.toml"), |
| 21 | + Path("pyproject.toml"), |
14 | 22 | ) |
15 | 23 |
|
16 | | -PYPROJECT = "pyproject.toml" |
17 | | - |
18 | | - |
19 | | -def _locate_config_file() -> Optional[pathlib.Path]: |
20 | | - for path in PATHS: |
21 | | - path_ = pathlib.Path(path) |
22 | | - if path_.is_file(): |
23 | | - return path_ |
24 | | - |
25 | | - pyproj_path = pathlib.Path(PYPROJECT) |
26 | | - if pyproj_path.is_file(): |
27 | | - return pyproj_path |
28 | 24 |
|
| 25 | +def _locate_config_file() -> Path | None: |
| 26 | + for path in CONFIG_FILE_PATHS: |
| 27 | + if path.is_file(): |
| 28 | + return path |
29 | 29 | return None |
30 | 30 |
|
31 | 31 |
|
32 | | -def load_config() -> Optional[dict]: |
33 | | - """Load the configuration if config file or config entry in pyproject.toml exists. If neither config file was found or pyproject.toml file doesn't have [tool.griffe2md] section, returns None.""" |
34 | | - config_path = _locate_config_file() |
35 | | - if config_path is None: |
| 32 | +def load_config() -> dict[str, Any] | None: |
| 33 | + """Load the configuration if config file or config entry in pyproject.toml exists. |
| 34 | +
|
| 35 | + If neither config file was found or pyproject.toml file doesn't have |
| 36 | + a `[tool.griffe2md]` section, None is returned. |
| 37 | + """ |
| 38 | + if not (config_path := _locate_config_file()): |
36 | 39 | return None |
37 | 40 |
|
38 | 41 | logger.debug("Loading config from %s", config_path) |
39 | 42 |
|
40 | | - with open(config_path, "rb") as f: |
| 43 | + with config_path.open("rb") as f: |
41 | 44 | config = tomllib.load(f) |
42 | 45 |
|
43 | | - if str(config_path) == PYPROJECT: |
44 | | - return (config.get("tool") or {}).get("griffe2md") |
| 46 | + if config_path.name == "pyproject.toml": |
| 47 | + return config.get("tool", {}).get("griffe2md", None) |
45 | 48 | return config |
0 commit comments