Skip to content
This repository has been archived by the owner on Jun 2, 2024. It is now read-only.

Commit

Permalink
feat: introduce --from-pr opt in install script
Browse files Browse the repository at this point in the history
  • Loading branch information
nullishamy committed May 20, 2024
1 parent 9e57952 commit 7cdd174
Showing 1 changed file with 118 additions and 23 deletions.
141 changes: 118 additions & 23 deletions install.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
#!/usr/bin/env python3

import os, zipfile, argparse, logging, io
from typing import Optional
from pathlib import Path
from dataclasses import dataclass
from urllib.request import urlopen, Request
from urllib.parse import urlparse

logger = logging.getLogger("catppuccin-gtk")
logger.setLevel(logging.DEBUG)
Expand All @@ -20,6 +22,17 @@ class InstallContext:
dest: Path
link: bool

def build_info(self, include_url=True) -> str:
url = build_release_url(self)
info = f"""Installation info:
flavor: {self.flavor}
accent: {self.accent}
dest: {self.dest.absolute()}
link: {self.link}"""
if include_url:
info += f"\nremote_url: {url}"
return info


def parse_args():
parser = argparse.ArgumentParser()
Expand Down Expand Up @@ -53,6 +66,13 @@ def parse_args():
help="Accent of the theme.",
)

parser.add_argument(
"--from-pr",
type=str,
dest="from_pr",
help="Pull artifacts from a PR instead of a release",
)

parser.add_argument(
"--dest",
"-d",
Expand Down Expand Up @@ -80,21 +100,27 @@ def build_release_url(ctx: InstallContext) -> str:
return f"{repo_root}/{release}/{zip_name}"


def install(ctx: InstallContext):
url = build_release_url(ctx)
build_info = f"""Installation info:
flavor: {ctx.flavor}
accent: {ctx.accent}
dest: {ctx.dest.absolute()}
link: {ctx.link}
def fetch_zip(url: str) -> Optional[zipfile.ZipFile]:
token = "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"
req = Request(
url,
method="GET",
headers={
"User-Agent": "curl/8.4.0",
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
},
)

remote_url: {url}"""
logger.info(build_info)
httprequest = Request(url)
# NOTE: This !!MUST!! be unredirected, otherwise the destination CDN will get confused
req.add_unredirected_header(
"Authorization",
f"Bearer {token}",
)

zip_file = None
logger.info("Starting download...")
with urlopen(httprequest) as response:
with urlopen(req) as response:
logger.info(f"Response status: {response.status}")
zip_file = zipfile.ZipFile(io.BytesIO(response.read()))
logger.info("Download finished, zip is valid")
Expand All @@ -103,28 +129,67 @@ def install(ctx: InstallContext):
first_bad_file = zip_file.testzip()
if first_bad_file is not None:
logger.error(f'Zip appears to be corrupt, first bad file is "{first_bad_file}"')
return
return None
logger.info("Download verified")
return zip_file


def add_libadwaita_links(ctx: InstallContext, rewrite: True):
dir_name = (
ctx.dest / f"catppuccin-{ctx.flavor}-{ctx.accent}-standard+default" / "gtk-4.0"
).absolute()
gtk4_dir = (Path(os.path.expanduser("~")) / ".config" / "gtk-4.0").absolute()
os.makedirs(gtk4_dir, exist_ok=True)

logger.info("Adding symlinks for libadwaita")
logger.info(f"Root: {dir_name}")
logger.info(f"Target: {gtk4_dir}")
try:
if rewrite:
os.remove(dir_name / "assets", gtk4_dir / "assets")
os.remove(dir_name / "gtk.css", gtk4_dir / "gtk.css")
os.remove(dir_name / "gtk-dark.css", gtk4_dir / "gtk-dark.css")
except FileNotFoundError:
logger.debug("Ignoring FileNotFound in symlink rewrite")

os.symlink(dir_name / "assets", gtk4_dir / "assets")
os.symlink(dir_name / "gtk.css", gtk4_dir / "gtk.css")
os.symlink(dir_name / "gtk-dark.css", gtk4_dir / "gtk-dark.css")


def install(ctx: InstallContext):
url = build_release_url(ctx)
logger.info(ctx.build_info())

zip_file = fetch_zip(url)
if zip_file is None:
return

logger.info("Extracting...")
zip_file.extractall(ctx.dest)
logger.info("Extraction complete")

if ctx.link:
dir_name = (ctx.dest / f"catppuccin-{ctx.flavor}-{ctx.accent}-standard+default" / 'gtk-4.0').absolute()
gtk4_dir = (Path(os.path.expanduser('~')) / '.config' / 'gtk-4.0').absolute()
os.makedirs(gtk4_dir, exist_ok=True)
add_libadwaita_links(ctx)


logger.info("Adding symlinks for libadwaita")
logger.info(f'Root: {dir_name}')
logger.info(f'Target: {gtk4_dir}')
os.symlink(dir_name / 'assets', gtk4_dir / 'assets')
os.symlink(dir_name / 'gtk.css', gtk4_dir / 'gtk.css')
os.symlink(dir_name / 'gtk-dark.css', gtk4_dir / 'gtk-dark.css')
def extract_artifact_id(artifact_url: str) -> str:
url = urlparse(artifact_url)
parts = url.path.split("/")
artifact_id = parts[-2]
return artifact_id


def construct_artifact_download_url(artifact_id: str) -> str:
root = "https://api.github.com/repos"
location = "catppuccin/gtk/actions/artifacts"
artifact = f"{artifact_id}/zip"
return f"{root}/{location}/{artifact}"


def main():
args = parse_args()

dest = Path(os.path.expanduser("~")) / ".local" / "share" / "themes"
os.makedirs(dest, exist_ok=True)

Expand All @@ -135,9 +200,39 @@ def main():
flavor=args.flavor, accent=args.accent, dest=dest, link=args.link
)

install(ctx)
if args.from_pr:
# Working from a pull request, special case it
artifact_id = extract_artifact_id(args.from_pr)
logger.info(f"Pulling artifact from id '{artifact_id}'")
url = construct_artifact_download_url(artifact_id)
logger.info(f"Downloading zip at '{url}'")
try:
artifacts = fetch_zip(url)
except Exception as e:
print(e.read())
print(e.url, e.headers)
raise e
if artifacts is None:
return

# The zip, inside the artifacts, that we want to pull out
zip_name = f"catppuccin-{args.flavor}-{args.accent}-standard+default.zip"
logger.info(f"Pulling '{zip_name}' from the artifacts")
info = artifacts.getinfo(zip_name)
logger.info(ctx.build_info(False))
logger.info("Extracting the artifact...")
artifacts.extract(info, dest)
logger.info("Extraction complete")

if ctx.link:
logger.info("Adding links (with rewrite)")
add_libadwaita_links(ctx, True)
logger.info("Links added")

logger.info('Theme installation complete!')
return

install(ctx)
logger.info("Theme installation complete!")


try:
Expand Down

0 comments on commit 7cdd174

Please sign in to comment.