├── .gitignore ├── LICENSE ├── README.md ├── priv ├── grpcbox_service_bhvr.erl ├── grpcbox_service_bhvr.template ├── grpcbox_service_client.erl └── grpcbox_service_client.template ├── rebar.config ├── rebar.lock └── src ├── grpcbox_plugin.app.src ├── grpcbox_plugin.erl └── grpcbox_plugin_prv.erl /.gitignore: -------------------------------------------------------------------------------- 1 | .rebar3 2 | _* 3 | .eunit 4 | *.o 5 | *.beam 6 | *.plt 7 | *.swp 8 | *.swo 9 | .erlang.cookie 10 | ebin 11 | log 12 | erl_crash.dump 13 | .rebar 14 | logs 15 | _build 16 | .idea 17 | *.iml 18 | rebar3.crashdump 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | Copyright 2017, Tristan Sloughter . 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | http://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. 191 | 192 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | grpcbox Plugin 2 | ===== 3 | 4 | A rebar3 plugin for generating a behaviour per grpc service, for use with [grpcbox](https://github.com/tsloughter/grpcbox). 5 | 6 | Build 7 | ----- 8 | 9 | ``` 10 | $ rebar3 compile 11 | ``` 12 | 13 | Use 14 | --- 15 | 16 | Add the plugin to your rebar config: 17 | 18 | ``` 19 | {deps, [grpcbox]}. 20 | 21 | {grpc, [{protos, "proto"}, 22 | {gpb_opts, [{module_name_suffix, "_pb"}]}]}. 23 | 24 | {plugins, [grpcbox_plugin]}. 25 | ``` 26 | 27 | Currently `grpcbox` and this plugin are a bit picky and the `gpb` options will always include `[use_packages, maps, type_specs, strings_as_binaries, {i, "."}, {o, "src"}]`. 28 | 29 | Assuming the `proto` directory of your application has the `route_guide.proto` found in this repo, `test/grpcbox_SUITE_data/route_guide.proto`, the output from running the plugin will be: 30 | 31 | ``` 32 | $ rebar3 grpc gen 33 | ===> Writing src/route_guide_pb.erl 34 | ===> Writing src/grpcbox_route_guide_behaviour.erl 35 | ``` 36 | -------------------------------------------------------------------------------- /priv/grpcbox_service_bhvr.erl: -------------------------------------------------------------------------------- 1 | %%%------------------------------------------------------------------- 2 | %% @doc Behaviour to implement for grpc service {{unmodified_service_name}}. 3 | %% @end 4 | %%%------------------------------------------------------------------- 5 | 6 | %% this module was generated and should not be modified manually 7 | 8 | -module({{module_name}}_bhvr). 9 | 10 | {{#methods}} 11 | %% {{^input_stream}}{{^output_stream}}Unary RPC{{/output_stream}}{{/input_stream}} 12 | -callback {{method}}({{^input_stream}}{{#output_stream}}{{pb_module}}:{{input}}(), grpcbox_stream:t(){{/output_stream}}{{/input_stream}}{{#input_stream}}{{^output_stream}}reference(), grpcbox_stream:t(){{/output_stream}}{{#output_stream}}reference(), grpcbox_stream:t(){{/output_stream}}{{/input_stream}}{{^input_stream}}{{^output_stream}}ctx:t(), {{pb_module}}:{{input}}(){{/output_stream}}{{/input_stream}}) -> 13 | {{#output_stream}}ok{{/output_stream}}{{^output_stream}}{ok, {{pb_module}}:{{output}}(), ctx:t()}{{/output_stream}} | grpcbox_stream:grpc_error_response(). 14 | 15 | {{/methods}} 16 | -------------------------------------------------------------------------------- /priv/grpcbox_service_bhvr.template: -------------------------------------------------------------------------------- 1 | {description, "Grpc service server behaviour template"}. 2 | {variables, 3 | [{unmodified_service_name, [], "Original name of the service, as it'll appear in a request"}, 4 | {pb_module, "", "Name of protobuf module to get type specs from"}, 5 | {module_name, [], "Name of the module for the service"}, 6 | {methods, [], "List of methods for service"}]}. 7 | {template, "grpcbox_service_bhvr.erl", "{{out_dir}}/{{module_name}}_bhvr.erl"}. 8 | -------------------------------------------------------------------------------- /priv/grpcbox_service_client.erl: -------------------------------------------------------------------------------- 1 | %%%------------------------------------------------------------------- 2 | %% @doc Client module for grpc service {{unmodified_service_name}}. 3 | %% @end 4 | %%%------------------------------------------------------------------- 5 | 6 | %% this module was generated and should not be modified manually 7 | 8 | -module({{module_name}}_client). 9 | 10 | -compile(export_all). 11 | -compile(nowarn_export_all). 12 | 13 | -include_lib("grpcbox/include/grpcbox.hrl"). 14 | 15 | -define(is_ctx(Ctx), is_tuple(Ctx) andalso element(1, Ctx) =:= ctx). 16 | 17 | -define(SERVICE, '{{unmodified_service_name}}'). 18 | -define(PROTO_MODULE, '{{pb_module}}'). 19 | -define(MARSHAL_FUN(T), fun(I) -> ?PROTO_MODULE:encode_msg(I, T) end). 20 | -define(UNMARSHAL_FUN(T), fun(I) -> ?PROTO_MODULE:decode_msg(I, T) end). 21 | -define(DEF(Input, Output, MessageType), #grpcbox_def{service=?SERVICE, 22 | message_type=MessageType, 23 | marshal_fun=?MARSHAL_FUN(Input), 24 | unmarshal_fun=?UNMARSHAL_FUN(Output)}). 25 | 26 | {{#methods}} 27 | %% @doc {{^input_stream}}{{^output_stream}}Unary RPC{{/output_stream}}{{/input_stream}} 28 | -spec {{method}}({{^input_stream}}{{pb_module}}:{{input}}(){{/input_stream}}) -> 29 | {{^output_stream}}{{^input_stream}}{ok, {{pb_module}}:{{output}}(), grpcbox:metadata()}{{/input_stream}}{{#input_stream}}{ok, grpcbox_client:stream()}{{/input_stream}}{{/output_stream}}{{#output_stream}}{{^input_stream}}{ok, grpcbox_client:stream()}{{/input_stream}}{{#input_stream}}{ok, grpcbox_client:stream()}{{/input_stream}}{{/output_stream}} | grpcbox_stream:grpc_error_response() | {error, any()}. 30 | {{method}}({{^input_stream}}Input{{/input_stream}}) -> 31 | {{method}}(ctx:new(){{^input_stream}}, Input{{/input_stream}}, #{}). 32 | 33 | -spec {{method}}(ctx:t(){{^input_stream}} | {{pb_module}}:{{input}}(){{/input_stream}}{{^input_stream}}, {{pb_module}}:{{input}}(){{/input_stream}} | grpcbox_client:options()) -> 34 | {{^output_stream}}{{^input_stream}}{ok, {{pb_module}}:{{output}}(), grpcbox:metadata()}{{/input_stream}}{{#input_stream}}{ok, grpcbox_client:stream()}{{/input_stream}}{{/output_stream}}{{#output_stream}}{{^input_stream}}{ok, grpcbox_client:stream()}{{/input_stream}}{{#input_stream}}{ok, grpcbox_client:stream()}{{/input_stream}}{{/output_stream}} | grpcbox_stream:grpc_error_response() | {error, any()}. 35 | {{method}}(Ctx{{^input_stream}}, Input{{/input_stream}}) when ?is_ctx(Ctx) -> 36 | {{method}}(Ctx{{^input_stream}}, Input{{/input_stream}}, #{}); 37 | {{method}}({{^input_stream}}Input, {{/input_stream}}Options) -> 38 | {{method}}(ctx:new(){{^input_stream}}, Input{{/input_stream}}, Options). 39 | 40 | -spec {{method}}(ctx:t(){{^input_stream}}, {{pb_module}}:{{input}}(){{/input_stream}}, grpcbox_client:options()) -> 41 | {{^output_stream}}{{^input_stream}}{ok, {{pb_module}}:{{output}}(), grpcbox:metadata()}{{/input_stream}}{{#input_stream}}{ok, grpcbox_client:stream()}{{/input_stream}}{{/output_stream}}{{#output_stream}}{{^input_stream}}{ok, grpcbox_client:stream()}{{/input_stream}}{{#input_stream}}{ok, grpcbox_client:stream()}{{/input_stream}}{{/output_stream}} | grpcbox_stream:grpc_error_response() | {error, any()}. 42 | {{method}}(Ctx{{^input_stream}}, Input{{/input_stream}}, Options) -> 43 | {{^output_stream}}{{^input_stream}}grpcbox_client:unary(Ctx, <<"/{{unmodified_service_name}}/{{unmodified_method}}">>, Input, ?DEF({{input}}, {{output}}, <<"{{message_type}}">>), Options){{/input_stream}}{{#input_stream}}grpcbox_client:stream(Ctx, <<"/{{unmodified_service_name}}/{{unmodified_method}}">>, ?DEF({{input}}, {{output}}, <<"{{message_type}}">>), Options){{/input_stream}}{{/output_stream}}{{#output_stream}}{{^input_stream}}grpcbox_client:stream(Ctx, <<"/{{unmodified_service_name}}/{{unmodified_method}}">>, Input, ?DEF({{input}}, {{output}}, <<"{{message_type}}">>), Options){{/input_stream}}{{#input_stream}}grpcbox_client:stream(Ctx, <<"/{{unmodified_service_name}}/{{unmodified_method}}">>, ?DEF({{input}}, {{output}}, <<"{{message_type}}">>), Options){{/input_stream}}{{/output_stream}}. 44 | 45 | {{/methods}} 46 | -------------------------------------------------------------------------------- /priv/grpcbox_service_client.template: -------------------------------------------------------------------------------- 1 | {description, "Grpc service client template"}. 2 | {variables, 3 | [{unmodified_service_name, [], "Original name of the service, as it'll appear in a request"}, 4 | {pb_module, "", "Name of protobuf module to get type specs from"}, 5 | {module_name, [], "Name of the module for the service"}, 6 | {methods, [], "List of methods for service"}]}. 7 | {template, "grpcbox_service_client.erl", "{{out_dir}}/{{module_name}}_client.erl"}. 8 | -------------------------------------------------------------------------------- /rebar.config: -------------------------------------------------------------------------------- 1 | {erl_opts, [debug_info]}. 2 | {deps, [{gpb, "~> 4.21"}, 3 | {providers, "~> 1.9"}]}. 4 | -------------------------------------------------------------------------------- /rebar.lock: -------------------------------------------------------------------------------- 1 | {"1.2.0", 2 | [{<<"cf">>,{pkg,<<"cf">>,<<"0.3.1">>},2}, 3 | {<<"erlware_commons">>,{pkg,<<"erlware_commons">>,<<"1.4.0">>},1}, 4 | {<<"getopt">>,{pkg,<<"getopt">>,<<"1.0.1">>},1}, 5 | {<<"gpb">>,{pkg,<<"gpb">>,<<"4.21.1">>},0}, 6 | {<<"providers">>,{pkg,<<"providers">>,<<"1.9.0">>},0}]}. 7 | [ 8 | {pkg_hash,[ 9 | {<<"cf">>, <<"5CB902239476E141EA70A740340233782D363A31EEA8AD37049561542E6CD641">>}, 10 | {<<"erlware_commons">>, <<"F9EE38412E1413944BE78736DDB9BDB4C0664ABA5133563F4F3B359A8ED0AD52">>}, 11 | {<<"getopt">>, <<"C73A9FA687B217F2FF79F68A3B637711BB1936E712B521D8CE466B29CBF7808A">>}, 12 | {<<"gpb">>, <<"72E229C242D252D690ADDCFD04A6416C26C4D4D2C3521E05570A7A78B48D3BD1">>}, 13 | {<<"providers">>, <<"46F6645B0C677B1029E02B013BFD69092A2232854DAF359F2378FA42AC0BEC0D">>}]}, 14 | {pkg_hash_ext,[ 15 | {<<"cf">>, <<"315E8D447D3A4B02BCDBFA397AD03BBB988A6E0AA6F44D3ADD0F4E3C3BF97672">>}, 16 | {<<"erlware_commons">>, <<"185ECF5CF43BAB3A013DDB3614CE7BBA7F6C7A827904E64E57DA54FCDFDCE2E6">>}, 17 | {<<"getopt">>, <<"53E1AB83B9CEB65C9672D3E7A35B8092E9BDC9B3EE80721471A161C10C59959C">>}, 18 | {<<"gpb">>, <<"C05C9AEA9E25BD341367A43B3D3EB68E951563911072259C5EC4CB6642F4EF22">>}, 19 | {<<"providers">>, <<"D287E874406A1505608642B0A3DB5B68D6ADA3F2AB001AEC87E7F4D7C79FC017">>}]} 20 | ]. 21 | -------------------------------------------------------------------------------- /src/grpcbox_plugin.app.src: -------------------------------------------------------------------------------- 1 | {application,grpcbox_plugin, 2 | [{description,"Rebar3 plugin to generate behaviours for grpc services"}, 3 | {vsn,"git"}, 4 | {registered,[]}, 5 | {applications,[kernel,stdlib,gpb,providers]}, 6 | {env,[]}, 7 | {modules,[]}, 8 | {licenses,["Apache 2.0"]}, 9 | {links,[{"Github", 10 | "https://github.com/tsloughter/grpcbox_plugin"}]}]}. 11 | -------------------------------------------------------------------------------- /src/grpcbox_plugin.erl: -------------------------------------------------------------------------------- 1 | -module(grpcbox_plugin). 2 | 3 | -export([init/1]). 4 | 5 | -spec init(rebar_state:t()) -> {ok, rebar_state:t()}. 6 | init(State) -> 7 | {ok, State1} = grpcbox_plugin_prv:init(State), 8 | {ok, State1}. 9 | -------------------------------------------------------------------------------- /src/grpcbox_plugin_prv.erl: -------------------------------------------------------------------------------- 1 | -module(grpcbox_plugin_prv). 2 | 3 | -export([init/1, do/1, format_error/1]). 4 | 5 | -include_lib("providers/include/providers.hrl"). 6 | 7 | -define(PROVIDER, gen). 8 | -define(NAMESPACE, grpc). 9 | -define(DEPS, [{default, app_discovery}]). 10 | 11 | %% =================================================================== 12 | %% Public API 13 | %% =================================================================== 14 | -spec init(rebar_state:t()) -> {ok, rebar_state:t()}. 15 | init(State) -> 16 | Provider = providers:create( 17 | [{name, ?PROVIDER}, % The 'user friendly' name of the task 18 | {namespace, ?NAMESPACE}, 19 | {module, ?MODULE}, % The module implementation of the task 20 | {bare, true}, % The task can be run by the user, always true 21 | {deps, ?DEPS}, % The list of dependencies 22 | {example, "rebar3 grpc gen"}, % How to use the plugin 23 | {opts, [{protos, $p, "protos", string, "directory of protos to build"}, 24 | {force, $f, "force", boolean, "overwrite already generated modules"}, 25 | {type, $t, "type", string, "generate 'client', 'server' or 'all'"}]}, 26 | {short_desc, "Generates behaviours for grpc services"}, 27 | {desc, "Generates behaviours for grpc services"}]), 28 | {ok, rebar_state:add_provider(State, Provider)}. 29 | 30 | 31 | -spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}. 32 | do(State) -> 33 | Apps = case rebar_state:current_app(State) of 34 | undefined -> 35 | rebar_state:project_apps(State); 36 | AppInfo -> 37 | [AppInfo] 38 | end, 39 | {Options, _} = rebar_state:command_parsed_args(State), 40 | lists:foreach(fun(AppInfo) -> handle_app(AppInfo, Options, State) end, Apps), 41 | {ok, State}. 42 | 43 | -spec format_error(any()) -> iolist(). 44 | format_error({compile_errors, Errors}) -> 45 | [[io_lib:format("Error building ~s~n", [File]) | 46 | [io_lib:format(" ~p: ~s", [Line, M:format_error(E)]) 47 | || {Line, M, E} <- Es]] 48 | || {File, Es} <- Errors]; 49 | format_error({gpb, File, Error}) -> 50 | io_lib:format("Error compiling proto file ~s ~s", [filename:basename(File), 51 | gpb_compile:format_error(Error)]); 52 | format_error(Reason) -> 53 | io_lib:format("~p", [Reason]). 54 | 55 | handle_app(AppInfo, Options, State) -> 56 | Opts = rebar_app_info:opts(AppInfo), 57 | BeamOutDir = rebar_app_info:ebin_dir(AppInfo), 58 | ok = filelib:ensure_dir(filename:join(BeamOutDir, "fake.beam")), 59 | GrpcOpts = rebar_opts:get(Opts, grpc, []), 60 | GpbOpts = proplists:get_value(gpb_opts, GrpcOpts, []), 61 | BaseDir = rebar_app_info:dir(AppInfo), 62 | GrpcOptOutDir = proplists:get_value(out_dir, GrpcOpts, filename:join(BaseDir, "src")), 63 | GrpcOutDir = filename:join(BaseDir, GrpcOptOutDir), 64 | GpbOutDir = filename:join(BaseDir, proplists:get_value(o, GpbOpts, GrpcOptOutDir)), 65 | 66 | ProtosDirs = case proplists:get_all_values(protos, Options) of 67 | [] -> 68 | case proplists:get_value(protos, GrpcOpts, [filename:join("priv", "protos")]) of 69 | [H | _] = Ds when is_list(H) -> 70 | Ds; 71 | D -> 72 | [D] 73 | end; 74 | Ds -> 75 | Ds 76 | end, 77 | ProtoFiles = lists:append([filelib:wildcard(filename:join([BaseDir, D, "*.proto"])) || D <- ProtosDirs]), 78 | 79 | Type = case proplists:get_value(type, Options, undefined) of 80 | undefined -> 81 | proplists:get_value(type, GrpcOpts, all); 82 | T when T =:= "all" orelse T =:= "client" -> 83 | T 84 | end, 85 | Templates = templates(Type), 86 | ProtoModules = [compile_pb(Filename, GpbOutDir, BeamOutDir, GpbOpts) || Filename <- ProtoFiles], 87 | [gen_services(Templates, ProtoModule, ProtoBeam, GrpcOutDir, GrpcOpts, State) 88 | || {ProtoModule, ProtoBeam} <- ProtoModules], 89 | ok. 90 | 91 | compile_pb(Filename, OutDir, BeamOutDir, GpbOpts) -> 92 | ModuleName = lists:flatten( 93 | [proplists:get_value(module_name_prefix, GpbOpts, ""), 94 | filename:basename(Filename, ".proto"), 95 | proplists:get_value(module_name_suffix, GpbOpts, "")]), 96 | GeneratedPB = filename:join(OutDir, ModuleName ++ ".erl"), 97 | CompiledPB = filename:join(BeamOutDir, ModuleName ++ ".beam"), 98 | ok = filelib:ensure_dir(GeneratedPB), 99 | case needs_update(Filename, GeneratedPB) of 100 | true -> 101 | rebar_log:log(info, "Writing ~s", [GeneratedPB]), 102 | case gpb_compile:file(Filename, [{rename,{msg_name,snake_case}}, 103 | {rename,{msg_fqname,base_name}}, 104 | use_packages, maps, 105 | strings_as_binaries, {i, "."}, 106 | {report_errors, false}, 107 | {o, OutDir} | GpbOpts]) of 108 | ok -> 109 | ok; 110 | {error, Error} -> 111 | erlang:error(?PRV_ERROR({gpb, Filename, Error})) 112 | end; 113 | false -> 114 | ok 115 | end, 116 | case needs_update(GeneratedPB, CompiledPB) of 117 | true -> 118 | GpbIncludeDir = filename:join(code:lib_dir(gpb), "include"), 119 | case compile:file(GeneratedPB, [{outdir, BeamOutDir}, {i, GpbIncludeDir}, return_errors]) of 120 | {ok, _} -> 121 | ok; 122 | {ok, _, Warnings} -> 123 | log_warnings(Warnings), 124 | ok; 125 | {error, Errors, Warnings} -> 126 | log_warnings(Warnings), 127 | throw(?PRV_ERROR({compile_errors, Errors})) 128 | end; 129 | false -> 130 | ok 131 | end, 132 | {module, Module} = code:load_abs(filename:join(BeamOutDir, ModuleName)), 133 | {Module, CompiledPB}. 134 | 135 | gen_services(Templates, ProtoModule, ProtoBeam, OutDir, GrpcConfig, State) -> 136 | ServiceDefs = [gen_service_def(S, ProtoModule, GrpcConfig, OutDir) 137 | || S <- ProtoModule:get_service_names()], 138 | WithTemplates = [{S, TemplateSuffix, TemplateName} 139 | || S <- ServiceDefs, {TemplateSuffix, TemplateName} <- Templates], 140 | Services = lists:filter(fun(S) -> filter_outdated(S, OutDir, ProtoBeam) end, WithTemplates), 141 | rebar_log:log(debug, "services: ~p", [Services]), 142 | [rebar_templater:new(TemplateName, maps:to_list(Service), true, State) 143 | || {Service, _, TemplateName} <- Services]. 144 | 145 | gen_service_def(Service, ProtoModule, GrpcConfig, FullOutDir) -> 146 | ServiceModules = proplists:get_value(service_modules, GrpcConfig, []), 147 | ServicePrefix = proplists:get_value(prefix, GrpcConfig, ""), 148 | ServiceSuffix = proplists:get_value(suffix, GrpcConfig, ""), 149 | {{_, Name}, Methods} = ProtoModule:get_service_def(Service), 150 | ModuleName = proplists:get_value(Name, ServiceModules, list_snake_case(atom_to_list(Name))), 151 | #{out_dir => FullOutDir, 152 | pb_module => atom_to_list(ProtoModule), 153 | unmodified_service_name => atom_to_list(Name), 154 | module_name => ServicePrefix ++ ModuleName ++ ServiceSuffix, 155 | methods => [resolve_method(M, ProtoModule) || M <- Methods]}. 156 | 157 | resolve_method(Method, ProtoModule) -> 158 | MessageType = {message_type, ProtoModule:msg_name_to_fqbin(maps:get(input, Method))}, 159 | MethodData = lists:flatmap(fun normalize_method_opt/1, maps:to_list(Method)), 160 | [MessageType | MethodData]. 161 | 162 | filter_outdated({#{module_name := ModuleName}, TemplateSuffix, _}, OutDir, ProtoBeam) -> 163 | ModulePath = filename:join([OutDir, ModuleName ++ "_" ++ TemplateSuffix ++ ".erl"]), 164 | ok = filelib:ensure_dir(ModulePath), 165 | needs_update(ProtoBeam, ModulePath). 166 | 167 | templates(S) when is_list(S) -> 168 | templates(list_to_existing_atom(S)); 169 | templates(all) -> 170 | [{"client", "grpcbox_service_client"}, 171 | {"bhvr", "grpcbox_service_bhvr"}]; 172 | templates(client) -> 173 | [{"client", "grpcbox_service_client"}]; 174 | templates(server) -> 175 | [{"bhvr", "grpcbox_service_bhvr"}]. 176 | 177 | normalize_method_opt({opts, _}) -> 178 | []; 179 | normalize_method_opt({name, Name}) -> 180 | StrName = atom_to_list(Name), 181 | [{method, list_snake_case(StrName)}, 182 | {unmodified_method, StrName}]; 183 | normalize_method_opt({K, V}) when V =:= true; V =:= false -> 184 | [{K, V}]; 185 | normalize_method_opt({K, V}) -> 186 | [{K, atom_to_list(V)}]. 187 | 188 | list_snake_case(NameString) -> 189 | Snaked = lists:foldl( 190 | fun(RE, Snaking) -> 191 | re:replace(Snaking, RE, "\\1_\\2", [{return, list}, global]) 192 | end, 193 | NameString, 194 | [%% uppercase followed by lowercase 195 | "(.)([A-Z][a-z]+)", 196 | %% any consecutive digits 197 | "(.)([0-9]+)", 198 | %% uppercase with lowercase 199 | %% or digit before it 200 | "([a-z0-9])([A-Z])"]), 201 | Snaked1 = string:replace(Snaked, ".", "_", all), 202 | Snaked2 = string:replace(Snaked1, "__", "_", all), 203 | string:to_lower(unicode:characters_to_list(Snaked2)). 204 | 205 | needs_update(Source, Artifact) -> 206 | filelib:last_modified(Source) >= filelib:last_modified(Artifact). 207 | 208 | log_warnings(Warnings) -> 209 | [begin 210 | rebar_api:warn("Warning building ~s~n", [File]), 211 | [rebar_api:warn(" ~p: ~s", [Line, M:format_error(E)]) || {Line, M, E} <- Es] 212 | end || {File, Es} <- Warnings]. 213 | --------------------------------------------------------------------------------