Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2875,6 +2875,11 @@ Translations

Creating a unit in the approved state requires permission to review strings.

Adding a unit with a target to the source language of a bilingual
component stores the target in all translations and requires permission
to add strings in each of them. Approved targets also require review
permission in each translation.

.. seealso::

* :ref:`component-manage_units`
Expand Down
1 change: 1 addition & 0 deletions docs/changes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ Weblate 2026.12
* Disabled repository-controlled reStructuredText parser imports during Sphinx extraction and checks.
* Kept the repository locked while the :ref:`addon-weblate.generate.generate` add-on writes files during installation.
* Escaped template syntax in notification settings help built from project and component names.
* Required per-language add and review permissions when :http:post:`adding a translated source string </api/translations/(string:project)/(string:component)/(string:language)/units/>`; source glossary terms now leave other languages untranslated.

* Warn before and after restoring a :ref:`project backup <projectbackup>` when a public-only billing plan makes the project public.

Expand Down
40 changes: 40 additions & 0 deletions weblate/api/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -19818,6 +19818,46 @@ def test_add_bilingual_source(self) -> None:
{"Source3", ""},
)

def test_add_bilingual_source_target_permissions(self) -> None:
self.component.manage_units = True
self.component.save(update_fields=["manage_units"])
self.grant_perm_to_user("unit.add", project=self.project)
WorkflowSetting.objects.create(
project=self.project,
language=Language.objects.get(code="cs"),
restrict_direct_editing=True,
)
self.user.clear_permissions_cache()
source_kwargs = {**self.translation_kwargs, "language__code": "en"}

response = self.do_request(
"api:translation-units",
source_kwargs,
method="post",
request={"source": ["Restricted"], "target": ["Target"]},
format="json",
code=400,
)
self.assertIn("Czech", str(response.data))
self.assertFalse(Unit.objects.filter(source="Restricted").exists())

self.do_request(
"api:translation-units",
source_kwargs,
method="post",
request={"source": ["Untranslated"], "target": [""]},
format="json",
code=200,
)
self.assertEqual(
set(
Unit.objects.filter(source="Untranslated").values_list(
"target", flat=True
)
),
{"Untranslated", ""},
)

def test_add_plural(self) -> None:
# Add to bilingual
self.component.manage_units = True
Expand Down
2 changes: 1 addition & 1 deletion weblate/glossary/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,6 @@ def clean(self) -> None:
def as_kwargs(self) -> NewUnitParams:
result = super().as_kwargs()
if self.cleaned_data["translation"].is_source:
result["target"] = result["source"]
result["target"] = None
result["skip_existing"] = bool(self.cleaned_data.get("terminology"))
return result
11 changes: 11 additions & 0 deletions weblate/glossary/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -1013,6 +1013,17 @@ def test_add(self) -> None:
# Should be added to the source and translation only
self.assertEqual(Unit.objects.count(), start + 2)

def test_add_translation_does_not_translate_other_languages(self) -> None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The source-language fanout case is no longer tested. The removed test covered adding a term via en without terminology, and nothing replaces it. Add a test that calls make_manager() and then do_add_unit(language="en"), asserting that only the source unit and no other language units are created.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At weblate/glossary/tests.py, line 1016:

<comment>The source-language fanout case is no longer tested. The removed test covered adding a term via `en` without `terminology`, and nothing replaces it. Add a test that calls `make_manager()` and then `do_add_unit(language="en")`, asserting that only the source unit and no other language units are created.</comment>

<file context>
@@ -1013,19 +1013,15 @@ class GlossaryTest(ReusableViewTestCase):
 
