Use pathlib.Path to return path locations

This commit is contained in:
Alexis Métaireau 2025-03-21 14:22:24 +01:00
parent dfcb74b427
commit ab6dd9c01d
No known key found for this signature in database
GPG key ID: C65C7A89A8FFC56E
10 changed files with 32 additions and 35 deletions

View file

@ -121,7 +121,7 @@ def delete_image_tag(tag: str) -> None:
def get_expected_tag() -> str: def get_expected_tag() -> str:
"""Get the tag of the Dangerzone image tarball from the image-id.txt file.""" """Get the tag of the Dangerzone image tarball from the image-id.txt file."""
with open(get_resource_path("image-id.txt")) as f: with get_resource_path("image-id.txt").open() as f:
return f.read().strip() return f.read().strip()
@ -130,7 +130,7 @@ def load_image_tarball() -> None:
tarball_path = get_resource_path("container.tar") tarball_path = get_resource_path("container.tar")
try: try:
res = subprocess.run( res = subprocess.run(
[get_runtime(), "load", "-i", tarball_path], [get_runtime(), "load", "-i", str(tarball_path)],
startupinfo=get_subprocess_startupinfo(), startupinfo=get_subprocess_startupinfo(),
capture_output=True, capture_output=True,
check=True, check=True,

View file

@ -51,7 +51,7 @@ class Application(QtWidgets.QApplication):
def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:
super(Application, self).__init__(*args, **kwargs) super(Application, self).__init__(*args, **kwargs)
self.setQuitOnLastWindowClosed(False) self.setQuitOnLastWindowClosed(False)
with open(get_resource_path("dangerzone.css"), "r") as f: with get_resource_path("dangerzone.css").open("r") as f:
style = f.read() style = f.read()
self.setStyleSheet(style) self.setStyleSheet(style)

View file

@ -63,7 +63,7 @@ class DangerzoneGui(DangerzoneCore):
path = get_resource_path("dangerzone.ico") path = get_resource_path("dangerzone.ico")
else: else:
path = get_resource_path("icon.png") path = get_resource_path("icon.png")
return QtGui.QIcon(path) return QtGui.QIcon(str(path))
def open_pdf_viewer(self, filename: str) -> None: def open_pdf_viewer(self, filename: str) -> None:
if platform.system() == "Darwin": if platform.system() == "Darwin":
@ -252,7 +252,7 @@ class Alert(Dialog):
def create_layout(self) -> QtWidgets.QBoxLayout: def create_layout(self) -> QtWidgets.QBoxLayout:
logo = QtWidgets.QLabel() logo = QtWidgets.QLabel()
logo.setPixmap( logo.setPixmap(
QtGui.QPixmap.fromImage(QtGui.QImage(get_resource_path("icon.png"))) QtGui.QPixmap.fromImage(QtGui.QImage(str(get_resource_path("icon.png"))))
) )
label = QtWidgets.QLabel() label = QtWidgets.QLabel()

View file

@ -62,7 +62,7 @@ def load_svg_image(filename: str, width: int, height: int) -> QtGui.QPixmap:
This answer is basically taken from: https://stackoverflow.com/a/25689790 This answer is basically taken from: https://stackoverflow.com/a/25689790
""" """
path = get_resource_path(filename) path = get_resource_path(filename)
svg_renderer = QtSvg.QSvgRenderer(path) svg_renderer = QtSvg.QSvgRenderer(str(path))
image = QtGui.QImage(width, height, QtGui.QImage.Format_ARGB32) image = QtGui.QImage(width, height, QtGui.QImage.Format_ARGB32)
# Set the ARGB to 0 to prevent rendering artifacts # Set the ARGB to 0 to prevent rendering artifacts
image.fill(0x00000000) image.fill(0x00000000)
@ -130,9 +130,8 @@ class MainWindow(QtWidgets.QMainWindow):
# Header # Header
logo = QtWidgets.QLabel() logo = QtWidgets.QLabel()
logo.setPixmap( icon_path = str(get_resource_path("icon.png"))
QtGui.QPixmap.fromImage(QtGui.QImage(get_resource_path("icon.png"))) logo.setPixmap(QtGui.QPixmap.fromImage(QtGui.QImage(icon_path)))
)
header_label = QtWidgets.QLabel("Dangerzone") header_label = QtWidgets.QLabel("Dangerzone")
header_label.setFont(self.dangerzone.fixed_font) header_label.setFont(self.dangerzone.fixed_font)
header_label.setStyleSheet("QLabel { font-weight: bold; font-size: 50px; }") header_label.setStyleSheet("QLabel { font-weight: bold; font-size: 50px; }")
@ -1306,7 +1305,7 @@ class DocumentWidget(QtWidgets.QWidget):
def load_status_image(self, filename: str) -> QtGui.QPixmap: def load_status_image(self, filename: str) -> QtGui.QPixmap:
path = get_resource_path(filename) path = get_resource_path(filename)
img = QtGui.QImage(path) img = QtGui.QImage(str(path))
image = QtGui.QPixmap.fromImage(img) image = QtGui.QPixmap.fromImage(img)
return image.scaled(QtCore.QSize(15, 15)) return image.scaled(QtCore.QSize(15, 15))

View file

@ -64,7 +64,7 @@ class Container(IsolationProvider):
# #
# [1] https://github.com/freedomofpress/dangerzone/issues/846 # [1] https://github.com/freedomofpress/dangerzone/issues/846
# [2] https://github.com/containers/common/blob/d3283f8401eeeb21f3c59a425b5461f069e199a7/pkg/seccomp/seccomp.json # [2] https://github.com/containers/common/blob/d3283f8401eeeb21f3c59a425b5461f069e199a7/pkg/seccomp/seccomp.json
seccomp_json_path = get_resource_path("seccomp.gvisor.json") seccomp_json_path = str(get_resource_path("seccomp.gvisor.json"))
security_args += ["--security-opt", f"seccomp={seccomp_json_path}"] security_args += ["--security-opt", f"seccomp={seccomp_json_path}"]
security_args += ["--cap-drop", "all"] security_args += ["--cap-drop", "all"]

View file

@ -130,7 +130,6 @@ def is_qubes_native_conversion() -> bool:
# This disambiguates if it is running a Qubes targetted build or not # This disambiguates if it is running a Qubes targetted build or not
# (Qubes-specific builds don't ship the container image) # (Qubes-specific builds don't ship the container image)
container_image_path = get_resource_path("container.tar") return not get_resource_path("container.tar").exists()
return not os.path.exists(container_image_path)
else: else:
return False return False

View file

@ -27,7 +27,7 @@ class DangerzoneCore(object):
self.appdata_path = util.get_config_dir() self.appdata_path = util.get_config_dir()
# Languages supported by tesseract # Languages supported by tesseract
with open(get_resource_path("ocr-languages.json"), "r") as f: with get_resource_path("ocr-languages.json").open("r") as f:
unsorted_ocr_languages = json.load(f) unsorted_ocr_languages = json.load(f)
self.ocr_languages = dict(sorted(unsorted_ocr_languages.items())) self.ocr_languages = dict(sorted(unsorted_ocr_languages.items()))

View file

@ -1,9 +1,9 @@
import pathlib
import platform import platform
import subprocess import subprocess
import sys import sys
import traceback import traceback
import unicodedata import unicodedata
from pathlib import Path
try: try:
import platformdirs import platformdirs
@ -11,40 +11,39 @@ except ImportError:
import appdirs as platformdirs import appdirs as platformdirs
def get_config_dir() -> str: def get_config_dir() -> Path:
return platformdirs.user_config_dir("dangerzone") return Path(platformdirs.user_config_dir("dangerzone"))
def get_resource_path(filename: str) -> str: def get_resource_path(filename: str) -> Path:
if getattr(sys, "dangerzone_dev", False): if getattr(sys, "dangerzone_dev", False):
# Look for resources directory relative to python file # Look for resources directory relative to python file
project_root = pathlib.Path(__file__).parent.parent project_root = Path(__file__).parent.parent
prefix = project_root / "share" prefix = project_root / "share"
else: else:
if platform.system() == "Darwin": if platform.system() == "Darwin":
bin_path = pathlib.Path(sys.executable) bin_path = Path(sys.executable)
app_path = bin_path.parent.parent app_path = bin_path.parent.parent
prefix = app_path / "Resources" / "share" prefix = app_path / "Resources" / "share"
elif platform.system() == "Linux": elif platform.system() == "Linux":
prefix = pathlib.Path(sys.prefix) / "share" / "dangerzone" prefix = Path(sys.prefix) / "share" / "dangerzone"
elif platform.system() == "Windows": elif platform.system() == "Windows":
exe_path = pathlib.Path(sys.executable) exe_path = Path(sys.executable)
dz_install_path = exe_path.parent dz_install_path = exe_path.parent
prefix = dz_install_path / "share" prefix = dz_install_path / "share"
else: else:
raise NotImplementedError(f"Unsupported system {platform.system()}") raise NotImplementedError(f"Unsupported system {platform.system()}")
resource_path = prefix / filename return prefix / filename
return str(resource_path)
def get_tessdata_dir() -> pathlib.Path: def get_tessdata_dir() -> Path:
if getattr(sys, "dangerzone_dev", False) or platform.system() in ( if getattr(sys, "dangerzone_dev", False) or platform.system() in (
"Windows", "Windows",
"Darwin", "Darwin",
): ):
# Always use the tessdata path from the Dangerzone ./share directory, for # Always use the tessdata path from the Dangerzone ./share directory, for
# development builds, or in Windows/macOS platforms. # development builds, or in Windows/macOS platforms.
return pathlib.Path(get_resource_path("tessdata")) return get_resource_path("tessdata")
# In case of Linux systems, grab the Tesseract data from any of the following # In case of Linux systems, grab the Tesseract data from any of the following
# locations. We have found some of the locations through trial and error, whereas # locations. We have found some of the locations through trial and error, whereas
@ -55,11 +54,11 @@ def get_tessdata_dir() -> pathlib.Path:
# #
# [1] https://tesseract-ocr.github.io/tessdoc/Installation.html # [1] https://tesseract-ocr.github.io/tessdoc/Installation.html
tessdata_dirs = [ tessdata_dirs = [
pathlib.Path("/usr/share/tessdata/"), # on some Debian Path("/usr/share/tessdata/"), # on some Debian
pathlib.Path("/usr/share/tesseract/tessdata/"), # on Fedora Path("/usr/share/tesseract/tessdata/"), # on Fedora
pathlib.Path("/usr/share/tesseract-ocr/tessdata/"), # ? (documented) Path("/usr/share/tesseract-ocr/tessdata/"), # ? (documented)
pathlib.Path("/usr/share/tesseract-ocr/4.00/tessdata/"), # on Debian Bullseye Path("/usr/share/tesseract-ocr/4.00/tessdata/"), # on Debian Bullseye
pathlib.Path("/usr/share/tesseract-ocr/5/tessdata/"), # on Debian Trixie Path("/usr/share/tesseract-ocr/5/tessdata/"), # on Debian Trixie
] ]
for dir in tessdata_dirs: for dir in tessdata_dirs:
@ -71,7 +70,7 @@ def get_tessdata_dir() -> pathlib.Path:
def get_version() -> str: def get_version() -> str:
try: try:
with open(get_resource_path("version.txt")) as f: with get_resource_path("version.txt").open() as f:
version = f.read().strip() version = f.read().strip()
except FileNotFoundError: except FileNotFoundError:
# In dev mode, in Windows, get_resource_path doesn't work properly for the container, but luckily # In dev mode, in Windows, get_resource_path doesn't work properly for the container, but luckily

View file

@ -74,7 +74,7 @@ class TestContainer(IsolationProviderTest):
container_utils.get_runtime(), container_utils.get_runtime(),
"load", "load",
"-i", "-i",
get_resource_path("container.tar"), get_resource_path("container.tar").absolute(),
], ],
returncode=-1, returncode=-1,
) )
@ -113,7 +113,7 @@ class TestContainer(IsolationProviderTest):
container_utils.get_runtime(), container_utils.get_runtime(),
"load", "load",
"-i", "-i",
get_resource_path("container.tar"), get_resource_path("container.tar").absolute(),
], ],
) )
with pytest.raises(errors.ImageNotPresentException): with pytest.raises(errors.ImageNotPresentException):

View file

@ -11,7 +11,7 @@ VERSION_FILE_NAME = "version.txt"
def test_get_resource_path() -> None: def test_get_resource_path() -> None:
share_dir = Path("share").resolve() share_dir = Path("share").resolve()
resource_path = Path(util.get_resource_path(VERSION_FILE_NAME)).parent resource_path = util.get_resource_path(VERSION_FILE_NAME).parent
assert share_dir.samefile(resource_path), ( assert share_dir.samefile(resource_path), (
f"{share_dir} is not the same file as {resource_path}" f"{share_dir} is not the same file as {resource_path}"
) )