browser: fix file browser for paths with spaces

This commit is contained in:
dece 2021-06-03 21:47:28 +02:00
parent 52716e66a7
commit 7cb6d03668

View file

@ -2,6 +2,7 @@
import logging import logging
from pathlib import Path from pathlib import Path
from urllib.parse import quote, unquote
from bebop.browser.browser import Browser from bebop.browser.browser import Browser
from bebop.page import Page from bebop.page import Page
@ -10,10 +11,9 @@ from bebop.page import Page
def open_file(browser: Browser, filepath: str, encoding="utf-8"): def open_file(browser: Browser, filepath: str, encoding="utf-8"):
"""Open a file and render it. """Open a file and render it.
This should be used only on Gemtext files or at least text files. This should be used only text files or directories. Anything else will
Anything else will produce garbage and may crash the program. In the produce garbage and may crash the program. In the future this should be able
future this should be able to use a different parser according to a MIME to use a different parser according to a MIME type or something.
type or something.
Arguments: Arguments:
- browser: Browser object making the request. - browser: Browser object making the request.
@ -23,28 +23,29 @@ def open_file(browser: Browser, filepath: str, encoding="utf-8"):
Returns: Returns:
The loaded file URI on success, None otherwise (e.g. file not found). The loaded file URI on success, None otherwise (e.g. file not found).
""" """
path = Path(filepath) path = Path(unquote(filepath))
if not path.exists(): if not path.exists():
logging.error(f"File {filepath} does not exist.") logging.error(f"File {path} does not exist.")
return None return None
if path.is_file(): if path.is_file():
try: try:
with open(filepath, "rt", encoding=encoding) as f: with open(path, "rt", encoding=encoding) as f:
text = f.read() text = f.read()
except (OSError, ValueError) as exc: except (OSError, ValueError) as exc:
browser.set_status_error(f"Failed to open file: {exc}") browser.set_status_error(f"Failed to open file: {exc}")
return None return None
browser.load_page(Page.from_text(text)) browser.load_page(Page.from_text(text))
elif path.is_dir(): elif path.is_dir():
gemtext = filepath + "\n\n" gemtext = str(path) + "\n\n"
for entry in sorted(path.iterdir()): for entry in sorted(path.iterdir()):
entry_path = quote(str(entry.absolute()))
name = entry.name name = entry.name
if entry.is_dir(): if entry.is_dir():
name += "/" name += "/"
gemtext += f"=> {entry} {name}\n" gemtext += f"=> {entry_path} {name}\n"
wrap_at = browser.config["text_width"] wrap_at = browser.config["text_width"]
browser.load_page(Page.from_gemtext(gemtext, wrap_at)) browser.load_page(Page.from_gemtext(gemtext, wrap_at))
file_url = "file://" + filepath file_url = f"file://{path}"
browser.current_url = file_url browser.current_url = file_url
return file_url return file_url