Skip to content

Commit

Permalink
Merge branch 'mr/cardao/e3.hash/add-PathLike-support' into 'master'
Browse files Browse the repository at this point in the history
Add PathLike type support for e3.hash methods

See merge request it/e3-core!69
  • Loading branch information
leocardao committed Dec 3, 2024
2 parents 25a4a43 + 39ab353 commit 7f2ea4b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/e3/hash.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,16 @@

if TYPE_CHECKING:
from typing import Literal
from os import PathLike


class HashError(e3.error.E3Error):
pass


def __compute_hash(
path: str, kind: Literal["md5"] | Literal["sha1"] | Literal["sha256"]
path: PathLike[str] | str,
kind: Literal["md5"] | Literal["sha1"] | Literal["sha256"],
) -> str:
if not os.path.isfile(path):
raise HashError(kind, f"cannot find {path}")
Expand All @@ -31,7 +33,7 @@ def __compute_hash(
return result.hexdigest()


def md5(path: str) -> str:
def md5(path: PathLike[str] | str) -> str:
"""Compute md5 hexadecimal digest of a file.
:param path: path to a file
Expand All @@ -42,7 +44,7 @@ def md5(path: str) -> str:
return __compute_hash(path, "md5")


def sha1(path: str) -> str:
def sha1(path: PathLike[str] | str) -> str:
"""Compute sha1 hexadecimal digest of a file.
:param str path: path to a file
Expand All @@ -53,7 +55,7 @@ def sha1(path: str) -> str:
return __compute_hash(path, "sha1")


def sha256(path: str) -> str:
def sha256(path: PathLike[str] | str) -> str:
"""Compute sha256 hexadecimal digest of a file.
:param str path: path to a file
Expand Down
17 changes: 17 additions & 0 deletions tests/tests_e3/hash/main_test.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
from __future__ import annotations

import os
from pathlib import Path

import e3.hash

import pytest
Expand All @@ -14,3 +19,15 @@ def test_hash():
)
with pytest.raises(e3.hash.HashError):
e3.hash.md5("doesnotexist")

# Check if PathLike[str] parameter is accepted
p = Path(f.name)
# Ensure `p` follow PathLike[str] rule
assert isinstance(os.fspath(p), str)

assert e3.hash.md5(p) == "f75b8179e4bbe7e2b4a074dcef62de95"
assert e3.hash.sha1(p) == "7fe70820e08a1aac0ef224d9c66ab66831cc4ab1"
assert (
e3.hash.sha256(p)
== "434728a410a78f56fc1b5899c3593436e61ab0c731e9072d95e96db290205e53"
)

0 comments on commit 7f2ea4b

Please sign in to comment.