Проверки и исправления¶
Пользовательские автоматические исправления¶
You can also implement your own automatic fixup in addition to the standard ones and
include them in AUTOFIX_LIST
.
The automatic fixes are powerful, but can also cause damage; be careful when writing one.
For example, the following automatic fixup would replace every occurrence of the string
foo
in a translation with bar
:
#
# Copyright © 2012 - 2020 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
from django.utils.translation import gettext_lazy as _
from weblate.trans.autofixes.base import AutoFix
class ReplaceFooWithBar(AutoFix):
"""Replace foo with bar."""
name = _("Foobar")
def fix_single_target(self, target, source, unit):
if "foo" in target:
return target.replace("foo", "bar"), True
return target, False
To install custom checks, provide a fully-qualified path to the Python class
in the AUTOFIX_LIST
, see Custom quality checks, addons and auto-fixes.
Настройка поведения¶
You can fine-tune the behavior of Weblate (mostly checks) for each source string (in source strings review, see Additional info on source strings) or in the Конфигурация компонента (Флаги перевода). Some file formats also allow to specify flags directly in the format (see Поддерживаемые форматы файлов).
The flags are comma-separated, the parameters are separated with colon. You can use quotes to include whitespace or special chars in the string. For example:
placeholders:"special:value":"other value", regex:.*
Вот список принимаемых в настоящее время флагов:
rst-text
Treat a text as an RST document, affects Перевод без изменения.
md-text
Treat text as a Markdown document.
dos-eol
Uses DOS end-of-line markers instead of Unix ones (
\r\n
instead of\n
).url
The string should consist of only a URL.
safe-html
The string should be HTML safe, see Небезопасный HTML-код.
read-only
The string is read-only and should not be edited in Weblate, see Строки только для чтения.
priority:N
Priority of the string. Higher priority strings are presented first for translation. The default priority is 100, the higher priority a string has, the earlier it is offered for translation.
max-length:N
Limit the maximal length for a string to N characters, see Максимальная длина перевода
xml-text
Treat text as XML document, affects Синтаксис XML and XML-разметка.
font-family:NAME
Define font-family for rendering checks, see Управление шрифтами.
font-weight:WEIGHT
Define font-weight for rendering checks, see Управление шрифтами.
font-size:SIZE
Define font-size for rendering checks, see Управление шрифтами.
font-spacing:SPACING
Define font-spacing for rendering checks, see Управление шрифтами.
placeholders:NAME
Placeholder strings expected in translation, see Символы-заполнители.
replacements:FROM:TO:FROM2:TO2...`
Replacements to perform when checking resulting text parameters (for example in Максимальный размер перевода or Максимальная длина перевода). The typical use case for this is to expand placeables to ensure that the text fits even with long names, for example:
replacements:%s:"John Doe"
.regex:REGEX
Регулярное выражение для сопоставления с переводом, смотрите раздел Регулярное выражение.
python-format
,c-format
,php-format
,python-brace-format
,javascript-format
,c-sharp-format
,java-format
,java-messageformat
,auto-java-messageformat
,qt-format
,qt-plural-format
,ruby-format
Treats all strings like format strings, affects Форматированные строки, Форматированные строки, Форматированные строки, Форматированные строки, Форматированные строки, Форматированные строки, Форматированные строки, Форматированные строки, Форматированные строки, Форматированные строки, Форматированные строки, Перевод без изменения.
strict-same
Make «Unchanged translation» avoid using built-in words blacklist, see Перевод без изменения.
ignore-bbcode
Skip the «BBcode markup» quality check.
ignore-duplicate
Пропускает проверку качества «Повторяющиеся слова».
ignore-double-space
Пропускает проверку качества «Двойной пробел».
ignore-angularjs-format
Пропускает проверку качества «Интерполяционная строка AngularJS».
ignore-c-format
Skip the «C format» quality check.
ignore-c-sharp-format
Skip the «C# format» quality check.
ignore-es-format
Пропускает проверку качества «Шаблонные литералы ECMAScript».
ignore-i18next-interpolation
Skip the «i18next interpolation» quality check.
ignore-java-format
Skip the «Java format» quality check.
ignore-java-messageformat
Skip the «Java MessageFormat» quality check.
ignore-javascript-format
Skip the «JavaScript format» quality check.
ignore-percent-placeholders
Skip the «Percent placeholders» quality check.
ignore-perl-format
Skip the «Perl format» quality check.
ignore-php-format
Skip the «PHP format» quality check.
ignore-python-brace-format
Skip the «Python brace format» quality check.
ignore-python-format
Skip the «Python format» quality check.
ignore-qt-format
Skip the «Qt format» quality check.
ignore-qt-plural-format
Skip the «Qt plural format» quality check.
ignore-ruby-format
Skip the «Ruby format» quality check.
ignore-translated
Пропускает проверку качества «Уже переведено».
ignore-inconsistent
Пропускает проверку качества «Противоречия».
ignore-kashida
Пропускает проверку качества «Используется кашида».
ignore-md-link
Пропускает проверку качества «Ссылки Markdown».
ignore-md-reflink
Пропускает проверку качества «Сноски Markdown».
ignore-md-syntax
Пропускает проверку качества «Синтаксис Markdown».
ignore-max-length
Пропускает проверку качества «Максимальная длина перевода».
ignore-max-size
Пропускает проверку качества «Максимальный размер перевода».
ignore-escaped-newline
Пропускает проверку качества «Несовпадающие n».
ignore-end-colon
Пропускает проверку качества «Несовпадающие двоеточия».
ignore-end-ellipsis
Пропускает проверку качества «Несовпадающие многоточия».
ignore-end-exclamation
Пропускает проверку качества «Несовпадающие восклицательные знаки».
ignore-end-stop
Пропускает проверку качества «Несовпадающие точки».
ignore-end-question
Пропускает проверку качества «Несовпадающие вопросительные знаки».
ignore-end-semicolon
Пропускает проверку качества «Несовпадающие точки с запятой».
ignore-newline-count
Skip the «Mismatching line breaks» quality check.
ignore-plurals
Пропускает проверку качества «Нет форм множественного числа».
ignore-placeholders
Skip the «Placeholders» quality check.
ignore-punctuation-spacing
Skip the «Punctuation spacing» quality check.
ignore-regex
Skip the «Regular expression» quality check.
ignore-same-plurals
Пропускает проверку качества «Одинаковые формы множественного числа».
ignore-begin-newline
Skip the «Starting newline» quality check.
ignore-begin-space
Skip the «Starting spaces» quality check.
ignore-end-newline
Skip the «Trailing newline» quality check.
ignore-end-space
Skip the «Trailing space» quality check.
ignore-same
Skip the «Unchanged translation» quality check.
ignore-safe-html
Skip the «Unsafe HTML» quality check.
ignore-url
Skip the «URL» quality check.
ignore-xml-tags
Skip the «XML markup» quality check.
ignore-xml-invalid
Skip the «XML syntax» quality check.
ignore-zero-width-space
Skip the «Zero-width space» quality check.
ignore-ellipsis
Skip the «Ellipsis» quality check.
ignore-long-untranslated
Skip the «Long untranslated» quality check.
ignore-multiple-failures
Skip the «Multiple failing checks» quality check.
ignore-unnamed-format
Skip the «Multiple unnamed variables» quality check.
ignore-optional-plural
Skip the «Unpluralised» quality check.
Примечание
Generally the rule is named ignore-*
for any check, using its
identifier, so you can use this even for your custom checks.
These flags are understood both in Конфигурация компонента settings, per source string settings and in the translation file itself (for example in GNU gettext).
Enforcing checks¶
Добавлено в версии 3.11.
You can configure a list of checks which can not be ignored by setting Enforced checks in Конфигурация компонента. Each listed check can not be ignored in the user interface and any string failing this check is marked as Needs editing (see Состояния перевода).
Управление шрифтами¶
Добавлено в версии 3.7.
The Максимальный размер перевода check used to calculate dimensions of the rendered text needs font info to be selected, which can be done in the Weblate font management tool in Fonts under the Manage menu of your translation project.
TrueType or OpenType fonts can be uploaded, set up font-groups and use those in the check.
The font-groups allow you to define different fonts for different languages, which is typically needed for non-latin languages:
The font-groups are identified by name, which can not contain whitespace or special characters, so that it can be easily used in the check definition:
Font-family and style is automatically recognized after uploading them:
You can have a number of fonts loaded into Weblate:
To use the fonts for checking the string length, pass it the appropriate flags (see Настройка поведения). You will probably need the following ones:
max-size:500
Defines maximal width.
font-family:ubuntu
Defines font group to use by specifying its identifier.
font-size:22
Defines font size.
Writing own checks¶
A wide range of quality checks are built-in, (see Проверки качества), though
they might not cover everything you want to check. The list of performed checks
can be adjusted using CHECK_LIST
, and you can also add custom checks.
Subclass the weblate.checks.Check
Set a few attributes.
Implement either the
check
(if you want to deal with plurals in your code) or thecheck_single
method (which does it for you).
Some examples:
To install custom checks, provide a fully-qualified path to the Python class
in the CHECK_LIST
, see Custom quality checks, addons and auto-fixes.
Checking translation text does not contain «foo»¶
This is a pretty simple check which just checks whether the translation is missing the string «foo».
#
# Copyright © 2012 - 2020 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
"""Simple quality check example."""
from django.utils.translation import gettext_lazy as _
from weblate.checks.base import TargetCheck
class FooCheck(TargetCheck):
# Used as identifier for check, should be unique
# Has to be shorter than 50 characters
check_id = "foo"
# Short name used to display failing check
name = _("Foo check")
# Description for failing check
description = _("Your translation is foo")
# Real check code
def check_single(self, source, target, unit):
return "foo" in target
Checking that Czech translation text plurals differ¶
Check using language info to verify the two plural forms in Czech language are not same.
#
# Copyright © 2012 - 2020 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
"""Quality check example for Czech plurals."""
from django.utils.translation import gettext_lazy as _
from weblate.checks.base import TargetCheck
class PluralCzechCheck(TargetCheck):
# Used as identifier for check, should be unique
# Has to be shorter than 50 characters
check_id = "foo"
# Short name used to display failing check
name = _("Foo check")
# Description for failing check
description = _("Your translation is foo")
# Real check code
def check_target_unit(self, sources, targets, unit):
if self.is_language(unit, ("cs",)):
return targets[1] == targets[2]
return False
def check_single(self, source, target, unit):
"""We don't check target strings here."""
return False