-
Notifications
You must be signed in to change notification settings - Fork 6
Test #65
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Test #65
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
2b51d26
Fix ruff linting issues and pytest failures (#57)
839c4aa
fix: configure pytest to support async tests natively (#58)
c2d5b65
Update format_and_test.yml
cbad924
Add documentation scraper and update docs.json (#59)
0c2619e
InkyPinkyPonky [no ci]
0a97612
Update high-level API to Layer 224 (#60)
3ca1f10
InkyPinkyPonky [no ci]
05aa52d
update pyproject.toml
9afafbe
fix(lint): resolve ASYNC240 errors by using anyio.Path (#61)
6eaecd3
InkyPinkyPonky [no ci]
22d0b5c
Add ButtonStyle enum and integrate it into button types (#62)
ee10722
InkyPinkyPonky [no ci]
230d3cc
update scrape_docs.py
50e9daa
feat: add icon field to high-level button classes (#64)
e290940
Apply suggestions from code review
d2320e2
InkyPinkyPonky [no ci]
a748f6a
Update __init__.py
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,180 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import json | ||
| import re | ||
| from pathlib import Path | ||
|
|
||
| import httpx | ||
| from lxml import html | ||
|
|
||
| ROOT_DIR = Path.cwd().absolute() | ||
| if ROOT_DIR.name == "dev_tools": | ||
| ROOT_DIR = ROOT_DIR.parent | ||
|
|
||
|
|
||
| SECTION_RE = re.compile(r"---(\w+)---") | ||
| COMBINATOR_RE = re.compile( | ||
| r"^([\w.]+)#([0-9a-f]+)\s(?:.*)=\s([\w<>.]+);$", | ||
| re.MULTILINE, | ||
| ) | ||
|
|
||
|
|
||
| BASE_URL = "https://corefork.telegram.org/" | ||
|
|
||
|
|
||
| MAX_TASKS = 10 | ||
|
|
||
|
|
||
| sem = asyncio.Semaphore(MAX_TASKS) | ||
|
|
||
|
|
||
| client = httpx.AsyncClient() | ||
|
|
||
|
|
||
| async def main(): | ||
| tl_data = parse_tl_file(ROOT_DIR / "compiler" / "api" / "source" / "main_api.tl") | ||
|
|
||
| it_count = ( | ||
| len(tl_data["constructor"]) + len(tl_data["method"]) + len(tl_data["type"]) | ||
| ) | ||
|
|
||
| print(f"Getting {it_count} objects from {BASE_URL}…") | ||
|
|
||
| doc_dict = {"type": {}, "constructor": {}, "method": {}} | ||
|
|
||
| tasks = [] | ||
|
|
||
| it_count_done = 0 | ||
|
|
||
| for it_type, items in tl_data.items(): | ||
| for it_name in items: | ||
| it_count_done += 1 | ||
| print(f"Parsing items {it_count_done}/{it_count}", end="\r", flush=True) | ||
| await sem.acquire() | ||
| tasks.append( | ||
| asyncio.create_task(get_object_data(it_type, it_name, doc_dict)), | ||
| ) | ||
|
|
||
| # Be sure that all tasks are done before continuing | ||
| await asyncio.gather(*tasks) | ||
|
|
||
| await client.aclose() | ||
|
|
||
| with (ROOT_DIR / "compiler" / "api" / "docs.json").open( | ||
| "w", | ||
| encoding="utf-8", | ||
| ) as f: | ||
| json.dump(doc_dict, f, indent=2, sort_keys=True) | ||
|
|
||
| print("\nDone!") | ||
|
|
||
|
|
||
| async def get_object_data(it_type: str, it_name: str, doc_dict: dict[str, dict]): | ||
| try: | ||
| request = await client.get(f"{BASE_URL}{it_type}/{it_name}") | ||
| if request.status_code != 200: | ||
| print(f"Error {request.status_code} for {it_type}/{it_name}\n") | ||
| return | ||
|
|
||
| tree = html.fromstring(request.text) | ||
|
|
||
| page_content_xp = tree.xpath("//div[@id='dev_page_content'][1]") | ||
| if not page_content_xp: | ||
| print(f"No page content for {it_type}/{it_name}") | ||
| return | ||
|
|
||
| page_content = page_content_xp[0] | ||
|
|
||
| # Get the description of the object - always used | ||
| desc_xp = page_content.xpath("./p[1]") | ||
|
|
||
| if desc_xp: | ||
| desc = desc_xp[0].text_content().strip() | ||
| else: | ||
| print(f"No description for {it_type}/{it_name}") | ||
| desc = "" | ||
|
|
||
| if it_type == "type": | ||
| doc_dict["type"][it_name] = {"desc": desc} | ||
| elif it_type in {"constructor", "method"}: | ||
| params_link_xp = page_content.xpath("./h3/a[@id='parameters'][1]") | ||
| if params_link_xp: | ||
| params_xp = ( | ||
| params_link_xp[0].getparent().getnext().xpath("./tbody[1]") | ||
| ) | ||
| if params_xp: | ||
| params = {} | ||
| for row in params_xp[0].xpath("./tr"): | ||
| cells = row.getchildren() | ||
| if len(cells) >= 3: | ||
| params[cells[0].text_content().strip()] = ( | ||
| cells[2].text_content().strip() | ||
| ) | ||
| else: | ||
| print(f"No parameters for {it_type}/{it_name}") | ||
| params = {} | ||
| else: | ||
| print(f"No parameters section for {it_type}/{it_name}") | ||
| params = {} | ||
|
|
||
| doc_dict[it_type][it_name] = {"desc": desc, "params": params} | ||
| else: | ||
| raise ValueError(f"Unknown type {it_type}") | ||
| finally: | ||
| sem.release() | ||
|
|
||
|
|
||
| def devectorize(ttype: str) -> str: | ||
| ivec = ttype.find("Vector<") | ||
| if ivec != -1: | ||
| return ttype[7:-1] | ||
|
|
||
| return ttype | ||
|
|
||
|
|
||
| def adjust_name(qualname: str) -> str: | ||
| names = qualname.split(".") | ||
|
|
||
| if len(names) == 2: | ||
| name = names[1][:1].upper() + names[1][1:] | ||
| return ".".join([names[0], name]) | ||
|
|
||
| return qualname[:1].upper() + qualname[1:] | ||
|
|
||
|
|
||
| def parse_tl_file(file_path: Path) -> dict[str, list[str]]: | ||
| lines = file_path.read_text().splitlines() | ||
|
|
||
| section = None | ||
|
|
||
| types = set() | ||
| constructors = set() | ||
| methods = set() | ||
|
|
||
| for line in lines: | ||
| if section_match := SECTION_RE.match(line): | ||
| section = section_match.group(1) | ||
| continue | ||
|
|
||
| if combinator_match := COMBINATOR_RE.match(line): | ||
| qualname, _id, qualtype = combinator_match.groups() | ||
|
|
||
| qualtype = devectorize(qualtype) | ||
|
|
||
| if section == "types": | ||
| types.add(qualtype) | ||
| constructors.add(adjust_name(qualname)) | ||
| elif section == "functions": | ||
| types.add(qualtype) | ||
| methods.add(adjust_name(qualname)) | ||
|
|
||
| return { | ||
| "type": sorted(types), | ||
| "constructor": sorted(constructors), | ||
| "method": sorted(methods), | ||
| } | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| asyncio.run(main()) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
suggestion (bug_risk): Creating the async HTTP client at import time can lead to lifecycle issues.
Creating
httpx.AsyncClient()at import time means any import of this module allocates a client and connection pool, even ifmain()is never called, and makes cleanup harder to guarantee if errors occur beforeclient.aclose().Prefer constructing and closing the client within
main()(or an async context manager), for example:This keeps side effects out of imports and ties the client lifetime to
main()execution.Suggested implementation:
To fully implement the lifecycle-safe client handling you described, you will also need to:
async def main(...):(or equivalent entrypoint) incompiler/api/scrape_docs.pyand change it to create the client in a context manager, e.g.:Update functions that currently rely on a global
client(e.g. ones doingawait client.get(...)) to instead acceptclient: httpx.AsyncClientas a parameter, and pass theclientobject through frommain().Remove any remaining references to a global
clientvariable in this module to ensure there is no accidental use of a stale or unclosed client.