Skip to content

Commit d625536

Browse files
committed
refactor: why is config a class?
??? girl what ¿¿¿
1 parent 0df0f7e commit d625536

File tree

7 files changed

+130
-132
lines changed

7 files changed

+130
-132
lines changed

src/reCBZ/__main__.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,15 @@
66
from pathlib import Path
77

88
import reCBZ
9+
import reCBZ.config as config
910
from reCBZ import wrappers, util
10-
from reCBZ.config import Config
1111
from reCBZ.profiles import profiles_list
1212

1313

1414
def print_title() -> None:
15-
align = int(Config.term_width() / 2) - 11
15+
align = int(config.term_width() / 2) - 11
1616
if align > 21: align = 21
17-
if align + 22 > Config.term_width() or align < 0:
17+
if align + 22 > config.term_width() or align < 0:
1818
align = 0
1919
align = align * ' '
2020
title_multiline = (f"{align}┬─┐┌─┐┌─┐┌┐ ┌─┐ ┌─┐┬ ┬\n"
@@ -202,7 +202,7 @@ def main():
202202
help="disable downscaling with --size")
203203
images_group.add_argument( "--nowebp",
204204
default=None,
205-
const=f'{Config.blacklisted_fmts} webp webpll',
205+
const=f'{config.blacklisted_fmts} webp webpll',
206206
dest="blacklisted_fmts",
207207
action="store_const",
208208
help="exclude webp from --auto and --assist")
@@ -278,7 +278,7 @@ def main():
278278
if args.profile is not None:
279279
prof_name = args.profile.upper()
280280
try:
281-
Config.set_profile(prof_name)
281+
config.set_profile(prof_name)
282282
except ValueError:
283283
print(f'{reCBZ.CMDNAME}: profile: invalid option "{prof_name}"')
284284
exit(1)
@@ -288,20 +288,20 @@ def main():
288288
try:
289289
newsize = tuple(map(int,newsize.split('x')))
290290
assert len(newsize) == 2
291-
Config.img_size = newsize
291+
config.img_size = newsize
292292
except (ValueError, AssertionError):
293293
print(f'{reCBZ.CMDNAME}: size: invalid option "{args.size_str}"')
294294
exit(1)
295295

296296
# this is probably not the most pythonic way to do this
297297
# I'm sorry guido-san...
298298
for key, val in args.__dict__.items():
299-
if key in Config.__dict__.keys() and val is not None:
300-
setattr(Config, key, val)
299+
if key in config.__dict__.keys() and val is not None:
300+
setattr(config, key, val)
301301

302302
if args.show_config:
303303
private = re.compile('^[A-Z]|\\<classmethod|^_')
304-
for key, val in Config.__dict__.items():
304+
for key, val in config.__dict__.items():
305305
if not private.search(f'{key} = {val}'):
306306
print(f"{key} = {val}")
307307

@@ -346,7 +346,7 @@ def main():
346346
new = []
347347
for filename in paths:
348348
comment = zipfile.ZipFile(filename).comment
349-
if not comment == str.encode(Config.ZIPCOMMENT):
349+
if not comment == str.encode(config.ZIPCOMMENT):
350350
new.append(filename)
351351
diff = len(paths) - len(new)
352352
if diff > 0:
@@ -358,7 +358,7 @@ def main():
358358

359359
# everything passed. do stuff
360360
exit_code = 0
361-
if reCBZ.SHOWTITLE and Config.loglevel >= 0: print_title()
361+
if reCBZ.SHOWTITLE and config.loglevel >= 0: print_title()
362362
try:
363363
if args.mode == 'join':
364364
wrappers.join_archives(paths[0], paths[1:])

src/reCBZ/archive.py

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
import reCBZ
1313
from reCBZ.formats import *
14-
from reCBZ.config import Config
14+
import reCBZ.config as config
1515
from reCBZ.util import mylog, map_workers, worker_sigint_CTRL_C, human_sort
1616

