mad_dtl.erl 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. -module(mad_dtl).
  2. -copyright('Sina Samavati').
  3. -compile(export_all).
  4. compile(Dir,Config) ->
  5. case mad_utils:get_value(erlydtl_opts, Config, []) of
  6. [] -> false;
  7. X -> compile_erlydtl_files(validate_erlydtl_opts(Dir,X)) end.
  8. get_kv(K, Opts, Default) ->
  9. V = mad_utils:get_value(K, Opts, Default),
  10. KV = {K, V},
  11. {KV, Opts -- [KV]}.
  12. file_to_beam(Bin, Filename) -> filename:join(Bin, filename:basename(Filename) ++ ".beam").
  13. validate_erlydtl_opts(Cwd, Opts) ->
  14. DefaultDocRoot = filename:join("priv", "templates"),
  15. {DocRoot, Opts1} = get_kv(doc_root, Opts, DefaultDocRoot),
  16. {OutDir, Opts2} = get_kv(out_dir, Opts1, "ebin"),
  17. {CompilerOpts, Opts3} = get_kv(compiler_options, Opts2, []),
  18. {SourceExt, Opts4} = get_kv(source_ext, Opts3, ".dtl"),
  19. {ModuleExt, Opts5} = get_kv(module_ext, Opts4, ""),
  20. {_, DocRootDir} = DocRoot,
  21. DocRoot1 = {doc_root, filename:join(Cwd, DocRootDir)},
  22. {_, OutDir1} = OutDir,
  23. OutDir2 = {out_dir, filename:join(Cwd, OutDir1)},
  24. [DocRoot1, OutDir2, CompilerOpts, SourceExt, ModuleExt|Opts5].
  25. module_name(File, Ext, NewExt) ->
  26. list_to_atom(filename:basename(File, Ext) ++ NewExt).
  27. compile_erlydtl_files(Opts) ->
  28. {{_, DocRoot}, Opts1} = get_kv(doc_root, Opts, ""),
  29. {{_, SourceExt}, Opts2} = get_kv(source_ext, Opts1, ""),
  30. {{_, ModuleExt}, Opts3} = get_kv(module_ext, Opts2, ""),
  31. {{_, OutDir}, _} = get_kv(out_dir, Opts3, ""),
  32. Files = filelib:fold_files(DocRoot, SourceExt, true,
  33. fun(F, Acc) -> [F|Acc] end, []),
  34. Compile = fun(F) ->
  35. ModuleName = module_name(F, SourceExt, ModuleExt),
  36. BeamFile = file_to_beam(OutDir, atom_to_list(ModuleName)),
  37. Compiled = mad_compile:is_compiled(BeamFile, F),
  38. if Compiled =:= false ->
  39. io:format("DTL Compiling ~s~n\r", [F]),
  40. erlydtl:compile(F, ModuleName, Opts3);
  41. true -> ok end
  42. end,
  43. lists:any(fun({error,_}) -> true; (ok) -> false end,[Compile(F) || F <- Files]).