schema/generate-schema.sh
#!/bin/bash
set -euo pipefail
topdir=$(git rev-parse --show-toplevel)
mydir=$(dirname $(readlink -f $0))
tdir="${mydir}/tmp"
mkdir -p "${tdir}"
trap "rm -rfv ${tdir}" EXIT

schema_version="v1"
schema_json="${schema_version}.json"
digest=$(sha256sum "${schema_json}" | awk '{print $1}')
echo "Generating COSA Schema ${schema_version}"

out="${tdir}/cosa_${schema_version}.go"

schematyper=
if test -f ${topdir}/bin/schematyper; then
    schematyper=${topdir}/bin/schematyper
else
    schematyper=$(which schematyper 2>/dev/null || true)
fi
if test -z "${schematyper}"; then
    if [ ! -d "${topdir}/schematyper" ]; then
        git clone https://github.com/idubinskiy/schematyper.git ${topdir}/schematyper
        go -C ${topdir}/schematyper mod edit -replace gopkg.in/alecthomas/kingpin.v2=github.com/alecthomas/kingpin/v2@v2.4.0
        go -C ${topdir}/schematyper mod tidy && go -C ${topdir}/schematyper mod vendor
        go -C ${topdir}/schematyper build
    fi
    schematyper=${topdir}/schematyper/schematyper
fi

${schematyper} \
    ${topdir}/src/"${schema_version}.json" \
    -o "${out}" \
    --package="builds" \
    --root-type=Build \
    --ptr-for-omit

# Avoid having a filename in generated code since it
# can vary depending on local checkout paths.
sed -e "s|^// generated.*|// generated by 'make schema'\n// source hash: ${digest}|g"  -i ${tdir}/cosa_v1.go

cat > "${tdir}/schema_doc.go" <<EOM
// Generated by ${0}
// Source hash: ${digest}
// DO NOT EDIT

package builds

var generatedSchemaJSON = \`$(< ${schema_json})
\`
EOM

cp -av ${tdir}/*go ${mydir}/../pkg/builds/
