Skip to content

Instantly share code, notes, and snippets.

@rrbutani
Created September 30, 2024 23:12
Show Gist options
  • Save rrbutani/2530c3d770bb0f35bc5556b1c3c0aa75 to your computer and use it in GitHub Desktop.
Save rrbutani/2530c3d770bb0f35bc5556b1c3c0aa75 to your computer and use it in GitHub Desktop.
use nix -p bazel_7
.direnv/
/bazel-*
MODULE.bazel.lock
#!/usr/bin/env bash
# $1: src dir
# $2: bld dir
#
# reads $src/inputs/a
# reads $bld/existing_outputs/b
# produces $bld/my_outputs/*
set -euo pipefail
# set -x # to show progress (debugging)
readonly src="$1" bld="$2"
input_a="${src}/inputs/a"
input_b="${bld}/existing_outputs/b"
out_dir="$bld/my_outputs"
rm -rf "$out_dir"
mkdir -p "$out_dir"
cat "$input_a" > "${out_dir}/a"
cat "$input_b" > "${out_dir}/b"
cat "$input_a" "$input_b" > "${out_dir}/both"
# NOTE: Normally would need to use `new_local_repository`..
filegroup(
name = "src",
srcs = ["//:src/inputs/a"], # can use glob
)
filegroup(
name = "bld",
srcs = ["//:bld/existing_outputs/b"], # can use glob
)
genrule(
name = "test",
tools = [
":build.bash",
],
srcs = [
":src",
":bld",
# for the purpose of getting at the dir locations..
":src/inputs/a",
":bld/existing_outputs/b",
],
outs = ["out.tar.gz"],
# NOTE: naive approach; doesn't work because we cannot modify
# `$(location :bld)`.
# cmd = "; ".join([
# "$(location :build.bash) $(location :src) $(location :bld)"
# ])
cmd = "; ".join([
# set up a temp dir:
"tmp=$$(mktemp -d)",
# get path to just `src` and just `dst` — not `src/inputs/a`, etc.
"src=$$(dirname $$(dirname $(location :src/inputs/a)))",
"bld=$$(dirname $$(dirname $(location :bld/existing_outputs/b)))",
# copy inputs to our temp dir to accommodate the script that mutates the
# `bld` dir which has both inputs and outputs:
'cp -R "$$src" "$$tmp/src"',
'cp -R "$$bld" "$$tmp/bld"',
# run the script, pointing at our copied directories:
# '$(location :build.bash) "$$tmp/src" "$$tmp/bld" 2>&1',
# NOTE: in this case we actually don't to make a copy of `src`: it is
# not modified by the `build.bash` script! i.e. this works too:
'$(location :build.bash) "$$src" "$$tmp/bld" 2>&1',
# for debugging:
'tree $$tmp',
# NOTE: normally we'd do this to copy back the outputs for Bazel...
# unfortunately we can't because genrules are not allowed to have
# directory outputs.
# 'cp -R $$bld/my_outputs $(location :out)'
# Instead we'll make a tarball with out outputs of interest:
'out="$(location :out.tar.gz)"',
'mkdir -p "$$(dirname "$$out")"',
'tar cvf "$$out" -C "$$tmp" "bld/my_outputs"',
])
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment