2023-01-02 00:14:48 +00:00
|
|
|
"""Rule for generating integrity files
|
|
|
|
|
|
|
|
Default output is a .sha256 file but .sha1 and .md5 files are also available
|
|
|
|
via output groups.
|
|
|
|
|
|
|
|
Based on https://github.com/bazelbuild/examples/blob/main/rules/implicit_output/hash.bzl
|
|
|
|
"""
|
|
|
|
|
2023-03-10 17:37:57 +00:00
|
|
|
def _hash(ctx, algo, file):
|
|
|
|
coreutils = ctx.toolchains["@aspect_bazel_lib//lib:coreutils_toolchain_type"]
|
2023-09-21 22:12:46 +00:00
|
|
|
out = ctx.actions.declare_file("{}.{}".format(file.basename, algo), sibling = file)
|
2023-01-02 00:14:48 +00:00
|
|
|
ctx.actions.run_shell(
|
2023-03-10 17:37:57 +00:00
|
|
|
outputs = [out],
|
|
|
|
inputs = [file],
|
|
|
|
tools = [coreutils.coreutils_info.bin],
|
|
|
|
# coreutils has --no-names option but it doesn't work in current version, so we have to use cut.
|
|
|
|
command = """HASH=$({coreutils} hashsum --{algo} {src} | {coreutils} cut -f1 -d " ") && {coreutils} echo -ne "$HASH {basename}" > {out}""".format(
|
2023-06-09 23:22:37 +00:00
|
|
|
coreutils = coreutils.coreutils_info.bin.path,
|
|
|
|
algo = algo,
|
|
|
|
src = file.path,
|
2023-03-10 17:37:57 +00:00
|
|
|
basename = file.basename,
|
2023-06-09 23:22:37 +00:00
|
|
|
out = out.path,
|
2023-03-10 17:37:57 +00:00
|
|
|
),
|
2023-01-02 00:14:48 +00:00
|
|
|
)
|
2023-03-10 17:37:57 +00:00
|
|
|
return out
|
2023-01-02 00:14:48 +00:00
|
|
|
|
2023-03-10 17:37:57 +00:00
|
|
|
def _impl(ctx):
|
|
|
|
# Create actions to generate the three output files.
|
|
|
|
# Actions are run only when the corresponding file is requested.
|
2023-01-02 00:14:48 +00:00
|
|
|
|
2023-03-10 17:37:57 +00:00
|
|
|
md5out = _hash(ctx, "md5", ctx.file.src)
|
|
|
|
sha1out = _hash(ctx, "sha1", ctx.file.src)
|
|
|
|
sha256out = _hash(ctx, "sha256", ctx.file.src)
|
2023-01-02 00:14:48 +00:00
|
|
|
|
|
|
|
# By default (if you run `bazel build` on this target, or if you use it as a
|
|
|
|
# source of another target), only the sha256 is computed.
|
|
|
|
return [
|
|
|
|
DefaultInfo(
|
|
|
|
files = depset([sha256out]),
|
|
|
|
),
|
|
|
|
OutputGroupInfo(
|
|
|
|
md5 = depset([md5out]),
|
|
|
|
sha1 = depset([sha1out]),
|
|
|
|
sha256 = depset([sha256out]),
|
|
|
|
),
|
|
|
|
]
|
|
|
|
|
|
|
|
_hashes = rule(
|
|
|
|
implementation = _impl,
|
2023-03-10 17:37:57 +00:00
|
|
|
toolchains = [
|
|
|
|
"@aspect_bazel_lib//lib:coreutils_toolchain_type",
|
|
|
|
],
|
2023-01-02 00:14:48 +00:00
|
|
|
attrs = {
|
|
|
|
"src": attr.label(
|
|
|
|
allow_single_file = True,
|
|
|
|
mandatory = True,
|
2023-06-09 23:22:37 +00:00
|
|
|
),
|
2023-01-02 00:14:48 +00:00
|
|
|
},
|
|
|
|
)
|
|
|
|
|
|
|
|
def hashes(name, src, **kwargs):
|
|
|
|
_hashes(
|
|
|
|
name = name,
|
|
|
|
src = src,
|
|
|
|
**kwargs
|
|
|
|
)
|