Skip to content

Commit

Permalink
Update types from typings module
Browse files Browse the repository at this point in the history
- Removes some types such as Dict because users on Python 3.9+ will not require them.
  • Loading branch information
R1kaB3rN committed Apr 29, 2024
1 parent d1184b5 commit e8ebdb5
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 58 deletions.
34 changes: 17 additions & 17 deletions umu/umu_dl_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from tarfile import open as tar_open, TarInfo
from pathlib import Path
from os import environ
from typing import Dict, List, Tuple, Union, Callable
from collections.abc import Callable
from hashlib import sha512
from shutil import rmtree
from http.client import HTTPException
Expand All @@ -23,13 +23,13 @@
tar_filter: Callable[[str, str], TarInfo] = None


def get_umu_proton(env: Dict[str, str]) -> Union[Dict[str, str]]:
def get_umu_proton(env: dict[str, str]) -> dict[str, str]:
"""Attempt to find existing Proton from the system.
Downloads the latest if not first found in:
~/.local/share/Steam/compatibilitytools.d
"""
files: List[Tuple[str, str]] = []
files: list[tuple[str, str]] = []
tmp: Path = Path(mkdtemp())
STEAM_COMPAT.mkdir(exist_ok=True, parents=True)

Expand All @@ -54,12 +54,12 @@ def get_umu_proton(env: Dict[str, str]) -> Union[Dict[str, str]]:
return env


