databuild/job/execute_wrapper.sh.tpl
2025-04-18 22:35:20 -07:00

47 lines
1.4 KiB
Smarty
Executable file

#!/bin/bash
set -e
%{RUNFILES_PREFIX}
EXECUTE_BINARY="$(rlocation "_main/$(basename "%{EXECUTE_PATH}")")"
JQ="$(rlocation "databuild+/runtime/$(basename "%{JQ_PATH}")")"
# First argument should be the path to a config file
CONFIG_FILE=${1:-}
# Create a temporary file for stdin if needed
if [[ -z "$CONFIG_FILE" ]] || [[ "$CONFIG_FILE" == "-" ]]; then
TMP_CONFIG=$(mktemp)
cat > "$TMP_CONFIG"
CONFIG_FILE="$TMP_CONFIG"
trap 'rm -f "$TMP_CONFIG"' EXIT
fi
# Use jq to validate the config file
# First check if the file starts with { and ends with }
if [[ $(head -c 1 "$CONFIG_FILE") != "{" ]] || [[ $(tail -c 2 "$CONFIG_FILE" | head -c 1) != "}" ]]; then
echo "The config file must be a non-empty JSON object:"
cat $CONFIG_FILE
exit 1
fi
# Then validate that it parses
if ! $JQ 'type == "object"' $CONFIG_FILE > /dev/null 2>&1; then
echo "The config file must be a non-empty JSON object:"
cat $CONFIG_FILE
exit 1
fi
# Should be a single JSON object
# Extract and set environment variables from the config
eval "$("$JQ" -r '.env | to_entries | .[] | "export " + .key + "=\"" + .value + "\""' "$CONFIG_FILE")"
# Extract arguments from the config
ARGS=()
while IFS= read -r arg; do
ARGS+=("$arg")
done < <("$JQ" -r '.args[]' "$CONFIG_FILE")
# Run the execution with both environment variables (already set) and arguments
exec "$EXECUTE_BINARY" "${ARGS[@]}"