Skip to content

Instantly share code, notes, and snippets.

@jmitchell
Created May 10, 2019 20:15
Show Gist options
  • Save jmitchell/847543a8b366e07408f0a16bfde68f99 to your computer and use it in GitHub Desktop.
Save jmitchell/847543a8b366e07408f0a16bfde68f99 to your computer and use it in GitHub Desktop.
Regenerate Elixir modules from protobuf schema at the specified URL. Depends on nix package manager.
#! /usr/bin/env nix-shell
#! nix-shell -i bash -p elixir_1_8 erlang protobuf curl
#! nix-shell -I nixpkgs=https://github.com/NixOS/nixpkgs-channels/archive/nixos-19.03.tar.gz
## Adapted from directions at https://github.com/tony612/protobuf-elixir
# lives at ./script/protobuf_regenerate.sh
set -ex
TARGET_DIR="$(dirname "$0")/../lib"
SCHEMA_URL="$1"
SCHEMA_FILE="${TARGET_DIR}/schema.proto"
# install protoc-gen-elixir plugin to ~/.mix/escripts/
mix escript.install --force hex protobuf
# download protobuf schema
curl "$SCHEMA_URL" > "$SCHEMA_FILE"
# generate elixir modules
protoc --proto_path="$TARGET_DIR" \
--elixir_out="$TARGET_DIR" \
--plugin="protoc-gen-elixir=$HOME/.mix/escripts/protoc-gen-elixir" \
"$SCHEMA_FILE"
# lives at ./lib/mix/tasks/protobuf/regenerate.ex
defmodule Mix.Tasks.Protobuf.Regenerate do
use Mix.Task
@default_schema_url "FIXME"
@moduledoc """
Fetches a protobuf schema and regenerates modules.
mix protobuf.regenerate [URL]
The protobuf schema URL is downloaded to ./lib/schema.proto. Then Elixir
modules are generated to ./lib/schema.pb.ex.
When URL is omitted it defaults to #{@default_schema_url}.
*Notice*: This task assumes the [nix package
manager](https://nixos.org/nix/) is installed.
"""
@shortdoc "Fetches protobuf schema and regenerates modules."
def run([url]) do
script_path = Path.join([File.cwd!(), "script", "protobuf_regenerate.sh"])
System.cmd(script_path, [url], into: IO.stream(:stdio, :line), stderr_to_stdout: true)
end
def run([]), do: run([@default_schema_url])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment