Erlang Rebar 使用指南之一:入门篇

时间:2023-03-08 21:26:43

Erlang Rebar 使用指南之一:入门篇

全文目录:

https://github.com/rebar/rebar/wiki

本章原文:

https://github.com/rebar/rebar/wiki/Getting-started

Rebar 是功能丰富的 Erlang 构建工具。用于Erlang/OTP项目的编译,测试,依赖管理,打包发布等。

Rebar 是自包含的脚本,可以方便地嵌入到项目中。

1 编译 rebar

    $ git clone git://github.com/rebar/rebar.git
    $ cd rebar
    $ ./bootstrap

查看命令说明:

    $ ./rebar -c
    $ ./rebar help clean

2 入门例子

2.1 创建一个程序目录

    $ mkdir myapp
    $ cd myapp

把 “1 编译 rebar” 得到的 rebar 复制到myapp目录中

    $ cp ../rebar/rebar .

2.2 创建第一个rebar项目

    $ ./rebar create-app appid=myapp
    $ touch rebar.config

上面命令执行后,在myapp/src生成了3个文件:
  myapp.app.src - OTP应用资源
  myapp_app.erl - 一个实现 OTP application behaviour
  myapp_sup.erl - 最顶层的 OTP Supervisor behaviour
 

2.3 编译项目

    $ ./rebar compile

上面命令执行后,生成ebin目录,包含与src/erl文件对应的.beam文件.
  src/myapp.app.src 生成 ebin/myapp.app

  清理项目

    $ ./rebar clean

2.4 测试项目

Rebar 支持 EUnit和Common Test测试框架。给项目增加 EUint 单元测试,  增加下面的代码到
  src/myapp_app.erl:

-export([start/2, stop/1]). 后面添加:

    %% eunit testing
    -ifdef(TEST).
    -include_lib("eunit/include/eunit.hrl").
    -endif.

在文件末尾添加:

    %% eunit testing
    -ifdef(TEST).

    simple_test() ->
        ok = application:start(myapp),
        ?assertNot(undefined == whereis(myapp_sup)).

    -endif.

ifdef 宏指示测试阶段代码,不会编译进产品中。
  开始编译和测试:

    $ ./rebar compile eunit

上面的命令将编译2次,一次输出到ebin/,一次输出到.eunit/:
    ==> myapp (compile)
    Compiled src/myapp_app.erl
    Compiled src/myapp_sup.erl
    ==> myapp (eunit)
    Compiled src/myapp_sup.erl
    Compiled src/myapp_app.erl
      Test passed.

    =INFO REPORT==== 30-Nov-2014::03:50:01 ===
        application: myapp
        exited: killed
        type: temporary
 

2.5 测试代码覆盖率统计

在myapp/rebar.config中加入下面的行:

    {cover_enabled, true}.

再次运行:

    $ rebar compile eunit

生成的统计页面在:.eunit/index.html