Skip to content

Commit e5966cf

Browse files
Merge pull request #10 from danila-schelkov/dev
Code improvement
2 parents 1ae7899 + 11f1714 commit e5966cf

24 files changed

+748
-623
lines changed

.github/workflows/lint.yml

Lines changed: 17 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -7,22 +7,21 @@ jobs:
77
runs-on: ubuntu-latest
88

99
steps:
10-
- uses: actions/checkout@v3
11-
- name: Set up Python 3.10
12-
uses: actions/setup-python@v2
13-
with:
14-
python-version: "3.10"
15-
16-
- name: Install requirements
17-
run: |
18-
pip install pipx
19-
pipx install cookiecutter
20-
pipx runpip cookiecutter install -r requirements.txt
10+
- uses: actions/checkout@v3
11+
- name: Set up Python 3.10
12+
uses: actions/setup-python@v4
13+
with:
14+
python-version: "3.10"
2115

22-
- name: Linting code by flake8
23-
run: |
24-
pipx run flake8 --show-source --statistics
25-
26-
- name: Check types by pyright
27-
run: |
28-
pipx run pyright
16+
- name: Install requirements
17+
run: |
18+
pip install flake8 pyright
19+
pip install -r requirements.txt
20+
21+
- name: Linting code by flake8
22+
run: |
23+
flake8 --show-source --statistics
24+
25+
- name: Check types by pyright
26+
run: |
27+
pyright

.pre-commit-config.yaml

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@ repos:
1313
hooks:
1414
- id: black
1515
language_version: python3.10
16-
- repo: https://github.com/PyCQA/flake8
17-
rev: 6.0.0
16+
- repo: https://github.com/charliermarsh/ruff-pre-commit
17+
rev: 'v0.0.261'
1818
hooks:
19-
- id: flake8
19+
- id: ruff
20+
args: [--fix, --exit-non-zero-on-fix]

system/bytestream.py

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,15 @@
11
import io
2-
from typing import Literal, Optional, Union
2+
from typing import Literal, Optional
33

44

55
class Reader(io.BytesIO):
66
def __init__(
77
self,
8-
buffer: bytes = b"",
9-
endian: Union[Literal["little"], Literal["big"]] = "little",
8+
initial_buffer: bytes = b"",
9+
endian: Literal["little", "big"] = "little",
1010
):
11-
super().__init__(buffer)
12-
13-
self.buffer = buffer
14-
self.endian = endian
11+
super().__init__(initial_buffer)
12+
self.endian: Literal["little", "big"] = endian
1513

1614
def read_integer(self, length: int, signed=False) -> int:
1715
return int.from_bytes(self.read(length), self.endian, signed=signed)
@@ -47,10 +45,10 @@ def read_string(self) -> str:
4745
class Writer(io.BytesIO):
4846
def __init__(self, endian: Literal["little", "big"] = "little"):
4947
super().__init__()
50-
self.endian = endian
48+
self._endian: Literal["little", "big"] = endian
5149

5250
def write_int(self, integer: int, length: int = 1, signed: bool = False):
53-
self.write(integer.to_bytes(length, self.endian, signed=signed))
51+
self.write(integer.to_bytes(length, self._endian, signed=signed))
5452

5553
def write_ubyte(self, integer: int):
5654
self.write_int(integer)

system/languages/en-EU.json

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,12 +48,12 @@
4848
"clean_dirs_description": "Clear In and Out dirs",
4949

5050
"not_latest": "Not the latest version installed",
51-
"collecting_inf": "Collecting information...",
51+
"collecting_inf": "File: %s. Collecting information...",
5252
"about_sc": "About texture. Filename: %s (%d), Pixel type: %d, Size: %sx%s",
5353
"decompression_error": "Error while decompressing! Trying to decode as is...",
5454
"skip_not_installed": "%s isn't installed! Reinitialize",
55-
"detected_comp": "Detected %s compression!",
56-
"unk_type": "Unknown pixel type: %s",
55+
"detected_comp": "%s compression detected",
56+
"unknown_pixel_type": "Unknown pixel type: %s",
5757
"crt_pic": "Creating picture...",
5858
"join_pic": "Joining picture...",
5959
"png_save": "Saving to png...",
@@ -73,7 +73,6 @@
7373
"cut_sprites_process": "Cutting sprites... (%d/%d)",
7474
"place_sprites_process": "Placing sprites... (%d/%d)",
7575
"not_implemented": "This feature will be added in future updates.\nYou can follow XCoder updates here: github.com/Vorono4ka/XCoder",
76-
"dec_sc": "Decoding .sc file...",
7776
"error": "ERROR! (%s.%s: %s)",
7877
"e1sc1": "Overwrite SC sprites",
7978
"cgl": "Changelog:\n%s",
@@ -88,4 +87,4 @@
8887
"disabled": "Disabled",
8988

9089
"install_to_unlock": "Install '%s' to unlock more functions!"
91-
}
90+
}

system/languages/ru-RU.json

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,12 +48,12 @@
4848
"clean_dirs_description": "Очистить In и Out папки",
4949

