|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import json |
| 4 | +from collections.abc import Mapping |
| 5 | +from typing import TYPE_CHECKING, Any |
| 6 | + |
| 7 | +import tomlkit |
| 8 | +import yaml |
| 9 | + |
| 10 | +from commitizen import out |
| 11 | + |
| 12 | +if TYPE_CHECKING: |
| 13 | + from commitizen.config import BaseConfig |
| 14 | + |
| 15 | + |
| 16 | +class DumpConfig: |
| 17 | + """Output the current commitizen configuration.""" |
| 18 | + |
| 19 | + def __init__(self, config: BaseConfig, arguments: dict[str, Any]) -> None: |
| 20 | + self.config: BaseConfig = config |
| 21 | + self.format: str = arguments.get("format", "toml") |
| 22 | + |
| 23 | + def __call__(self) -> None: |
| 24 | + settings = dict(self.config.settings) |
| 25 | + |
| 26 | + if self.format == "toml": |
| 27 | + filtered = _filter_none_values(settings) |
| 28 | + doc = tomlkit.document() |
| 29 | + tool_table = tomlkit.table() |
| 30 | + cz_table = tomlkit.table() |
| 31 | + for key, value in filtered.items(): |
| 32 | + cz_table.add(key, value) |
| 33 | + tool_table.add("commitizen", cz_table) |
| 34 | + doc.add("tool", tool_table) |
| 35 | + out.write(tomlkit.dumps(doc)) |
| 36 | + elif self.format == "yaml": |
| 37 | + out.write( |
| 38 | + yaml.safe_dump( |
| 39 | + {"tool": {"commitizen": settings}}, |
| 40 | + default_flow_style=False, |
| 41 | + allow_unicode=True, |
| 42 | + ) |
| 43 | + ) |
| 44 | + else: |
| 45 | + out.write( |
| 46 | + json.dumps({"tool": {"commitizen": settings}}, indent=2, default=str) |
| 47 | + ) |
| 48 | + |
| 49 | + |
| 50 | +def _filter_none_values(settings: Mapping[str, Any]) -> dict[str, Any]: |
| 51 | + return { |
| 52 | + key: _filter_none_values(value) if isinstance(value, Mapping) else value |
| 53 | + for key, value in settings.items() |
| 54 | + if value is not None |
| 55 | + } |
0 commit comments