Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

265 righe
9.4 KiB

  1. #### TODO ####
  2. - write a rebar3 template for plugin writing, make it easier on our poor souls
  3. - rework the tutorial to use the rebar3 template for plugins
  4. # Plugins #
  5. Rebar3's system is based on the concept of *[providers](https://github.com/tsloughter/providers)*. A provider has three callbacks:
  6. - `init(State) -> {ok, NewState}`, which helps set up the state required, state dependencies, etc.
  7. - `do(State) -> {ok, NewState} | {error, Error}`, which does the actual work.
  8. - `format_error(Error) -> String`, which allows to print errors when they happen, and to filter out sensitive elements from the state.
  9. A provider should also be an OTP Library application, which can be fetched as any other Erlang dependency, except for Rebar3 rather than your own system or application.
  10. This document contains the following elements:
  11. - [Using a Plugin](#using-a-plugin)
  12. - [Reference](#reference)
  13. - [Provider Interface](#provider-interface)
  14. - [List of Possible Dependencies](#list-of-possible-dependencies)
  15. - [Rebar State Manipulation](#rebar-state-manipulation)
  16. - [Tutorial](#tutorial)
  17. ## Using a Plugin ##
  18. ## Reference ##
  19. ### Provider Interface ###
  20. ### List of Possible Dependencies ###
  21. ### Rebar State Manipulation ###
  22. ## Tutorial ##
  23. ### First version ###
  24. In this tutorial, we'll show how to start from scratch, and get a basic plugin written. The plugin will be quite simple: it will look for instances of 'TODO:' lines in comments and report them as warnings. The final code for the plugin can be found on [bitbucket](https://bitbucket.org/ferd/rebar3-todo-plugin).
  25. The first step is to create a new OTP Application that will contain the plugin:
  26. → git init
  27. Initialized empty Git repository in /Users/ferd/code/self/rebar3-todo-plugin/.git/
  28. → mkdir src
  29. → touch src/provider_todo.erl src/provider_todo.app.src
  30. Let's edit the app file to make sure the description is fine:
  31. ```erlang
  32. {application, provider_todo, [
  33. {description, "example rebar3 plubin"},
  34. {vsn, "0.1.0"},
  35. {registered, []},
  36. {applications, [kernel, stdlib]},
  37. {env, []}
  38. ]}.
  39. ```
  40. Open up the `provider_todo.erl` file and make sure you have the following skeleton in place:
  41. ```erlang
  42. -module(provider_todo).
  43. -behaviour(provider).
  44. -export([init/1, do/1, format_error/1]).
  45. -include_lib("rebar3/include/rebar.hrl").
  46. -define(PROVIDER, todo).
  47. -define(DEPS, [app_discovery]).
  48. %% ===================================================================
  49. %% Public API
  50. %% ===================================================================
  51. -spec init(rebar_state:t()) -> {ok, rebar_state:t()}.
  52. init(State) ->
  53. Provider = providers:create([
  54. {name, ?PROVIDER}, % The 'user friendly' name of the task
  55. {module, ?MODULE}, % The module implementation of the task
  56. {bare, true}, % The task can be run by the user, always true
  57. {deps, ?DEPS}, % The list of dependencies
  58. {example, "rebar $PLUGIN"}, % How to use the plugin
  59. {opts, []} % list of options understood by the plugin
  60. {short_desc, ""},
  61. {desc, ""}
  62. ]),
  63. {ok, rebar_state:add_provider(State, Provider)}.
  64. -spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}.
  65. do(State) ->
  66. {ok, State}.
  67. -spec format_error(any()) -> iolist().
  68. format_error(Reason) ->
  69. io_lib:format("~p", [Reason]).
  70. ```
  71. This shows all the basic content needed. Note that we leave the `DEPS` macro to the value `app_discovery`, used to mean that the plugin should at least find the project's source code (excluding dependencies).
  72. In this case, we need to change very little in `init/1`. Here's the new provider description:
  73. ```erlang
  74. Provider = providers:create([
  75. {name, ?PROVIDER}, % The 'user friendly' name of the task
  76. {module, ?MODULE}, % The module implementation of the task
  77. {bare, true}, % The task can be run by the user, always true
  78. {deps, ?DEPS}, % The list of dependencies
  79. {example, "rebar todo"}, % How to use the plugin
  80. {opts, []}, % list of options understood by the plugin
  81. {short_desc, "Reports TODOs in source code"},
  82. {desc, "Scans top-level application source and find "
  83. "instances of TODO: in commented out content "
  84. "to report it to the user."}
  85. ]),
  86. ```
  87. Instead, most of the work will need to be done directly in `do/1`. We'll use the `rebar_state` module to fetch all the applications we need. This can be done by calling the `project_apps/1` function, which returns the list of the project's top-level applications.
  88. ```erlang
  89. do(State) ->
  90. lists:foreach(fun check_todo_app/1, rebar_state:project_apps(State)),
  91. {ok, State}.
  92. ```
  93. This, on a high level, means that we'll check each top-level app one at a time (there may often be more than one top-level application when working with releases)
  94. The rest is filler code specific to the plugin, in charge of reading each app path, go read code in there, and find instances of 'TODO:' in comments in the code:
  95. ```erlang
  96. check_todo_app(App) ->
  97. Path = filename:join(rebar_app_info:dir(App),"src"),
  98. Mods = find_source_files(Path),
  99. case lists:foldl(fun check_todo_mod/2, [], Mods) of
  100. [] -> ok;
  101. Instances -> display_todos(rebar_app_info:name(App), Instances)
  102. end.
  103. find_source_files(Path) ->
  104. [filename:join(Path, Mod) || Mod <- filelib:wildcard("*.erl", Path)].
  105. check_todo_mod(ModPath, Matches) ->
  106. {ok, Bin} = file:read_file(ModPath),
  107. case find_todo_lines(Bin) of
  108. [] -> Matches;
  109. Lines -> [{ModPath, Lines} | Matches]
  110. end.
  111. find_todo_lines(File) ->
  112. case re:run(File, "%+.*(TODO:.*)", [{capture, all_but_first, binary}, global, caseless]) of
  113. {match, DeepBins} -> lists:flatten(DeepBins);
  114. nomatch -> []
  115. end.
  116. display_todos(_, []) -> ok;
  117. display_todos(App, FileMatches) ->
  118. io:format("Application ~s~n",[App]),
  119. [begin
  120. io:format("\t~s~n",[Mod]),
  121. [io:format("\t ~s~n",[TODO]) || TODO <- TODOs]
  122. end || {Mod, TODOs} <- FileMatches],
  123. ok.
  124. ```
  125. Just using `io:format/2` to output is going to be fine.
  126. To test the plugin, push it to a source repository somewhere. Pick one of your projects, and add something to the rebar.config:
  127. ```erlang
  128. {plugins, [
  129. {provider_todo, ".*", {git, "git@bitbucket.org:ferd/rebar3-todo-plugin.git", {branch, "master"}}}
  130. ]}.
  131. ```
  132. Then you can just call it directly:
  133. ```
  134. → rebar3 todo
  135. ===> Fetching provider_todo
  136. Cloning into '.tmp_dir539136867963'...
  137. ===> Compiling provider_todo
  138. Application merklet
  139. /Users/ferd/code/self/merklet/src/merklet.erl
  140. todo: consider endianness for absolute portability
  141. ```
  142. Rebar3 will download and install the plugin, and figure out when to run it. Once compiled, it can be run at any time again.
  143. ### Optionally Search Deps ###
  144. Let's extend things a bit. Maybe from time to time (when cutting a release), we'd like to make sure none of our dependencies contain 'TODO:'s either.
  145. To do this, we'll need to go parse command line arguments a bit, and change our execution model. The `?DEPS` macro will now need to specify that the `todo` provider can only run *after* dependencies have been installed:
  146. ```erlang
  147. -define(DEPS, [install_deps]).
  148. ```
  149. We can add the option to the list we use to configure the provider in `init/1`:
  150. ```erlang
  151. {opts, [ % list of options understood by the plugin
  152. {deps, $d, "deps", undefined, "also run against dependencies"}
  153. ]},
  154. ```
  155. Meaning that deps can be flagged in by using the option `-d` (or `--deps`), and if it's not defined, well, we get the default value `undefined`. The last element of the 4-tuple is documentation for the option.
  156. And then we can implement the switch to figure out what to search:
  157. ```erlang
  158. do(State) ->
  159. Apps = case discovery_type(State) of
  160. project -> rebar_state:project_apps(State);
  161. deps -> rebar_state:project_apps(State) ++ rebar_state:src_deps(State)
  162. end,
  163. lists:foreach(fun check_todo_app/1, Apps),
  164. {ok, State}.
  165. [...]
  166. discovery_type(State) ->
  167. {Args, _} = rebar_state:command_parsed_args(State),
  168. case proplists:get_value(deps, Args) of
  169. undefined -> project;
  170. _ -> deps
  171. end.
  172. ```
  173. The `deps` option is found using `rebar_state:command_parsed_args(State)`, which will return a proplist of terms on the command-line after 'todo', and will take care of validating whether the flags are accepted or not. The rest can remain the same.
  174. Push the new code for the plugin, and try it again on a project with dependencies:
  175. ```
  176. → rebar3 todo --deps
  177. ===> Fetching provider_todo
  178. ===> Compiling provider_todo
  179. ===> Fetching bootstrap
  180. ===> Fetching file_monitor
  181. ===> Fetching recon
  182. [...]
  183. Application dirmon
  184. /Users/ferd/code/self/figsync/apps/dirmon/src/dirmon_tracker.erl
  185. TODO: Peeranha should expose the UUID from a node.
  186. Application meck
  187. /Users/ferd/code/self/figsync/_deps/meck/src/meck_proc.erl
  188. TODO: What to do here?
  189. TODO: What to do here?
  190. ```
  191. Rebar3 will now go pick dependencies before running the plugin on there.
  192. you can also see that the help will be completed for you:
  193. ```
  194. → rebar3 help todo
  195. Scans top-level application source and find instances of TODO: in commented out content to report it to the user.
  196. Usage: rebar todo [-d]
  197. -d, --deps also run against dependencies
  198. ```
  199. That's it, the todo plugin is now complete! It's ready to ship and be included in other repositories.