I18N.jl/src/I18N.jl

111 lines
3.4 KiB
Julia

module I18N
using Dates
language_map = include("codes.jl")
translationpath(langcode, domain = "base") =
joinpath(realpath("."), "locales/$(langcode)/LC_MESSAGES/$(domain).pot")
macro __str(phrase)
push!(Main.i18n_cache, (file = __source__.file,
line = __source__.line,
strid = phrase))
return esc(quote
get(get(i18n, I18N.language(), Dict()),
$phrase, $phrase)
end)
end
macro translations(languages...)
return esc(quote
i18n = Dict{String,Dict{String,String}}()
# (lang, file.jl, line) => translation
i18n_cache = Any[]
# lang => [(name, mail, year)]
i18n_translators = Dict{String,Array{Tuple{String,String,String}}}()
for language in $languages
i18n[string(language)] = Dict{String,String}()
end
end)
end
macro translate(lang, id, translation)
return esc(:(i18n[string($lang)][$id] = $translation))
end
function translator_list(translators)
join(map(t -> string("# ", t[1], " ", "<", t[2], ">", " ",
t[3], "."),
translators),
"\n")
end
function po_header(LANG, PROGRAM, VERSION, C_YEARS, C_AUTHORS, TRANSLATORS)
"""# $LANG translation for $PROGRAM $VERSION
# Copyright (C) $C_YEARS $C_AUTHORS
# This file is distributed under the same license as $PROGRAM.
$(translator_list(TRANSLATORS))
#
msgid ""
msgstr ""
"""
end
function format(file, line, phrase, translation = "")
string("#: ", relpath(string(file)), ":", line, "\n",
"msgid ", "\"", phrase, "\"", "\n",
"msgstr ", "\"", translation, "\"", "\n\n")
end
lang_expand(lang) = language_map[lang]
current_year() = Dates.today() |> year
macro write_po_files(name = nothing, version = nothing,
authors = nothing, year = nothing)
return esc(quote
unique!(i18n_cache)
# Sort by line & by file
sort!(i18n_cache, by = x -> x[2])
sort!(i18n_cache, by = first)
# Write to file
for language in keys(i18n)
translationfile = I18N.translationpath(string(language))
mkpath(dirname(translationfile))
open(translationfile, "w") do io
translators = get(i18n_translators, language, [])
write(io, I18N.po_header(lang_expand(language),
something($name, uppercasefirst(basename(realpath(".")))),
something($version, "0.1.0-dev"),
something($year, I18N.current_year()),
join(something($authors,
first.(translators)),
", "), translators))
for tr in i18n_cache
translation = get(get(i18n, language, Dict()), tr.strid, "")
write(io,
I18N.format(tr.file, tr.line, tr.strid, translation))
end
end
end
end)
end
macro translator(lang, name, email, copyright)
# @show $lang
return esc(quote
if !($lang in keys(i18n_translators))
i18n_translators[$lang] = []
end
push!(i18n_translators[$lang], ($name, $email, $copyright))
end)
end
@inline language() = "en"
export @__str, @translations, @translate,
@translator, @write_po_files, lang_expand
end # module