Skip to content

Commit 6749982

Browse files
refactor: refactor project with sourcery
1 parent b4c3eaf commit 6749982

60 files changed

Lines changed: 353 additions & 590 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

compiler/api/compiler.py

Lines changed: 25 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -135,11 +135,10 @@ def get_type_hint(type: str) -> str:
135135

136136
if is_core:
137137
return f"Optional[{type}] = None" if is_flag else type
138-
else:
139-
ns, name = type.split(".") if "." in type else ("", type)
140-
type = '"raw.base.' + ".".join([ns, name]).strip(".") + '"'
138+
ns, name = type.split(".") if "." in type else ("", type)
139+
type = '"raw.base.' + ".".join([ns, name]).strip(".") + '"'
141140

142-
return f'{type}{" = None" if is_flag else ""}'
141+
return f'{type}{" = None" if is_flag else ""}'
143142

144143

145144
def sort_args(args):
@@ -183,7 +182,7 @@ def get_docstring_arg_type(t: str):
183182
return "``bool``"
184183
else:
185184
return f"``{t.lower()}``"
186-
elif t == "TLObject" or t == "X":
185+
elif t in {"TLObject", "X"}:
187186
return "Any object from :obj:`~hydrogram.raw.types`"
188187
elif t == "!X":
189188
return "Any function from :obj:`~hydrogram.raw.functions`"
@@ -201,10 +200,7 @@ def get_references(t: str, kind: str):
201200
else:
202201
raise ValueError("Invalid kind")
203202

204-
if t:
205-
return "\n ".join(t), len(t)
206-
207-
return None, 0
203+
return ("\n ".join(t), len(t)) if t else (None, 0)
208204

209205

210206
# noinspection PyShadowingBuiltins
@@ -225,32 +221,23 @@ def start(format: bool = False):
225221
combinator_tmpl = f2.read()
226222

227223
with open(NOTICE_PATH, encoding="utf-8") as f:
228-
notice = []
229-
230-
for line in f.readlines():
231-
notice.append(f"# {line}".strip())
232-
224+
notice = [f"# {line}".strip() for line in f]
233225
notice = "\n".join(notice)
234226

235-
section = None
236227
layer = None
237228
combinators = []
238229

230+
section = None
239231
for line in schema:
240-
# Check for section changer lines
241-
section_match = SECTION_RE.match(line)
242-
if section_match:
232+
if section_match := SECTION_RE.match(line):
243233
section = section_match.group(1)
244234
continue
245235

246-
# Save the layer version
247-
layer_match = LAYER_RE.match(line)
248-
if layer_match:
236+
if layer_match := LAYER_RE.match(line):
249237
layer = layer_match.group(1)
250238
continue
251239

252-
combinator_match = COMBINATOR_RE.match(line)
253-
if combinator_match:
240+
if combinator_match := COMBINATOR_RE.match(line):
254241
# noinspection PyShadowingBuiltins
255242
qualname, id, qualtype = combinator_match.groups()
256243

@@ -350,14 +337,7 @@ def start(format: bool = False):
350337
references, ref_count = get_references(qualtype, "types")
351338

352339
if references:
353-
docstring += (
354-
f"\n\n Functions:\n This object can be returned by "
355-
f"{ref_count} function{'s' if ref_count > 1 else ''}.\n\n"
356-
f" .. currentmodule:: hydrogram.raw.functions\n\n"
357-
f" .. autosummary::\n"
358-
f" :nosignatures:\n\n"
359-
f" " + references
360-
)
340+
docstring += f"\n\n Functions:\n This object can be returned by {ref_count} function{'s' if ref_count > 1 else ''}.\n\n .. currentmodule:: hydrogram.raw.functions\n\n .. autosummary::\n :nosignatures:\n\n {references}"
361341

