Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions EDMC.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import os
import queue
import sys
from pathlib import Path
from time import sleep, time
from typing import TYPE_CHECKING, Any
from common_utils import log_locale, SERVER_RETRY
Expand Down Expand Up @@ -226,14 +227,14 @@ def main() -> None: # noqa: C901, CCR001
# system, chances are its the current locale, and not utf-8. Otherwise if it was copied, its probably
# utf8. Either way, try the system FIRST because reading something like cp1251 in UTF-8 results in garbage
# but the reverse results in an exception.
json_file = os.path.abspath(args.j)
json_file = str(Path(args.j).resolve())
try:
with open(json_file) as file_handle:
data = json.load(file_handle)
except UnicodeDecodeError:
with open(json_file, encoding='utf-8') as file_handle:
data = json.load(file_handle)
config.set('querytime', int(os.path.getmtime(args.j)))
config.set('querytime', int(Path(args.j).stat().st_mtime))

else:
# Get state from latest Journal file
Expand Down
3 changes: 2 additions & 1 deletion EDMCLogging.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,6 @@ class InterceptHandler(logging.Handler):

def emit(self, record: logging.LogRecord) -> None:
"""Intercept standard logging and send to Loguru with context."""

level: str | int
try:
level = loguru_logger.level(record.levelname).name
Expand Down Expand Up @@ -367,9 +366,11 @@ def get_plugin_logger(plugin_name: str, loglevel: int = _default_loglevel) -> Lo
class EDMCContextFilter(logging.Filter):
"""
Legacy compatibility shim.

EDMC now intercepts standard logging globally via Loguru,
making manual context filtering obsolete.
"""

