Cleanup: pep8

This commit is contained in:
Campbell Barton
2018-07-07 08:48:35 +02:00
parent 252207cc7a
commit 4b373ed086
4 changed files with 89 additions and 64 deletions

View File

@@ -120,8 +120,11 @@ def check(check_ctxt, msgs, key, msgsrc, settings):
key[1][0].isalpha() and not key[1][0].isupper()): key[1][0].isalpha() and not key[1][0].isupper()):
not_capitalized.add(key) not_capitalized.add(key)
if end_point is not None: if end_point is not None:
if (key[1].strip().endswith('.') and not key[1].strip().endswith('...') and if (
key[1] not in settings.WARN_MSGID_END_POINT_ALLOWED): key[1].strip().endswith('.') and
(not key[1].strip().endswith('...')) and
key[1] not in settings.WARN_MSGID_END_POINT_ALLOWED
):
end_point.add(key) end_point.add(key)
if undoc_ops is not None: if undoc_ops is not None:
if key[1] == settings.UNDOC_OPS_STR: if key[1] == settings.UNDOC_OPS_STR:
@@ -183,8 +186,10 @@ def print_info(reports, pot):
# if py_in_rna and key in py_in_rna: # if py_in_rna and key in py_in_rna:
# _print("\t\t-> RNA message also used in py UI code!") # _print("\t\t-> RNA message also used in py UI code!")
if spell_errors and spell_errors.get(key): if spell_errors and spell_errors.get(key):
lines = ["\t\t-> {}: misspelled, suggestions are ({})".format(w, "'" + "', '".join(errs) + "'") lines = [
for w, errs in spell_errors[key]] "\t\t-> {}: misspelled, suggestions are ({})".format(w, "'" + "', '".join(errs) + "'")
for w, errs in spell_errors[key]
]
_print("\n".join(lines)) _print("\n".join(lines))
_print("\t\t{}".format("\n\t\t".join(pot.msgs[key].sources))) _print("\t\t{}".format("\n\t\t".join(pot.msgs[key].sources)))
@@ -215,13 +220,13 @@ def dump_rna_messages(msgs, reports, settings, verbose=False):
""" """
def class_blacklist(): def class_blacklist():
blacklist_rna_class = {getattr(bpy.types, cls_id) for cls_id in ( blacklist_rna_class = {getattr(bpy.types, cls_id) for cls_id in (
# core classes # core classes
"Context", "Event", "Function", "UILayout", "UnknownType", "Property", "Struct", "Context", "Event", "Function", "UILayout", "UnknownType", "Property", "Struct",
# registerable classes # registerable classes
"Panel", "Menu", "Header", "RenderEngine", "Operator", "OperatorMacro", "Macro", "KeyingSetInfo", "Panel", "Menu", "Header", "RenderEngine", "Operator", "OperatorMacro", "Macro", "KeyingSetInfo",
# window classes # window classes
"Window", "Window",
) )
} }
# More builtin classes we don't need to parse. # More builtin classes we don't need to parse.
@@ -380,6 +385,7 @@ def dump_rna_messages(msgs, reports, settings, verbose=False):
# Dump Messages # Dump Messages
operator_categories = {} operator_categories = {}
def process_cls_list(cls_list): def process_cls_list(cls_list):
if not cls_list: if not cls_list:
return return
@@ -447,6 +453,7 @@ def dump_py_messages_from_files(msgs, reports, files, settings):
i18n_contexts = bpy.app.translations.contexts i18n_contexts = bpy.app.translations.contexts
root_paths = tuple(bpy.utils.resource_path(t) for t in ('USER', 'LOCAL', 'SYSTEM')) root_paths = tuple(bpy.utils.resource_path(t) for t in ('USER', 'LOCAL', 'SYSTEM'))
def make_rel(path): def make_rel(path):
for rp in root_paths: for rp in root_paths:
if path.startswith(rp): if path.startswith(rp):
@@ -510,6 +517,7 @@ def dump_py_messages_from_files(msgs, reports, files, settings):
return [_extract_string_merge(estr_ls, nds_ls) for estr_ls, nds_ls in bag] return [_extract_string_merge(estr_ls, nds_ls) for estr_ls, nds_ls in bag]
i18n_ctxt_ids = {v for v in bpy.app.translations.contexts_C_to_py.values()} i18n_ctxt_ids = {v for v in bpy.app.translations.contexts_C_to_py.values()}
def _ctxt_to_ctxt(node): def _ctxt_to_ctxt(node):
# We must try, to some extend, to get contexts from vars instead of only literal strings... # We must try, to some extend, to get contexts from vars instead of only literal strings...
ctxt = extract_strings(node)[0] ctxt = extract_strings(node)[0]
@@ -561,9 +569,9 @@ def dump_py_messages_from_files(msgs, reports, files, settings):
translate_kw = { translate_kw = {
"text": ((("text_ctxt",), _ctxt_to_ctxt), "text": ((("text_ctxt",), _ctxt_to_ctxt),
(("operator",), _op_to_ctxt), (("operator",), _op_to_ctxt),
),
"msgid": ((("msgctxt",), _ctxt_to_ctxt),
), ),
"msgid": ((("msgctxt",), _ctxt_to_ctxt),
),
"message": (), "message": (),
} }
@@ -611,7 +619,7 @@ def dump_py_messages_from_files(msgs, reports, files, settings):
func_translate_args[func_id] = pgettext_variants_args func_translate_args[func_id] = pgettext_variants_args
for func_id in func_ids: for func_id in func_ids:
func_translate_args[func_id] = pgettext_variants_args func_translate_args[func_id] = pgettext_variants_args
#print(func_translate_args) # print(func_translate_args)
# Break recursive nodes look up on some kind of nodes. # Break recursive nodes look up on some kind of nodes.
# E.g. we don't want to get strings inside subscripts (blah["foo"])! # E.g. we don't want to get strings inside subscripts (blah["foo"])!
@@ -666,7 +674,7 @@ def dump_py_messages_from_files(msgs, reports, files, settings):
if kw.arg == arg_kw: if kw.arg == arg_kw:
context_elements[arg_kw] = kw.value context_elements[arg_kw] = kw.value
break break
#print(context_elements) # print(context_elements)
for kws, proc in translate_kw[msgid]: for kws, proc in translate_kw[msgid]:
if set(kws) <= context_elements.keys(): if set(kws) <= context_elements.keys():
args = tuple(context_elements[k] for k in kws) args = tuple(context_elements[k] for k in kws)
@@ -676,7 +684,7 @@ def dump_py_messages_from_files(msgs, reports, files, settings):
msgctxts[msgid] = ctxt msgctxts[msgid] = ctxt
break break
#print(translate_args) # print(translate_args)
# do nothing if not found # do nothing if not found
for arg_kw, (arg_pos, _) in func_args.items(): for arg_kw, (arg_pos, _) in func_args.items():
msgctxt = msgctxts[arg_kw] msgctxt = msgctxts[arg_kw]
@@ -706,7 +714,7 @@ def dump_py_messages(msgs, reports, addons, settings, addons_only=False):
return [] return []
if os.path.isdir(path): if os.path.isdir(path):
return [os.path.join(dpath, fn) for dpath, _, fnames in os.walk(path) for fn in fnames return [os.path.join(dpath, fn) for dpath, _, fnames in os.walk(path) for fn in fnames
if not fn.startswith("_") and fn.endswith(".py")] if not fn.startswith("_") and fn.endswith(".py")]
return [path] return [path]
files = [] files = []
@@ -738,7 +746,9 @@ def dump_src_messages(msgs, reports, settings):
pygettexts = tuple(re.compile(r).search for r in settings.PYGETTEXT_KEYWORDS) pygettexts = tuple(re.compile(r).search for r in settings.PYGETTEXT_KEYWORDS)
_clean_str = re.compile(settings.str_clean_re).finditer _clean_str = re.compile(settings.str_clean_re).finditer
clean_str = lambda s: "".join(m.group("clean") for m in _clean_str(s))
def clean_str(s):
return "".join(m.group("clean") for m in _clean_str(s))
def dump_src_file(path, rel_path, msgs, reports, settings): def dump_src_file(path, rel_path, msgs, reports, settings):
def process_entry(_msgctxt, _msgid): def process_entry(_msgctxt, _msgid):
@@ -873,10 +883,10 @@ def dump_messages(do_messages, do_checks, settings):
process_msg(msgs, settings.DEFAULT_CONTEXT, cat[1], process_msg(msgs, settings.DEFAULT_CONTEXT, cat[1],
"Language categories labels from bl_i18n_utils/settings.py", reports, None, settings) "Language categories labels from bl_i18n_utils/settings.py", reports, None, settings)
#pot.check() # pot.check()
pot.unescape() # Strings gathered in py/C source code may contain escaped chars... pot.unescape() # Strings gathered in py/C source code may contain escaped chars...
print_info(reports, pot) print_info(reports, pot)
#pot.check() # pot.check()
if do_messages: if do_messages:
print("Writing messages…") print("Writing messages…")

