German translation added.

This commit is contained in:
A.C.M. 2024-01-27 00:10:42 +01:00
parent 6c07b50b8a
commit 12c3dfa77f
60 changed files with 1339 additions and 84 deletions

View File

@ -1,4 +1,4 @@
local S = minetest.get_translator(minetest.get_current_modname())
local S = auto_beetle.S
--
-- items

View File

@ -4,6 +4,18 @@
auto_beetle={}
auto_beetle.gravity = automobiles_lib.gravity
auto_beetle.S = nil
if(minetest.get_translator ~= nil) then
auto_beetle.S = minetest.get_translator(minetest.get_current_modname())
else
auto_beetle.S = function ( s ) return s end
end
local S = auto_beetle.S
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "custom_physics.lua")
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "fuel_management.lua")
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "ground_detection.lua")

View File

@ -0,0 +1,3 @@
# textdomain: automobiles_beetle
Beetle Body=Käfer Karroserie
Beetle=Käfer

View File

@ -0,0 +1,3 @@
# textdomain: automobiles_beetle
Beetle Body=
Beetle=

View File

@ -1,4 +1,4 @@
local S = minetest.get_translator(minetest.get_current_modname())
local S = buggy.S
--
-- items

View File

@ -1,3 +1,4 @@
local S = buggy.S
function buggy.driver_formspec(name)
local player = minetest.get_player_by_name(name)
@ -15,10 +16,10 @@ function buggy.driver_formspec(name)
"size[6,7]",
}, "")
basic_form = basic_form.."button[1,1.0;4,1;go_out;Go Offboard]"
basic_form = basic_form.."button[1,2.5;4,1;top;Close/Open Rag]"
basic_form = basic_form.."button[1,4.0;4,1;lights;Lights]"
basic_form = basic_form.."checkbox[1,5.5;yaw;Direction by mouse;"..yaw.."]"
basic_form = basic_form.."button[1,1.0;4,1;go_out;" .. S("Go Offboard") .. "]"
basic_form = basic_form.."button[1,2.5;4,1;top;" .. S("Close/Open Rag") .. "]"
basic_form = basic_form.."button[1,4.0;4,1;lights;" .. S("Lights") .. "]"
basic_form = basic_form.."checkbox[1,5.5;yaw;" .. S("Direction by mouse") .. ";"..yaw.."]"
minetest.show_formspec(name, "buggy:driver_main", basic_form)
end

View File

@ -4,6 +4,18 @@
buggy={}
buggy.gravity = automobiles_lib.gravity
buggy.S = nil
if(minetest.get_translator ~= nil) then
buggy.S = minetest.get_translator(minetest.get_current_modname())
else
buggy.S = function ( s ) return s end
end
local S = buggy.S
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "custom_physics.lua")
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "control.lua")
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "fuel_management.lua")

View File

@ -0,0 +1,9 @@
# textdomain: automobiles_buggy
### buggy_crafts.lua ###
Buggy Body=Buggy Karrosserie
Buggy Wheel=Buggy Rad
Buggy=Buggy
Go Offboard=Aussteigen
Close/Open Rag=Öffne/Schließe Sonnendach
Lights=Lichter
Direction by mouse=Lenke mit Maus

View File

@ -1,6 +1,9 @@
# textdomain: automobiles_buggy
### buggy_crafts.lua ###
Buggy Body=Korpo de Buggy
Buggy Wheel=Rado de Buggy
Buggy=Buggy
Go Offboard=
Close/Open Rag=
Lights=
Direction by mouse=

View File

@ -1,6 +1,9 @@
# textdomain: automobiles_buggy
### buggy_crafts.lua ###
Buggy Body=
Buggy Wheel=
Buggy=
Go Offboard=
Close/Open Rag=
Lights=
Direction by mouse=

View File

