Always resolve relative paths in Document class

Make the Document class always resolve relative input/output file paths,
which are usually passed as arguments by users.

Previously, resolving relative filepaths was a job left to the
instantiators of the Document class. This was error-prone since this
conversion must happen in all the places where we instantiated the
Document class.
This commit is contained in:
deeplow 2022-09-19 13:11:46 +01:00
parent be5a942a73
commit 7aa08457bd
No known key found for this signature in database
GPG key ID: 577982871529A52A
4 changed files with 16 additions and 10 deletions

View file

@ -12,8 +12,9 @@ def validate_input_filename(
) -> Optional[str]:
if value is None:
return None
Document.validate_input_filename(value)
return value
filename = Document.normalize_filename(value)
Document.validate_input_filename(filename)
return filename
@errors.handle_document_errors
@ -22,5 +23,6 @@ def validate_output_filename(
) -> Optional[str]:
if value is None:
return None
Document.validate_output_filename(value)
return value
filename = Document.normalize_filename(value)
Document.validate_output_filename(filename)
return filename

View file

@ -36,11 +36,11 @@ def cli_main(
display_banner()
document = Document(os.path.abspath(filename))
document = Document(filename)
# Validate safe PDF output filename
if output_filename:
document.output_filename = os.path.abspath(output_filename)
document.output_filename = output_filename
else:
document.output_filename = (
f"{os.path.splitext(document.input_filename)[0]}-safe.pdf"

View file

@ -23,6 +23,10 @@ class Document:
if input_filename:
self.input_filename = input_filename
@staticmethod
def normalize_filename(filename: str) -> str:
return os.path.abspath(filename)
@staticmethod
def validate_input_filename(filename: str) -> None:
try:
@ -41,7 +45,7 @@ class Document:
if not filename.endswith(".pdf"):
raise DocumentFilenameException("Safe PDF filename must end in '.pdf'")
try:
with open(os.path.abspath(filename), "wb"):
with open(filename, "wb"):
pass
except PermissionError as e:
raise DocumentFilenameException("Safe PDF filename is not writable") from e
@ -55,6 +59,7 @@ class Document:
@input_filename.setter
def input_filename(self, filename: str) -> None:
filename = self.normalize_filename(filename)
self.validate_input_filename(filename)
self._input_filename = filename
@ -67,5 +72,6 @@ class Document:
@output_filename.setter
def output_filename(self, filename: str) -> None:
filename = self.normalize_filename(filename)
self.validate_output_filename(filename)
self._output_filename = filename

View file

@ -102,9 +102,7 @@ def gui_main(filename: Optional[str]) -> bool:
if filename is None:
new_window()
else:
# If filename is passed as an argument, open it
input_filename: str = os.path.abspath(os.path.expanduser(filename))
new_window(input_filename)
new_window(filename)
# Open a new window, if all windows are closed
def application_activated() -> None: