Skip to content

Commit

Permalink
Move hash_file to utils
Browse files Browse the repository at this point in the history
  • Loading branch information
septatrix committed Mar 29, 2024
1 parent 31af101 commit 248dfb4
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 13 deletions.
16 changes: 3 additions & 13 deletions mkosi/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import uuid
from collections.abc import Iterator, Mapping, Sequence
from pathlib import Path
from typing import Optional, TextIO, Union, cast
from typing import Optional, Union, cast

from mkosi.archive import extract_tar, make_cpio, make_tar
from mkosi.burn import run_burn
Expand Down Expand Up @@ -75,6 +75,7 @@
flock,
flock_or_die,
format_rlimit,
hash_file,
make_executable,
one_zero,
parents_below,
Expand Down Expand Up @@ -2457,17 +2458,6 @@ def copy_initrd(context: Context) -> None:
break


def hash_file(of: TextIO, path: Path) -> None:
bs = 16 * 1024**2
h = hashlib.sha256()

with path.open("rb") as sf:
while (buf := sf.read(bs)):
h.update(buf)

of.write(h.hexdigest() + " *" + path.name + "\n")


def calculate_sha256sum(context: Context) -> None:
if not context.config.checksum:
return
Expand All @@ -2478,7 +2468,7 @@ def calculate_sha256sum(context: Context) -> None:
with complete_step("Calculating SHA256SUMS…"):
with open(context.workspace / context.config.output_checksum, "w") as f:
for p in context.staging.iterdir():
hash_file(f, p)
print(hash_file(p) + " *" + p.name, file=f)

(context.workspace / context.config.output_checksum).rename(context.staging / context.config.output_checksum)

Expand Down
13 changes: 13 additions & 0 deletions mkosi/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import errno
import fcntl
import functools
import hashlib
import importlib
import importlib.resources
import itertools
Expand Down Expand Up @@ -298,3 +299,15 @@ def _write_contents(target, source):
p.parent.chmod(0o755)

yield p


def hash_file(path: Path) -> str:
# TODO Replace with hashlib.file_digest after dropping support for Python 3.10.
bs = 16 * 1024**2
h = hashlib.sha256()

with path.open("rb") as sf:
while (buf := sf.read(bs)):
h.update(buf)

return h.hexdigest()

0 comments on commit 248dfb4

Please sign in to comment.