Skip to content

Instantly share code, notes, and snippets.

@btoo
Last active August 26, 2022 02:12
Show Gist options
  • Save btoo/fe96ae81f3a439d05c1534ff5bd816c9 to your computer and use it in GitHub Desktop.
Save btoo/fe96ae81f3a439d05c1534ff5bd816c9 to your computer and use it in GitHub Desktop.
i stole this protobuf-to-typescript converter from a really smart friend of mine
#!/usr/bin/env bash
DIR=$(dirname "${BASH_SOURCE[0]}")
DIR=$(cd "$DIR" || exit; pwd -P)
if ! type protoc &> /dev/null; then
echo "Dependency 'protoc' is not installed."
echo
echo " If you are on macOS, you can use 'brew install protobuf'."
echo
echo " Otherwise you can use a pre-built binary from 'https://github.com/protocolbuffers/protobuf/releases/'"
exit 0
fi
function usage() {
echo "Usage: proto2ts.sh [-I <INCLUDE_PATH>] PROTO_FILE"
}
while getopts "I:h?" option ; do
case "$option" in
I) INCLUDES+=("${OPTARG}") ;;
h|\?) usage ; exit 0 ;;
esac
done
shift $((OPTIND - 1))
if (($# == 0)); then
usage
exit 1
fi
INCLUDES=("${INCLUDES[@]/#/-I}")
read -r -p "Generate methods for binary payloads? [y/n]: " response;
case "$response" in
[yY][eE][sS]|[yY]) ENCODE_METHODS=true ;;
*) ENCODE_METHODS=false ;;
esac
read -r -p "Generate methods for JSON payloads? [y/n]: " response;
case "$response" in
[yY][eE][sS]|[yY]) JSON_METHODS=true ;;
*) JSON_METHODS=false ;;
esac
PLUGIN_PATH="$DIR/../node_modules/.bin/protoc-gen-ts_proto"
PROTO_FILE=$(basename "$1")
PROTO_PATH=$(dirname "$1")
cd "$PROTO_PATH" || exit 1
# Generate code based on the provided `.proto` file.
protoc \
--plugin="$PLUGIN_PATH" \
--ts_proto_opt=forceLong=string \
--ts_proto_opt=useOptionals=true \
--ts_proto_opt=outputEncodeMethods=$ENCODE_METHODS \
--ts_proto_opt=outputJsonMethods=$JSON_METHODS \
--ts_proto_opt=outputClientImpl=false \
--ts_proto_out=. \
"${INCLUDES[@]}" \
"$PROTO_FILE"
# Echo a line-break for nicer output.
echo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment