Coverage for klayout_pex/util/argparse_helpers.py: 85%
33 statements
« prev ^ index » next coverage.py v7.6.9, created at 2024-12-17 17:24 +0000
« prev ^ index » next coverage.py v7.6.9, created at 2024-12-17 17:24 +0000
1#! /usr/bin/env python3
2#
3# --------------------------------------------------------------------------------
4# SPDX-FileCopyrightText: 2024 Martin Jan Köhler and Harald Pretl
5# Johannes Kepler University, Institute for Integrated Circuits.
6#
7# This file is part of KPEX
8# (see https://github.com/martinjankoehler/klayout-pex).
9#
10# This program is free software: you can redistribute it and/or modify
11# it under the terms of the GNU General Public License as published by
12# the Free Software Foundation, either version 3 of the License, or
13# (at your option) any later version.
14#
15# This program is distributed in the hope that it will be useful,
16# but WITHOUT ANY WARRANTY; without even the implied warranty of
17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18# GNU General Public License for more details.
19#
20# You should have received a copy of the GNU General Public License
21# along with this program. If not, see <http://www.gnu.org/licenses/>.
22# SPDX-License-Identifier: GPL-3.0-or-later
23# --------------------------------------------------------------------------------
24#
26import argparse
27from enum import Enum, StrEnum
28from typing import *
31def render_enum_help(topic: str,
32 enum_cls: Type[Enum],
33 print_default: bool = True,
34 lowercase_strenum: bool = False) -> str:
35 def canonic_string(name: str, member: str) -> str:
36 if issubclass(enum_cls, StrEnum):
37 if name.lower() == 'default':
38 return 'default'
39 return member.lower() if lowercase_strenum else member
40 return name.lower()
41 if not hasattr(enum_cls, 'DEFAULT'):
42 print_default = False
43 case_list = [f"'{canonic_string(name, member)}'" for name, member in enum_cls.__members__.items()]
44 enum_help = f"{topic} ∈ \u007b{', '.join(case_list)}\u007d"
45 if print_default:
46 default_case: enum_cls = getattr(enum_cls, 'DEFAULT')
47 if issubclass(enum_cls, StrEnum):
48 default_value: str = default_case.value
49 if lowercase_strenum:
50 default_value = default_value.lower()
51 else:
52 default_value = default_case.name.lower()
53 enum_help += f".\nDefaults to '{default_value}'"
54 return enum_help
57def true_or_false(arg) -> bool:
58 if isinstance(arg, bool):
59 return arg
61 match str(arg).lower():
62 case 'yes' | 'true' | 't' | 'y' | 1:
63 return True
64 case 'no' | 'false' | 'f' | 'n' | 0:
65 return False
66 case _:
67 raise argparse.ArgumentTypeError('Boolean value expected.')