Skip to content

Commit

Permalink
Merge pull request #190 from Nitrokey/fetch-update-error-message
Browse files Browse the repository at this point in the history
nk3: Improve error message for fetch-update
  • Loading branch information
robin-nitrokey committed Feb 9, 2022
2 parents 8a16a1e + 859f37a commit 210992c
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
10 changes: 7 additions & 3 deletions pynitrokey/cli/nk3/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
from pynitrokey.nk3.exceptions import TimeoutException
from pynitrokey.nk3.updates import get_repo
from pynitrokey.nk3.utils import Version
from pynitrokey.updates import OverwriteError

T = TypeVar("T", bound=Nitrokey3Base)

Expand Down Expand Up @@ -250,15 +251,18 @@ def fetch_update(path: str, force: bool, version: Optional[str]) -> None:
path = update.download_to_dir(path, overwrite=force, callback=bar.update)
else:
if not force and os.path.exists(path):
raise CliException(
f"{path} already exists. Use --force to overwrite the file."
)
raise OverwriteError(path)
with open(path, "wb") as f:
update.download(f, callback=bar.update)

bar.close()

local_print(f"Successfully downloaded firmware release {update.tag} to {path}")
except OverwriteError as e:
raise CliException(
f"{e.path} already exists. Use --force to overwrite the file.",
support_hint=False,
)
except Exception as e:
raise CliException(f"Failed to download firmware update {update.tag}", e)

Expand Down
17 changes: 14 additions & 3 deletions pynitrokey/updates.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,17 @@
ProgressCallback = Callable[[int, int], None]


class DownloadError(Exception):
def __init__(self, msg: str) -> None:
super().__init__("Cannot download firmware: " + msg)


class OverwriteError(Exception):
def __init__(self, path: str) -> None:
super().__init__(f"File {path} already exists and may not be overwritten")
self.path = path


class FirmwareUpdate:
def __init__(self, tag: str, url: str) -> None:
self.tag = tag
Expand All @@ -37,14 +48,14 @@ def download_to_dir(
callback: Optional[ProgressCallback] = None,
) -> str:
if not os.path.exists(d):
raise Exception(f"Cannot download firmware: {d} does not exist")
raise DownloadError(f"Directory {d} does not exist")
if not os.path.isdir(d):
raise Exception(f"Cannot download firmware: {d} is not a directory")
raise DownloadError(f"{d} is not a directory")
url = urllib.parse.urlparse(self.url)
filename = os.path.basename(url.path)
path = os.path.join(d, filename)
if os.path.exists(path) and not overwrite:
raise Exception(f"File {path} already exists and may not be overwritten")
raise OverwriteError(path)
with open(path, "wb") as f:
self.download(f, callback=callback)
return path
Expand Down

0 comments on commit 210992c

Please sign in to comment.