5050
"not_latest": "Установлена не последняя версия",
51-
"collecting_inf": "Сбор информации...",
51+
"collecting_inf": "Файл: %s. Сбор информации...",
5252
"about_sc": "О текстуре. Файл: %s (%d), Тип пикселя: %d, Размеры: %dx%d",
5353
"decompression_error": "Ошибка распаковки! Проведите повторную инициализацию!",
5454
"skip_not_installed": "%s не установлен! Пропускаем...",
55-
"detected_comp": "Обнаружено %s сжатие!",
56-
"unk_type": "Неизвестный подтип: %s",
55+
"detected_comp": "Обнаружено сжатие: %s",
56+
"unknown_pixel_type": "Неизвестный подтип: %s",
5757
"crt_pic": "Создаём картинку...",
5858
"join_pic": "Соединяем картинку...",
5959
"png_save": "Сохраняем в png...",
@@ -73,7 +73,6 @@
7373
"cut_sprites_process": "Вырезаем спрайты... (%d/%d)",
7474
"place_sprites_process": "Ставим спрайты на место... (%d/%d)",
7575
"not_implemented": "Данная возможность будет добавлена в будущих обновлениях.\nЗа обновлениями XCoder вы можете следить здесь: github.com/Vorono4ka/XCoder",
76-
"dec_sc": "Декодируем SC...",
7776
"error": "ОШИБКА! (%s.%s: %s)",
7877
"e1sc1": "Перезапись спрайтов",
7978
"cgl": "Список изменений: \n%s",
@@ -88,4 +87,4 @@
8887
"disabled": "Выключено",
8988

9089
"install_to_unlock": "Установите '%s' чтобы открыть больше функций!"
91-
}
90+
}

system/languages/ua-UA.json

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,12 +48,12 @@
4848
"clean_dirs_description": "Очистити папки і файли в них",
4949

5050
"not_latest": "Встановлена не остання версія",
51-
"collecting_inf": "Збираємо інформацію...",
51+
"collecting_inf": "Файл: %s. Збираємо інформацію...",
5252
"about_sc": "Про текстуру. Назва файлу: %s (%d), Тип пікселів: %d, Величина: %sx%s",
5353
"decompression_error": "Помилка при розпакуванні! Намагаємся розпакувати як є...",
5454
"skip_not_installed": "%s не встановлений, повторіть налаштування",
55-
"detected_comp": "Виявлено %s компресію!",
56-
"unk_type": "Невідомий вид пікселів: %s",
55+
"detected_comp": "Виявлено компресію: %s",
56+
"unknown_pixel_type": "Невідомий вид пікселів: %s",
5757
"crt_pic": "Створюємо зоображеня...",
5858
"join_pic": "З'єднуємо зоображення...",
5959
"png_save": "Зберігаємо PNG...",
@@ -73,7 +73,6 @@
7373
"cut_sprites_process": "Обрізаємо спрайти... (%d/%d)",
7474
"place_sprites_process": "Вставляємо спрайти... (%d/%d)",
7575
"not_implemented": "Ця функція буде додана у наступних оновленнях.\nТи можеш сладкувати за оновленнями тут: github.com/Vorono4ka/XCoder",
76-
"dec_sc": "Розпаковуємо .sc файл...",
7776
"error": "Помилка! (%s.%s: %s)",
7877
"e1sc1": "Переписати SC спрайти",
7978
"cgl": "Список змін:\n%s",
@@ -88,4 +87,4 @@
8887
"disabled": "Виключено",
8988

9089
"install_to_unlock": "Встанови '%s' щоб розблокувати більше функції!"
91-
}
90+
}

system/lib/__init__.py

Lines changed: 64 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
11
import sys
22
import time
33

4+
from loguru import logger
5+
46
from system import clear
57
from system.lib.config import config
68
from system.lib.console import Console
79
from system.lib.features.directories import clear_directories
810
from system.lib.features.initialization import initialize
9-
from system.lib.features.update.check import check_update, check_for_outdated, get_tags
10-
from system.lib.menu import menu, Menu
11+
from system.lib.features.update.check import check_for_outdated, check_update, get_tags
12+
from system.lib.menu import Menu, menu
1113
from system.localization import locale
1214