1717
# TODO:
@@ -105,17 +105,16 @@ def __init__(self, filename:str):
105105
self.fp:Path = Path(filename)
106106
else:
107107
raise ValueError(f"{filename}: invalid path")
108-
self.opt_ignore = Config.ignore_err
109-
self._zip_compress = Config.compress_zip
110-
self._fmt_blacklist = Config.blacklisted_fmts
111-
self._fmt_samples = Config.samples_count
112-
self._pages_format = Config.img_format
113-
self._pages_quality = Config.img_quality
114-
self._pages_size = Config.img_size
115-
self._pages_bw = Config.grayscale
116-
self._pages_noup = Config.no_upscale
117-
self._pages_nodown = Config.no_downscale
118-
self._pages_filter = Config.RESAMPLE_TYPE
108+
self.opt_ignore = config.ignore_err
109+
self._fmt_blacklist = config.blacklisted_fmts
110+
self._fmt_samples = config.samples_count
111+
self._pages_format = config.img_format
112+
self._pages_quality = config.img_quality
113+
self._pages_size = config.img_size
114+
self._pages_bw = config.grayscale
115+
self._pages_noup = config.no_upscale
116+
self._pages_nodown = config.no_downscale
117+
self._pages_filter = config.RESAMPLE_TYPE
119118
self._index:list = []
120119
self._chapter_lengths = []
121120
self._chapters = []
@@ -313,11 +312,11 @@ def _write_zip(self, savepath):
313312
dest += f'{Archive.chapter_prefix}{i+1:0{lead_zeroes}d}/'
314313
dest += f'{page.fp.relative_to(local_parent_dir)}'
315314
dest = Path(dest)
316-
if self._zip_compress:
315+
if config.compress_zip:
317316
new_zip.write(page.fp, dest, ZIP_DEFLATED, 9)
318317
else:
319318
new_zip.write(page.fp, dest, ZIP_STORED)
320-
new_zip.comment = str.encode(Config.ZIPCOMMENT)
319+
new_zip.comment = str.encode(config.ZIPCOMMENT)
321320
new_zip.close()
322321
return savepath
323322

src/reCBZ/config.py

Lines changed: 63 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -7,79 +7,78 @@
77
import tomli as tomllib
88
from PIL import Image
99

10-
from reCBZ.profiles import profiles_list
1110
import reCBZ
11+
from reCBZ.profiles import profiles_list
1212

13+
# LANCZOS sacrifices performance for optimal upscale quality
14+
RESAMPLE_TYPE = Image.Resampling.LANCZOS
15+
ZIPCOMMENT:str = 'repacked with reCBZ'
1316
_cfg = tomllib.loads(resources.read_text("reCBZ", "defaults.toml"))
1417

18+
overwrite:bool = _cfg["general"]["overwrite"]
19+
ignore_err:bool = _cfg["general"]["ignore"]
20+
force_write:bool = _cfg["general"]["force"]
21+
no_write:bool = _cfg["general"]["nowrite"]
22+
loglevel:int = _cfg["general"]["loglevel"]
23+
processes:int = _cfg["general"]["processes"]
24+
samples_count:int = _cfg["general"]["samplecount"]
25+
archive_format:str = _cfg["archive"]["archiveformat"]
26+
compress_zip:int = _cfg["archive"]["compresszip"]
27+
right_to_left:bool = _cfg["archive"]["righttoleft"]
28+
img_format:str = _cfg["image"]["imageformat"]
29+
img_quality:int = _cfg["image"]["quality"]
30+
img_size:tuple = _cfg["image"]["size"]
31+
no_upscale:bool = _cfg["image"]["noupscale"]
32+
no_downscale:bool = _cfg["image"]["nodownscale"]
33+
grayscale:bool = _cfg["image"]["grayscale"]
34+
blacklisted_fmts:str = _cfg["image"]["blacklistedfmts"]
35+
ebook_profile = None
1536

16-
class Config():
17-
# LANCZOS sacrifices performance for optimal upscale quality
18-
RESAMPLE_TYPE = Image.Resampling.LANCZOS
19-
ZIPCOMMENT:str = 'repacked with reCBZ'
2037