@ -0,0 +1,495 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Script to generate Minetest translation template files and update
# translation files.
#
# Copyright (C) 2019 Joachim Stolberg, 2020 FaceDeer, 2020 Louis Royer,
# 2023 Wuzzy.
# License: LGPLv2.1 or later (see LICENSE file for details)
import os, fnmatch, re, shutil, errno
from sys import argv as _argv
from sys import stderr as _stderr
# Running params
params = {"recursive": False,
"help": False,
"verbose": False,
"folders": [],
"old-file": False,
"break-long-lines": False,
"print-source": False,
"truncate-unused": False,
}
# Available CLI options
options = {"recursive": ['--recursive', '-r'],
"help": ['--help', '-h'],
"verbose": ['--verbose', '-v'],
"old-file": ['--old-file', '-o'],
"break-long-lines": ['--break-long-lines', '-b'],
"print-source": ['--print-source', '-p'],
"truncate-unused": ['--truncate-unused', '-t'],
}
# Strings longer than this will have extra space added between
# them in the translation files to make it easier to distinguish their
# beginnings and endings at a glance
doublespace_threshold = 80
# These symbols mark comment lines showing the source file name.
# A comment may look like "##[ init.lua ]##".
symbol_source_prefix = "##["
symbol_source_suffix = "]##"
# comment to mark the section of old/unused strings
comment_unused = "##### not used anymore #####"
def set_params_folders(tab: list):
'''Initialize params["folders"] from CLI arguments.'''
# Discarding argument 0 (tool name)
for param in tab[1:]:
stop_param = False
for option in options:
if param in options[option]:
stop_param = True
break
if not stop_param:
params["folders"].append(os.path.abspath(param))
def set_params(tab: list):
'''Initialize params from CLI arguments.'''
for option in options:
for option_name in options[option]:
if option_name in tab:
params[option] = True
break
def print_help(name):
'''Prints some help message.'''
print(f'''SYNOPSIS
{name} [OPTIONS] [PATHS...]
DESCRIPTION
{', '.join(options["help"])}
prints this help message
{', '.join(options["recursive"])}
run on all subfolders of paths given
{', '.join(options["old-file"])}
create *.old files
{', '.join(options["break-long-lines"])}
add extra line breaks before and after long strings
{', '.join(options["print-source"])}
add comments denoting the source file
{', '.join(options["verbose"])}
add output information
{', '.join(options["truncate-unused"])}
delete unused strings from files
''')
def main():
'''Main function'''
set_params(_argv)
set_params_folders(_argv)
if params["help"]:
print_help(_argv[0])
else:
# Add recursivity message
print("Running ", end='')
if params["recursive"]:
print("recursively ", end='')
# Running
if len(params["folders"]) >= 2:
print("on folder list:", params["folders"])
for f in params["folders"]:
if params["recursive"]:
run_all_subfolders(f)
else:
update_folder(f)
elif len(params["folders"]) == 1:
print("on folder", params["folders"][0])
if params["recursive"]:
run_all_subfolders(params["folders"][0])
else:
update_folder(params["folders"][0])
else:
print("on folder", os.path.abspath("./"))
if params["recursive"]:
run_all_subfolders(os.path.abspath("./"))
else:
update_folder(os.path.abspath("./"))
# Group 2 will be the string, groups 1 and 3 will be the delimiters (" or ')
# See https://stackoverflow.com/questions/46967465/regex-match-text-in-either-single-or-double-quote
pattern_lua_quoted = re.compile(
r'(?:^|[\.=,{\(\s])' # Look for beginning of file or anything that isn't a function identifier
r'N?F?S\s*\(\s*' # Matches S, FS, NS or NFS function call
r'(["\'])((?:\\\1|(?:(?!\1)).)*)(\1)' # Quoted string
r'[\s,\)]', # End of call or argument
re.DOTALL)
# Handles the [[ ... ]] string delimiters
pattern_lua_bracketed = re.compile(
r'(?:^|[\.=,{\(\s])' # Same as for pattern_lua_quoted
r'N?F?S\s*\(\s*' # Same as for pattern_lua_quoted
r'\[\[(.*?)\]\]' # [[ ... ]] string delimiters
r'[\s,\)]', # Same as for pattern_lua_quoted
re.DOTALL)
# Handles "concatenation" .. " of strings"
pattern_concat = re.compile(r'["\'][\s]*\.\.[\s]*["\']', re.DOTALL)
# Handles a translation line in *.tr file.
# Group 1 is the source string left of the equals sign.
# Group 2 is the translated string, right of the equals sign.
pattern_tr = re.compile(
r'(.*)' # Source string
# the separating equals sign, if NOT preceded by @, unless
# that @ is preceded by another @
r'(?:(?<!(?<!@)@)=)'
r'(.*)' # Translation string
)
pattern_name = re.compile(r'^name[ ]*=[ ]*([^ \n]*)')
pattern_tr_filename = re.compile(r'\.tr$')
# Matches bad use of @ signs in Lua string
pattern_bad_luastring = re.compile(
r'^@$|' # single @, OR
r'[^@]@$|' # trailing unescaped @, OR
r'(?<!@)@(?=[^@1-9])' # an @ that is not escaped or part of a placeholder
)
# Attempt to read the mod's name from the mod.conf file or folder name. Returns None on failure
def get_modname(folder):
try:
with open(os.path.join(folder, "mod.conf"), "r", encoding='utf-8') as mod_conf:
for line in mod_conf:
match = pattern_name.match(line)
if match:
return match.group(1)
except FileNotFoundError:
if not os.path.isfile(os.path.join(folder, "modpack.txt")):
folder_name = os.path.basename(folder)
# Special case when run in Minetest's builtin directory
if folder_name == "builtin":
return "__builtin"
else:
return folder_name
else:
return None
return None
# If there are already .tr files in /locale, returns a list of their names
def get_existing_tr_files(folder):
out = []
for root, dirs, files in os.walk(os.path.join(folder, 'locale/')):
for name in files:
if pattern_tr_filename.search(name):
out.append(name)
return out
# from https://stackoverflow.com/questions/600268/mkdir-p-functionality-in-python/600612#600612
# Creates a directory if it doesn't exist, silently does
# nothing if it already exists
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else: raise
# Converts the template dictionary to a text to be written as a file
# dKeyStrings is a dictionary of localized string to source file sets
# dOld is a dictionary of existing translations and comments from
# the previous version of this text
def strings_to_text(dkeyStrings, dOld, mod_name, header_comments, textdomain):
# if textdomain is specified, insert it at the top
if textdomain != None:
lOut = [textdomain] # argument is full textdomain line
# otherwise, use mod name as textdomain automatically
else:
lOut = [f"# textdomain: {mod_name}"]
if header_comments is not None:
lOut.append(header_comments)
dGroupedBySource = {}
for key in dkeyStrings:
sourceList = list(dkeyStrings[key])
sourceString = "\n".join(sourceList)
listForSource = dGroupedBySource.get(sourceString, [])
listForSource.append(key)
dGroupedBySource[sourceString] = listForSource
lSourceKeys = list(dGroupedBySource.keys())
lSourceKeys.sort()
for source in lSourceKeys:
localizedStrings = dGroupedBySource[source]
if params["print-source"]:
if lOut[-1] != "":
lOut.append("")
lOut.append(source)
for localizedString in localizedStrings:
val = dOld.get(localizedString, {})
translation = val.get("translation", "")
comment = val.get("comment")
if params["break-long-lines"] and len(localizedString) > doublespace_threshold and not lOut[-1] == "":
lOut.append("")
if comment != None and comment != "" and not comment.startswith("# textdomain:"):
lOut.append(comment)
lOut.append(f"{localizedString}={translation}")
if params["break-long-lines"] and len(localizedString) > doublespace_threshold:
lOut.append("")
unusedExist = False
if not params["truncate-unused"]:
for key in dOld:
if key not in dkeyStrings:
val = dOld[key]
translation = val.get("translation")
comment = val.get("comment")
# only keep an unused translation if there was translated
# text or a comment associated with it
if translation != None and (translation != "" or comment):
if not unusedExist:
unusedExist = True
lOut.append("\n\n" + comment_unused + "\n")
if params["break-long-lines"] and len(key) > doublespace_threshold and not lOut[-1] == "":
lOut.append("")
if comment != None:
lOut.append(comment)
lOut.append(f"{key}={translation}")
if params["break-long-lines"] and len(key) > doublespace_threshold:
lOut.append("")
return "\n".join(lOut) + '\n'
# Writes a template.txt file
# dkeyStrings is the dictionary returned by generate_template
def write_template(templ_file, dkeyStrings, mod_name):
# read existing template file to preserve comments
existing_template = import_tr_file(templ_file)
text = strings_to_text(dkeyStrings, existing_template[0], mod_name, existing_template[2], existing_template[3])
mkdir_p(os.path.dirname(templ_file))
with open(templ_file, "wt", encoding='utf-8') as template_file:
template_file.write(text)
# Gets all translatable strings from a lua file
def read_lua_file_strings(lua_file):
lOut = []
with open(lua_file, encoding='utf-8') as text_file:
text = text_file.read()
text = re.sub(pattern_concat, "", text)
strings = []
for s in pattern_lua_quoted.findall(text):
strings.append(s[1])
for s in pattern_lua_bracketed.findall(text):
strings.append(s)
for s in strings:
found_bad = pattern_bad_luastring.search(s)
if found_bad:
print("SYNTAX ERROR: Unescaped '@' in Lua string: " + s)
continue
s = s.replace('\\"', '"')
s = s.replace("\\'", "'")
s = s.replace("\n", "@n")
s = s.replace("\\n", "@n")
s = s.replace("=", "@=")
lOut.append(s)
return lOut
# Gets strings from an existing translation file
# returns both a dictionary of translations
# and the full original source text so that the new text
# can be compared to it for changes.
# Returns also header comments in the third return value.
def import_tr_file(tr_file):
dOut = {}
text = None
in_header = True
header_comments = None
textdomain = None
if os.path.exists(tr_file):
with open(tr_file, "r", encoding='utf-8') as existing_file :
# save the full text to allow for comparison
# of the old version with the new output
text = existing_file.read()
existing_file.seek(0)
# a running record of the current comment block
# we're inside, to allow preceeding multi-line comments
# to be retained for a translation line
latest_comment_block = None
for line in existing_file.readlines():
line = line.rstrip('\n')
# "##### not used anymore #####" comment
if line == comment_unused:
# Always delete the 'not used anymore' comment.
# It will be re-added to the file if neccessary.
latest_comment_block = None
if header_comments != None:
in_header = False
continue
# Comment lines
elif line.startswith("#"):
# Source file comments: ##[ file.lua ]##
if line.startswith(symbol_source_prefix) and line.endswith(symbol_source_suffix):
# This line marks the end of header comments.
if params["print-source"]:
in_header = False
# Remove those comments; they may be added back automatically.
continue
# Store first occurance of textdomain
# discard all subsequent textdomain lines
if line.startswith("# textdomain:"):
if textdomain == None:
textdomain = line
continue
elif in_header:
# Save header comments (normal comments at top of file)
if not header_comments:
header_comments = line
else:
header_comments = header_comments + "\n" + line
else:
# Save normal comments
if line.startswith("# textdomain:") and textdomain == None:
textdomain = line
elif not latest_comment_block:
latest_comment_block = line
else:
latest_comment_block = latest_comment_block + "\n" + line
continue
match = pattern_tr.match(line)
if match:
# this line is a translated line
outval = {}
outval["translation"] = match.group(2)
if latest_comment_block:
# if there was a comment, record that.
outval["comment"] = latest_comment_block
latest_comment_block = None
in_header = False
dOut[match.group(1)] = outval
return (dOut, text, header_comments, textdomain)
# like os.walk but returns sorted filenames
def sorted_os_walk(folder):
tuples = []
t = 0
for root, dirs, files in os.walk(folder):
tuples.append( (root, dirs, files) )
t = t + 1
tuples = sorted(tuples)
paths_and_files = []
f = 0
for tu in tuples:
root = tu[0]
dirs = tu[1]
files = tu[2]
files = sorted(files, key=str.lower)
for filename in files:
paths_and_files.append( (os.path.join(root, filename), filename) )
f = f + 1
return paths_and_files
# Walks all lua files in the mod folder, collects translatable strings,
# and writes it to a template.txt file
# Returns a dictionary of localized strings to source file lists
# that can be used with the strings_to_text function.
def generate_template(folder, mod_name):
dOut = {}
paths_and_files = sorted_os_walk(folder)
for paf in paths_and_files:
fullpath_filename = paf[0]
filename = paf[1]
if fnmatch.fnmatch(filename, "*.lua"):
found = read_lua_file_strings(fullpath_filename)
if params["verbose"]:
print(f"{fullpath_filename}: {str(len(found))} translatable strings")
for s in found:
sources = dOut.get(s, set())
sources.add(os.path.relpath(fullpath_filename, start=folder))
dOut[s] = sources
if len(dOut) == 0:
return None
# Convert source file set to list, sort it and add comment symbols.
# Needed because a set is unsorted and might result in unpredictable.
# output orders if any source string appears in multiple files.
for d in dOut:
sources = dOut.get(d, set())
sources = sorted(list(sources), key=str.lower)
newSources = []
for i in sources:
newSources.append(f"{symbol_source_prefix} {i} {symbol_source_suffix}")
dOut[d] = newSources
templ_file = os.path.join(folder, "locale/template.txt")
write_template(templ_file, dOut, mod_name)
return dOut
# Updates an existing .tr file, copying the old one to a ".old" file
# if any changes have happened
# dNew is the data used to generate the template, it has all the
# currently-existing localized strings
def update_tr_file(dNew, mod_name, tr_file):
if params["verbose"]:
print(f"updating {tr_file}")
tr_import = import_tr_file(tr_file)
dOld = tr_import[0]
textOld = tr_import[1]
textNew = strings_to_text(dNew, dOld, mod_name, tr_import[2], tr_import[3])
if textOld and textOld != textNew:
print(f"{tr_file} has changed.")
if params["old-file"]:
shutil.copyfile(tr_file, f"{tr_file}.old")
with open(tr_file, "w", encoding='utf-8') as new_tr_file:
new_tr_file.write(textNew)
# Updates translation files for the mod in the given folder
def update_mod(folder):
modname = get_modname(folder)
if modname is not None:
print(f"Updating translations for {modname}")
data = generate_template(folder, modname)
if data == None:
print(f"No translatable strings found in {modname}")
else:
for tr_file in get_existing_tr_files(folder):
update_tr_file(data, modname, os.path.join(folder, "locale/", tr_file))
else:
print(f"Unable to determine the mod name in folder {folder}. Missing 'name' field in mod.conf.", file=_stderr)
exit(1)
# Determines if the folder being pointed to is a mod or a mod pack
# and then runs update_mod accordingly
def update_folder(folder):
is_modpack = os.path.exists(os.path.join(folder, "modpack.txt")) or os.path.exists(os.path.join(folder, "modpack.conf"))
if is_modpack:
subfolders = [f.path for f in os.scandir(folder) if f.is_dir() and not f.name.startswith('.')]
for subfolder in subfolders:
update_mod(subfolder)
else:
update_mod(folder)
print("Done.")
def run_all_subfolders(folder):
for modfolder in [f.path for f in os.scandir(folder) if f.is_dir() and not f.name.startswith('.')]:
update_folder(modfolder)
main()

