Skip to content

Commit

Permalink
Update print statements for standalone usage
Browse files Browse the repository at this point in the history
- Prefer applying bold to all non-debug related statements by default during the ULWGL setup process
  • Loading branch information
R1kaB3rN committed Mar 15, 2024
1 parent 61cb792 commit ea3c19b
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 49 deletions.
46 changes: 28 additions & 18 deletions ULWGL/ulwgl_dl_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@
from ssl import create_default_context
from json import loads as loads_json
from urllib.request import urlopen
from sys import stderr
from ulwgl_plugins import enable_zenity
from socket import gaierror
from ulwgl_log import log
from ulwgl_consts import STEAM_COMPAT, ULWGL_CACHE
from ulwgl_util import console_log

try:
from tarfile import tar_filter
Expand Down Expand Up @@ -124,7 +124,7 @@ def _fetch_proton(
proton, proton_url = files[1]
proton_dir: str = proton[: proton.find(".tar.gz")] # Proton dir

print(f"Downloading {hash} ...", file=stderr)
console_log(f"Downloading {hash} ...")

# Verify the scheme from Github for resources
if not proton_url.startswith("https:") or not hash_url.startswith("https:"):
Expand Down Expand Up @@ -163,7 +163,7 @@ def _fetch_proton(
err: str = f"Unable to download {proton}\ngithub.com request timed out"
raise TimeoutError(err)
except FileNotFoundError:
print(f"Downloading {proton} ...", file=stderr)
console_log(f"Downloading {proton} ...")

with urlopen(proton_url, timeout=180, context=create_default_context()) as resp: # noqa: S310
# Without Proton, the launcher will not work
Expand All @@ -177,7 +177,7 @@ def _fetch_proton(
with cache.joinpath(proton).open(mode="wb") as file:
file.write(resp.read())

print("Completed.", file=stderr)
console_log("Completed.")

with cache.joinpath(proton).open(mode="rb") as file:
if (
Expand All @@ -186,7 +186,7 @@ def _fetch_proton(
):
err: str = "Digests mismatched.\nFalling back to cache ..."
raise ValueError(err)
print(f"{proton}: SHA512 is OK", file=stderr)
console_log(f"{proton}: SHA512 is OK")

_extract_dir(cache.joinpath(proton), steam_compat)
environ["PROTONPATH"] = steam_compat.joinpath(proton_dir).as_posix()
Expand All @@ -205,23 +205,23 @@ def _extract_dir(proton: Path, steam_compat: Path) -> None:
log.debug("Using no filter for archive")
log.warning("Archive will be extracted insecurely")

print(f"Extracting {proton} -> {steam_compat.as_posix()} ...", file=stderr)
console_log(f"Extracting {proton} -> {steam_compat} ...")
tar.extractall(path=steam_compat.as_posix()) # noqa: S202
print("Completed.", file=stderr)
console_log("Completed.")


def _cleanup(tarball: str, proton: str, cache: Path, steam_compat: Path) -> None:
"""Remove files that may have been left in an incomplete state to avoid corruption.
We want to do this when a download for a new release is interrupted
"""
print("Keyboard Interrupt.\nCleaning ...", file=stderr)
console_log("Keyboard Interrupt.\nCleaning ...")

if cache.joinpath(tarball).is_file():
print(f"Purging {tarball} in {cache} ...", file=stderr)
console_log(f"Purging {tarball} in {cache} ...")
cache.joinpath(tarball).unlink()
if steam_compat.joinpath(proton).is_dir():
print(f"Purging {proton} in {steam_compat} ...", file=stderr)
console_log(f"Purging {proton} in {steam_compat} ...")
rmtree(steam_compat.joinpath(proton).as_posix())


Expand All @@ -235,16 +235,18 @@ def _get_from_steamcompat(
proton_dir: str = files[1][0][: files[1][0].find(".tar.gz")]

for proton in steam_compat.glob("ULWGL-Proton*"):
print(f"{proton.name} found in: {steam_compat.as_posix()}", file=stderr)
console_log(f"{proton.name} found in: {steam_compat}")
console_log(f"Using {proton.name}")

environ["PROTONPATH"] = proton.as_posix()
env["PROTONPATH"] = environ["PROTONPATH"]

# Notify the user that they're not using the latest
if proton_dir and proton.name != proton_dir:
print(
"ULWGL-Proton is outdated.\nFor latest release, please download "
+ files[1][1],
file=stderr,
link: str = files[1][1]
console_log(
"ULWGL-Proton is outdated.\n"
f"For latest release, please download {link}"
)

return env
Expand Down Expand Up @@ -283,16 +285,18 @@ def _get_from_cache(
if path:
proton_dir: str = name[: name.find(".tar.gz")] # Proton dir

print(f"{name} found in: {path}", file=stderr)
console_log(f"{name} found in: {path}")
try:
_extract_dir(path, steam_compat)

console_log(f"Using {proton_dir}")
environ["PROTONPATH"] = steam_compat.joinpath(proton_dir).as_posix()
env["PROTONPATH"] = environ["PROTONPATH"]

return env
except KeyboardInterrupt:
if steam_compat.joinpath(proton_dir).is_dir():
print(f"Purging {proton_dir} in {steam_compat} ...", file=stderr)
console_log(f"Purging {proton_dir} in {steam_compat} ...")
rmtree(steam_compat.joinpath(proton_dir).as_posix())
raise

Expand All @@ -307,9 +311,15 @@ def _get_latest(
When the digests mismatched or when interrupted, refer to cache for an old version
"""
if files:
print("Fetching latest release ...", file=stderr)
console_log("Fetching latest release ...")

try:
tarball: str = files[1][0]
proton_dir: str = tarball[: tarball.find(".tar.gz")] # Proton dir

_fetch_proton(env, steam_compat, cache, files)

console_log(f"Using {proton_dir}")
env["PROTONPATH"] = environ["PROTONPATH"]
except ValueError:
log.exception("Exception")
Expand Down
56 changes: 25 additions & 31 deletions ULWGL/ulwgl_util.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from tarfile import open as tar_open, TarInfo
from os import getuid
from ulwgl_consts import CONFIG, STEAM_COMPAT, ULWGL_LOCAL
from ulwgl_consts import CONFIG, STEAM_COMPAT, ULWGL_LOCAL, Color
from typing import Any, Dict, List, Callable
from json import load, dump
from ulwgl_log import log
Expand Down Expand Up @@ -97,10 +97,9 @@ def setup_runtime(root: Path, json: Dict[str, Any]) -> None: # noqa: D103
)
raise TimeoutError(err)
except FileNotFoundError:
console_log(f"Downloading {runtime_platform_value} ...")

print(f"Downloading {runtime_platform_value} ...", file=stderr)

# noqa S310 we hardcode the URL and trust it
# We hardcode the URL and trust it
with urlopen(base_url, timeout=60, context=create_default_context()) as resp: # noqa: S310
if resp.status != 200:
err: str = (
Expand Down Expand Up @@ -212,15 +211,16 @@ def _install_ulwgl(
and ULWGL_VERSION.json
"""
log.debug("New install detected")
console_log("Setting up Unified Launcher for Windows Games on Linux ...")

local.mkdir(parents=True, exist_ok=True)

# Config
print(f"Copying {CONFIG} -> {local} ...", file=stderr)
console_log(f"Copying {CONFIG} -> {local} ...")
copy(root.joinpath(CONFIG), local.joinpath(CONFIG))

# Reaper
print(f"Copying reaper -> {local} ...", file=stderr)
console_log(f"Copying reaper -> {local} ...")
copy(root.joinpath("reaper"), local.joinpath("reaper"))

# Runtime platform
Expand All @@ -229,15 +229,15 @@ def _install_ulwgl(
# Launcher files
for file in root.glob("*.py"):
if not file.name.startswith("ulwgl_test"):
print(f"Copying {file} -> {local} ...", file=stderr)
console_log(f"Copying {file} -> {local} ...")
copy(file, local.joinpath(file.name))

local.joinpath("ulwgl-run").symlink_to("ulwgl_run.py")

# Runner
steam_compat.mkdir(parents=True, exist_ok=True)

print(f"Copying ULWGL-Launcher -> {steam_compat} ...", file=stderr)
console_log(f"Copying ULWGL-Launcher -> {steam_compat} ...")

# Remove existing files if they exist -- this is a clean install.
if steam_compat.joinpath("ULWGL-Launcher").is_dir():
Expand All @@ -254,7 +254,7 @@ def _install_ulwgl(
"../../../ULWGL/ulwgl_run.py"
)

print("Completed.", file=stderr)
console_log("Completed.")


def _update_ulwgl(
Expand Down Expand Up @@ -288,16 +288,13 @@ def _update_ulwgl(
# Directory is absent
if not local.joinpath("reaper").is_file():
log.warning("Reaper not found")
print(
f"Reaper not found\nCopying {key} -> {local} ...",
file=stderr,
)
console_log(f"Copying {key} -> {local} ...")

copy(root.joinpath("reaper"), local.joinpath("reaper"))

# Update
if val != reaper:
print(f"Updating {key} to {val} ...", file=stderr)
console_log(f"Updating {key} to {val}")

local.joinpath("reaper").unlink(missing_ok=True)
copy(root.joinpath("reaper"), local.joinpath("reaper"))
Expand All @@ -310,10 +307,7 @@ def _update_ulwgl(
# Directory is absent
if not local.joinpath("pressure-vessel").is_dir():
log.warning("Pressure Vessel not found")
print(
f"Pressure Vessel not found\nCopying {key} -> {local} ...",
file=stderr,
)
console_log(f"Copying {key} -> {val} ...")

copytree(
root.joinpath("pressure-vessel"),
Expand All @@ -323,7 +317,7 @@ def _update_ulwgl(
)
elif local.joinpath("pressure-vessel").is_dir() and val != pv:
# Update
print(f"Updating {key} to {val} ...", file=stderr)
console_log(f"Updating {key} to {val}")

rmtree(local.joinpath("pressure-vessel").as_posix())
copytree(
Expand All @@ -340,17 +334,13 @@ def _update_ulwgl(

# Directory is absent
if not (local.joinpath(runtime).is_dir() or local.joinpath(val).is_dir()):
print(
"Runtime Platform not found",
file=stderr,
)
log.warning("Runtime Platform not found")

# Download the runtime from the official source
setup_runtime(root, json_root)
elif local.joinpath(runtime).is_dir() and val != runtime:
# Update
print(f"Updating {key} to {val} ...", file=stderr)
console_log(f"Updating {key} to {val}")

rmtree(local.joinpath(runtime).as_posix())
setup_runtime(root, json_root)
Expand All @@ -362,7 +352,7 @@ def _update_ulwgl(
launcher: str = json_local["ulwgl"]["versions"]["launcher"]

if val != launcher:
print(f"Updating {key} to {val} ...", file=stderr)
console_log(f"Updating {key} to {val}")

# Python files
for file in root.glob("*.py"):
Expand All @@ -382,11 +372,7 @@ def _update_ulwgl(
# Directory is absent
if not steam_compat.joinpath("ULWGL-Launcher").is_dir():
log.warning("ULWGL-Launcher not found")
print(
"ULWGL-Launcher not found\n"
+ f"Copying ULWGL-Launcher -> {steam_compat} ...",
file=stderr,
)
console_log(f"Copying ULWGL-Launcher -> {steam_compat} ...")

copytree(
root.joinpath("ULWGL-Launcher"),
Expand All @@ -400,7 +386,7 @@ def _update_ulwgl(
)
elif steam_compat.joinpath("ULWGL-Launcher").is_dir() and val != runner:
# Update
print(f"Updating {key} to {val} ...", file=stderr)
console_log(f"Updating {key} to {val}")

rmtree(steam_compat.joinpath("ULWGL-Launcher").as_posix())
copytree(
Expand Down Expand Up @@ -452,3 +438,11 @@ def _get_json(path: Path, config: str) -> Dict[str, Any]:
raise ValueError(err)

return json


def console_log(msg: str) -> None:
"""Display non-debug-related statements to the console.
Intended to be used to notify ULWGL setup progress state
"""
print(f"{Color.BOLD.value}{msg}{Color.RESET.value}", file=stderr)

0 comments on commit ea3c19b

Please sign in to comment.