split-i18n-files.escript 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. try
  25. ok = split(Path, Module, <<"en">>, Descs),
  26. ok = split(Path, Module, <<"zh">>, Descs)
  27. catch
  28. throw : already_done ->
  29. ok
  30. end.
  31. split(Path, Module, Lang, Fields) when is_map(Fields) ->
  32. split(Path, Module, Lang, maps:to_list(Fields));
  33. split(Path, Module, Lang, Fields) when is_list(Fields) ->
  34. Split = lists:map(fun({Name, Desc})-> do_split(Path, Name, Lang, Desc) end, Fields),
  35. IoData = [Module, " {\n\n", Split, "}\n"],
  36. %% assert it's a valid HOCON object
  37. {ok, _} = hocon:binary(IoData),
  38. %io:format(user, "~s", [IoData]).
  39. WritePath = case Lang of
  40. <<"en">> ->
  41. Path;
  42. <<"zh">> ->
  43. rename(Path, "zh")
  44. end,
  45. ok = filelib:ensure_dir(WritePath),
  46. ok = file:write_file(WritePath, IoData),
  47. ok.
  48. rename(FilePath, Lang) ->
  49. Dir = filename:dirname(FilePath),
  50. BaseName = filename:basename(FilePath),
  51. filename:join([Dir, Lang, BaseName]).
  52. do_split(_Path, _Name, _Lang, #{<<"desc">> := Desc}) when is_binary(Desc) ->
  53. throw(already_done);
  54. do_split(Path, Name, Lang, #{<<"desc">> := Desc} = D) ->
  55. try
  56. Label = maps:get(<<"label">>, D, #{}),
  57. DescL = maps:get(Lang, Desc),
  58. LabelL = maps:get(Lang, Label, undefined),
  59. [fmt([Name, ".desc:\n"], DescL),
  60. fmt([Name, ".label:\n"], LabelL)
  61. ]
  62. catch
  63. C : E : S->
  64. erlang:raise(C, {Path, Name, E}, S)
  65. end.
  66. tq() ->
  67. "\"\"\"".
  68. fmt(_Key, undefined) ->
  69. [];
  70. fmt(Key, Content) ->
  71. [Key, tq(), Content, tq(), "\n\n"].