View File

@ -1,4 +1,4 @@
local S = minetest.get_translator(minetest.get_current_modname())
local S = catrelle.S
--
-- items

View File

@ -4,6 +4,18 @@
catrelle={}
catrelle.gravity = automobiles_lib.gravity
catrelle.S = nil
if(minetest.get_translator ~= nil) then
catrelle.S = minetest.get_translator(minetest.get_current_modname())
else
catrelle.S = function ( s ) return s end
end
local S = catrelle.S
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "custom_physics.lua")
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "fuel_management.lua")
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "ground_detection.lua")

View File

@ -0,0 +1,5 @@
# textdomain: automobiles_catrelle
### crafts.lua ###
Catrelle Body=Catrelle Karrosserie
Catrelle=Catrelle
Catrelle 4F=Catrelle 4F

View File

@ -1,5 +1,5 @@
# textdomain: automobiles_catrelle
### crafts.lua ###
Catrelle Body=Korpo de Catrelle
Catrelle=Catrelle
Catrelle 4F=

View File

@ -1,5 +1,5 @@
# textdomain: automobiles_coupe
### coupe_crafts.lua ###
Coupe Body=
Coupe=
# textdomain: automobiles_catrelle
### crafts.lua ###
Catrelle Body=
Catrelle=
Catrelle 4F=

View File

@ -1,4 +1,4 @@
local S = minetest.get_translator(minetest.get_current_modname())
local S = coupe.S
--
-- items

View File

@ -4,6 +4,18 @@
coupe={}
coupe.gravity = automobiles_lib.gravity
coupe.S = nil
if(minetest.get_translator ~= nil) then
coupe.S = minetest.get_translator(minetest.get_current_modname())
else
coupe.S = function ( s ) return s end
end
local S = coupe.S
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "custom_physics.lua")
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "control.lua")
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "fuel_management.lua")

View File

@ -0,0 +1,4 @@
# textdomain: automobiles_coupe
### coupe_crafts.lua ###
Coupe Body=Coupe Karrosserie
Coupe=Coupe

View File

@ -1,5 +1,4 @@
# textdomain: automobiles_coupe
### coupe_crafts.lua ###
Coupe Body=Korpo de Coupe
Coupe=Coupe

View File

@ -1,5 +1,4 @@
# textdomain: automobiles_coupe
### coupe_crafts.lua ###
Coupe Body=
Coupe=

View File

@ -1,4 +1,4 @@
local S = minetest.get_translator(minetest.get_current_modname())
local S = delorean.S
--
-- items

View File

