Coverage for pyTooling / Licensing / __init__.py: 92%
75 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-08 23:46 +0000
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-08 23:46 +0000
1# ==================================================================================================================== #
2# _____ _ _ _ _ _ #
3# _ __ _ |_ _|__ ___ | (_)_ __ __ _ | | (_) ___ ___ _ __ ___(_)_ __ __ _ #
4# | '_ \| | | || |/ _ \ / _ \| | | '_ \ / _` | | | | |/ __/ _ \ '_ \/ __| | '_ \ / _` | #
5# | |_) | |_| || | (_) | (_) | | | | | | (_| |_| |___| | (_| __/ | | \__ \ | | | | (_| | #
6# | .__/ \__, ||_|\___/ \___/|_|_|_| |_|\__, (_)_____|_|\___\___|_| |_|___/_|_| |_|\__, | #
7# |_| |___/ |___/ |___/ #
8# ==================================================================================================================== #
9# Authors: #
10# Patrick Lehmann #
11# #
12# License: #
13# ==================================================================================================================== #
14# Copyright 2017-2026 Patrick Lehmann - Bötzingen, Germany #
15# #
16# Licensed under the Apache License, Version 2.0 (the "License"); #
17# you may not use this file except in compliance with the License. #
18# You may obtain a copy of the License at #
19# #
20# http://www.apache.org/licenses/LICENSE-2.0 #
21# #
22# Unless required by applicable law or agreed to in writing, software #
23# distributed under the License is distributed on an "AS IS" BASIS, #
24# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
25# See the License for the specific language governing permissions and #
26# limitations under the License. #
27# #
28# SPDX-License-Identifier: Apache-2.0 #
29# ==================================================================================================================== #
30#
31"""
32The Licensing module implements mapping tables for various license names and identifiers.
34.. seealso::
36 List of SPDX identifiers:
38 * https://spdx.org/licenses/
39 * https://github.com/spdx/license-list-XML
41 List of `Python classifiers <https://pypi.org/classifiers/>`__
43.. hint::
45 See :ref:`high-level help <LICENSING>` for explanations and usage examples.
46"""
47from dataclasses import dataclass
48from typing import Any, Dict, Optional as Nullable
51try:
52 from pyTooling.Decorators import export, readonly
53 from pyTooling.MetaClasses import ExtendedType
54except (ImportError, ModuleNotFoundError): # pragma: no cover
55 print("[pyTooling.Licensing] Could not import from 'pyTooling.*'!")
57 try:
58 from Decorators import export, readonly
59 from MetaClasses import ExtendedType
60 except (ImportError, ModuleNotFoundError) as ex: # pragma: no cover
61 print("[pyTooling.Licensing] Could not import directly!")
62 raise ex
65__all__ = [
66 "PYTHON_LICENSE_NAMES",
68 "Apache_2_0_License",
69 "BSD_3_Clause_License",
70 "GPL_2_0_or_later",
71 "MIT_License",
73 "SPDX_INDEX"
74]
77@export
78@dataclass
79class PythonLicenseName:
80 """A *data class* to represent the license's short name and the package classifier for a license."""
82 ShortName: str #: License's short name
83 Classifier: str #: Package classifier for a license.
85 def __str__(self) -> str:
86 """
87 The string representation of this name tuple returns the short name of the license.
89 :returns: Short name of the license.
90 """
91 return self.ShortName
94#: Mapping of SPDX identifiers to Python license names
95PYTHON_LICENSE_NAMES: Dict[str, PythonLicenseName] = {
96 "Apache-2.0": PythonLicenseName("Apache 2.0", "Apache Software License"),
97 "BSD-3-Clause": PythonLicenseName("BSD", "BSD License"),
98 "MIT": PythonLicenseName("MIT", "MIT License"),
99 "GPL-2.0-or-later": PythonLicenseName("GPL-2.0-or-later", "GNU General Public License v2 or later (GPLv2+)"),
100}
103@export
104class License(metaclass=ExtendedType, slots=True):
105 """Representation of a license."""
107 _spdxIdentifier: str #: Unique SPDX identifier.
108 _name: str #: Name of the license.
109 _osiApproved: bool #: OSI approval status
110 _fsfApproved: bool #: FSF approval status
112 def __init__(self, spdxIdentifier: str, name: str, osiApproved: bool = False, fsfApproved: bool = False) -> None:
113 self._spdxIdentifier = spdxIdentifier
114 self._name = name
115 self._osiApproved = osiApproved
116 self._fsfApproved = fsfApproved
118 @readonly
119 def Name(self) -> str:
120 """
121 Returns the license' name.
123 :returns: License name.
124 """
125 return self._name
127 @readonly
128 def SPDXIdentifier(self) -> str:
129 """
130 Returns the license' unique `SPDX identifier <https://spdx.org/licenses/>`__.
132 :returns: The the unique SPDX identifier.
133 """
134 return self._spdxIdentifier
136 @readonly
137 def OSIApproved(self) -> bool:
138 """
139 Returns true, if the license is approved by OSI (`Open Source Initiative <https://opensource.org/>`__).
141 :returns: ``True``, if the license is approved by the Open Source Initiative.
142 """
143 return self._osiApproved
145 @readonly
146 def FSFApproved(self) -> bool:
147 """
148 Returns true, if the license is approved by FSF (`Free Software Foundation <https://www.fsf.org/>`__).
150 :returns: ``True``, if the license is approved by the Free Software Foundation.
151 """
152 return self._fsfApproved
154 @readonly
155 def PythonLicenseName(self) -> str:
156 """
157 Returns the Python license name for this license if it's defined.
159 :returns: The Python license name.
160 :raises ValueError: If there is no license name defined for the license. |br| (See and check :data:`~pyTooling.Licensing.PYTHON_LICENSE_NAMES`)
161 """
162 try:
163 item: PythonLicenseName = PYTHON_LICENSE_NAMES[self._spdxIdentifier]
164 except KeyError as ex:
165 raise ValueError("License has no Python specify information.") from ex
167 return item.ShortName
169 @readonly
170 def PythonClassifier(self) -> str:
171 """
172 Returns the Python package classifier for this license if it's defined.
174 :returns: The Python package classifier.
175 :raises ValueError: If there is no classifier defined for the license. |br| (See and check :data:`~pyTooling.Licensing.PYTHON_LICENSE_NAMES`)
177 .. seealso::
179 List of `Python classifiers <https://pypi.org/classifiers/>`__
180 """
181 try:
182 item: PythonLicenseName = PYTHON_LICENSE_NAMES[self._spdxIdentifier]
183 except KeyError as ex:
184 raise ValueError(f"License has no Python specify information.") from ex
186 osi = "OSI Approved :: " if self._osiApproved else ""
187 return f"License :: {osi}{item.Classifier}"
189 def __eq__(self, other: Any) -> bool:
190 """
191 Returns true, if both licenses are identical (comparison based on SPDX identifiers).
193 :returns: ``True``, if both licenses are identical.
194 :raises TypeError: If second operand is not of type :class:`License` or :class:`str`.
195 """
196 if isinstance(other, License):
197 return self._spdxIdentifier == other._spdxIdentifier
198 else:
199 ex = TypeError(f"Second operand of type '{other.__class__.__name__}' is not supported by equal operator.")
200 ex.add_note(f"Supported types for second operand: License, str")
201 raise ex
203 def __ne__(self, other: Any) -> bool:
204 """
205 Returns true, if both licenses are not identical (comparison based on SPDX identifiers).
207 :returns: ``True``, if both licenses are not identical.
208 :raises TypeError: If second operand is not of type :class:`License` or :class:`str`.
209 """
210 if isinstance(other, License):
211 return self._spdxIdentifier != other._spdxIdentifier
212 else:
213 ex = TypeError(f"Second operand of type '{other.__class__.__name__}' is not supported by unequal operator.")
214 ex.add_note(f"Supported types for second operand: License, str")
215 raise ex
217 def __le__(self, other: Any) -> bool:
218 """Returns true, if both licenses are compatible."""
219 raise NotImplementedError("License compatibility check is not yet implemented.")
221 def __ge__(self, other: Any) -> bool:
222 """Returns true, if both licenses are compatible."""
223 raise NotImplementedError("License compatibility check is not yet implemented.")
225 def __repr__(self) -> str:
226 """
227 Returns the internal unique representation (a.k.a SPDX identifier).
229 :returns: SPDX identifier of the license.
230 """
231 return self._spdxIdentifier
233 def __str__(self) -> str:
234 """
235 Returns the license' name.
237 :returns: Name of the license.
238 """
239 return self._name
242Apache_2_0_License = License("Apache-2.0", "Apache License 2.0", True, True)
243BSD_3_Clause_License = License("BSD-3-Clause", "BSD 3-Clause Revised License", True, True)
244GPL_2_0_or_later = License("GPL-2.0-or-later", "GNU General Public License v2.0 or later", True, True)
245MIT_License = License("MIT", "MIT License", True, True)
248#: Mapping of predefined licenses
249SPDX_INDEX: Dict[str, License] = {
250 "Apache-2.0": Apache_2_0_License,
251 "BSD-3-Clause": BSD_3_Clause_License,
252 "GPL-2.0-or-later": GPL_2_0_or_later,
253 "MIT": MIT_License
254}