···
+
#!/usr/bin/env nix-shell
+
#! nix-shell -i "python3 -I" -p "python3.withPackages(p: with p; [ rich structlog ])"
+
from abc import ABC, abstractclassmethod, abstractmethod
+
from contextlib import contextmanager
+
from pathlib import Path
+
from structlog.contextvars import bound_contextvars as log_context
+
from typing import ClassVar, List, Tuple
+
import hashlib, re, structlog
+
logger = structlog.getLogger("sha-to-SRI")
+
alphabet: ClassVar[str]
+
return cls.__name__.lower()
+
def toSRI(self, s: str) -> str:
+
digest = self.decode(s)
+
assert len(digest) == self.n
+
from base64 import b64encode
+
return f"{self.hashName}-{b64encode(digest).decode()}"
+
def all(cls, h) -> 'List[Encoding]':
+
return [ c(h) for c in cls.__subclasses__() ]
+
def length(self) -> int:
+
def regex(self) -> str:
+
return f"[{self.alphabet}]{{{self.length}}}"
+
def decode(self, s: str) -> bytes:
+
alphabet = "0123456789abcdfghijklmnpqrsvwxyz"
+
inverted = { c: i for i, c in enumerate(alphabet) }
+
return 1 + (8 * self.n) // 5
+
def decode(self, s: str):
+
assert len(s) == self.length
+
out = [ 0 for _ in range(self.n) ]
+
# TODO: Do better than a list of byte-sized ints
+
for n, c in enumerate(reversed(s)):
+
digit = self.inverted[c]
+
i, j = divmod(5 * n, 8)
+
out[i] = out[i] | (digit << j) & 0xff
+
raise ValueError(f"Invalid nix32 hash: '{s}'")
+
def decode(self, s: str):
+
from binascii import unhexlify
+
class Base64(Encoding):
+
alphabet = "A-Za-z0-9+/"
+
def format(self) -> Tuple[int, int]:
+
"""Number of characters in data and padding."""
+
i, k = divmod(self.n, 3)
+
return 4 * i + (0 if k == 0 else k + 1), (3 - k) % 3
+
return sum(self.format)
+
data, padding = self.format
+
return f"[{self.alphabet}]{{{data}}}={{{padding}}}"
+
from base64 import b64decode
+
return b64decode(s, validate = True)
+
_HASHES = (hashlib.new(n) for n in ('SHA-256', 'SHA-512'))
+
h.name: Encoding.all(h)
+
(f"({h}-)?" if e.name == 'base64' else '') +
+
f"(?P<{h}_{e.name}>{e.regex})"
+
) for h, encodings in ENCODINGS.items()
+
_DEF_RE = re.compile("|".join(
+
f"(?P<{h}>{h} = (?P<{h}_quote>['\"])({re})(?P={h}_quote);)"
+
for h, re in RE.items()
+
def defToSRI(s: str) -> str:
+
def f(m: re.Match[str]) -> str:
+
for h, encodings in ENCODINGS.items():
+
s = m.group(f"{h}_{e.name}")
+
return f'hash = "{e.toSRI(s)}";'
+
raise ValueError(f"Match with '{h}' but no subgroup")
+
raise ValueError("Match with no hash")
+
except ValueError as exn:
+
return _DEF_RE.sub(f, s)
+
def atomicFileUpdate(target: Path):
+
'''Atomically replace the contents of a file.
+
Guarantees that no temporary files are left behind, and `target` is either
+
left untouched, or overwritten with new content if no exception was raised.
+
Yields a pair `(original, new)` of open files.
+
`original` is the pre-existing file at `target`, open for reading;
+
`new` is an empty, temporary file in the same filder, open for writing.
+
Upon exiting the context, the files are closed; if no exception was
+
raised, `new` (atomically) replaces the `target`, otherwise it is deleted.
+
# That's mostly copied from noto-emoji.py, should DRY it out
+
from tempfile import mkstemp
+
with target.open() as original:
+
with tmpPath.open('w') as new:
+
tmpPath.replace(target)
+
tmpPath.unlink(missing_ok = True)
+
def fileToSRI(p: Path):
+
with atomicFileUpdate(p) as (og, new):
+
for i, line in enumerate(og):
+
with log_context(line=i):
+
new.write(defToSRI(line))
+
"(generated by)|(do not edit)",
+
if __name__ == "__main__":
+
from sys import argv, stderr
+
logger.info("Starting!")
+
with log_context(path=str(p)):
+
if p.name == "yarn.nix" or p.name.find("generated") != -1:
+
logger.warning("File looks autogenerated, skipping!")
+
if _SKIP_RE.search(line):
+
logger.warning("File looks autogenerated, skipping!")
+
except Exception as exn:
+
"Unhandled exception, skipping file!",
+
logger.info("Finished processing file")