@ -368,7 +368,7 @@ minetest.register_entity("automobiles_delorean:delorean", {
sound_handle = nil,
owner = "",
static_save = true,
infotext = "A very nice delorean!",
infotext = S("A very nice delorean!"),
hp = 50,
buoyancy = 2,
physics = automobiles_lib.physics,
@ -408,7 +408,7 @@ minetest.register_entity("automobiles_delorean:delorean", {
_formspec_function = delorean.driver_formspec,
_destroy_function = delorean.destroy,
_vehicle_name = "Delorean",
_vehicle_name = S("Delorean"),
_drive_wheel_pos = {x=-4.66, y=6.31, z=15.69},
_drive_wheel_angle = 15,
_seat_pos = {{x=-4.65,y=0.48,z=9.5},{x=4.65,y=0.48,z=9.5}},

View File

@ -1,4 +1,4 @@
local S = delorean.S
--------------
-- Manual --
--------------
@ -31,10 +31,10 @@ function delorean.driver_formspec(name)
"size[6,7]",
}, "")
basic_form = basic_form.."button[1,1.0;4,1;go_out;Go Offboard]"
basic_form = basic_form.."button[1,2.5;4,1;lights;Lights]"
if ent._car_type == 1 then basic_form = basic_form.."checkbox[1,4.0;flight;Flight Mode;"..flight.."]" end
basic_form = basic_form.."checkbox[1,5.5;yaw;Direction by mouse;"..yaw.."]"
basic_form = basic_form.."button[1,1.0;4,1;go_out;" .. S("Go Offboard") .. "]"
basic_form = basic_form.."button[1,2.5;4,1;lights;" .. S("Lights") .. "]"
if ent._car_type == 1 then basic_form = basic_form.."checkbox[1,4.0;flight;" .. S("Flight Mode") .. ";"..flight.."]" end
basic_form = basic_form.."checkbox[1,5.5;yaw;" .. S("Direction by mouse") .. ";"..yaw.."]"
minetest.show_formspec(name, "delorean:driver_main", basic_form)
end

View File

@ -4,6 +4,18 @@
delorean={}
delorean.gravity = automobiles_lib.gravity
delorean.S = nil
if(minetest.get_translator ~= nil) then
delorean.S = minetest.get_translator(minetest.get_current_modname())
else
delorean.S = function ( s ) return s end
end
local S = delorean.S
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "custom_physics.lua")
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "fuel_management.lua")
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "ground_detection.lua")

View File

@ -0,0 +1,10 @@
# textdomain: automobiles_delorean
### coupe_crafts.lua ###
Delorean Body=Delorean Karrosserie
Time Machine=Zeitmaschine
Delorean=Delorean
A very nice delorean!=Ein sehr schöner Delorean!
Go Offboard=Aussteigen
Lights=Lichter
Flight Mode=Flugmodus
Direction by mouse=Lenke mit Maus

View File

@ -1,5 +1,10 @@
# textdomain: automobiles_delorean
### crafts.lua ###
Delorean Body=Korpo de Delorean
Time Machine=
Delorean=Delorean
A very nice delorean!=
Go Offboard=
Lights=
Flight Mode=
Direction by mouse=

View File

@ -1,5 +1,10 @@
# textdomain: automobiles_coupe
# textdomain: automobiles_delorean
### coupe_crafts.lua ###
Coupe Body=
Coupe=
Delorean Body=
Time Machine=
Delorean=
A very nice delorean!=
Go Offboard=
Lights=
Flight Mode=
Direction by mouse=

View File

