split-i18n-files.escript 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #!/usr/bin/env escript
  2. %% This script is for one-time use.
  3. %% will be deleted after the migration is done.
  4. -mode(compile).
  5. main([]) ->
  6. %% we need to parse hocon
  7. %% so we'll just add all compiled libs to path
  8. code:add_pathsz(find_ebin_paths("_build/default/lib/*")),
  9. Files = filelib:wildcard("rel/i18n/*.hocon"),
  10. ok = lists:foreach(fun split_file/1, Files),
  11. ok.
  12. find_ebin_paths(DirPattern) ->
  13. LibDirs = filelib:wildcard(DirPattern),
  14. lists:filtermap(fun add_ebin/1, LibDirs).
  15. add_ebin(Dir) ->
  16. EbinDir = filename:join(Dir, "ebin"),
  17. case filelib:is_dir(EbinDir) of
  18. true -> {true, EbinDir};
  19. false -> false
  20. end.
  21. split_file(Path) ->
  22. {ok, DescMap} = hocon:load(Path),
  23. [{Module, Descs}] = maps:to_list(DescMap),
  24. ok = split(Path, Module, <<"en">>, Descs),
  25. ok = split(Path, Module, <<"zh">>, Descs),
  26. ok.
  27. split(Path, Module, Lang, Fields) when is_map(Fields) ->
  28. split(Path, Module, Lang, maps:to_list(Fields));
  29. split(Path, Module, Lang, Fields) when is_list(Fields) ->
  30. Split = lists:map(fun({Name, Desc})-> do_split(Path, Name, Lang, Desc) end, Fields),
  31. IoData = [Module, " {\n\n", Split, "}\n"],
  32. %% assert it's a valid HOCON object
  33. {ok, _} = hocon:binary(IoData),
  34. %io:format(user, "~s", [IoData]).
  35. WritePath = case Lang of
  36. <<"en">> ->
  37. Path;
  38. <<"zh">> ->
  39. rename(Path, "zh")
  40. end,
  41. ok = filelib:ensure_dir(WritePath),
  42. ok = file:write_file(WritePath, IoData),
  43. ok.
  44. rename(FilePath, Lang) ->
  45. Dir = filename:dirname(FilePath),
  46. BaseName = filename:basename(FilePath),
  47. filename:join([Dir, Lang, BaseName]).
  48. do_split(Path, Name, Lang, #{<<"desc">> := Desc} = D) ->
  49. try
  50. Label = maps:get(<<"label">>, D, #{}),
  51. DescL = maps:get(Lang, Desc),
  52. LabelL = maps:get(Lang, Label, undefined),
  53. [fmt([Name, ".desc:\n"], DescL),
  54. fmt([Name, ".label:\n"], LabelL)
  55. ]
  56. catch
  57. C : E : S->
  58. erlang:raise(C, {Path, Name, E}, S)
  59. end.
  60. tq() ->
  61. "\"\"\"".
  62. fmt(_Key, undefined) ->
  63. [];
  64. fmt(Key, Content) ->
  65. [Key, tq(), Content, tq(), "\n\n"].