21-
overwrite:bool = _cfg["general"]["overwrite"]
22-
ignore_err:bool = _cfg["general"]["ignore"]
23-
force_write:bool = _cfg["general"]["force"]
24-
no_write:bool = _cfg["general"]["nowrite"]
25-
loglevel:int = _cfg["general"]["loglevel"]
26-
processes:int = _cfg["general"]["processes"]
27-
samples_count:int = _cfg["general"]["samplecount"]
28-
archive_format:str = _cfg["archive"]["archiveformat"]
29-
compress_zip:int = _cfg["archive"]["compresszip"]
30-
right_to_left:bool = _cfg["archive"]["righttoleft"]
31-
img_format:str = _cfg["image"]["imageformat"]
32-
img_quality:int = _cfg["image"]["quality"]
33-
img_size:tuple = _cfg["image"]["size"]
34-
no_upscale:bool = _cfg["image"]["noupscale"]
35-
no_downscale:bool = _cfg["image"]["nodownscale"]
36-
grayscale:bool = _cfg["image"]["grayscale"]
37-
blacklisted_fmts:str = _cfg["image"]["blacklistedfmts"]
38-
ebook_profile = None
38+
def pcount() -> int:
39+
default_value = 4
40+
if processes > 0:
41+
return processes
42+
else:
43+
logical_cores = os.cpu_count()
44+
try:
45+
assert logical_cores is not None
46+
if logical_cores not in range(1,3):
47+
logical_cores -= 1 # be kind
48+
return logical_cores
49+
except AssertionError:
50+
return default_value
3951

40-
@classmethod
41-
def pcount(cls) -> int:
42-
default_value = 4
43-
if cls.processes > 0:
44-
return cls.processes
45-
else:
46-
logical_cores = os.cpu_count()
47-
try:
48-
assert logical_cores is not None
49-
if logical_cores not in range(1,3):
50-
logical_cores -= 1 # be kind
51-
return logical_cores
52-
except AssertionError:
53-
return default_value
5452

55-
@classmethod
56-
def term_width(cls) -> int:
57-
# limit output message width. ignored if verbose
58-
try:
59-
TERM_COLUMNS, TERM_LINES = os.get_terminal_size()
60-
assert TERM_COLUMNS > 0 and TERM_LINES > 0
61-
if TERM_COLUMNS > 120: max_width = 120
62-
elif TERM_COLUMNS < 30: max_width = 30
63-
else: max_width = TERM_COLUMNS - 2
64-
except (AssertionError, OSError):
65-
print("[!] Can't determine terminal size, defaulting to 78 cols")
66-
max_width = 78
67-
return max_width
53+
def term_width() -> int:
54+
# limit output message width. ignored if verbose
55+
try:
56+
TERM_COLUMNS, TERM_LINES = os.get_terminal_size()
57+
assert TERM_COLUMNS > 0 and TERM_LINES > 0
58+
if TERM_COLUMNS > 120: max_width = 120
59+
elif TERM_COLUMNS < 30: max_width = 30
60+
else: max_width = TERM_COLUMNS - 2
61+
except (AssertionError, OSError):
62+
print("[!] Can't determine terminal size, defaulting to 78 cols")
63+
max_width = 78
64+
return max_width
65+
66+
67+
def set_profile(name) -> None:
68+
global blacklisted_fmts, ebook_profile, archive_format, img_size, grayscale
69+
dic = {prof.nickname:prof for prof in profiles_list}
70+
try:
71+
profile = dic[name]
72+
except KeyError:
73+
raise ValueError(f"Invalid profile '{name}'")
74+
grayscale = profile.gray
75+
img_size = profile.size
76+
# if profile.prefer_epub:
77+
archive_format = 'epub'
78+
ebook_profile = profile
79+
blacklisted_fmts += profile.blacklisted_fmts
6880

69-
@classmethod
70-
def set_profile(cls, name) -> None:
71-
dic = {prof.nickname:prof for prof in profiles_list}
72-
try:
73-
profile = dic[name]
74-
except KeyError:
75-
raise ValueError(f"Invalid profile '{name}'")
76-
cls.grayscale = profile.gray
77-
cls.img_size = profile.size
78-
# if profile.prefer_epub:
79-
cls.archive_format = 'epub'
80-
cls.ebook_profile = profile
81-
cls.blacklisted_fmts += profile.blacklisted_fmts
8281