@ -1,10 +1,20 @@
-- Minetest 5.4.1 : automobiles
local S = minetest.get_translator(minetest.get_current_modname())
automobiles_lib = {
storage = minetest.get_mod_storage()
}
automobiles_lib.S = nil
if(minetest.get_translator ~= nil) then
automobiles_lib.S = minetest.get_translator(minetest.get_current_modname())
else
automobiles_lib.S = function ( s ) return s end
end
local S = automobiles_lib.S
local storage = automobiles_lib.storage
automobiles_lib.fuel = {['biofuel:biofuel'] = 1,['biofuel:bottle_fuel'] = 1,
@ -308,12 +318,12 @@ function automobiles_lib.setText(self, vehicle_name)
local properties = self.object:get_properties()
local formatted = ""
if self.hp_max then
formatted = " Current hp: " .. string.format(
formatted = S(" Current hp: ") .. string.format(
"%.2f", self.hp_max
)
end
if properties then
properties.infotext = "Nice ".. vehicle_name .." of " .. self.owner .. "." .. formatted
properties.infotext = S("Nice @1 of @2.@3", vehicle_name, self.owner, formatted)
self.object:set_properties(properties)
end
end
@ -670,13 +680,13 @@ initial_properties = {
})
minetest.register_privilege("valet_parking", {
description = "Gives a valet parking priv for a player",
description = S("Gives a valet parking priv for a player"),
give_to_singleplayer = true
})
minetest.register_chatcommand("transfer_vehicle", {
params = "<new_owner>",
description = "Transfer the property of a vehicle to another player",
description = S("Transfer the property of a vehicle to another player"),
privs = {interact=true},
func = function(name, param)
local player = minetest.get_player_by_name(name)
@ -691,25 +701,25 @@ minetest.register_chatcommand("transfer_vehicle", {
if entity then
if entity.owner == name or minetest.check_player_privs(name, {protection_bypass=true}) then
entity.owner = param
minetest.chat_send_player(name,core.colorize('#00ff00', " >>> This vehicle now is property of: "..param))
minetest.chat_send_player(name,core.colorize('#00ff00', S(" >>> This vehicle now is property of: ")..param))
automobiles_lib.setText(entity, "vehicle")
else
minetest.chat_send_player(name,core.colorize('#ff0000', " >>> only the owner or moderators can transfer this vehicle"))
minetest.chat_send_player(name,core.colorize('#ff0000', S(" >>> only the owner or moderators can transfer this vehicle")))
end
end
end
else
minetest.chat_send_player(name,core.colorize('#ff0000', " >>> the target player must be logged in"))
minetest.chat_send_player(name,core.colorize('#ff0000', S(" >>> the target player must be logged in")))
end
else
minetest.chat_send_player(name,core.colorize('#ff0000', " >>> you are not inside a vehicle to perform the command"))
minetest.chat_send_player(name,core.colorize('#ff0000', S(" >>> you are not inside a vehicle to perform the command")))
end
end
})
minetest.register_chatcommand("noobfy_the_vehicles", {
params = "<true/false>",
description = "Enable/disable the NOOB mode for the vehicles",
description = S("Enable/disable the NOOB mode for the vehicles"),
privs = {server=true},
func = function(name, param)
local command = param
@ -717,11 +727,11 @@ minetest.register_chatcommand("noobfy_the_vehicles", {
if command == "false" then
automobiles_lib.noob_mode = false
automobiles_lib.extra_stepheight = 0
minetest.chat_send_player(name, ">>> Noob mode is disabled - A restart is required to changes take full effect")
minetest.chat_send_player(name, S(">>> Noob mode is disabled - A restart is required to changes take full effect"))
else
automobiles_lib.noob_mode = true
automobiles_lib.extra_stepheight = 1
minetest.chat_send_player(name, ">>> Noob mode is enabled - A restart is required to changes take full effect")
minetest.chat_send_player(name, S(">>> Noob mode is enabled - A restart is required to changes take full effect"))
end
local save = 2
if automobiles_lib.noob_mode == true then save = 1 end

View File

@ -0,0 +1,22 @@
# textdomain: automobiles_lib
### init.lua ###
Current hp: = Aktuelle Lp:
Nice @1 of @2.@3=Schöne(r) @1 von @2.@3
Car Engine=Motor
Car Wheel=Autoreifen
Gives a valet parking priv for a player=Gibt einen Parkservice für einen Spieler
Transfer the property of a vehicle to another player=Überträgt das Eigentum des Fahrzeuges an einem anderen Spieler
>>> This vehicle now is property of: = >>> Dieses Fahrzeug ist nun Eigentum von:
>>> only the owner or moderators can transfer this vehicle= >>> Nur der Eigentümer oder Moderator kann das Eigentum des Fahrzeuges übertragen
>>> the target player must be logged in= >>> der Zielspieler muß dafür eingeloggt sein.
>>> you are not inside a vehicle to perform the command= >>> du sitzt in keinem Fahrzeug um das Kommando auszuführen
Enable/disable the NOOB mode for the vehicles=Ein/Ausschalten des NOOB Moduses für die Fahrzeuge
>>> Noob mode is disabled - A restart is required to changes take full effect= >>> Noob Modus ist ausgeschalten - Ein Neustart für die Änderungen ist erforderlich
>>> Noob mode is enabled - A restart is required to changes take full effect= >>> Noob Modus ist eingeschalten - Ein Neustart für die Änderungen ist erforderlich
Preview=Vorschau
Set Hex=Gib Hexzahl
Set Color=Gib Farbe
Cancel=Abbrechen
### painter.lua ###
Automobiles Painter= Automobil Pinsel
Only the owner can paint this entity.=Nur der Eigentümer kann dieses Objekt einfärben.

View File

@ -1,8 +1,22 @@
# textdomain: automobiles_lib
### init.lua ###
Current hp: =
Nice @1 of @2.@3=
Car Engine=Aŭta Motoro
Car Wheel=Aŭta Rado
Gives a valet parking priv for a player=
Transfer the property of a vehicle to another player=
>>> This vehicle now is property of: =
>>> only the owner or moderators can transfer this vehicle=
>>> the target player must be logged in=
>>> you are not inside a vehicle to perform the command=
Enable/disable the NOOB mode for the vehicles=
>>> Noob mode is disabled - A restart is required to changes take full effect=
>>> Noob mode is enabled - A restart is required to changes take full effect=
Preview=
Set Hex=
Set Color=
Cancel=
### painter.lua ###
Automobiles Painter=Aŭta Pentrilo
Only the owner can paint this entity.=

View File

@ -1,8 +1,22 @@
# textdomain: automobiles_lib
### init.lua ###
Current hp: =
Nice @1 of @2.@3=
Car Engine=
Car Wheel=
Gives a valet parking priv for a player=
Transfer the property of a vehicle to another player=
>>> This vehicle now is property of: =
>>> only the owner or moderators can transfer this vehicle=
>>> the target player must be logged in=
>>> you are not inside a vehicle to perform the command=
Enable/disable the NOOB mode for the vehicles=
>>> Noob mode is disabled - A restart is required to changes take full effect=
>>> Noob mode is enabled - A restart is required to changes take full effect=
Preview=
Set Hex=
Set Color=
Cancel=
### painter.lua ###
Automobiles Painter=
Only the owner can paint this entity.=

View File

@ -21,7 +21,7 @@ Copyright (C) 2018 Hume2
THE SOFTWARE.
]]--
local S = minetest.get_translator(minetest.get_current_modname())
local S = automobiles_lib.S
local function is_hex(color)
if not color or color:len() ~= 7 then return end
@ -54,12 +54,12 @@ local function painter_form(player, rgb)
-- Color preview
"image[0.2,0.2;2,2;automobiles_painting.png^[colorize:" .. color .. ":255]" ..
"label[0.3,1.2;Preview]" ..
"label[0.3,1.2;" .. S("Preview") .. "]" ..
-- Hex field
"field_close_on_enter[hex;false]" ..
"field[2.4,0.2;3,0.8;hex;;" .. color .. "]" ..
"button[2.4,1;3,0.8;set_hex;Set Hex]" ..
"button[2.4,1;3,0.8;set_hex;" .. S("Set Hex") .. "]" ..
-- RGB sliders
"container[0,2.4]" ..
@ -83,8 +83,8 @@ local function painter_form(player, rgb)
"container_end[]" ..
-- Bottom buttons
"button_exit[0.2,4.2;2.8,0.8;set_color;Set Color]" ..
"button_exit[3.2,4.2;2.2,0.8;quit;Cancel]"
"button_exit[0.2,4.2;2.8,0.8;set_color;" .. S("Set Color") .. "]" ..
"button_exit[3.2,4.2;2.2,0.8;quit;" .. S("Cancel") .. "]"
)
end
@ -160,7 +160,7 @@ minetest.register_tool("automobiles_lib:painter", {
local rgb = is_hex(color) and hex_to_rgb(color) or {r = 0, g = 0, b = 0}
painter_form(user, rgb)
else
minetest.chat_send_player(player_name, "Only the owner can paint this entity.")
minetest.chat_send_player(player_name, S("Only the owner can paint this entity."))
end
end
end

View File

@ -11,6 +11,16 @@ motorcycle.max_acc_factor = 8
motorcycle.front_wheel_xpos = 0
motorcycle.rear_wheel_xpos = 0
if(minetest.get_translator ~= nil) then
motorcycle.S = minetest.get_translator(minetest.get_current_modname())
else
motorcycle.S = function ( s ) return s end
end
local S = motorcycle.S
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "custom_physics.lua")
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "control.lua")
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "fuel_management.lua")

View File

@ -0,0 +1,8 @@
# textdomain: automobiles_motorcycle
### motorcycle_crafts.lua ###
Motorcycle Body=Motorrad Fahrgestell
Motorcycle Wheel=Motorrad Reifen
Motorcycle=Motorrad
A very nice motorcycle!=Ein sehr schönes Motorrad!
Go Offboard=Aussteigen
Direction by mouse=Lenke mit Maus

View File

@ -1,6 +1,8 @@
# textdomain: automobiles_motorcycle
### motorcycle_crafts.lua ###
Motorcycle Body=Motorcikla Korpo
Motorcycle Wheel=Motorcikla Rado
Motorcycle=Motorciklo
A very nice motorcycle!=
Go Offboard=
Direction by mouse=

View File

@ -1,6 +1,8 @@
# textdomain: automobiles_motorcycle
### motorcycle_crafts.lua ###
Motorcycle Body=
Motorcycle Wheel=
Motorcycle=
A very nice motorcycle!=
Go Offboard=
Direction by mouse=

View File

@ -1,5 +1,4 @@
local S = minetest.get_translator(minetest.get_current_modname())
local S = motorcycle.S
--
-- items
--

View File

@ -1,6 +1,7 @@
--
-- entity
--
local S = motorcycle.S
minetest.register_entity('automobiles_motorcycle:lights',{
initial_properties = {
@ -125,7 +126,7 @@ minetest.register_entity("automobiles_motorcycle:motorcycle", {
sound_handle = nil,
owner = "",
static_save = true,
infotext = "A very nice motorcycle!",
infotext = S("A very nice motorcycle!"),
hp = 50,
buoyancy = 2,
physics = automobiles_lib.physics,

View File

@ -1,4 +1,4 @@
local S = motorcycle.S
function motorcycle.driver_formspec(name)
local player = minetest.get_player_by_name(name)
@ -16,8 +16,8 @@ function motorcycle.driver_formspec(name)
local yaw = "false"
if ent._yaw_by_mouse then yaw = "true" end
basic_form = basic_form.."button[1,1.0;4,1;go_out;Go Offboard]"
basic_form = basic_form.."checkbox[1,3.0;yaw;Direction by mouse;"..yaw.."]"
basic_form = basic_form.."button[1,1.0;4,1;go_out;" .. S("Go Offboard") .. "]"
basic_form = basic_form.."checkbox[1,3.0;yaw;" .. S("Direction by mouse") .. ";" ..yaw.."]"
minetest.show_formspec(name, "motorcycle:driver_main", basic_form)
end

View File

@ -8,6 +8,18 @@ roadster.gravity = automobiles_lib.gravity
roadster.max_speed = 12
roadster.max_acc_factor = 5
roadster.S = nil
if(minetest.get_translator ~= nil) then
roadster.S = minetest.get_translator(minetest.get_current_modname())
else
roadster.S = function ( s ) return s end
end
local S = roadster.S
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "custom_physics.lua")
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "control.lua")
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "fuel_management.lua")

View File

@ -0,0 +1,9 @@
# textdomain: automobiles_roadster
### roadster_crafts.lua ###
Roadster Body=Roadster Karrosserie
Roadster Wheel=Roadster Rad
Roadster=Roadster
Go Offboard=Aussteigen
Close/Open Ragtop=Öffne/Schließe Sonnendach
Lights=Lichter
Direction by mouse=Lenken mit Maus

View File

@ -1,6 +1,9 @@
# textdomain: automobiles_roadster
### roadster_crafts.lua ###
Roadster Body=Korpo de Roadster
Roadster Wheel=Rado de Roadster
Roadster=Roadster
Go Offboard=
Close/Open Ragtop=
Lights=
Direction by mouse=

View File

@ -1,6 +1,9 @@
# textdomain: automobiles_roadster
### roadster_crafts.lua ###
Roadster Body=
Roadster Wheel=
Roadster=
Go Offboard=
Close/Open Ragtop=
Lights=
Direction by mouse=

View File

@ -1,4 +1,4 @@
local S = minetest.get_translator(minetest.get_current_modname())
local S = roadster.S
--
-- items

View File

@ -1,3 +1,4 @@
local S = roadster.S
function roadster.driver_formspec(name)
local player = minetest.get_player_by_name(name)
@ -15,10 +16,10 @@ function roadster.driver_formspec(name)
"size[6,7]",
}, "")
basic_form = basic_form.."button[1,1.0;4,1;go_out;Go Offboard]"
basic_form = basic_form.."button[1,2.5;4,1;top;Close/Open Ragtop]"
basic_form = basic_form.."button[1,4.0;4,1;lights;Lights]"
basic_form = basic_form.."checkbox[1,5.5;yaw;Direction by mouse;"..yaw.."]"
basic_form = basic_form.."button[1,1.0;4,1;go_out;" .. S("Go Offboard") .. "]"
basic_form = basic_form.."button[1,2.5;4,1;top;" .. S("Close/Open Ragtop") .. "]"
basic_form = basic_form.."button[1,4.0;4,1;lights;" .. S("Lights") .. "]"
basic_form = basic_form.."checkbox[1,5.5;yaw;" .. S("Direction by mouse") .. ";"..yaw.."]"
minetest.show_formspec(name, "roadster:driver_main", basic_form)
end

View File

@ -1,4 +1,4 @@
local S = minetest.get_translator(minetest.get_current_modname())
local S = trans_am.S
--
-- items

View File

@ -1,6 +1,7 @@
--
-- entity
--
local S = trans_am.S
minetest.register_entity('automobiles_trans_am:wheel',{
initial_properties = {
@ -292,7 +293,7 @@ minetest.register_entity("automobiles_trans_am:trans_am", {
sound_handle = nil,
owner = "",
static_save = true,
infotext = "A very nice Trans Am!",
infotext = S("A very nice Trans Am!"),
hp = 50,
buoyancy = 2,
physics = automobiles_lib.physics,

View File

@ -4,6 +4,18 @@
trans_am={}
trans_am.gravity = automobiles_lib.gravity
trans_am.S = nil
if(minetest.get_translator ~= nil) then
trans_am.S = minetest.get_translator(minetest.get_current_modname())
else
trans_am.S = function ( s ) return s end
end
local S = trans_am.S
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "custom_physics.lua")
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "fuel_management.lua")
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "ground_detection.lua")

View File

@ -0,0 +1,5 @@
# textdomain: automobiles_trans_am
### crafts.lua ###
Trans Am Body=Trans Am Karrosserie
Trans Am=Trans Am
A very nice Trans Am!=Ein sehr schöner Trans Am!

View File

@ -1,5 +1,5 @@
# textdomain: automobiles_trans_am
### crafts.lua ###
Trans Am Body=Korpo de Trans Am
Trans Am=Trans Am
A very nice Trans Am!=

View File

@ -1,5 +1,5 @@
# textdomain: automobiles_coupe
### coupe_crafts.lua ###
Coupe Body=
Coupe=
# textdomain: automobiles_trans_am
### crafts.lua ###
Trans Am Body=
Trans Am=
A very nice Trans Am!=

View File

@ -11,6 +11,18 @@ vespa.max_acc_factor = 6
vespa.front_wheel_xpos = 0
vespa.rear_wheel_xpos = 0
vespa.S = nil
if(minetest.get_translator ~= nil) then
vespa.S = minetest.get_translator(minetest.get_current_modname())
else
vespa.S = function ( s ) return s end
end
local S = vespa.S
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "custom_physics.lua")
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "control.lua")
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "fuel_management.lua")

View File

@ -0,0 +1,9 @@
# textdomain: automobiles_vespa
### motorcycle_crafts.lua ###
Vespa Body=Vespa Karrosserie
Vespa Wheel=Vesta Rad
Vespa=Vespa
A very nice vespa!=Eine sehr schöne Vespa!
Out of fuel=Kein Sprit mehr
Go Offboard=Aussteigen
Direction by mouse=Lenken mit Maus

View File

@ -1,6 +1,9 @@
# textdomain: automobiles_vespa
### motorcycle_crafts.lua ###
Vespa Body=Vespa Korpo
Vespa Wheel=Vespa Rado
Vespa=Vespa
A very nice vespa!=
Out of fuel=
Go Offboard=
Direction by mouse=

View File

@ -1,6 +1,9 @@
# textdomain: automobiles_vespa
### motorcycle_crafts.lua ###
Vespa Body=
Vespa Wheel=
Vespa=
A very nice vespa!=
Out of fuel=
Go Offboard=
Direction by mouse=

View File

@ -1,4 +1,4 @@
local S = minetest.get_translator(minetest.get_current_modname())
local S = vespa.S
--
-- items

View File

@ -1,6 +1,7 @@
--
-- entity
--
local S = vespa.S
minetest.register_entity('automobiles_vespa:lights',{
initial_properties = {
@ -120,7 +121,7 @@ minetest.register_entity("automobiles_vespa:vespa", {
sound_handle = nil,
owner = "",
static_save = true,
infotext = "A very nice vespa!",
infotext = S("A very nice vespa!"),
hp = 50,
buoyancy = 2,
physics = automobiles_lib.physics,
@ -430,7 +431,7 @@ minetest.register_entity("automobiles_vespa:vespa", {
if self._energy <= 0 then
self._engine_running = false
if self.sound_handle then minetest.sound_stop(self.sound_handle) end
minetest.chat_send_player(self.driver_name, "Out of fuel")
minetest.chat_send_player(self.driver_name, S("Out of fuel"))
else
self._last_engine_sound_update = self._last_engine_sound_update + dtime
if self._last_engine_sound_update > 0.300 then

View File

@ -1,4 +1,4 @@
local S = vespa.S
function vespa.driver_formspec(name)
local player = minetest.get_player_by_name(name)
@ -16,8 +16,8 @@ function vespa.driver_formspec(name)
local yaw = "false"
if ent._yaw_by_mouse then yaw = "true" end
basic_form = basic_form.."button[1,1.0;4,1;go_out;Go Offboard]"
basic_form = basic_form.."checkbox[1,3.0;yaw;Direction by mouse;"..yaw.."]"
basic_form = basic_form.."button[1,1.0;4,1;go_out;" .. S("Go Offboard") .. "]"
basic_form = basic_form.."checkbox[1,3.0;yaw;" .. S("Direction by mouse") .. ";"..yaw.."]"
minetest.show_formspec(name, "vespa:driver_main", basic_form)
end

495
mod_translation_updater.py Executable file
View File

@ -0,0 +1,495 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Script to generate Minetest translation template files and update
# translation files.
#
# Copyright (C) 2019 Joachim Stolberg, 2020 FaceDeer, 2020 Louis Royer,
# 2023 Wuzzy.
# License: LGPLv2.1 or later (see LICENSE file for details)
import os, fnmatch, re, shutil, errno
from sys import argv as _argv
from sys import stderr as _stderr
# Running params
params = {"recursive": False,
"help": False,
"verbose": False,
"folders": [],
"old-file": False,
"break-long-lines": False,
"print-source": False,
"truncate-unused": False,
}
# Available CLI options
options = {"recursive": ['--recursive', '-r'],
"help": ['--help', '-h'],
"verbose": ['--verbose', '-v'],
"old-file": ['--old-file', '-o'],
"break-long-lines": ['--break-long-lines', '-b'],
"print-source": ['--print-source', '-p'],
"truncate-unused": ['--truncate-unused', '-t'],
}
# Strings longer than this will have extra space added between
# them in the translation files to make it easier to distinguish their
# beginnings and endings at a glance
doublespace_threshold = 80
# These symbols mark comment lines showing the source file name.
# A comment may look like "##[ init.lua ]##".
symbol_source_prefix = "##["
symbol_source_suffix = "]##"
# comment to mark the section of old/unused strings
comment_unused = "##### not used anymore #####"
def set_params_folders(tab: list):
'''Initialize params["folders"] from CLI arguments.'''
# Discarding argument 0 (tool name)
for param in tab[1:]:
stop_param = False
for option in options:
if param in options[option]:
stop_param = True
break
if not stop_param:
params["folders"].append(os.path.abspath(param))
def set_params(tab: list):
'''Initialize params from CLI arguments.'''
for option in options:
for option_name in options[option]:
if option_name in tab:
params[option] = True
break
def print_help(name):
'''Prints some help message.'''
print(f'''SYNOPSIS
{name} [OPTIONS] [PATHS...]
DESCRIPTION
{', '.join(options["help"])}
prints this help message
{', '.join(options["recursive"])}
run on all subfolders of paths given
{', '.join(options["old-file"])}
create *.old files
{', '.join(options["break-long-lines"])}
add extra line breaks before and after long strings
{', '.join(options["print-source"])}
add comments denoting the source file
{', '.join(options["verbose"])}
add output information
{', '.join(options["truncate-unused"])}
delete unused strings from files
''')
def main():
'''Main function'''
set_params(_argv)
set_params_folders(_argv)
if params["help"]:
print_help(_argv[0])
else:
# Add recursivity message
print("Running ", end='')
if params["recursive"]:
print("recursively ", end='')
# Running
if len(params["folders"]) >= 2:
print("on folder list:", params["folders"])
for f in params["folders"]:
if params["recursive"]:
run_all_subfolders(f)
else:
update_folder(f)
elif len(params["folders"]) == 1:
print("on folder", params["folders"][0])
if params["recursive"]:
run_all_subfolders(params["folders"][0])
else:
update_folder(params["folders"][0])
else:
print("on folder", os.path.abspath("./"))
if params["recursive"]:
run_all_subfolders(os.path.abspath("./"))
else:
update_folder(os.path.abspath("./"))
# Group 2 will be the string, groups 1 and 3 will be the delimiters (" or ')
# See https://stackoverflow.com/questions/46967465/regex-match-text-in-either-single-or-double-quote
pattern_lua_quoted = re.compile(
r'(?:^|[\.=,{\(\s])' # Look for beginning of file or anything that isn't a function identifier
r'N?F?S\s*\(\s*' # Matches S, FS, NS or NFS function call
r'(["\'])((?:\\\1|(?:(?!\1)).)*)(\1)' # Quoted string
r'[\s,\)]', # End of call or argument
re.DOTALL)
# Handles the [[ ... ]] string delimiters
pattern_lua_bracketed = re.compile(
r'(?:^|[\.=,{\(\s])' # Same as for pattern_lua_quoted
r'N?F?S\s*\(\s*' # Same as for pattern_lua_quoted
r'\[\[(.*?)\]\]' # [[ ... ]] string delimiters
r'[\s,\)]', # Same as for pattern_lua_quoted
re.DOTALL)
# Handles "concatenation" .. " of strings"
pattern_concat = re.compile(r'["\'][\s]*\.\.[\s]*["\']', re.DOTALL)
# Handles a translation line in *.tr file.
# Group 1 is the source string left of the equals sign.
# Group 2 is the translated string, right of the equals sign.
pattern_tr = re.compile(
r'(.*)' # Source string
# the separating equals sign, if NOT preceded by @, unless
# that @ is preceded by another @
r'(?:(?<!(?<!@)@)=)'
r'(.*)' # Translation string
)
pattern_name = re.compile(r'^name[ ]*=[ ]*([^ \n]*)')
pattern_tr_filename = re.compile(r'\.tr$')
# Matches bad use of @ signs in Lua string
pattern_bad_luastring = re.compile(
r'^@$|' # single @, OR
r'[^@]@$|' # trailing unescaped @, OR
r'(?<!@)@(?=[^@1-9])' # an @ that is not escaped or part of a placeholder
)
# Attempt to read the mod's name from the mod.conf file or folder name. Returns None on failure
def get_modname(folder):
try:
with open(os.path.join(folder, "mod.conf"), "r", encoding='utf-8') as mod_conf:
for line in mod_conf:
match = pattern_name.match(line)
if match:
return match.group(1)
except FileNotFoundError:
if not os.path.isfile(os.path.join(folder, "modpack.txt")):
folder_name = os.path.basename(folder)
# Special case when run in Minetest's builtin directory
if folder_name == "builtin":
return "__builtin"
else:
return folder_name
else:
return None
return None
# If there are already .tr files in /locale, returns a list of their names
def get_existing_tr_files(folder):
out = []
for root, dirs, files in os.walk(os.path.join(folder, 'locale/')):
for name in files:
if pattern_tr_filename.search(name):
out.append(name)
return out
# from https://stackoverflow.com/questions/600268/mkdir-p-functionality-in-python/600612#600612
# Creates a directory if it doesn't exist, silently does
# nothing if it already exists
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else: raise
# Converts the template dictionary to a text to be written as a file
# dKeyStrings is a dictionary of localized string to source file sets
# dOld is a dictionary of existing translations and comments from
# the previous version of this text
def strings_to_text(dkeyStrings, dOld, mod_name, header_comments, textdomain):
# if textdomain is specified, insert it at the top
if textdomain != None:
lOut = [textdomain] # argument is full textdomain line
# otherwise, use mod name as textdomain automatically
else:
lOut = [f"# textdomain: {mod_name}"]
if header_comments is not None:
lOut.append(header_comments)
dGroupedBySource = {}
for key in dkeyStrings:
sourceList = list(dkeyStrings[key])
sourceString = "\n".join(sourceList)
listForSource = dGroupedBySource.get(sourceString, [])
listForSource.append(key)
dGroupedBySource[sourceString] = listForSource
lSourceKeys = list(dGroupedBySource.keys())
lSourceKeys.sort()
for source in lSourceKeys:
localizedStrings = dGroupedBySource[source]
if params["print-source"]:
if lOut[-1] != "":
lOut.append("")
lOut.append(source)
for localizedString in localizedStrings:
val = dOld.get(localizedString, {})
translation = val.get("translation", "")
comment = val.get("comment")
if params["break-long-lines"] and len(localizedString) > doublespace_threshold and not lOut[-1] == "":
lOut.append("")
if comment != None and comment != "" and not comment.startswith("# textdomain:"):
lOut.append(comment)
lOut.append(f"{localizedString}={translation}")
if params["break-long-lines"] and len(localizedString) > doublespace_threshold:
lOut.append("")
unusedExist = False
if not params["truncate-unused"]:
for key in dOld:
if key not in dkeyStrings:
val = dOld[key]
translation = val.get("translation")
comment = val.get("comment")
# only keep an unused translation if there was translated
# text or a comment associated with it
if translation != None and (translation != "" or comment):
if not unusedExist:
unusedExist = True
lOut.append("\n\n" + comment_unused + "\n")
if params["break-long-lines"] and len(key) > doublespace_threshold and not lOut[-1] == "":
lOut.append("")
if comment != None:
lOut.append(comment)
lOut.append(f"{key}={translation}")
if params["break-long-lines"] and len(key) > doublespace_threshold:
lOut.append("")
return "\n".join(lOut) + '\n'
# Writes a template.txt file
# dkeyStrings is the dictionary returned by generate_template
def write_template(templ_file, dkeyStrings, mod_name):
# read existing template file to preserve comments
existing_template = import_tr_file(templ_file)
text = strings_to_text(dkeyStrings, existing_template[0], mod_name, existing_template[2], existing_template[3])
mkdir_p(os.path.dirname(templ_file))
with open(templ_file, "wt", encoding='utf-8') as template_file:
template_file.write(text)
# Gets all translatable strings from a lua file
def read_lua_file_strings(lua_file):
lOut = []
with open(lua_file, encoding='utf-8') as text_file:
text = text_file.read()
text = re.sub(pattern_concat, "", text)
strings = []
for s in pattern_lua_quoted.findall(text):
strings.append(s[1])
for s in pattern_lua_bracketed.findall(text):
strings.append(s)
for s in strings:
found_bad = pattern_bad_luastring.search(s)
if found_bad:
print("SYNTAX ERROR: Unescaped '@' in Lua string: " + s)
continue
s = s.replace('\\"', '"')
s = s.replace("\\'", "'")
s = s.replace("\n", "@n")
s = s.replace("\\n", "@n")
s = s.replace("=", "@=")
lOut.append(s)
return lOut
# Gets strings from an existing translation file
# returns both a dictionary of translations
# and the full original source text so that the new text
# can be compared to it for changes.
# Returns also header comments in the third return value.
def import_tr_file(tr_file):
dOut = {}
text = None
in_header = True
header_comments = None
textdomain = None
if os.path.exists(tr_file):
with open(tr_file, "r", encoding='utf-8') as existing_file :
# save the full text to allow for comparison
# of the old version with the new output
text = existing_file.read()
existing_file.seek(0)
# a running record of the current comment block
# we're inside, to allow preceeding multi-line comments
# to be retained for a translation line
latest_comment_block = None
for line in existing_file.readlines():
line = line.rstrip('\n')
# "##### not used anymore #####" comment
if line == comment_unused:
# Always delete the 'not used anymore' comment.
# It will be re-added to the file if neccessary.
latest_comment_block = None
if header_comments != None:
in_header = False
continue
# Comment lines
elif line.startswith("#"):
# Source file comments: ##[ file.lua ]##
if line.startswith(symbol_source_prefix) and line.endswith(symbol_source_suffix):
# This line marks the end of header comments.
if params["print-source"]:
in_header = False
# Remove those comments; they may be added back automatically.
continue
# Store first occurance of textdomain
# discard all subsequent textdomain lines
if line.startswith("# textdomain:"):
if textdomain == None:
textdomain = line
continue
elif in_header:
# Save header comments (normal comments at top of file)
if not header_comments:
header_comments = line
else:
header_comments = header_comments + "\n" + line
else:
# Save normal comments
if line.startswith("# textdomain:") and textdomain == None:
textdomain = line
elif not latest_comment_block:
latest_comment_block = line
else:
latest_comment_block = latest_comment_block + "\n" + line
continue
match = pattern_tr.match(line)
if match:
# this line is a translated line
outval = {}
outval["translation"] = match.group(2)
if latest_comment_block:
# if there was a comment, record that.
outval["comment"] = latest_comment_block
latest_comment_block = None
in_header = False
dOut[match.group(1)] = outval
return (dOut, text, header_comments, textdomain)
# like os.walk but returns sorted filenames
def sorted_os_walk(folder):
tuples = []
t = 0
for root, dirs, files in os.walk(folder):
tuples.append( (root, dirs, files) )
t = t + 1
tuples = sorted(tuples)
paths_and_files = []
f = 0
for tu in tuples:
root = tu[0]
dirs = tu[1]
files = tu[2]
files = sorted(files, key=str.lower)
for filename in files:
paths_and_files.append( (os.path.join(root, filename), filename) )
f = f + 1
return paths_and_files
# Walks all lua files in the mod folder, collects translatable strings,
# and writes it to a template.txt file
# Returns a dictionary of localized strings to source file lists
# that can be used with the strings_to_text function.
def generate_template(folder, mod_name):
dOut = {}
paths_and_files = sorted_os_walk(folder)
for paf in paths_and_files:
fullpath_filename = paf[0]
filename = paf[1]
if fnmatch.fnmatch(filename, "*.lua"):
found = read_lua_file_strings(fullpath_filename)
if params["verbose"]:
print(f"{fullpath_filename}: {str(len(found))} translatable strings")
for s in found:
sources = dOut.get(s, set())
sources.add(os.path.relpath(fullpath_filename, start=folder))
dOut[s] = sources
if len(dOut) == 0:
return None
# Convert source file set to list, sort it and add comment symbols.
# Needed because a set is unsorted and might result in unpredictable.
# output orders if any source string appears in multiple files.
for d in dOut:
sources = dOut.get(d, set())
sources = sorted(list(sources), key=str.lower)
newSources = []
for i in sources:
newSources.append(f"{symbol_source_prefix} {i} {symbol_source_suffix}")
dOut[d] = newSources
templ_file = os.path.join(folder, "locale/template.txt")
write_template(templ_file, dOut, mod_name)
return dOut
# Updates an existing .tr file, copying the old one to a ".old" file
# if any changes have happened
# dNew is the data used to generate the template, it has all the
# currently-existing localized strings
def update_tr_file(dNew, mod_name, tr_file):
if params["verbose"]:
print(f"updating {tr_file}")
tr_import = import_tr_file(tr_file)
dOld = tr_import[0]
textOld = tr_import[1]
textNew = strings_to_text(dNew, dOld, mod_name, tr_import[2], tr_import[3])
if textOld and textOld != textNew:
print(f"{tr_file} has changed.")
if params["old-file"]:
shutil.copyfile(tr_file, f"{tr_file}.old")
with open(tr_file, "w", encoding='utf-8') as new_tr_file:
new_tr_file.write(textNew)
# Updates translation files for the mod in the given folder
def update_mod(folder):
modname = get_modname(folder)
if modname is not None:
print(f"Updating translations for {modname}")
data = generate_template(folder, modname)
if data == None:
print(f"No translatable strings found in {modname}")
else:
for tr_file in get_existing_tr_files(folder):
update_tr_file(data, modname, os.path.join(folder, "locale/", tr_file))
else:
print(f"Unable to determine the mod name in folder {folder}. Missing 'name' field in mod.conf.", file=_stderr)
exit(1)
# Determines if the folder being pointed to is a mod or a mod pack
# and then runs update_mod accordingly
def update_folder(folder):
is_modpack = os.path.exists(os.path.join(folder, "modpack.txt")) or os.path.exists(os.path.join(folder, "modpack.conf"))
if is_modpack:
subfolders = [f.path for f in os.scandir(folder) if f.is_dir() and not f.name.startswith('.')]
for subfolder in subfolders:
update_mod(subfolder)
else:
update_mod(folder)
print("Done.")
def run_all_subfolders(folder):
for modfolder in [f.path for f in os.scandir(folder) if f.is_dir() and not f.name.startswith('.')]:
update_folder(modfolder)
main()