sha256-to-hash.py: Gracefully handles errors, like invalid hashes in examples
This commit is contained in:
parent
9012e71c9b
commit
a0b1f164af
1 changed files with 18 additions and 9 deletions
|
@ -4,13 +4,12 @@
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import re
|
import logging, re
|
||||||
|
|
||||||
|
|
||||||
nix32alphabet = "0123456789abcdfghijklmnpqrsvwxyz"
|
nix32alphabet = "0123456789abcdfghijklmnpqrsvwxyz"
|
||||||
nix32inverted = { c: i for i, c in enumerate(nix32alphabet) }
|
nix32inverted = { c: i for i, c in enumerate(nix32alphabet) }
|
||||||
|
|
||||||
|
|
||||||
def nix32decode(s: str) -> bytes:
|
def nix32decode(s: str) -> bytes:
|
||||||
# only support sha256 hashes for now
|
# only support sha256 hashes for now
|
||||||
assert len(s) == 52
|
assert len(s) == 52
|
||||||
|
@ -60,9 +59,7 @@ def sha256toSRI(m: re.Match) -> str:
|
||||||
from base64 import b64decode
|
from base64 import b64decode
|
||||||
return toSRI(b64decode(m['base64']))
|
return toSRI(b64decode(m['base64']))
|
||||||
|
|
||||||
begin, end = m.span()
|
raise ValueError("Got a match where none of the groups captured")
|
||||||
raise ValueError("Got a match where none of the groups captured:\n"
|
|
||||||
f"'{m.string[begin:end]}'")
|
|
||||||
|
|
||||||
|
|
||||||
# Ohno I used evil, irregular backrefs instead of making 2 variants ^^'
|
# Ohno I used evil, irregular backrefs instead of making 2 variants ^^'
|
||||||
|
@ -73,10 +70,22 @@ _def_re = re.compile(
|
||||||
)
|
)
|
||||||
|
|
||||||
def defToSRI(s: str) -> str:
|
def defToSRI(s: str) -> str:
|
||||||
return _def_re.sub(
|
def f(m: re.Match[str]) -> str:
|
||||||
lambda m: f'hash = "{sha256toSRI(m)}";',
|
try:
|
||||||
s,
|
return f'hash = "{sha256toSRI(m)}";'
|
||||||
)
|
|
||||||
|
except ValueError as exn:
|
||||||
|
begin, end = m.span()
|
||||||
|
match = m.string[begin:end]
|
||||||
|
|
||||||
|
logging.error(
|
||||||
|
f"Skipping '%s': an exception was raised during rewriting",
|
||||||
|
match,
|
||||||
|
exc_info = exn,
|
||||||
|
)
|
||||||
|
return match
|
||||||
|
|
||||||
|
return _def_re.sub(f, s)
|
||||||
|
|
||||||
|
|
||||||
@contextmanager
|
@contextmanager
|
||||||
|
|
Loading…
Reference in a new issue