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.

Revisions

  1. jmitchell created this gist May 10, 2019.
    25 changes: 25 additions & 0 deletions protobuf_regenerate.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    #! /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"
    29 changes: 29 additions & 0 deletions regenerate.ex
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    # 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