View File

@@ -32,9 +32,9 @@ import tempfile
#import time #import time
from bl_i18n_utils import ( from bl_i18n_utils import (
settings, settings,
utils_rtl, utils_rtl,
) )
import bpy import bpy
@@ -44,6 +44,8 @@ from bpy.app.translations import locale_explode
_valid_po_path_re = re.compile(r"^\S+:[0-9]+$") _valid_po_path_re = re.compile(r"^\S+:[0-9]+$")
def is_valid_po_path(path): def is_valid_po_path(path):
return bool(_valid_po_path_re.match(path)) return bool(_valid_po_path_re.match(path))
@@ -57,9 +59,10 @@ def get_best_similar(data):
# We also consider to never make a match when len differs more than -len_key / 2, +len_key * 2 (which is valid # We also consider to never make a match when len differs more than -len_key / 2, +len_key * 2 (which is valid
# as long as use_similar is not below ~0.7). # as long as use_similar is not below ~0.7).
# Gives an overall ~20% of improvement! # Gives an overall ~20% of improvement!
#tmp = difflib.get_close_matches(key[1], similar_pool, n=1, cutoff=use_similar)
#if tmp: # tmp = difflib.get_close_matches(key[1], similar_pool, n=1, cutoff=use_similar)
#tmp = tmp[0] # if tmp:
# tmp = tmp[0]
tmp = None tmp = None
s = difflib.SequenceMatcher() s = difflib.SequenceMatcher()
s.set_seq2(key[1]) s.set_seq2(key[1])
@@ -178,9 +181,11 @@ def enable_addons(addons=None, support=None, disable=False, check_only=False):
userpref = bpy.context.user_preferences userpref = bpy.context.user_preferences
used_ext = {ext.module for ext in userpref.addons} used_ext = {ext.module for ext in userpref.addons}
ret = [mod for mod in addon_utils.modules() ret = [
if ((addons and mod.__name__ in addons) or mod for mod in addon_utils.modules()
(not addons and addon_utils.module_bl_info(mod)["support"] in support))] if ((addons and mod.__name__ in addons) or
(not addons and addon_utils.module_bl_info(mod)["support"] in support))
]
if not check_only: if not check_only:
for mod in ret: for mod in ret:
@@ -229,18 +234,21 @@ class I18nMessage:
def _get_msgctxt(self): def _get_msgctxt(self):
return "".join(self.msgctxt_lines) return "".join(self.msgctxt_lines)
def _set_msgctxt(self, ctxt): def _set_msgctxt(self, ctxt):
self.msgctxt_lines = [ctxt] self.msgctxt_lines = [ctxt]
msgctxt = property(_get_msgctxt, _set_msgctxt) msgctxt = property(_get_msgctxt, _set_msgctxt)
def _get_msgid(self): def _get_msgid(self):
return "".join(self.msgid_lines) return "".join(self.msgid_lines)
def _set_msgid(self, msgid): def _set_msgid(self, msgid):
self.msgid_lines = [msgid] self.msgid_lines = [msgid]
msgid = property(_get_msgid, _set_msgid) msgid = property(_get_msgid, _set_msgid)
def _get_msgstr(self): def _get_msgstr(self):
return "".join(self.msgstr_lines) return "".join(self.msgstr_lines)
def _set_msgstr(self, msgstr): def _set_msgstr(self, msgstr):
self.msgstr_lines = [msgstr] self.msgstr_lines = [msgstr]
msgstr = property(_get_msgstr, _set_msgstr) msgstr = property(_get_msgstr, _set_msgstr)
@@ -250,12 +258,15 @@ class I18nMessage:
lstrip2 = len(self.settings.PO_COMMENT_PREFIX_SOURCE_CUSTOM) lstrip2 = len(self.settings.PO_COMMENT_PREFIX_SOURCE_CUSTOM)
return ([l[lstrip1:] for l in self.comment_lines if l.startswith(self.settings.PO_COMMENT_PREFIX_SOURCE)] + return ([l[lstrip1:] for l in self.comment_lines if l.startswith(self.settings.PO_COMMENT_PREFIX_SOURCE)] +
[l[lstrip2:] for l in self.comment_lines [l[lstrip2:] for l in self.comment_lines
if l.startswith(self.settings.PO_COMMENT_PREFIX_SOURCE_CUSTOM)]) if l.startswith(self.settings.PO_COMMENT_PREFIX_SOURCE_CUSTOM)])
def _set_sources(self, sources): def _set_sources(self, sources):
cmmlines = self.comment_lines.copy() cmmlines = self.comment_lines.copy()
for l in cmmlines: for l in cmmlines:
if (l.startswith(self.settings.PO_COMMENT_PREFIX_SOURCE) or if (
l.startswith(self.settings.PO_COMMENT_PREFIX_SOURCE_CUSTOM)): l.startswith(self.settings.PO_COMMENT_PREFIX_SOURCE) or
l.startswith(self.settings.PO_COMMENT_PREFIX_SOURCE_CUSTOM)
):
self.comment_lines.remove(l) self.comment_lines.remove(l)
lines_src = [] lines_src = []
lines_src_custom = [] lines_src_custom = []
@@ -791,7 +802,7 @@ class I18nMessages:
if len(k) > 1 and src_rna in src_to_msg: if len(k) > 1 and src_rna in src_to_msg:
k &= src_to_msg[src_rna] k &= src_to_msg[src_rna]
msgmap["rna_tip"]["key"] = k msgmap["rna_tip"]["key"] = k
#print(k) # print(k)
btip = getattr(msgs, msgmap["but_tip"]["msgstr"]) btip = getattr(msgs, msgmap["but_tip"]["msgstr"])
#print("button tip: " + btip) #print("button tip: " + btip)
if btip and btip not in {rtip, etip}: if btip and btip not in {rtip, etip}:
@@ -1051,12 +1062,13 @@ class I18nMessages:
import subprocess import subprocess
with tempfile.NamedTemporaryFile(mode='w+', encoding="utf-8") as tmp_po_f: with tempfile.NamedTemporaryFile(mode='w+', encoding="utf-8") as tmp_po_f:
self.write_messages_to_po(tmp_po_f) self.write_messages_to_po(tmp_po_f)
cmd = (self.settings.GETTEXT_MSGFMT_EXECUTABLE, cmd = (
"--statistics", # show stats self.settings.GETTEXT_MSGFMT_EXECUTABLE,
tmp_po_f.name, "--statistics", # show stats
"-o", tmp_po_f.name,
fname, "-o",
) fname,
)
print("Running ", " ".join(cmd)) print("Running ", " ".join(cmd))
ret = subprocess.call(cmd) ret = subprocess.call(cmd)
print("Finished.") print("Finished.")
@@ -1081,6 +1093,7 @@ class I18nMessages:
EOT = b"0x04" # Used to concatenate context and msgid EOT = b"0x04" # Used to concatenate context and msgid
_msgid_offset = 0 _msgid_offset = 0
_msgstr_offset = 0 _msgstr_offset = 0
def _gen(v): def _gen(v):
nonlocal _msgid_offset, _msgstr_offset nonlocal _msgid_offset, _msgstr_offset
msgid = v.msgid.encode("utf-8") msgid = v.msgid.encode("utf-8")
@@ -1188,6 +1201,7 @@ class I18n:
def _py_file_get(self): def _py_file_get(self):
return self.src.get(self.settings.PARSER_PY_ID) return self.src.get(self.settings.PARSER_PY_ID)
def _py_file_set(self, value): def _py_file_set(self, value):
self.src[self.settings.PARSER_PY_ID] = value self.src[self.settings.PARSER_PY_ID] = value
py_file = property(_py_file_get, _py_file_set) py_file = property(_py_file_get, _py_file_set)
@@ -1252,7 +1266,8 @@ class I18n:
_ctx_txt = "s are" _ctx_txt = "s are"
else: else:
_ctx_txt = " is" _ctx_txt = " is"
lines = (("", lines = ((
"",
"Average stats for all {} translations:\n".format(self.nbr_trans), "Average stats for all {} translations:\n".format(self.nbr_trans),
" {:>6.1%} done!\n".format(self.lvl / self.nbr_trans), " {:>6.1%} done!\n".format(self.lvl / self.nbr_trans),
" {:>6.1%} of messages are tooltips.\n".format(self.lvl_ttips / self.nbr_trans), " {:>6.1%} of messages are tooltips.\n".format(self.lvl_ttips / self.nbr_trans),
@@ -1350,10 +1365,10 @@ class I18n:
comment_lines = [self.settings.PO_COMMENT_PREFIX + c for c in user_comments] + common_comment_lines comment_lines = [self.settings.PO_COMMENT_PREFIX + c for c in user_comments] + common_comment_lines
self.trans[uid].msgs[key] = I18nMessage(ctxt, [key[1]], [msgstr], comment_lines, False, is_fuzzy, self.trans[uid].msgs[key] = I18nMessage(ctxt, [key[1]], [msgstr], comment_lines, False, is_fuzzy,
settings=self.settings) settings=self.settings)
#key = self.settings.PO_HEADER_KEY # key = self.settings.PO_HEADER_KEY
#for uid, trans in self.trans.items(): # for uid, trans in self.trans.items():
#if key not in trans.msgs: # if key not in trans.msgs:
#trans.msgs[key] # trans.msgs[key]
self.unescape() self.unescape()
def write(self, kind, langs=set()): def write(self, kind, langs=set()):

View File

@@ -101,7 +101,7 @@ def write_subimage(sub_x, sub_y, sub_w, sub_h,
sub_w, sub_h, sub_w, sub_h,
sub_x, sub_y, sub_x, sub_y,
# redundant but including to maintain consistency # redundant but including to maintain consistency
pixel_w, pixel_h, pixel_w, pixel_h,
)) ))
for y in range(sub_h): for y in range(sub_h):

View File

@@ -1,22 +1,22 @@
# ***** BEGIN GPL LICENSE BLOCK ***** # ***** BEGIN GPL LICENSE BLOCK *****
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation, # along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# #
# Contributor(s): Campbell Barton # ***** END GPL LICENSE BLOCK *****
#
# #**** END GPL LICENSE BLOCK #**** # <pep8 compliant>
defs = """ defs = """
SPACE_EMPTY, SPACE_EMPTY,