72 lines
2.0 KiB
Python
72 lines
2.0 KiB
Python
from typing import Optional
|
|
from click import Path as PathArgument
|
|
from urllib.parse import urlparse
|
|
from asyncio import run
|
|
from click import group
|
|
from click import argument
|
|
from click import option
|
|
from click import pass_context
|
|
from functools import update_wrapper
|
|
from playwright.async_api import Route
|
|
from playwright.async_api import async_playwright
|
|
from re import compile as re_compile
|
|
from sys import exit
|
|
from urllib.request import urlopen
|
|
|
|
from theme_check.utils import get_default_screenshot_directory
|
|
from theme_check.utils import get_url_slug
|
|
|
|
|
|
def async_command(f):
|
|
def wrapper(*args, **kwargs):
|
|
return run(f(*args, **kwargs))
|
|
return update_wrapper(wrapper, f)
|
|
|
|
|
|
@group()
|
|
@pass_context
|
|
def cli(ctx):
|
|
pass
|
|
|
|
|
|
async def get_css(route: Route) -> None:
|
|
css_regex = re_compile(r'.*(?P<path>static/[\w-]*/style.css(.map)?).*')
|
|
mapped_path = css_regex.sub(r'file:///home/csechet/src/publik-base-theme/\g<path>', route.request.url)
|
|
with urlopen(mapped_path, 'r') as mapped_file:
|
|
mapped_content = mapped_file.read()
|
|
await route.fulfill(
|
|
body=mapped_content,
|
|
)
|
|
|
|
|
|
@cli.command()
|
|
@argument('url', type=str)
|
|
@option('-o', '--output-directory', type=PathArgument(), default=None)
|
|
@pass_context
|
|
@async_command
|
|
async def compare(ctx, url: str, output_directory: Optional[str]):
|
|
if output_directory is None:
|
|
output_directory = get_default_screenshot_directory()
|
|
output_directory.mkdir(parents=True)
|
|
|
|
async with async_playwright() as p:
|
|
browser = await p.firefox.launch()
|
|
context = await browser.new_context()
|
|
await context.route(re_compile(r'.*\.css(.map)?.*'), get_css)
|
|
page = await context.new_page()
|
|
await page.goto(url)
|
|
url_slug = get_url_slug(url)
|
|
screenshot_bytes = await page.screenshot()
|
|
with open(output_directory / url_slug, 'wb') as screenshot_file:
|
|
screenshot_file.write(screenshot_bytes)
|
|
|
|
await browser.close()
|
|
|
|
|
|
def main():
|
|
exit(cli())
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|