def _fetch_releases() -> List[Tuple[str, str]]:
def _fetch_releases() -> list[tuple[str, str]]:
"""Fetch the latest releases from the Github API."""
files: List[Tuple[str, str]] = []
files: list[tuple[str, str]] = []
url: str = "https://api.github.com"
repo: str = "/repos/Open-Wine-Components/umu-proton/releases"
headers: Dict[str, str] = {
headers: dict[str, str] = {
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
"User-Agent": "",
Expand Down Expand Up @@ -110,8 +110,8 @@ def _fetch_releases() -> List[Tuple[str, str]]:


def _fetch_proton(
env: Dict[str, str], tmp: Path, files: List[Tuple[str, str]]
) -> Dict[str, str]:
env: dict[str, str], tmp: Path, files: list[tuple[str, str]]
) -> dict[str, str]:
"""Download the latest umu-proton and set it as PROTONPATH."""
hash, hash_url = files[0]
proton, proton_url = files[1]
Expand Down Expand Up @@ -147,7 +147,7 @@ def _fetch_proton(
# Create a popup with zenity when the env var is set
if environ.get("UMU_ZENITY") == "1":
bin: str = "curl"
opts: List[str] = [
opts: list[str] = [
"-LJO",
"--silent",
proton_url,
Expand Down Expand Up @@ -218,8 +218,8 @@ def _cleanup(tarball: str, proton: str, tmp: Path, steam_compat: Path) -> None:


def _get_from_steamcompat(
env: Dict[str, str], steam_compat: Path
) -> Union[Dict[str, str], None]:
env: dict[str, str], steam_compat: Path
) -> dict[str, str] | None:
"""Refer to Steam compat folder for any existing Proton directories.
Executed when an error occurs when retrieving and setting the latest
Expand All @@ -228,7 +228,7 @@ def _get_from_steamcompat(
version: str = (
"GE-Proton" if environ.get("PROTONPATH") == "GE-Proton" else "UMU-Proton"
)
protons: List[Path] = sorted(
protons: list[Path] = sorted(
[proton for proton in steam_compat.glob("*") if proton.name.startswith(version)]
)

Expand All @@ -244,8 +244,8 @@ def _get_from_steamcompat(


def _get_latest(
env: Dict[str, str], steam_compat: Path, tmp: Path, files: List[Tuple[str, str]]
) -> Union[Dict[str, str], None]:
env: dict[str, str], steam_compat: Path, tmp: Path, files: list[tuple[str, str]]
) -> dict[str, str] | None:
"""Download the latest Proton for new installs.
Either GE-Proton or UMU-Proton can be downloaded. When download the latest
Expand Down Expand Up @@ -279,7 +279,7 @@ def _get_latest(
# Set latest UMU/GE-Proton
if version == "UMU-Proton":
log.debug("Updating UMU-Proton")
protons: List[Path] = sorted( # Previous stable builds
protons: list[Path] = sorted( # Previous stable builds
[
file
for file in steam_compat.glob("*")
Expand Down Expand Up @@ -331,7 +331,7 @@ def _get_latest(
return env


def _update_proton(proton: str, steam_compat: Path, protons: List[Path]) -> None:
def _update_proton(proton: str, steam_compat: Path, protons: list[Path]) -> None:
"""Create a symbolic link and remove the previous UMU-Proton.
The symbolic link will be used by clients to reference the PROTONPATH
Expand All @@ -350,7 +350,7 @@ def _update_proton(proton: str, steam_compat: Path, protons: List[Path]) -> None
return

with ThreadPoolExecutor() as executor:
futures: List[Future] = []
futures: list[Future] = []
for proton in protons:
if proton.is_dir():
log.debug("Previous stable build found")
Expand Down
20 changes: 10 additions & 10 deletions umu/umu_plugins.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
from subprocess import Popen, TimeoutExpired, PIPE, STDOUT
from os import environ
from pathlib import Path
from typing import Dict, Set, Any, List, Tuple
from typing import Any
from argparse import Namespace
from shutil import which
from umu_log import log


def set_env_toml(
env: Dict[str, str], args: Namespace
) -> Tuple[Dict[str, str], List[str]]:
env: dict[str, str], args: Namespace
) -> tuple[dict[str, str], list[str]]:
"""Read a TOML file then sets the environment variables for the Steam RT.
In the TOML file, certain keys map to Steam RT environment variables. For example:
Expand All @@ -25,9 +25,9 @@ def set_env_toml(
msg: str = "tomllib requires Python 3.11"
raise ModuleNotFoundError(msg)

toml: Dict[str, Any] = None
toml: dict[str, Any] = None
path_config: str = Path(getattr(args, "config", None)).expanduser().as_posix()
opts: List[str] = []
opts: list[str] = []

if not Path(path_config).is_file():
msg: str = "Path to configuration is not a file: " + getattr(
Expand Down Expand Up @@ -59,13 +59,13 @@ def set_env_toml(
return env, opts


def _check_env_toml(toml: Dict[str, Any]) -> Dict[str, Any]:
def _check_env_toml(toml: dict[str, Any]) -> dict[str, Any]:
"""Check for required or empty key/value pairs when reading a TOML config.
NOTE: Casing matters in the config and we do not check if the game id is set
"""
table: str = "umu"
required_keys: List[str] = ["proton", "prefix", "exe"]
required_keys: list[str] = ["proton", "prefix", "exe"]

if table not in toml:
err: str = f"Table '{table}' in TOML is not defined."
Expand Down Expand Up @@ -105,13 +105,13 @@ def _check_env_toml(toml: Dict[str, Any]) -> Dict[str, Any]:
return toml


def enable_steam_game_drive(env: Dict[str, str]) -> Dict[str, str]:
def enable_steam_game_drive(env: dict[str, str]) -> dict[str, str]:
"""Enable Steam Game Drive functionality.
Expects STEAM_COMPAT_INSTALL_PATH to be set
STEAM_RUNTIME_LIBRARY_PATH will not be set if the exe directory does not exist
"""
paths: Set[str] = set()
paths: set[str] = set()
root: Path = Path("/")

# Check for mount points going up toward the root
Expand Down Expand Up @@ -141,7 +141,7 @@ def enable_steam_game_drive(env: Dict[str, str]) -> Dict[str, str]:
return env


def enable_zenity(command: str, opts: List[str], msg: str) -> int:
def enable_zenity(command: str, opts: list[str], msg: str) -> int:
"""Execute the command and pipe the output to Zenity.
Intended to be used for long running operations (e.g. large file downloads)
Expand Down
36 changes: 17 additions & 19 deletions umu/umu_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import sys
from argparse import ArgumentParser, Namespace, RawTextHelpFormatter
from pathlib import Path
from typing import Dict, Any, List, Set, Union, Tuple
from typing import Any
from re import match
from subprocess import run
from umu_dl_util import get_umu_proton
Expand All @@ -29,8 +29,8 @@
)


def parse_args() -> Union[Namespace, Tuple[str, List[str]]]: # noqa: D103
opt_args: Set[str] = {"--help", "-h", "--config"}
def parse_args() -> Namespace | tuple[str, list[str]]: # noqa: D103
opt_args: set[str] = {"--help", "-h", "--config"}
parser: ArgumentParser = ArgumentParser(
description="Unified Linux Wine Game Launcher",
epilog=(
Expand Down Expand Up @@ -58,7 +58,7 @@ def parse_args() -> Union[Namespace, Tuple[str, List[str]]]: # noqa: D103

def set_log() -> None:
"""Adjust the log level for the logger."""
levels: Set[str] = {"1", "warn", "debug"}
levels: set[str] = {"1", "warn", "debug"}

if os.environ["UMU_LOG"] not in levels:
return
Expand Down Expand Up @@ -117,7 +117,7 @@ def setup_pfx(path: str) -> None:
log.debug("User home directory exists: %s", wineuser)


def check_env(env: Dict[str, str]) -> Union[Dict[str, str], Dict[str, Any]]:
def check_env(env: set[str, str]) -> dict[str, str] | dict[str, Any]:
"""Before executing a game, check for environment variables and set them.
GAMEID is strictly required
Expand Down Expand Up @@ -179,8 +179,8 @@ def check_env(env: Dict[str, str]) -> Union[Dict[str, str], Dict[str, Any]]:


def set_env(
env: Dict[str, str], args: Union[Namespace, Tuple[str, List[str]]]
) -> Dict[str, str]:
env: dict[str, str], args: Namespace | tuple[str, list[str]]
) -> dict[str, str]:
"""Set various environment variables for the Steam RT.
Filesystem paths will be formatted and expanded as POSIX
Expand Down Expand Up @@ -234,23 +234,23 @@ def set_env(


def build_command(
env: Dict[str, str],
env: dict[str, str],
local: Path,
root: Path,
command: List[str],
opts: List[str] = None,
) -> List[str]:
command: list[str],
opts: list[str] = None,
) -> list[str]:
"""Build the command to be executed."""
verb: str = env["PROTON_VERB"]

# Raise an error if the _v2-entry-point cannot be found
if not local.joinpath("umu").is_file():
msg: str = (
err: str = (
"Path to _v2-entry-point cannot be found in: "
f"{local}\n"
"Please install a Steam Runtime platform"
)
raise FileNotFoundError(msg)
raise FileNotFoundError(err)

if not Path(env.get("PROTONPATH")).joinpath("proton").is_file():
err: str = "The following file was not found in PROTONPATH: proton"
Expand Down Expand Up @@ -279,7 +279,7 @@ def build_command(


def main() -> int: # noqa: D103
env: Dict[str, str] = {
env: list[str, str] = {
"WINEPREFIX": "",
"GAMEID": "",
"PROTON_CRASH_REPORT_DIR": "/tmp/umu_crashreports",
Expand All @@ -303,14 +303,12 @@ def main() -> int: # noqa: D103
"ULWGL_ID": "",
"UMU_ZENITY": "",
}
command: List[str] = []
opts: List[str] = None
# Expected files in this dir: pressure vessel, launcher files, runner,
# config, reaper
command: list[str] = []
opts: list[str] = None
root: Path = Path(__file__).resolve().parent
executor: ThreadPoolExecutor = ThreadPoolExecutor()
future: Future = None
args: Union[Namespace, Tuple[str, List[str]]] = parse_args()
args: Namespace | tuple[str, list[str]] = parse_args()

if os.geteuid() == 0:
err: str = "This script should never be run as the root user"
Expand Down
25 changes: 13 additions & 12 deletions umu/umu_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
from tarfile import open as tar_open, TarInfo
from os import environ
from umu_consts import CONFIG, UMU_LOCAL
from typing import Any, Dict, List, Callable
from typing import Any
from collections.abc import Callable
from json import load, dump
from umu_log import log
from pathlib import Path
Expand All @@ -24,7 +25,7 @@
tar_filter: Callable[[str, str], TarInfo] = None


def setup_runtime(json: Dict[str, Any]) -> None: # noqa: D103
def setup_runtime(json: dict[str, Any]) -> None: # noqa: D103
tmp: Path = Path(mkdtemp())
ret: int = 0 # Exit code from zenity
archive: str = "SteamLinuxRuntime_sniper.tar.xz" # Archive containing the rt
Expand All @@ -40,7 +41,7 @@ def setup_runtime(json: Dict[str, Any]) -> None: # noqa: D103
# Optionally create a popup with zenity
if environ.get("UMU_ZENITY") == "1":
bin: str = "curl"
opts: List[str] = [
opts: list[str] = [
"-LJO",
"--silent",
f"{base_url}/{archive}",
Expand Down Expand Up @@ -120,7 +121,7 @@ def setup_runtime(json: Dict[str, Any]) -> None: # noqa: D103
check_runtime(source_dir, json)

# Move each file to the destination directory, overwriting if it exists
futures: List[Future] = [
futures: list[Future] = [
executor.submit(_move, file, source_dir, UMU_LOCAL)
for file in source_dir.glob("*")
]
Expand Down Expand Up @@ -153,7 +154,7 @@ def setup_umu(root: Path, local: Path) -> None:
"""
log.debug("Root: %s", root)
log.debug("Local: %s", local)
json: Dict[str, Any] = _get_json(root, CONFIG)
json: dict[str, Any] = _get_json(root, CONFIG)

# New install or umu dir is empty
if not local.exists() or not any(local.iterdir()):
Expand All @@ -162,7 +163,7 @@ def setup_umu(root: Path, local: Path) -> None:
return _update_umu(local, json, _get_json(local, CONFIG))


def _install_umu(root: Path, local: Path, json: Dict[str, Any]) -> None:
def _install_umu(root: Path, local: Path, json: dict[str, Any]) -> None:
"""Copy the configuration file and download the runtime.
The launcher will only copy umu_version.json to ~/.local/share/umu
Expand All @@ -185,8 +186,8 @@ def _install_umu(root: Path, local: Path, json: Dict[str, Any]) -> None:

def _update_umu(
local: Path,
json_root: Dict[str, Any],
json_local: Dict[str, Any],
json_root: dict[str, Any],
json_local: dict[str, Any],
) -> None:
"""For existing installations, update the runtime and umu_version.json.
Expand All @@ -200,7 +201,7 @@ def _update_umu(
will be reflected in umu_version.json at ~/.local/share/umu each launch
"""
executor: ThreadPoolExecutor = ThreadPoolExecutor()
futures: List[Future] = []
futures: list[Future] = []
log.debug("Existing install detected")

for key, val in json_root["umu"]["versions"].items():
Expand Down Expand Up @@ -258,15 +259,15 @@ def _update_umu(
dump(json_local, file, indent=4)


def _get_json(path: Path, config: str) -> Dict[str, Any]:
def _get_json(path: Path, config: str) -> dict[str, Any]:
"""Validate the state of the configuration file umu_version.json in a path.
The configuration file will be used to update the runtime and it reflects
the tools currently used by launcher.
The key/value pairs 'umu' and 'versions' must exist
"""
json: Dict[str, Any] = None
json: dict[str, Any] = None

# umu_version.json in the system path should always exist
if not path.joinpath(config).is_file():
Expand Down Expand Up @@ -309,7 +310,7 @@ def _move(file: Path, src: Path, dst: Path) -> None:
move(src_file, dest_file)


def check_runtime(src: Path, json: Dict[str, Any]) -> int:
def check_runtime(src: Path, json: dict[str, Any]) -> int:
"""Validate the file hierarchy of the runtime platform.
The mtree file included in the Steam runtime platform will be used to
Expand Down

0 comments on commit e8ebdb5

Please sign in to comment.