362342
with open(dir_path / f"{snake(module)}.py", "w") as f:
363343
f.write(
@@ -392,7 +372,7 @@ def start(format: bool = False):
392372

393373
combinator_docs = docs["method"] if c.section == "functions" else docs["constructor"]
394374

395-
for i, arg in enumerate(sorted_args):
375+
for arg in sorted_args:
396376
arg_name, arg_type = arg
397377
is_optional = FLAGS_RE.match(arg_type)
398378
arg_type = arg_type.split("?")[-1]
@@ -402,31 +382,21 @@ def start(format: bool = False):
402382
arg_docs = arg_docs["params"].get(arg_name, "N/A") if arg_docs else "N/A"
403383

404384
docstring_args.append(
405-
"{} ({}{}):\n {}\n".format(
406-
arg_name,
407-
get_docstring_arg_type(arg_type),
408-
", *optional*" if is_optional else "",
409-
arg_docs,
410-
)
385+
f'{arg_name} ({get_docstring_arg_type(arg_type)}{", *optional*" if is_optional else ""}):\n {arg_docs}\n'
411386
)
412387

413388
if c.section == "types":
414389
constructor_docs = docs["constructor"].get(c.qualname, None)
415390

416-
if constructor_docs:
417-
constructor_docs = constructor_docs["desc"]
418-
else:
419-
constructor_docs = "Telegram API type."
420-
391+
constructor_docs = (
392+
constructor_docs["desc"] if constructor_docs else "Telegram API type."
393+
)
421394
docstring += constructor_docs + "\n"
422395
docstring += f"\n Constructor of :obj:`~hydrogram.raw.base.{c.qualtype}`."
396+
elif function_docs := docs["method"].get(c.qualname, None):
397+
docstring += function_docs["desc"] + "\n"
423398
else:
424-
function_docs = docs["method"].get(c.qualname, None)
425-
426-
if function_docs:
427-
docstring += function_docs["desc"] + "\n"
428-
else:
429-
docstring += "Telegram API function."
399+
docstring += "Telegram API function."
430400

431401
docstring += f"\n\n Details:\n - Layer: ``{layer}``\n - ID: ``{c.id[2:].upper()}``\n\n"
432402
docstring += " Parameters:\n " + (
@@ -439,14 +409,7 @@ def start(format: bool = False):
439409
references, count = get_references(c.qualname, "constructors")
440410

441411
if references:
442-
docstring += (
443-
f"\n Functions:\n This object can be returned by "
444-
f"{count} function{'s' if count > 1 else ''}.\n\n"
445-
f" .. currentmodule:: hydrogram.raw.functions\n\n"
446-
f" .. autosummary::\n"
447-
f" :nosignatures:\n\n"
448-
f" " + references
449-
)
412+
docstring += f"\n Functions:\n This object can be returned by {count} function{'s' if count > 1 else ''}.\n\n .. currentmodule:: hydrogram.raw.functions\n\n .. autosummary::\n :nosignatures:\n\n {references}"
450413

451414
write_types = read_types = "" if c.has_flags else "# No flags\n "
452415

@@ -503,20 +466,10 @@ def start(format: bool = False):
503466

504467
write_types += "\n "
505468
write_types += f"if self.{arg_name} is not None:\n "
506-
write_types += "b.write(Vector(self.{}{}))\n ".format(
507-
arg_name,
508-
f", {sub_type.title()}" if sub_type in CORE_TYPES else "",
509-
)
469+
write_types += f'b.write(Vector(self.{arg_name}{f", {sub_type.title()}" if sub_type in CORE_TYPES else ""}))\n '
510470

511471
read_types += "\n "
512-
read_types += (
513-
"{} = TLObject.read(b{}) if flags{} & (1 << {}) else []\n ".format(
514-
arg_name,
515-
f", {sub_type.title()}" if sub_type in CORE_TYPES else "",
516-
number,
517-
index,
518-
)
519-
)
472+
read_types += f'{arg_name} = TLObject.read(b{f", {sub_type.title()}" if sub_type in CORE_TYPES else ""}) if flags{number} & (1 << {index}) else []\n '
520473
else:
521474
write_types += "\n "
522475
write_types += f"if self.{arg_name} is not None:\n "
@@ -525,28 +478,20 @@ def start(format: bool = False):
525478
read_types += "\n "
526479
read_types += f"{arg_name} = TLObject.read(b) if flags{number} & (1 << {index}) else None\n "
527480
else:
481+
write_types += "\n "
528482
if arg_type in CORE_TYPES:
529-
write_types += "\n "
530483
write_types += f"b.write({arg_type.title()}(self.{arg_name}))\n "
531484

532485
read_types += "\n "
533486
read_types += f"{arg_name} = {arg_type.title()}.read(b)\n "
534487
elif "vector" in arg_type.lower():
535488
sub_type = arg_type.split("<")[1][:-1]
536489

537-
write_types += "\n "
538-
write_types += "b.write(Vector(self.{}{}))\n ".format(
539-
arg_name,
540-
f", {sub_type.title()}" if sub_type in CORE_TYPES else "",
541-
)
490+
write_types += f'b.write(Vector(self.{arg_name}{f", {sub_type.title()}" if sub_type in CORE_TYPES else ""}))\n '
542491

543492
read_types += "\n "
544-
read_types += "{} = TLObject.read(b{})\n ".format(
545-
arg_name,
546-
f", {sub_type.title()}" if sub_type in CORE_TYPES else "",
547-
)
493+
read_types += f'{arg_name} = TLObject.read(b{f", {sub_type.title()}" if sub_type in CORE_TYPES else ""})\n '
548494
else:
549-
write_types += "\n "
550495
write_types += f"b.write(self.{arg_name}.write())\n "
551496

552497
read_types += "\n "

compiler/docs/compiler.py

Lines changed: 30 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def build(path, level=0):
5050
if not i.startswith("__"):
5151
build("/".join([path, i]), level=level + 1)
5252
except NotADirectoryError:
53-
with open(path + "/" + i, encoding="utf-8") as f:
53+
with open(f"{path}/{i}", encoding="utf-8") as f:
5454
p = ast.parse(f.read())
5555

5656
for node in ast.walk(p):
@@ -60,20 +60,20 @@ def build(path, level=0):
6060
else:
6161
continue
6262

63-
full_path = os.path.basename(path) + "/" + snek(name).replace("_", "-") + ".rst"
63+
full_path = f"{os.path.basename(path)}/" + snek(name).replace("_", "-") + ".rst"
6464

6565
if level:
66-
full_path = base + "/" + full_path
66+
full_path = f"{base}/{full_path}"
6767

6868
namespace = path.split("/")[-1]
6969
if namespace in ["base", "types", "functions"]:
7070
namespace = ""
7171

72-
full_name = f"{(namespace + '.') if namespace else ''}{name}"
72+
full_name = f"{f'{namespace}.' if namespace else ''}{name}"
7373

74-
os.makedirs(os.path.dirname(DESTINATION + "/" + full_path), exist_ok=True)
74+
os.makedirs(os.path.dirname(f"{DESTINATION}/{full_path}"), exist_ok=True)
7575

76-
with open(DESTINATION + "/" + full_path, "w", encoding="utf-8") as f:
76+
with open(f"{DESTINATION}/{full_path}", "w", encoding="utf-8") as f:
7777
f.write(
7878
page_template.format(
7979
title=full_name,
@@ -99,20 +99,20 @@ def build(path, level=0):
9999
entities.append(f'{i} <{snek(i).replace("_", "-")}>')
100100

101101
if k != base:
102-
inner_path = base + "/" + k + "/index" + ".rst"
102+
inner_path = f"{base}/{k}/index.rst"
103103
module = f"hydrogram.raw.{base}.{k}"
104104
else:
105105
for i in sorted(all_entities, reverse=True):
106106
if i != base:
107107
entities.insert(0, f"{i}/index")
108108

109-
inner_path = base + "/index" + ".rst"
109+
inner_path = f"{base}/index.rst"
110110
module = f"hydrogram.raw.{base}"
111111

112-
with open(DESTINATION + "/" + inner_path, "w", encoding="utf-8") as f:
112+
with open(f"{DESTINATION}/{inner_path}", "w", encoding="utf-8") as f:
113113
if k == base:
114114
f.write(":tocdepth: 1\n\n")
115-
k = "Raw " + k
115+
k = f"Raw {k}"
116116

117117
f.write(
118118
toctree.format(
@@ -333,23 +333,23 @@ def get_title_list(s: str) -> list:
333333
""",
334334
}
335335

336-
root = HYDROGRAM_API_DEST + "/methods"
336+
root = f"{HYDROGRAM_API_DEST}/methods"
337337

338338
shutil.rmtree(root, ignore_errors=True)
339339
os.mkdir(root)
340340

341-
with open(HOME + "/template/methods.rst") as f:
341+
with open(f"{HOME}/template/methods.rst") as f:
342342
template = f.read()
343343

344-
with open(root + "/index.rst", "w") as f:
344+
with open(f"{root}/index.rst", "w") as f:
345345
fmt_keys = {}
346346

347347
for k, v in categories.items():
348348
name, *methods = get_title_list(v)
349-
fmt_keys.update({k: "\n ".join(f"{m} <{m}>" for m in methods)})
349+
fmt_keys[k] = "\n ".join(f"{m} <{m}>" for m in methods)
350350

351351
for method in methods:
352-
with open(root + f"/{method}.rst", "w") as f2:
352+
with open(f"{root}/{method}.rst", "w") as f2:
353353
title = f"{method}()"
354354

355355
f2.write(title + "\n" + "=" * len(title) + "\n\n")
@@ -358,7 +358,7 @@ def get_title_list(s: str) -> list:
358358
functions = ["idle", "compose"]
359359

360360
for func in functions:
361-
with open(root + f"/{func}.rst", "w") as f2:
361+
with open(f"{root}/{func}.rst", "w") as f2:
362362
title = f"{func}()"
363363

364364
f2.write(title + "\n" + "=" * len(title) + "\n\n")
@@ -495,25 +495,25 @@ def get_title_list(s: str) -> list:
495495
""",
496496
}
497497

498-
root = HYDROGRAM_API_DEST + "/types"
498+
root = f"{HYDROGRAM_API_DEST}/types"
499499

500500
shutil.rmtree(root, ignore_errors=True)
501501
os.mkdir(root)
502502

503-
with open(HOME + "/template/types.rst") as f:
503+
with open(f"{HOME}/template/types.rst") as f:
504504
template = f.read()
505505

506-
with open(root + "/index.rst", "w") as f:
506+
with open(f"{root}/index.rst", "w") as f:
507507
fmt_keys = {}
508508

509509
for k, v in categories.items():
510510
name, *types = get_title_list(v)
511511

512-
fmt_keys.update({k: "\n ".join(types)})
512+
fmt_keys[k] = "\n ".join(types)
513513

514514
# noinspection PyShadowingBuiltins
515515
for type in types:
516-
with open(root + f"/{type}.rst", "w") as f2:
516+
with open(f"{root}/{type}.rst", "w") as f2:
517517
title = f"{type}"
518518

519519
f2.write(title + "\n" + "=" * len(title) + "\n\n")
@@ -606,35 +606,29 @@ def get_title_list(s: str) -> list:
606606
""",
607607
}
608608

609-
root = HYDROGRAM_API_DEST + "/bound-methods"
609+
root = f"{HYDROGRAM_API_DEST}/bound-methods"
610610

611611
shutil.rmtree(root, ignore_errors=True)
612612
os.mkdir(root)
613613

614-
with open(HOME + "/template/bound-methods.rst") as f:
614+
with open(f"{HOME}/template/bound-methods.rst") as f:
615615
template = f.read()
616616

617-
with open(root + "/index.rst", "w") as f:
617+
with open(f"{root}/index.rst", "w") as f:
618618
fmt_keys = {}
619619

620620
for k, v in categories.items():
621621
name, *bound_methods = get_title_list(v)
622622

623-
fmt_keys.update(
624-
{f"{k}_hlist": "\n ".join(f"- :meth:`~{bm}`" for bm in bound_methods)}
625-
)
623+
fmt_keys[f"{k}_hlist"] = "\n ".join(f"- :meth:`~{bm}`" for bm in bound_methods)
626624

627-
fmt_keys.update(
628-
{
629-
f"{k}_toctree": "\n ".join(
630-
"{} <{}>".format(bm.split(".")[1], bm) for bm in bound_methods
631-
)
632-
}
625+
fmt_keys[f"{k}_toctree"] = "\n ".join(
626+
"{} <{}>".format(bm.split(".")[1], bm) for bm in bound_methods
633627
)
634628

635629
# noinspection PyShadowingBuiltins
636630
for bm in bound_methods:
637-
with open(root + f"/{bm}.rst", "w") as f2:
631+
with open(f"{root}/{bm}.rst", "w") as f2:
638632
title = f"{bm}()"
639633

640634
f2.write(title + "\n" + "=" * len(title) + "\n\n")
@@ -649,10 +643,10 @@ def start():
649643

650644
shutil.rmtree(DESTINATION, ignore_errors=True)
651645

652-
with open(HOME + "/template/page.txt", encoding="utf-8") as f:
646+
with open(f"{HOME}/template/page.txt", encoding="utf-8") as f:
653647
page_template = f.read()
654648

655-
with open(HOME + "/template/toctree.txt", encoding="utf-8") as f:
649+
with open(f"{HOME}/template/toctree.txt", encoding="utf-8") as f:
656650
toctree = f.read()
657651

658652
generate(TYPES_PATH, TYPES_BASE)

0 commit comments

Comments
 (0)