Skip to content

Commit

Permalink
License, formatting, and multi-version python import fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
brandonscript committed Mar 11, 2024
1 parent df21974 commit 331bf36
Show file tree
Hide file tree
Showing 8 changed files with 258 additions and 188 deletions.
4 changes: 3 additions & 1 deletion Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,12 @@ setuptools = "*"
wheel = "*"

[requires]
python_version = "3.10"
python_version = "3.6"

[scripts]
test = "pytest"
build = "./dist/build.sh"
publish-test = "./dist/publish.sh --test"
publish-real = "./dist/publish.sh"
lint-check = "ruff check tinta"
lint-fix = "ruff fix tinta"
286 changes: 143 additions & 143 deletions Pipfile.lock

Large diffs are not rendered by default.

7 changes: 5 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -127,13 +127,16 @@ select = [
"E112",
"E117",
"I002",
"UP035",
"I001",
"I002",
# "UP035",
]
# To add, when supported by ruff: "W503", "E203"
# see: https://github.com/astral-sh/ruff/issues/2402

[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["E402", "F401"]
"typ.py" = ["F401"]

[tool.ruff.lint.isort]
force-sort-within-sections = false
Expand All @@ -150,7 +153,7 @@ quote-style = "double"

[tool.pytest.ini_options]
pythonpath = ["."]
minversion = "7.4"
minversion = "7.0"
addopts = "-rP -vv --color=yes"
testpaths = ["tests"]
python_files = ["*_test.py", "test_*.py"]
Expand Down
20 changes: 18 additions & 2 deletions tinta/ansi.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,22 @@
#!/usr/bin/env python

# Tinta
# Copyright 2024 github.com/brandoncript

# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

# If you use this software, you must also agree under the terms of the Hippocratic License 3.0 to not use this software in a way that directly or indirectly causes harm. You can find the full text of the license at https://firstdonoharm.dev.

"""This class is a low-level helper class for managing colors in Tinta."""

import configparser
import sys
from pathlib import Path
from typing import List, Optional, Union

from .typ import MissingColorError

Expand All @@ -19,7 +35,7 @@ class AnsiColors:
ANSI values in colors.ini.
"""

def __init__(self, path: str | Path | None = None):
def __init__(self, path: Optional[Union[str, Path]] = None):
path = Path(path) if path else Path(__file__).parent / "colors.ini"
if not path.is_absolute():
path = Path().cwd() / path
Expand Down Expand Up @@ -83,6 +99,6 @@ def reverse_get(self, code: int) -> str:
f"Color with ANSI code '{code}' not found in colors.ini."
)

def list_colors(self) -> list[str]:
def list_colors(self) -> List[str]:
"""Returns a list of all colors in the colors.ini file."""
return list(config["colors"].keys())
5 changes: 5 additions & 0 deletions tinta/colorize.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

# This module is a modified version of the original AnsiColors module, and further
# modified by github.com/brandoncript to be used in the Tinta project. It is
# distributed under the same license as the original module, as well as the
# MIT License.

import re
from typing import List, Optional, Tuple, Union

Expand Down
35 changes: 15 additions & 20 deletions tinta/discover.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,13 @@
# Tinta
# Copyright 2024 github.com/brandoncript

# This program is bound to the Hippocratic License 2.1
# Full text is available here:
# https://firstdonoharm.dev/version/2/1/license

# Further to adherence to the Hippocratic License, permission is hereby
# granted, free of charge, to any person obtaining a copy of this software
# and associated documentation files (the "Software") under the terms of the
# MIT License to deal in the Software without restriction, including without
# limitation the rights to use, copy, modify, merge, publish, distribute,
# sublicense, and / or sell copies of the Software, and to permit persons
# to whom the Software is furnished to do so, subject to the conditions layed
# out in the MIT License.

# Where a conflict or dispute would arise between these two licenses, HLv2.1
# shall take precedence.
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

# If you use this software, you must also agree under the terms of the Hippocratic License 3.0 to not use this software in a way that directly or indirectly causes harm. You can find the full text of the license at https://firstdonoharm.dev.

"""This discover module is used to discover the colors available on your system.
Expand Down Expand Up @@ -51,13 +43,16 @@
244 245 246 247 248 249 250 251 252 253 254 255
"""

import sys
from collections.abc import Iterable
from typing import List, TypeVar, Union
from typing import List, Union

if sys.version_info >= (3, 8):
from typing import Literal, TypeVar
elif sys.version_info >= (3, 5):
from typing import TypeVar

try:
from typing import Literal
except ImportError:
from typing import Literal
from typing_extensions import Literal

color_sets = {
"standard": [0, 1, 2, 3, 4, 5, 6, 7],
Expand Down
45 changes: 34 additions & 11 deletions tinta/tinta.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,30 @@
import sys
from itertools import zip_longest
from pathlib import Path
from typing import Any, cast, Optional, overload, Union
from typing import Any, cast, List, Optional, overload, Union

from typing_extensions import deprecated, Self
try:
from typing import deprecated
except ImportError:
try:
from typing_extensions import deprecated
except ImportError:
from typing import cast

def deprecated(msg: str) -> Any:
def _decorator(func: Any) -> Any:
return cast(Any, func)

return _decorator


try:
from typing import Self
except ImportError:
try:
from typing_extensions import Self
except ImportError:
Self = "Tinta"

from .ansi import AnsiColors
from .colorize import ANSI_RESET_HEX, colorize
Expand All @@ -48,7 +69,7 @@ def __init__(cls, name, bases, dct):
super(_MetaTinta, cls).__init__(name, bases, dct)
cls.colors = AnsiColors()

def load_colors(cls, path: str | Path):
def load_colors(cls, path: Union[str, Path]):
loaded_colors = AnsiColors(path)

# Check if any of the color names loaded match the built-in methods. If so, raise an error.
Expand Down Expand Up @@ -107,10 +128,12 @@ class Tinta(metaclass=_MetaTinta):
print(): Prints the output of a Tinta instance, then resets.
"""

color: int | str
color: Union[int, str]
colors: AnsiColors

def __init__(self, *s: Any, color: Optional[str | int] = None, sep: str = SEP):
def __init__(
self, *s: Any, color: Optional[Union[str, int]] = None, sep: str = SEP
):
"""Main intializer for Tinta
Args:
Expand All @@ -119,9 +142,9 @@ def __init__(self, *s: Any, color: Optional[str | int] = None, sep: str = SEP):
"""

self.color = color or 0 # 0 is the default color for terminals
self.style: list[str] = []
self._parts: list["Tinta.Part"] = []
self._prefixes: list[str] = []
self.style: List[str] = []
self._parts: List["Tinta.Part"] = []
self._prefixes: List[str] = []

# Inject ANSI helper functions
for c in vars(self.colors):
Expand Down Expand Up @@ -258,11 +281,11 @@ def get_text(self, sep: str = SEP) -> str:
return self.to_str(sep=sep)

@property
def parts(self) -> list["Tinta.Part"]:
def parts(self) -> List["Tinta.Part"]:
"""A list of Tinta.Part objects.
Returns:
list[Part]: A list of Tinta.Part objects"""
List[Part]: A list of Tinta.Part objects"""

return self._parts

Expand Down Expand Up @@ -412,7 +435,7 @@ def remove(self, qty: int = 1) -> "Tinta":

# pylint: disable=redefined-outer-name
def tint(
self, color: Optional[str | int] = None, *s: Any, sep: str = SEP
self, color: Optional[Union[str, int]] = None, *s: Any, sep: str = SEP
) -> "Tinta":
"""Adds segments of text colored with the specified color.
Can be used in place of calling named color methods.
Expand Down
44 changes: 35 additions & 9 deletions tinta/typ.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,40 @@
#!/usr/bin/env python

# Tinta
# Copyright 2024 github.com/brandoncript

# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

# If you use this software, you must also agree under the terms of the Hippocratic License 3.0 to not use this software in a way that directly or indirectly causes harm. You can find the full text of the license at https://firstdonoharm.dev.

"""This module contains type hints and utility functions for Tinta."""
import functools
import inspect
from collections.abc import Callable
from typing import Any, cast, Literal
import sys
from typing import Any, Callable, cast

if sys.version_info >= (3, 10):
from typing import Literal, ParamSpec, TypeVar

P = ParamSpec("P") if sys.version_info >= (3, 10) else ... # type: ignore
R = TypeVar("R") # type: ignore

GenericCallable = Callable[P, R]
elif sys.version_info >= (3, 8):
from typing import Literal

GenericCallable = Any
else:
from typing_extensions import Literal

from typing_extensions import ParamSpec, TypeVar
GenericCallable = Any

P = ParamSpec("P")
R = TypeVar("R")

StringType = Literal["pln", "esc", "fmt"]
StringType = Literal["pln", "esc", "fmt"] # type: ignore


class MissingColorError(Exception):
Expand All @@ -17,12 +43,12 @@ class MissingColorError(Exception):
pass


def copy_kwargs(func: Callable[P, R]) -> Callable[..., Callable[P, R]]:
def copy_kwargs(func: GenericCallable) -> Callable[..., GenericCallable]:
"""Decorator does nothing but casts the original function to match the given function signature"""

@functools.wraps(func, updated=())
def _cast_func(_func: Callable[..., Any]) -> Callable[P, R]:
return cast(Callable[P, R], _func)
def _cast_func(_func: Callable[..., Any]) -> GenericCallable:
return cast(GenericCallable, _func)

if inspect.isfunction(func):
return _cast_func
Expand Down

0 comments on commit 331bf36

Please sign in to comment.