13-
from loguru import logger
14-
1515
logger.remove()
1616
logger.add(
1717
"./logs/info/{time:YYYY-MM-DD}.log",
@@ -64,99 +64,121 @@ def refill_menu():
6464
import sc_compression
6565

6666
del sc_compression
67-
67+
except ImportError:
68+
logger.warning(locale.install_to_unlock % "sc-compression")
69+
else:
6870
from system.lib.features.csv.compress import compress_csv
6971
from system.lib.features.csv.decompress import decompress_csv
7072

7173
try:
7274
import PIL
7375

7476
del PIL
75-
76-
from system.lib.features.sc.decode import sc_decode
77-
from system.lib.features.sc.encode import sc_encode
78-
from system.lib.features.sc.decode_and_cut import decode_and_cut
79-
from system.lib.features.sc.assembly_encode import sc1_encode
77+
except ImportError:
78+
logger.warning(locale.install_to_unlock % "PILLOW")
79+
else:
80+
from system.lib.features.sc.decode import (
81+
decode_and_render_objects,
82+
decode_textures_only,
83+
)
84+
from system.lib.features.sc.encode import (
85+
collect_objects_and_encode,
86+
encode_textures_only,
87+
)
8088

8189
sc_category = Menu.Category(0, locale.sc_label)
8290
sc_category.add(
83-
Menu.Item(locale.decode_sc, locale.decode_sc_description, sc_decode)
91+
Menu.Item(
92+
name=locale.decode_sc,
93+
description=locale.decode_sc_description,
94+
handler=decode_textures_only,
95+
)
8496
)
8597
sc_category.add(
86-
Menu.Item(locale.encode_sc, locale.encode_sc_description, sc_encode)
98+
Menu.Item(
99+
name=locale.encode_sc,
100+
description=locale.encode_sc_description,
101+
handler=encode_textures_only,
102+
)
87103
)
88104
sc_category.add(
89105
Menu.Item(
90-
locale.decode_by_parts,
91-
locale.decode_by_parts_description,
92-
decode_and_cut,
106+
name=locale.decode_by_parts,
107+
description=locale.decode_by_parts_description,
108+
handler=decode_and_render_objects,
93109
)
94110
)
95111
sc_category.add(
96112
Menu.Item(
97-
locale.encode_by_parts,
98-
locale.encode_by_parts_description,
99-
sc1_encode,
113+
name=locale.encode_by_parts,
114+
description=locale.encode_by_parts_description,
115+
handler=collect_objects_and_encode,
100116
)
101117
)
102118
sc_category.add(
103119
Menu.Item(
104-
locale.overwrite_by_parts,
105-
locale.overwrite_by_parts_description,
106-
lambda: sc1_encode(True),
120+
name=locale.overwrite_by_parts,
121+
description=locale.overwrite_by_parts_description,
122+
handler=lambda: collect_objects_and_encode(True),
107123
)
108124
)
109125
menu.add_category(sc_category)
110-
except ImportError:
111-
logger.warning(locale.install_to_unlock % "PILLOW")
112126

113127
csv_category = Menu.Category(1, locale.csv_label)
114128
csv_category.add(
115129
Menu.Item(
116-
locale.decompress_csv, locale.decompress_csv_description, decompress_csv
130+
name=locale.decompress_csv,
131+
description=locale.decompress_csv_description,
132+
handler=decompress_csv,
117133
)
118134
)
119135
csv_category.add(
120136
Menu.Item(
121-
locale.compress_csv, locale.compress_csv_description, compress_csv
137+
name=locale.compress_csv,
138+
description=locale.compress_csv_description,
139+
handler=compress_csv,
122140
)
123141
)
124142
menu.add_category(csv_category)
125-
except ImportError:
126-
logger.warning(locale.install_to_unlock % "sc-compression")
127143

128144
other = Menu.Category(10, locale.other_features_label)
129145
other.add(
130-
Menu.Item(locale.check_update, locale.version % config.version, check_update)
146+
Menu.Item(
147+
name=locale.check_update,
148+
description=locale.version % config.version,
149+
handler=check_update,
150+
)
131151
)
132-
other.add(Menu.Item(locale.check_for_outdated, None, check_for_outdated))
152+
other.add(Menu.Item(name=locale.check_for_outdated, handler=check_for_outdated))
133153
other.add(
134154
Menu.Item(
135-
locale.reinit,
136-
locale.reinit_description,
137-
lambda: (initialize(), refill_menu()),
155+
name=locale.reinit,
156+
description=locale.reinit_description,
157+
handler=lambda: (initialize(), refill_menu()),
138158
)
139159
)
140160
other.add(
141161
Menu.Item(
142-
locale.change_language,
143-
locale.change_lang_description % config.language,
144-
lambda: (config.change_language(locale.change()), refill_menu()),
162+
name=locale.change_language,
163+
description=locale.change_lang_description % config.language,
164+
handler=lambda: (config.change_language(locale.change()), refill_menu()),
145165
)
146166
)
147167
other.add(
148168
Menu.Item(
149-
locale.clear_directories,
150-
locale.clean_dirs_description,
151-
lambda: clear_directories() if Console.question(locale.clear_qu) else -1,
169+
name=locale.clear_directories,
170+
description=locale.clean_dirs_description,
171+
handler=lambda: clear_directories()
172+
if Console.question(locale.clear_qu)
173+
else -1,
152174
)
153175
)
154176
other.add(
155177
Menu.Item(
156-
locale.toggle_update_auto_checking,
157-
locale.enabled if config.auto_update else locale.disabled,
158-
lambda: (config.toggle_auto_update(), refill_menu()),
178+
name=locale.toggle_update_auto_checking,
179+
description=locale.enabled if config.auto_update else locale.disabled,
180+
handler=lambda: (config.toggle_auto_update(), refill_menu()),
159181
)
160182
)
161-
other.add(Menu.Item(locale.exit, None, lambda: (clear(), exit())))
183+
other.add(Menu.Item(name=locale.exit, handler=lambda: (clear(), exit())))
162184
menu.add_category(other)

0 commit comments

Comments
 (0)