最近用erlang開發(fā)項目,用rebar3進行項目的管理荔茬,在linux環(huán)境下運行只盹,開發(fā)過程中要對代碼進行測試測試,項目啟動后兔院,測試過程中會發(fā)現(xiàn)一些小的問題殖卑,代碼修改后要執(zhí)行:rebar3 shell,重新啟動項目才能把更新后的代碼加載到項目中坊萝,感覺很麻煩和費時孵稽。
想著可以不用重啟項目的情況下,部署更新后的代碼十偶,于是查資料已便可以找到一個解決方案菩鲜。主要思路:是在應(yīng)用啟動后,在應(yīng)用的根目錄下惦积,不停止應(yīng)用執(zhí)行一個簡單編譯命令接校,就可以讓變更后的代碼生效,最終寫了下面的代碼:
-module(userc).
-author("pingjianwei").
%% API
-compile(export_all).
%% 宏WORK_DIRS里,列出的目錄是項目開發(fā)過程中經(jīng)常改動
%%的代碼的目錄蛛勉,這些目錄的路徑全是相對于項目的根目錄鹿寻。
-define(WORK_DIRS, [
"src/",
"src/repo/",
"src/model/",
"src/protocol/model/",
"src/protocol/model/mcht/",
"src/protocol/model/ums/",
"src/protocol/model/up/",
"src/protocol/processor/",
"src/ums/",
"src/utils/",
"src/web_handle/",
"src/web_rest_api/"
]).
%% 定義頭文件的目錄
-define(INCLUDE_DIRS, ["/src/include/"]).
cfile(FileName) ->
%% code:add_path(?OUT_DIR),
{ok,RootPath} =file:get_cwd(),
try
cfile(FileName, ?WORK_DIRS)
catch
Exception :ErrorMsg-> io:format("~p:~p",[Exception,ErrorMsg])
after
%保證無論身么情況下,保證編譯完成后诽凌,回到應(yīng)用根目錄
c:cd(RootPath)
end.
cfile(FileName, []) ->
{erlang:atom_to_list(FileName) ++ ":not find", ?WORK_DIRS};
cfile(FileName, [Path | Left]) ->
FileDir = Path ++ erlang:atom_to_list(FileName) ++ ".erl",
case file:read_file_info(FileDir) of
{ok, _} ->
%找到要編譯erl文件目錄毡熏,切換file server到該目錄下
c:cd(Path),
IncludeDirs = [begin {i, Dir} end || Dir <- ?INCLUDE_DIRS],
io:format("outdir : ~p ~n",[get_out_dir(FileName)]),
%% CompileOptions變量定義了,copile時的一些選項
% 1.{outdir, get_out_dir(FileName)} 指定文件輸出目錄
% 2.{parse_transform, lager_transform},編譯日志輸出模塊
% 3.{parse_transform, lager_transform}侣诵,編譯生成記錄操作函數(shù)
CompileOptions = [{outdir, get_out_dir(FileName)}, {parse_transform, lager_transform},
{parse_transform, exprecs}, report, verbose] ++ IncludeDirs,
case compile:file(FileName, CompileOptions) of
%加載編譯后的beam文件
{ok, T} -> c:l(T), {ok, T};
Err -> Err
end;
_ ->
cfile(FileName, Left)
end.
%%這個函數(shù)是獲取runtime時,beam文件的存放的目錄
get_out_dir(FileName) when is_atom(FileName) ->
Path = code:which(FileName),
PathBin = list_to_binary(Path),
{Pos,_} =binary:match(PathBin,list_to_binary([atom_to_binary(FileName,utf8),<<".beam">>])),
OutDirBin =binary:part(PathBin,0,Pos),
binary_to_list(OutDirBin).
用法說明
1.userc.erl文件放在應(yīng)用的根目錄下
TIM截圖20171021223027.png
2.進入linux環(huán)境痢法,并進入應(yīng)用的根目錄,rebar3 shell 啟動項目
3.執(zhí)行:c(userc),編譯該文件
4.代碼調(diào)試過程中杜顺,修改了某個模塊的名字财搁,可以執(zhí)行:userc:cfile(模塊的名字)躬络,比如test.erl.可以這么編譯:userc:cfile(test)妇拯。注意:被編譯模塊路徑必須添加到:?WORK_DIRS宏里洗鸵,否者就找不到源文件
但是如果一次性膘滨,改了多個地方甘凭,用這個反而麻煩火邓,還是重啟項目好丹弱,后期考慮铲咨,添加一個函數(shù):usec:all/0, 就能編譯指定目錄的的所有文件躲胳,等測試好了纤勒,到時候再和大家分享。