一、生成插件工程
假設插件名爲testp,執行rebar3 new plugins testp,即生成了插件工程項目,查看目錄結構如圖:
testp.erl文件調用初始化的代碼,而插件最重要的代碼在testp_prv.erl的文件,文件裏提供了三個接口,分別爲init/1,do/1,format_error/1,init做插件初始化的工作,初始化命名空間/初始化命令,然後將命令加入到rebar3,貼一份配置:
init(State) ->
Provider = providers:create([
{name, compile}, % The 'user friendly' name of the task
{module, ?MODULE}, % The module implementation of the task
{namespace, testp},
{bare, true}, % The task can be run by the user, always true
{deps, ?DEPS}, % The list of dependencies
{example, "rebar3 testp compile"}, % How to use the plugin
{opts, []}, % list of options understood by the plugin
{short_desc, "rebar3 testp compiler"},
{desc, "rebar3 testp compiler"}
]),
{ok, rebar_state:add_provider(State, Provider)}.
這份配置就是爲rebar3添加一個rebar3 testp compile命令,如果只輸入rebar3 testp,會提示rebar3 testp compiler。
第二個方法do就是主要的業務邏輯了,執行了rebar3 testp compiler命令就會調用裏面的do方法。
如果想添加多個命令,可以在testp.erl裏多寫一個命令的init調用,然後再添加一個命令類似的prv文件,寫不同的do業務邏輯,就可以上傳git,將git地址配置在rebar.config的plugins裏了,rebar3 compile編譯就自動拉取插件代碼。
插件還可以配置鉤子(provider_hook)使用,例如添加編譯前調用
{provider_hooks,[{pre[{compile, {testp, compile}}]}]},編譯後調用將pre改爲post即可