Skip to content

Commit

Permalink
IMPROVE: Propagate exceptions
Browse files Browse the repository at this point in the history
- Propagate KeyError from KeyHandler
- Do not catch UnsupportedMetadataOperation in metadatawidget since it
will never be thrown
- Fix lint
  • Loading branch information
jcjgraf committed Feb 9, 2021
1 parent 77ee889 commit 16ec200
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 47 deletions.
16 changes: 4 additions & 12 deletions vimiv/gui/metadatawidget.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,12 +121,8 @@ def metadata_list_keys(self, n_cols: int = 3, to_term: bool = False):
* ``--to-term``: Print the keys to the terminal instead.
"""

try:
keys = sorted(set(self.handler.get_keys()))
_logger.debug("Successfully got keys")
except metadata.UnsupportedMetadataOperation:
# TODO: should actually never happen
pass
keys = sorted(set(self.handler.get_keys()))
_logger.debug("Successfully got keys")
if to_term:
print(*keys, sep="\n")
elif n_cols < 1:
Expand Down Expand Up @@ -166,12 +162,8 @@ def _update_text(self):
e.strip() for e in api.settings.metadata.current_keyset.value.split(",")
]
_logger.debug(f"Read metadata.current_keys {keys}")
try:
data = self.handler.fetch_keys(keys)
_logger.debug("Fetched metadata")
except data.UnsupportedMetadataOperation:
# TODO: should never happen
pass
data = self.handler.fetch_keys(keys)
_logger.debug("Fetched metadata")

if data:
self.setText(utils.format_html_table(data.values()))
Expand Down
67 changes: 33 additions & 34 deletions vimiv/imutils/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,16 +68,16 @@ def _get_ydimension(self):
return self.reader.size().height()

def __getitem__(self, key: str) -> Tuple[str, str, str]:
"""Intrypoint to extract the key of the image at _path.
"""Entrypoint to extract the key of the image at _path.
Args:
key: internal key to fetch.
Throws:
KeyError
"""
try:
key, func = super().get(key.lower())
return (key, key, func())
except KeyError:
return ("", "", "")
key, func = super().__getitem__(key.lower())
return (key, key, func())

def get_keys(self) -> Iterable[str]:
"""Returns a sequence of all available metadata keys."""
Expand Down Expand Up @@ -119,6 +119,9 @@ def fetch_key(self, _base_key: str) -> Tuple[str, str, str]:
Args:
_base_key: metadata key to fetch.
Throws:
KeyError
"""
self.raise_exception("Getting formatted keys")

Expand Down Expand Up @@ -150,7 +153,7 @@ def __init__(self, filename=""):
def fetch_key(self, base_key: str) -> Tuple[str, str, str]:
key = base_key.rpartition(".")[2]

try:
with contextlib.suppress(piexif.InvalidImageDateError):
for ifd in self._metadata:
if ifd == "thumbnail":
continue
Expand Down Expand Up @@ -189,10 +192,7 @@ def fetch_key(self, base_key: str) -> Tuple[str, str, str]:
): # (int, int) <=> numerator, denominator
return (keyname, keyname, f"{val[0]}/{val[1]}")

except (piexif.InvalidImageDataError, KeyError):
return ("", "", "")

return ("", "", "")
raise KeyError(f"Key '{base_key}' not found")

def get_keys(self) -> Iterable[str]:
return (
Expand Down Expand Up @@ -271,28 +271,23 @@ def fetch_key(self, base_key: str) -> Tuple[str, str, str]:
# For backwards compability, assume it has one of the following prefixes
for prefix in ["", "Exif.Image.", "Exif.Photo."]:
key = f"{prefix}{base_key}"
try:
key_name = self._metadata[key].name

try:
key_value = self._metadata[key].human_value
key_name = self._metadata[key].name

# Not all metadata (i.e. IPTC) provide human_value, take raw_value
except AttributeError:
value = self._metadata[key].raw_value

# For IPTC the raw_value is a list of strings
if isinstance(value, list):
key_value = ", ".join(value)
else:
key_value = value
try:
key_value = self._metadata[key].human_value

return (key, key_name, key_value)
# Not all metadata (i.e. IPTC) provide human_value, take raw_value
except AttributeError:
value = self._metadata[key].raw_value

except KeyError:
_logger.debug("Key %s is invalid for the current image", key)
# For IPTC the raw_value is a list of strings
if isinstance(value, list):
key_value = ", ".join(value)
else:
key_value = value

return ("", "", "")
return (key, key_name, key_value)
raise KeyError(f"Key '{base_key}' not found")

def get_keys(self) -> Iterable[str]:
"""Return a iteable of all available metadata keys."""
Expand Down Expand Up @@ -361,10 +356,11 @@ def _external_handler(self) -> ExternalKeyHandler:
def fetch_keys(self, desired_keys: Sequence[str]) -> Dict[Any, Tuple[str, str]]:
"""Extracts a list of metadata keys.
Throws: UnsupportedMetadataOperation.
Args:
desired_keys: list of metadata keys to extract.
Throws:
UnsupportedMetadataOperation
"""
metadata = dict()

Expand All @@ -382,10 +378,12 @@ def fetch_keys(self, desired_keys: Sequence[str]) -> Dict[Any, Tuple[str, str]]:
def fetch_key(self, key: str) -> Tuple[str, str, str]:
"""Extracts a single metadata key.
Throws: UnsupportedMetadataOperation.
Args:
key: single metadata key to extract.
Throws:
UnsupportedMetadataOperation
KeyError
"""
if key.lower().startswith("vimiv"):
return self._internal_handler[key]
Expand All @@ -394,7 +392,8 @@ def fetch_key(self, key: str) -> Tuple[str, str, str]:
def get_keys(self) -> Iterable[str]:
"""Retrieve the name of all metadata keys available.
Throws: UnsupportedMetadataOperation
Throws:
UnsupportedMetadataOperation
"""
return itertools.chain(
self._internal_handler.get_keys(), self._external_handler.get_keys()
Expand Down
3 changes: 2 additions & 1 deletion vimiv/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ def info() -> str:
f"Qt: {QT_VERSION_STR}\n"
f"PyQt: {PYQT_VERSION_STR}\n\n"
f"Svg Support: {bool(QtSvg)}\n"
f"Pyexiv2: {metadata.pyexiv2.__version__ if metadata.pyexiv2 is not None else None}\n"
"Pyexiv2: "
f"{metadata.pyexiv2.__version__ if metadata.pyexiv2 is not None else None}\n"
f"Piexif: {metadata.piexif.VERSION if metadata.piexif is not None else None}"
)

Expand Down

0 comments on commit 16ec200

Please sign in to comment.