-    def test_add_source_does_not_translate_other_languages(self) -> None:
-        self.do_add_unit(language="en")
+    def test_add_translation_does_not_translate_other_languages(self) -> None:
+        self.do_add_unit(language="cs")
         units = Unit.objects.filter(
</file context>

self.do_add_unit(language="cs")
units = Unit.objects.filter(
translation__component=self.glossary_component, source="source"
)
self.assertEqual(units.count(), 2)
self.assertEqual(
set(units.values_list("translation__language__code", "target")),
{("en", "source"), ("cs", "překlad")},
)

def test_add_existing(self) -> None:
"""Test for adding term from translate page while there is existing one."""
glossary = self.glossary_component.translation_set.get(
Expand Down
26 changes: 26 additions & 0 deletions weblate/trans/models/translation.py
Original file line number Diff line number Diff line change
Expand Up @@ -882,7 +882,7 @@
continue
with start_span(
op="unit.update_from_unit",
name=f"{self.full_slug}:{newunit.unit_attributes['pos']}",

Check failure on line 885 in weblate/trans/models/translation.py

View workflow job for this annotation

GitHub Actions / mypy

Value of type "UnitAttributesDict | None" is not indexable
):
newunit.update_from_unit(
user=user,
Expand Down Expand Up @@ -1289,7 +1289,7 @@
# Include intermediate language as it might add new strings
filenames.append(filename)

return filenames

Check failure on line 1292 in weblate/trans/models/translation.py

View workflow job for this annotation

GitHub Actions / mypy

Incompatible return value type (got "list[str | None]", expected "list[str]")

def get_git_blob_hash(self) -> str:
"""Return current VCS blob hash for file."""
Expand Down Expand Up @@ -1544,7 +1544,7 @@
@staticmethod
def clear_committed_disk_states(units_to_clear_disk_state: set[int]) -> None:
"""Clear disk states for units that no longer have pending changes."""
units_with_remaining_changes = set()

Check failure on line 1547 in weblate/trans/models/translation.py

View workflow job for this annotation

GitHub Actions / mypy

Need type annotation for "units_with_remaining_changes" (hint: "units_with_remaining_changes: set[<type>] = ...")
for unit_ids in batched(units_to_clear_disk_state, 1000):
units_with_remaining_changes.update(
PendingUnitChange.objects.filter(unit_id__in=unit_ids).values_list(
Expand Down Expand Up @@ -1822,7 +1822,7 @@
if not self.filename:
return []
if self.component.file_format_cls.simple_filename:
return [self.get_filename()]

Check failure on line 1825 in weblate/trans/models/translation.py

View workflow job for this annotation

GitHub Actions / mypy

List item 0 has incompatible type "str | None"; expected "str"
return [
self.component.check_file_is_valid(filename)
for filename in self.store.get_filenames()
Expand Down Expand Up @@ -2776,14 +2776,14 @@

try:
# Prepare msgmerge args based on add-ons (if configured)
args = self.component.file_format_cls.get_msgmerge_args(component)

Check failure on line 2779 in weblate/trans/models/translation.py

View workflow job for this annotation

GitHub Actions / mypy

"type[TranslationFormat[Any, Any, Any]]" has no attribute "get_msgmerge_args"
repo_temp_dir = component.repository.get_repo_temp_dir()
# Update translation files
for translation in component.translation_set.exclude(
language=component.source_language
):
filename = translation.get_filename()
component.file_format_cls.update_bilingual(

Check failure on line 2786 in weblate/trans/models/translation.py

View workflow job for this annotation

GitHub Actions / mypy

"type[TranslationFormat[Any, Any, Any]]" has no attribute "update_bilingual"
filename,
temp.name,
args=args,
Expand Down Expand Up @@ -2866,8 +2866,8 @@
) from error
# Actually replace file content
self.component.file_format_cls.save_atomic(
self.get_filename(),

Check failure on line 2869 in weblate/trans/models/translation.py

View workflow job for this annotation

GitHub Actions / mypy

Argument 1 to "save_atomic" of "TranslationFormat" has incompatible type "str | None"; expected "str"
lambda handle: handle.write(filecopy),

Check failure on line 2870 in weblate/trans/models/translation.py

View workflow job for this annotation

GitHub Actions / mypy

Argument 2 to "save_atomic" of "TranslationFormat" has incompatible type "Callable[[IO[bytes]], int]"; expected "Callable[[IO[bytes]], None]"
repo_temp_dir=self.component.repository.get_repo_temp_dir(),
)

Expand Down Expand Up @@ -3109,12 +3109,12 @@

if method == "replace":
result = self.handle_replace(
request, author, fileobj, ignore_language=ignore_language

Check failure on line 3112 in weblate/trans/models/translation.py

View workflow job for this annotation

GitHub Actions / mypy

Argument 2 to "handle_replace" of "Translation" has incompatible type "User | None"; expected "User"
)

elif method == "source":
result = self.handle_source(
request, author, fileobj, ignore_language=ignore_language

Check failure on line 3117 in weblate/trans/models/translation.py

View workflow job for this annotation

GitHub Actions / mypy

Argument 2 to "handle_source" of "Translation" has incompatible type "User | None"; expected "User"
)
else:
store = self.load_uploaded_file(
Expand Down Expand Up @@ -3487,6 +3487,32 @@
"language"
),
)
if (
request is not None
and (any(target) if isinstance(target, list) else target)
and not (component.is_glossary and "read-only" in parsed_flags)
):
# A source-language target is copied into every translation.
for translation in translations[1:]:
for permission in (
("unit.add",)
if state != STATE_APPROVED
else ("unit.add", "unit.review")
):
if not (allowed := user.has_perm(permission, translation)):
raise ValidationError(
gettext(
"Could not add the translation to %(language)s: %(reason)s"
)
% {
"language": translation.language,
"reason": getattr(
allowed,
"reason",
gettext("Permission denied."),
),
}
)
elif component.is_glossary and "terminology" in parsed_flags:
add_terminology = True
translations = (
Expand Down
Loading