Quellcode durchsuchen

[O] Remove HyPyUtils Dependency

Azalea (on HyDEV-Daisy) vor 3 Jahren
Ursprung
Commit
b0bc4e64a9
6 geänderte Dateien mit 97 neuen und 9 gelöschten Zeilen
  1. 2 1
      hyfetch/__init__.py
  2. 42 0
      hyfetch/color_util.py
  3. 8 3
      hyfetch/main.py
  4. 43 0
      hyfetch/serializer.py
  5. 1 1
      setup.py
  6. 1 4
      test.py

+ 2 - 1
hyfetch/__init__.py

@@ -1,8 +1,9 @@
 from __future__ import annotations
+
 from . import main
 
 
-__version__ = '1.0.5'
+__version__ = main.VERSION
 
 
 if __name__ == '__main__':

+ 42 - 0
hyfetch/color_util.py

@@ -7,6 +7,48 @@ from typing_extensions import Literal
 AnsiMode = Literal['default', 'ansi', '8bit', 'rgb']
 
 
+MINECRAFT_COLORS = ["&0/\033[0;30m", "&1/\033[0;34m", "&2/\033[0;32m", "&3/\033[0;36m", "&4/\033[0;31m",
+                    "&5/\033[0;35m", "&6/\033[0;33m", "&7/\033[0;37m", "&8/\033[1;30m", "&9/\033[1;34m",
+                    "&a/\033[1;32m", "&b/\033[1;36m", "&c/\033[1;31m", "&d/\033[1;35m", "&e/\033[1;33m",
+                    "&f/\033[1;37m",
+                    "&r/\033[0m", "&l/\033[1m", "&o/\033[3m", "&n/\033[4m", "&-/\n"]
+MINECRAFT_COLORS = [(r[:2], r[3:]) for r in MINECRAFT_COLORS]
+
+
+def color(msg: str) -> str:
+    """
+    Replace extended minecraft color codes in string
+    :param msg: Message with minecraft color codes
+    :return: Message with escape codes
+    """
+    for code, esc in MINECRAFT_COLORS:
+        msg = msg.replace(code, esc)
+
+    while '&gf(' in msg or '&gb(' in msg:
+        i = msg.index('&gf(') if '&gf(' in msg else msg.index('&gb(')
+        end = msg.index(')', i)
+        code = msg[i + 4:end]
+        fore = msg[i + 2] == 'f'
+
+        if code.startswith('#'):
+            rgb = tuple(int(code.lstrip('#')[i:i+2], 16) for i in (0, 2, 4))
+        else:
+            code = code.replace(',', ' ').replace(';', ' ').replace('  ', ' ')
+            rgb = tuple(int(c) for c in code.split(' '))
+
+        msg = msg[:i] + RGB(*rgb).to_ansi_rgb(foreground=fore) + msg[end + 1:]
+
+    return msg
+
+
+def printc(msg: str):
+    """
+    Print with color
+    :param msg: Message with minecraft color codes
+    """
+    print(color(msg + '&r'))
+
+
 def redistribute_rgb(r: int, g: int, b: int) -> tuple[int, int, int]:
     """
     Redistribute RGB after lightening

+ 8 - 3
hyfetch/main.py

@@ -7,14 +7,14 @@ from dataclasses import dataclass
 from pathlib import Path
 from typing import Iterable
 
-from hypy_utils import printc, json_stringify, color
-
-from .color_util import AnsiMode
+from .color_util import AnsiMode, printc, color
 from .neofetch_util import run_neofetch
 from .presets import PRESETS, ColorProfile
+from .serializer import json_stringify
 
 CONFIG_PATH = Path.home() / '.config/hyfetch.json'
 CONFIG_PATH.parent.mkdir(exist_ok=True, parents=True)
+VERSION = '1.0.6'
 
 
 @dataclass
@@ -140,9 +140,14 @@ def run():
     parser.add_argument('-m', '--mode', help=f'Color mode', choices=['8bit', 'rgb'])
     parser.add_argument('--c-scale', dest='scale', help=f'Lighten colors by a multiplier', type=float)
     parser.add_argument('--c-set-l', dest='light', help=f'Set lightness value of the colors', type=float)
+    parser.add_argument('-V', '--version', dest='version', action='store_true', help=f'Check version')
 
     args = parser.parse_args()
 
+    if args.version:
+        print(f'Version is {VERSION}')
+        return
+
     # Load config
     config = check_config()
 

+ 43 - 0
hyfetch/serializer.py

@@ -0,0 +1,43 @@
+from __future__ import annotations
+
+import dataclasses
+import json
+from datetime import datetime, date
+
+
+class EnhancedJSONEncoder(json.JSONEncoder):
+    """
+    An improvement to the json.JSONEncoder class, which supports:
+    encoding for dataclasses, encoding for datetime, and sets
+    """
+
+    def default(self, o: object) -> object:
+
+        # Support encoding dataclasses
+        # https://stackoverflow.com/a/51286749/7346633
+        if dataclasses.is_dataclass(o):
+            return dataclasses.asdict(o)
+
+        # Support encoding datetime
+        if isinstance(o, (datetime, date)):
+            return o.isoformat()
+
+        # Support for sets
+        # https://stackoverflow.com/a/8230505/7346633
+        if isinstance(o, set):
+            return list(o)
+
+        return super().default(o)
+
+
+def json_stringify(obj: object, indent: int | None = None) -> str:
+    """
+    Serialize json string with support for dataclasses and datetime and sets and with custom
+    configuration.
+    Preconditions:
+        - obj != None
+    :param obj: Objects
+    :param indent: Indent size or none
+    :return: Json strings
+    """
+    return json.dumps(obj, indent=indent, cls=EnhancedJSONEncoder, ensure_ascii=False)

+ 1 - 1
setup.py

@@ -32,7 +32,7 @@ setup(
     packages=['hyfetch'],
     package_data={'hyfetch': ['hyfetch/*']},
     include_package_data=True,
-    install_requires=['setuptools', 'hypy_utils>=1.0.6', 'typing_extensions'],
+    install_requires=['setuptools', 'typing_extensions'],
     entry_points={
         "console_scripts": [
             "hyfetch=hyfetch.main:run",

+ 1 - 4
test.py

@@ -1,6 +1,4 @@
-from hypy_utils import printc
-
-from hyfetch.color_util import RGB
+from hyfetch.color_util import RGB, printc
 from hyfetch.neofetch_util import get_command_path, run_neofetch
 from hyfetch.presets import PRESETS
 
@@ -35,6 +33,5 @@ def test_rgb_8bit_conversion():
     print()
 
 
-
 if __name__ == '__main__':
     test_rgb_8bit_conversion()