def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
warnings.warn(
Expand Down
13 changes: 7 additions & 6 deletions EDMCSystemProfiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,19 @@
import webbrowser
import platform
import sys
from os import chdir, environ, path
from os import chdir, environ
import pathlib
import logging
from journal_lock import JournalLock

if getattr(sys, "frozen", False):
# Under py2exe sys.path[0] is the executable name
if sys.platform == "win32":
chdir(path.dirname(sys.path[0]))
exe_dir = pathlib.Path(sys.path[0]).parent
chdir(exe_dir)
# Allow executable to be invoked from any cwd
environ["TCL_LIBRARY"] = path.join(path.dirname(sys.path[0]), "lib", "tcl")
environ["TK_LIBRARY"] = path.join(path.dirname(sys.path[0]), "lib", "tk")
environ["TCL_LIBRARY"] = str(exe_dir / "lib" / "tcl")
environ["TK_LIBRARY"] = str(exe_dir / "lib" / "tk")

else:
# We still want to *try* to have CWD be where the main script is, even if
Expand Down Expand Up @@ -115,12 +116,12 @@ def main(active_config: config.Config) -> None:
root.withdraw() # Hide the window initially to calculate the dimensions
try:
icon_image = tk.PhotoImage(
file=path.join(active_config.respath_path, "io.edcd.EDMarketConnector.png")
file=pathlib.Path(active_config.respath_path) / "io.edcd.EDMarketConnector.png"
)

root.iconphoto(True, icon_image)
except tk.TclError:
root.iconbitmap(path.join(active_config.respath_path, "EDMarketConnector.ico"))
root.iconbitmap(pathlib.Path(active_config.respath_path) / "EDMarketConnector.ico")

sys_report = get_sys_report(active_config)

Expand Down
6 changes: 3 additions & 3 deletions EDMarketConnector.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import sys
import threading
import webbrowser
from os import chdir, environ
from os import environ
from time import localtime, strftime, time
from typing import TYPE_CHECKING, Any, Literal, MutableMapping
from constants import applongname, appname, protocolhandler_redirect
Expand All @@ -39,7 +39,7 @@
else:
# We still want to *try* to have CWD be where the main script is, even if
# not frozen.
chdir(pathlib.Path(__file__).parent)
os.chdir(pathlib.Path(__file__).parent)

# config will now cause an appname logger to be set up, so we need the
# console redirect before this
Expand Down Expand Up @@ -412,7 +412,7 @@ def already_running_popup():
sys.stdout.truncate()
else:
# Potential Git Repo?
if os.path.exists(".git"):
if pathlib.Path(".git").exists():
try:
git_branch = subprocess.check_output(
['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
Expand Down
34 changes: 15 additions & 19 deletions build.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
See LICENSE file.
"""

from collections.abc import Sequence
import datetime
import os
import shutil
import sys
import pathlib
Expand Down Expand Up @@ -73,9 +73,9 @@ def system_check(dist_dir: pathlib.Path) -> str:

def generate_data_files(
app_name: str, gitversion_file: str, plugins: list[str]
) -> list[tuple[object, object]]:
) -> Sequence[tuple[object, object]]:
"""Create the required datafiles to build."""
l10n_dir = "L10n"
l10n_dir = pathlib.Path("L10n")
fdevids_dir = pathlib.Path("FDevIDs")
license_dir = pathlib.Path("docs/Licenses")
data_files = [
Expand All @@ -97,26 +97,22 @@ def generate_data_files(
],
),
(
l10n_dir,
[
pathlib.Path(l10n_dir) / x
for x in os.listdir(l10n_dir)
if x.endswith(".strings")
],
str(l10n_dir),
[str(x) for x in l10n_dir.iterdir() if x.suffix == ".strings"],
),
(
fdevids_dir,
str(fdevids_dir),
[
pathlib.Path(fdevids_dir / "commodity.csv"),
pathlib.Path(fdevids_dir / "rare_commodity.csv"),
str(fdevids_dir / "commodity.csv"),
str(fdevids_dir / "rare_commodity.csv"),
],
),
("plugins", plugins),
]
# Add all files recursively from license directories
for root, dirs, files in os.walk(license_dir):
file_list = [os.path.join(root, f) for f in files]
dest_dir = os.path.join(license_dir, os.path.relpath(root, license_dir))
for root, dirs, files in license_dir.walk():
file_list = [str(root / f) for f in files]
dest_dir = str(license_dir / root.relative_to(license_dir))
data_files.append((dest_dir, file_list))

return data_files
Expand All @@ -131,9 +127,9 @@ def _scan_dist_for_modules( # noqa: C901, CCR001
def add(name: str, origin: str):
modules.setdefault(name, set()).add(origin)

for root, dirs, files in os.walk(dist_dir):
for root, dirs, files in dist_dir.walk():
for name in files:
path = pathlib.Path(root) / name
path = root / name # root is a Path object, name is a string

# Loose files
if path.suffix in (".py", ".pyc"):
Expand All @@ -153,12 +149,12 @@ def add(name: str, origin: str):
add(top, str(rel))

# Zips
if path.suffix == ".zip":
elif path.suffix == ".zip":
try:
with zipfile.ZipFile(path) as z:
for info in z.infolist():
if info.filename.endswith((".py", ".pyc")):
parts = info.filename.split("/") # type: ignore
parts = tuple(info.filename.split("/"))
if not parts:
continue

Expand Down
8 changes: 2 additions & 6 deletions collate.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@

import csv
import json
import os
import pathlib
import sys
from traceback import print_exc
Expand All @@ -33,11 +32,8 @@ def __make_backup(file_name: pathlib.Path, suffix: str = '.bak') -> None:
:param suffix: The suffix to use for backup files (default '.bak')
"""
backup_name = file_name.parent / (file_name.name + suffix)

if pathlib.Path.is_file(backup_name):
os.unlink(backup_name)

os.rename(file_name, backup_name)
backup_name.unlink(missing_ok=True)
file_name.rename(backup_name)


def addcommodities(data) -> None: # noqa: CCR001
Expand Down
4 changes: 2 additions & 2 deletions companion.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
from enum import StrEnum
from pathlib import Path
from queue import Queue
from typing import TYPE_CHECKING, Any, TypeVar, Union, Iterator
from typing import TYPE_CHECKING, Any, TypeVar, Iterator
from collections.abc import Mapping
from dataclasses import dataclass
from requests.adapters import HTTPAdapter
Expand Down Expand Up @@ -73,7 +73,7 @@ class CAPIData(UserDict):

def __init__(
self,
data: Union[str, dict[str, Any], 'CAPIData', None] = None,
data: "str | dict[str, Any] | 'CAPIData' | None" = None,
source_host: str | None = None,
source_endpoint: str | None = None,
request_cmdr: str | None = None
Expand Down
2 changes: 1 addition & 1 deletion config/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ def git_shorthash_from_head() -> str | None:

:return: str | None: None if we couldn't determine the short hash.
"""
if IS_FROZEN or not os.path.exists(".git"):
if IS_FROZEN or not pathlib.Path(".git").exists():
return None

try:
Expand Down
1 change: 1 addition & 0 deletions dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ def process(self, logfile: str | None = None) -> None:
def poll(self, first_time: bool = False) -> None:
"""
Legacy compatibility shim for backwards compatibility with plugins.

Status.json is now handled entirely via filesystem event observers.
"""
warnings.warn(
Expand Down
10 changes: 6 additions & 4 deletions edshipyard.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@
from __future__ import annotations

import json
import os
import pathlib
import re
import time
from collections import defaultdict
from typing import Union
from update import check_for_datafile_updates
import outfitting
import util_ships
Expand All @@ -18,7 +16,7 @@

logger = get_main_logger()

__Module = dict[str, Union[str, list[str]]] # Have to keep old-style here for compatibility
__Module = dict[str, str | list[str]]

# Map API ship names to ED Shipyard names
ship_map = ship_name_map.copy()
Expand Down Expand Up @@ -199,7 +197,11 @@ def class_rating(module: __Module) -> str:
# Look for last ship of this type
ship = util_ships.ship_file_name(data['ship'].get('shipName'), data['ship']['name'])
regexp = re.compile(re.escape(ship) + r'\.\d{4}-\d\d-\d\dT\d\d\.\d\d\.\d\d\.txt')
oldfiles = sorted([x for x in os.listdir(config.get_str('outdir')) if regexp.match(x)])
out_dir = pathlib.Path(config.get_str('outdir'))
oldfiles = sorted(
[x for x in out_dir.iterdir() if regexp.match(x.name)],
key=lambda p: p.name # Sort based on the filename string
)
if oldfiles:
with (pathlib.Path(config.get_str('outdir')) / oldfiles[-1]).open() as h:
if h.read() == string:
Expand Down
7 changes: 3 additions & 4 deletions journal_lock.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
"""
from __future__ import annotations

import os
import pathlib
import sys
import tkinter as tk
Expand Down Expand Up @@ -125,10 +124,10 @@ def release_lock(self) -> bool:
self.locked = False

# Physically remove the lockfile from disk on a clean exit
if self.journal_dir_lockfile_name and self.journal_dir_lockfile_name.exists():
if self.journal_dir_lockfile_name:
try:
os.remove(self.journal_dir_lockfile_name)
except Exception:
self.journal_dir_lockfile_name.unlink(missing_ok=True)
except OSError:
pass # Prevent crashing if a file hook holds it open briefly during shutdown

return True
Expand Down
4 changes: 2 additions & 2 deletions killswitch.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from copy import deepcopy
from typing import (
TYPE_CHECKING, Any, NamedTuple,
TypedDict, TypeVar, cast, Union
TypedDict, TypeVar, cast
)
from collections.abc import Callable, Mapping, MutableMapping, MutableSequence, Sequence
import requests
Expand All @@ -26,7 +26,7 @@
OLD_KILLSWITCH_URL = 'https://raw.githubusercontent.com/EDCD/EDMarketConnector/releases/killswitches.json'
DEFAULT_KILLSWITCH_URL = 'https://raw.githubusercontent.com/EDCD/EDMarketConnector/releases/killswitches_v2.json'
CURRENT_KILLSWITCH_VERSION = 2
UPDATABLE_DATA = Union[Mapping, Sequence] # Have to keep old-style
UPDATABLE_DATA = Mapping | Sequence
_current_version: semantic_version.Version = config.appversion_nobuild()

T = TypeVar('T', bound=UPDATABLE_DATA)
Expand Down
13 changes: 7 additions & 6 deletions l10n.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import re
import sys
from contextlib import suppress
from os import listdir, sep
from typing import TextIO, cast
from collections.abc import Iterable
import pathlib
Expand Down Expand Up @@ -106,7 +105,7 @@ def install(self, lang: str | None = None) -> None: # noqa: CCR001
return

self.translations = {None: self.contents(cast(str, lang))}
for plugin in listdir(config.plugin_dir_path):
for plugin in (x.name for x in pathlib.Path(config.plugin_dir_path).iterdir()):
plugin_path = config.plugin_dir_path / plugin / LOCALISATION_DIR
if pathlib.Path.is_dir(plugin_path):
try:
Expand Down Expand Up @@ -162,9 +161,11 @@ def translate(self, x: str, context: str | None = None, lang: str | None = None)
plugin_path: pathlib.Path | None = None

if context:
# TODO: There is probably a better way to go about this now.
plugin_name = context[len(config.plugin_dir)+1:].split(sep)[0]
plugin_path = config.plugin_dir_path / plugin_name / LOCALISATION_DIR
context_path = pathlib.Path(context)
# .is_relative_to() prevents crashes if context isn't actually in the plugin dir
if context_path.is_relative_to(config.plugin_dir_path):
plugin_name = context_path.relative_to(config.plugin_dir_path).parts[0]
plugin_path = config.plugin_dir_path / plugin_name / LOCALISATION_DIR

if lang:
contents: dict[str, str] = self.contents(lang=lang, plugin_path=plugin_path)
Expand Down Expand Up @@ -192,7 +193,7 @@ def available(self) -> set[str]:
"""Return a list of available language codes."""
path = self.respath()

available = {x[:-len('.strings')] for x in listdir(path) if x.endswith('.strings')}
available = {x.stem for x in pathlib.Path(path).iterdir() if x.suffix == '.strings'}

return available

Expand Down
3 changes: 1 addition & 2 deletions loadout.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import json
import re
import time
from os import listdir
from pathlib import Path
import companion
import util_ships
Expand Down Expand Up @@ -43,7 +42,7 @@ def export(data: companion.CAPIData, requested_filename: str | None = None) -> N
# Look for last ship of this type
ship = util_ships.ship_file_name(data['ship'].get('shipName'), data['ship']['name'])
regexp = re.compile(re.escape(ship) + r'\.\d\d\d\d-\d\d-\d\dT\d\d\.\d\d\.\d\d\.txt')
oldfiles = sorted([x for x in listdir(config.get_str('outdir')) if regexp.match(x)])
oldfiles = sorted([x.name for x in Path(config.get_str('outdir')).iterdir() if regexp.match(x.name)])
if oldfiles:
with open(Path(config.get_str('outdir')) / Path(oldfiles[-1])) as h:
if h.read() == string:
Expand Down
Loading
Loading