Skip to content

Commit

Permalink
Fix parsing of values in pyproject.toml
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielNoord committed Jul 6, 2022
1 parent 590e223 commit 06ab0f6
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 11 deletions.
28 changes: 17 additions & 11 deletions pydocstringformatter/_configuration/toml_parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@

import argparse
import os
from typing import Any, Final
from typing import Any

import tomli

from pydocstringformatter._utils.exceptions import TomlParsingError, UnrecognizedOption

OPTIONS_TYPES: Final = {"write": "store_true", "exclude": "store"}


def get_toml_file() -> dict[str, Any] | None:
"""See if there is a pyproject.toml and extract the correct section if it exists."""
Expand All @@ -26,19 +24,27 @@ def get_toml_file() -> dict[str, Any] | None:
return None


def parse_toml_option(opt: str, value: Any) -> list[str]:
def parse_toml_option(
parser: argparse.ArgumentParser, opt: str, value: Any
) -> list[str]:
"""Parse an options value in the correct argument type for argparse."""
# pylint: disable=protected-access
try:
action = OPTIONS_TYPES[opt]
action = parser._option_string_actions[f"--{opt}"]
except KeyError as exc:
raise UnrecognizedOption(f"Don't recognize option {opt}") from exc
try:
action = parser._option_string_actions[f"-{opt}"]
except KeyError:
raise UnrecognizedOption(f"Don't recognize option {opt}") from exc

if action == "store_true":
if isinstance(action, argparse._StoreTrueAction):
if value is True:
return [f"--{opt}"]
return [action.option_strings[0]]
return []
if action == "store":
return [f"--{opt}", value]
if isinstance(action, argparse._StoreAction):
if isinstance(value, int):
value = str(value)
return [action.option_strings[0], value]
return [] # pragma: no cover


Expand All @@ -50,6 +56,6 @@ def parse_toml_file(
arguments: list[str] = []

for key, value in toml_sect.items():
arguments += parse_toml_option(key, value)
arguments += parse_toml_option(parser, key, value)

parser.parse_args(arguments, namespace)
3 changes: 3 additions & 0 deletions tests/data/config/valid_toml/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
[tool.pydocstringformatter]
write = true
max-summary-lines = 2
# Also test short options
w = true

0 comments on commit 06ab0f6

Please sign in to comment.