diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/rebar_mustache.erl | 230 | ||||
-rw-r--r-- | src/rebar_prv_new.erl | 69 | ||||
-rw-r--r-- | src/rebar_prv_update.erl | 14 | ||||
-rw-r--r-- | src/rebar_templater.erl | 71 |
4 files changed, 323 insertions, 61 deletions
diff --git a/src/rebar_mustache.erl b/src/rebar_mustache.erl new file mode 100644 index 0000000..9016c0f --- /dev/null +++ b/src/rebar_mustache.erl @@ -0,0 +1,230 @@ +%% The MIT License +%% +%% Copyright (c) 2009 Tom Preston-Werner <tom@mojombo.com> +%% +%% Permission is hereby granted, free of charge, to any person obtaining a copy +%% of this software and associated documentation files (the "Software"), to deal +%% in the Software without restriction, including without limitation the rights +%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +%% copies of the Software, and to permit persons to whom the Software is +%% furnished to do so, subject to the following conditions: +%% +%% The above copyright notice and this permission notice shall be included in +%% all copies or substantial portions of the Software. +%% +%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +%% THE SOFTWARE. + +%% See the README at http://github.com/mojombo/mustache.erl for additional +%% documentation and usage examples. + +-module(rebar_mustache). %% v0.1.0 +-author("Tom Preston-Werner"). +-export([compile/1, compile/2, render/1, render/2, render/3, get/2, get/3, escape/1, start/1]). + +-record(mstate, {mod = undefined, + section_re = undefined, + tag_re = undefined}). + +-define(MUSTACHE_STR, "rebar_mustache"). + +compile(Body) when is_list(Body) -> + State = #mstate{}, + CompiledTemplate = pre_compile(Body, State), + % io:format("~p~n~n", [CompiledTemplate]), + % io:format(CompiledTemplate ++ "~n", []), + {ok, Tokens, _} = erl_scan:string(CompiledTemplate), + {ok, [Form]} = erl_parse:parse_exprs(Tokens), + Bindings = erl_eval:new_bindings(), + {value, Fun, _} = erl_eval:expr(Form, Bindings), + Fun; +compile(Mod) -> + TemplatePath = template_path(Mod), + compile(Mod, TemplatePath). + +compile(Mod, File) -> + code:purge(Mod), + {module, _} = code:load_file(Mod), + {ok, TemplateBin} = file:read_file(File), + Template = re:replace(TemplateBin, "\"", "\\\\\"", [global, {return,list}]), + State = #mstate{mod = Mod}, + CompiledTemplate = pre_compile(Template, State), + % io:format("~p~n~n", [CompiledTemplate]), + % io:format(CompiledTemplate ++ "~n", []), + {ok, Tokens, _} = erl_scan:string(CompiledTemplate), + {ok, [Form]} = erl_parse:parse_exprs(Tokens), + Bindings = erl_eval:new_bindings(), + {value, Fun, _} = erl_eval:expr(Form, Bindings), + Fun. + +render(Mod) -> + TemplatePath = template_path(Mod), + render(Mod, TemplatePath). + +render(Body, Ctx) when is_list(Body) -> + TFun = compile(Body), + render(undefined, TFun, Ctx); +render(Mod, File) when is_list(File) -> + render(Mod, File, dict:new()); +render(Mod, CompiledTemplate) -> + render(Mod, CompiledTemplate, dict:new()). + +render(Mod, File, Ctx) when is_list(File) -> + CompiledTemplate = compile(Mod, File), + render(Mod, CompiledTemplate, Ctx); +render(Mod, CompiledTemplate, Ctx) -> + Ctx2 = dict:store('__mod__', Mod, Ctx), + lists:flatten(CompiledTemplate(Ctx2)). + +pre_compile(T, State) -> + SectionRE = "\{\{\#([^\}]*)}}\s*(.+?){{\/\\1\}\}\s*", + {ok, CompiledSectionRE} = re:compile(SectionRE, [dotall]), + TagRE = "\{\{(#|=|!|<|>|\{)?(.+?)\\1?\}\}+", + {ok, CompiledTagRE} = re:compile(TagRE, [dotall]), + State2 = State#mstate{section_re = CompiledSectionRE, tag_re = CompiledTagRE}, + "fun(Ctx) -> " ++ + "CFun = fun(A, B) -> A end, " ++ + compiler(T, State2) ++ " end.". + +compiler(T, State) -> + Res = re:run(T, State#mstate.section_re), + case Res of + {match, [{M0, M1}, {N0, N1}, {C0, C1}]} -> + Front = string:substr(T, 1, M0), + Back = string:substr(T, M0 + M1 + 1), + Name = string:substr(T, N0 + 1, N1), + Content = string:substr(T, C0 + 1, C1), + "[" ++ compile_tags(Front, State) ++ + " | [" ++ compile_section(Name, Content, State) ++ + " | [" ++ compiler(Back, State) ++ "]]]"; + nomatch -> + compile_tags(T, State) + end. + +compile_section(Name, Content, State) -> + Mod = State#mstate.mod, + Result = compiler(Content, State), + "fun() -> " ++ + "case " ++ ?MUSTACHE_STR ++ ":get(" ++ Name ++ ", Ctx, " ++ atom_to_list(Mod) ++ ") of " ++ + "\"true\" -> " ++ + Result ++ "; " ++ + "\"false\" -> " ++ + "[]; " ++ + "List when is_list(List) -> " ++ + "[fun(Ctx) -> " ++ Result ++ " end(dict:merge(CFun, SubCtx, Ctx)) || SubCtx <- List]; " ++ + "Else -> " ++ + "throw({template, io_lib:format(\"Bad context for ~p: ~p\", [" ++ Name ++ ", Else])}) " ++ + "end " ++ + "end()". + +compile_tags(T, State) -> + Res = re:run(T, State#mstate.tag_re), + case Res of + {match, [{M0, M1}, K, {C0, C1}]} -> + Front = string:substr(T, 1, M0), + Back = string:substr(T, M0 + M1 + 1), + Content = string:substr(T, C0 + 1, C1), + Kind = tag_kind(T, K), + Result = compile_tag(Kind, Content, State), + "[\"" ++ Front ++ + "\" | [" ++ Result ++ + " | " ++ compile_tags(Back, State) ++ "]]"; + nomatch -> + "[\"" ++ T ++ "\"]" + end. + +tag_kind(_T, {-1, 0}) -> + none; +tag_kind(T, {K0, K1}) -> + string:substr(T, K0 + 1, K1). + +compile_tag(none, Content, State) -> + Mod = State#mstate.mod, + ?MUSTACHE_STR ++ ":escape(" ++ ?MUSTACHE_STR ++ ":get(" ++ Content ++ ", Ctx, " ++ atom_to_list(Mod) ++ "))"; +compile_tag("{", Content, State) -> + Mod = State#mstate.mod, + ?MUSTACHE_STR ++ ":get(" ++ Content ++ ", Ctx, " ++ atom_to_list(Mod) ++ ")"; +compile_tag("!", _Content, _State) -> + "[]". + +template_dir(Mod) -> + DefaultDirPath = filename:dirname(code:which(Mod)), + case application:get_env(mustache, templates_dir) of + {ok, DirPath} when is_list(DirPath) -> + case filelib:ensure_dir(DirPath) of + ok -> DirPath; + _ -> DefaultDirPath + end; + _ -> + DefaultDirPath + end. +template_path(Mod) -> + DirPath = template_dir(Mod), + Basename = atom_to_list(Mod), + filename:join(DirPath, Basename ++ ".mustache"). + +get(Key, Ctx) when is_list(Key) -> + {ok, Mod} = dict:find('__mod__', Ctx), + get(list_to_atom(Key), Ctx, Mod); +get(Key, Ctx) -> + {ok, Mod} = dict:find('__mod__', Ctx), + get(Key, Ctx, Mod). + +get(Key, Ctx, Mod) when is_list(Key) -> + get(list_to_atom(Key), Ctx, Mod); +get(Key, Ctx, Mod) -> + case dict:find(Key, Ctx) of + {ok, Val} -> + % io:format("From Ctx {~p, ~p}~n", [Key, Val]), + to_s(Val); + error -> + case erlang:function_exported(Mod, Key, 1) of + true -> + Val = to_s(Mod:Key(Ctx)), + % io:format("From Mod/1 {~p, ~p}~n", [Key, Val]), + Val; + false -> + case erlang:function_exported(Mod, Key, 0) of + true -> + Val = to_s(Mod:Key()), + % io:format("From Mod/0 {~p, ~p}~n", [Key, Val]), + Val; + false -> + [] + end + end + end. + +to_s(Val) when is_integer(Val) -> + integer_to_list(Val); +to_s(Val) when is_float(Val) -> + io_lib:format("~.2f", [Val]); +to_s(Val) when is_atom(Val) -> + atom_to_list(Val); +to_s(Val) -> + Val. + +escape(HTML) -> + escape(HTML, []). + +escape([], Acc) -> + lists:reverse(Acc); +escape(["<" | Rest], Acc) -> + escape(Rest, lists:reverse("<", Acc)); +escape([">" | Rest], Acc) -> + escape(Rest, lists:reverse(">", Acc)); +escape(["&" | Rest], Acc) -> + escape(Rest, lists:reverse("&", Acc)); +escape([X | Rest], Acc) -> + escape(Rest, [X | Acc]). + +%%--------------------------------------------------------------------------- + +start([T]) -> + Out = render(list_to_atom(T)), + io:format(Out ++ "~n", []). diff --git a/src/rebar_prv_new.erl b/src/rebar_prv_new.erl new file mode 100644 index 0000000..e5233cd --- /dev/null +++ b/src/rebar_prv_new.erl @@ -0,0 +1,69 @@ +-module(rebar_prv_new). + +-behaviour(rebar_provider). + +-export([init/1, + do/1]). + +-include("rebar.hrl"). + +-define(PROVIDER, new). +-define(DEPS, []). + +%% =================================================================== +%% Public API +%% =================================================================== + +-spec init(rebar_state:t()) -> {ok, rebar_state:t()}. +init(State) -> + State1 = rebar_state:add_provider(State, #provider{name = ?PROVIDER, + provider_impl = ?MODULE, + bare = false, + deps = ?DEPS, + example = "rebar new <template>", + short_desc = "", + desc = info(create), + opts = []}), + {ok, State1}. + +-spec do(rebar_state:t()) -> {ok, rebar_state:t()}. +do(State) -> + case rebar_state:command_args(State) of + [TemplateName] -> + Template = list_to_atom(TemplateName), + rebar_templater:new(Template, State), + {ok, State}; + [] -> + {ok, State} + end. + +%% =================================================================== +%% Internal functions +%% =================================================================== + +info(create) -> + io_lib:format( + "Create skel based on template and vars.~n" + "~n" + "Valid command line options:~n" + " template= [var=foo,...]~n", []); +info(create_app) -> + io_lib:format( + "Create simple app skel.~n" + "~n" + "Valid command line options:~n" + " [appid=myapp]~n", []); +info(create_lib) -> + io_lib:format( + "Create simple lib skel.~n" + "~n" + "Valid command line options:~n" + " [libid=mylib]~n", []); +info(create_node) -> + io_lib:format( + "Create simple node skel.~n" + "~n" + "Valid command line options:~n" + " [nodeid=mynode]~n", []); +info(list_templates) -> + io_lib:format("List available templates.~n", []). diff --git a/src/rebar_prv_update.erl b/src/rebar_prv_update.erl index a12f5b0..c1aa14b 100644 --- a/src/rebar_prv_update.erl +++ b/src/rebar_prv_update.erl @@ -20,13 +20,13 @@ -spec init(rebar_state:t()) -> {ok, rebar_state:t()}. init(State) -> State1 = rebar_state:add_provider(State, #provider{name = ?PROVIDER, - provider_impl = ?MODULE, - bare = false, - deps = ?DEPS, - example = "rebar update cowboy", - short_desc = "", - desc = "", - opts = []}), + provider_impl = ?MODULE, + bare = false, + deps = ?DEPS, + example = "rebar update cowboy", + short_desc = "", + desc = "", + opts = []}), {ok, State1}. -spec do(rebar_state:t()) -> {ok, rebar_state:t()} | relx:error(). diff --git a/src/rebar_templater.erl b/src/rebar_templater.erl index dd89f3a..f22329b 100644 --- a/src/rebar_templater.erl +++ b/src/rebar_templater.erl @@ -26,19 +26,14 @@ %% ------------------------------------------------------------------- -module(rebar_templater). --export(['create-app'/2, - 'create-lib'/2, - 'create-node'/2, - 'list-templates'/2, - create/2]). +-export([new/2, + list_templates/1, + create/1]). %% API for other utilities that need templating functionality -export([resolve_variables/2, render/2]). -%% for internal use only --export([info/2]). - -include("rebar.hrl"). -define(TEMPLATE_RE, "^[^._].*\\.template\$"). @@ -47,19 +42,15 @@ %% Public API %% =================================================================== -'create-app'(Config, _File) -> - %% Alias for create w/ template=simpleapp - create1(Config, "simpleapp"). - -'create-lib'(Config, _File) -> - %% Alias for create w/ template=simplelib - create1(Config, "simplelib"). - -'create-node'(Config, _File) -> +new(app, Config) -> + create1(Config, "simpleapp"); +new(lib, Config) -> + create1(Config, "simplelib"); +new(node, Config) -> %% Alias for create w/ template=simplenode create1(Config, "simplenode"). -'list-templates'(Config, _File) -> +list_templates(Config) -> {AvailTemplates, Files} = find_templates(Config), ?DEBUG("Available templates: ~p\n", [AvailTemplates]), @@ -76,7 +67,7 @@ end, AvailTemplates), ok. -create(Config, _) -> +create(Config) -> TemplateId = template_id(Config), create1(Config, TemplateId). @@ -109,33 +100,6 @@ render(Bin, Context) -> %% Internal functions %% =================================================================== -info(help, create) -> - ?CONSOLE( - "Create skel based on template and vars.~n" - "~n" - "Valid command line options:~n" - " template= [var=foo,...]~n", []); -info(help, 'create-app') -> - ?CONSOLE( - "Create simple app skel.~n" - "~n" - "Valid command line options:~n" - " [appid=myapp]~n", []); -info(help, 'create-lib') -> - ?CONSOLE( - "Create simple lib skel.~n" - "~n" - "Valid command line options:~n" - " [libid=mylib]~n", []); -info(help, 'create-node') -> - ?CONSOLE( - "Create simple node skel.~n" - "~n" - "Valid command line options:~n" - " [nodeid=mynode]~n", []); -info(help, 'list-templates') -> - ?CONSOLE("List available templates.~n", []). - create1(Config, TemplateId) -> {AvailTemplates, Files} = find_templates(Config), ?DEBUG("Available templates: ~p\n", [AvailTemplates]), @@ -168,7 +132,7 @@ create1(Config, TemplateId) -> end, %% Load variables from disk file, if provided - Context1 = case rebar_config:get_global(Config, template_vars, undefined) of + Context1 = case rebar_state:get(Config, template_vars, undefined) of undefined -> Context0; File -> @@ -201,7 +165,7 @@ create1(Config, TemplateId) -> ?DEBUG("Final template def ~p: ~p\n", [TemplateId, FinalTemplate]), %% Execute the instructions in the finalized template - Force = rebar_config:get_global(Config, force, "0"), + Force = rebar_state:get(Config, force, "0"), execute_template(Files, FinalTemplate, Type, Template, Context, Force, []). find_templates(Config) -> @@ -224,11 +188,11 @@ cache_escript_files(Config) -> fun(Name, _, GetBin, Acc) -> [{Name, GetBin()} | Acc] end, - [], rebar_config:get_xconf(Config, escript)), + [], rebar_state:get(Config, escript)), Files. template_id(Config) -> - case rebar_config:get_global(Config, template, undefined) of + case rebar_state:get(Config, template, undefined) of undefined -> ?ABORT("No template specified.\n", []); TemplateId -> @@ -245,12 +209,11 @@ find_disk_templates(Config) -> HomeFiles = rebar_utils:find_files(filename:join([os:getenv("HOME"), ".rebar", "templates"]), ?TEMPLATE_RE), - Recursive = rebar_config:is_recursive(Config), - LocalFiles = rebar_utils:find_files(".", ?TEMPLATE_RE, Recursive), + LocalFiles = rebar_utils:find_files(".", ?TEMPLATE_RE, true), [{file, F} || F <- OtherTemplates ++ HomeFiles ++ LocalFiles]. find_other_templates(Config) -> - case rebar_config:get_global(Config, template_dir, undefined) of + case rebar_state:get(Config, template_dir, undefined) of undefined -> []; TemplateDir -> @@ -296,7 +259,7 @@ parse_vars(Other, _Dict) -> update_vars(_Config, [], Dict) -> Dict; update_vars(Config, [Key | Rest], Dict) -> - Value = rebar_config:get_global(Config, Key, dict:fetch(Key, Dict)), + Value = rebar_state:get(Config, Key, dict:fetch(Key, Dict)), update_vars(Config, Rest, dict:store(Key, Value, Dict)). |