8382
preload_profile = _cfg["archive"]["ebookprofile"]
8483
if preload_profile != '':
85-
Config.set_profile(preload_profile.upper())
84+
set_profile(preload_profile.upper())

src/reCBZ/epub.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
from ebooklib import epub
2323

2424
from reCBZ.util import mylog
25-
from reCBZ.config import Config
25+
import reCBZ.config as config
2626

2727
POP_COVER = True
2828

@@ -54,11 +54,11 @@ def single_chapter_epub(name:str, pages:list) -> str:
5454
for page_i, page in enumerate(pages, start=1):
5555
static_dest = f'static/{page_i}{page.fmt.ext[0]}'
5656
mime_type = page.fmt.mime
57-
if Config.ebook_profile is not None:
57+
if config.ebook_profile is not None:
5858
if page.landscape:
59-
height, width = Config.ebook_profile.size
59+
height, width = config.ebook_profile.size
6060
else:
61-
width, height = Config.ebook_profile.size
61+
width, height = config.ebook_profile.size
6262
else:
6363
width, height = page.size
6464
size_str = f'width={width} height={height}'
@@ -95,18 +95,18 @@ def single_chapter_epub(name:str, pages:list) -> str:
9595
book.add_item(epub.EpubNav())
9696
book.spine = (page for page in spine)
9797

98-
if Config.right_to_left is True:
98+
if config.right_to_left is True:
9999
book.set_direction('rtl')
100100
# formerly necessary. turns out it's not an issue if you don't set lr in
101101
# the first place
102102
# if 'Kindle' in str(Config.ebook_profile):
103103
# book.add_metadata(None, 'meta', '', {'name': 'primary-writing-mode',
104104
# 'content': 'horizontal-rl'}),
105105

106-
if Config.ebook_profile is not None:
107-
for tag in Config.ebook_profile.epub_properties:
106+
if config.ebook_profile is not None:
107+
for tag in config.ebook_profile.epub_properties:
108108
book.add_metadata(*tag)
109-
source_fp = f'{name}{Config.ebook_profile.epub_ext}'
109+
source_fp = f'{name}{config.ebook_profile.epub_ext}'
110110
else:
111111
source_fp = f'{name}.epub'
112112

@@ -142,11 +142,11 @@ def multi_chapter_epub(name:str, chapters:list) -> str:
142142
chapter_name = f'Ch {chapter_i:0{lead_zeroes}d}'
143143
static_dest = f'static/{chapter_name}/{page_i}{page.fmt.ext[0]}'
144144
mime_type = page.fmt.mime
145-
if Config.ebook_profile is not None:
145+
if config.ebook_profile is not None:
146146
if page.landscape:
147-
height, width = Config.ebook_profile.size
147+
height, width = config.ebook_profile.size
148148
else:
149-
width, height = Config.ebook_profile.size
149+
width, height = config.ebook_profile.size
150150
else:
151151
width, height = page.size
152152
size_str = f'width={width} height={height}'
@@ -174,13 +174,13 @@ def multi_chapter_epub(name:str, chapters:list) -> str:
174174
book.add_item(epub.EpubNav())
175175
book.spine = ['nav', *(page for page in spine)]
176176

177-
if Config.right_to_left is True:
177+
if config.right_to_left is True:
178178
book.set_direction('rtl')
179179

180-
if Config.ebook_profile is not None:
181-
for tag in Config.ebook_profile.epub_properties:
180+
if config.ebook_profile is not None:
181+
for tag in config.ebook_profile.epub_properties:
182182
book.add_metadata(*tag)
183-
source_fp = f'{name}{Config.ebook_profile.epub_ext}'
183+
source_fp = f'{name}{config.ebook_profile.epub_ext}'
184184
else:
185185
source_fp = f'{name}.epub'
186186

src/reCBZ/formats.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
from PIL import Image
2-
from reCBZ.config import Config
2+
import reCBZ.config as config
33

44

55
class LossyFmt():
66
lossless:bool = False
7-
quality:int = Config.img_quality
7+
quality:int = config.img_quality
88

99

1010
class LosslessFmt():

0 commit comments

Comments
 (0)