Просмотр исходного кода

Fixes #23778: Extract generated panel labels

Extend makemessages to extract labels derived from panel attribute names,
making them available for translation without explicit label declarations.
Preserve existing label overrides and source references.
Martin Hauser 1 день назад
Родитель
Сommit
4c41d3c7ed

+ 6 - 0
.github/workflows/ci.yml

@@ -151,6 +151,12 @@ jobs:
             echo "PSYCOPG_IMPL=binary" >> "$GITHUB_ENV"
           fi
 
+      # The makemessages extraction test runs GNU gettext
+      - name: Install GNU gettext
+        run: |
+          sudo apt-get update
+          sudo apt-get install -y gettext
+
       - name: Install dependencies
         run: |
           python -m pip install --upgrade pip

+ 2 - 0
docs/development/translations.md

@@ -14,6 +14,8 @@ To update the English `.po` file from which all translations are derived, use th
 ./manage.py makemessages -l en -i "project-static/*"
 ```
 
+NetBox also extracts labels derived from attribute names in installed apps' `ui/panels.py` modules and in `netbox/ui/panels.py`.
+
 Then, commit the change and push to the `main` branch on GitHub. Any new strings will appear for translation on Transifex automatically.
 
 !!! note

+ 87 - 0
netbox/core/management/commands/makemessages.py

@@ -0,0 +1,87 @@
+import ast
+from functools import cached_property
+from importlib import import_module
+from inspect import getsourcefile
+from pathlib import Path
+
+from django.apps import apps
+from django.core.management.commands.makemessages import BuildFile
+from django.core.management.commands.makemessages import Command as _Command
+from django.utils.translation import override
+
+from netbox.ui.panels import ObjectAttributesPanel
+
+
+class PanelBuildFile(BuildFile):
+    """Expose derived panel labels to gettext without changing the source files."""
+
+    @cached_property
+    def panel_labels(self):
+        if self.domain != 'django':
+            return {}
+        module_name = self.command.panel_modules.get(Path(self.path).resolve())
+        if module_name is None:
+            return {}
+
+        labels = {}
+        # The msgid must not depend on the active language
+        with override(None):
+            module = import_module(module_name)
+            for node in ast.parse(self.source, filename=self.path).body:
+                if not isinstance(node, ast.ClassDef):
+                    continue
+                panel = getattr(module, node.name, None)
+                if not isinstance(panel, type) or not issubclass(panel, ObjectAttributesPanel):
+                    continue
+
+                for statement in node.body:
+                    if isinstance(statement, ast.Assign):
+                        targets = statement.targets
+                    elif isinstance(statement, ast.AnnAssign):
+                        targets = [statement.target]
+                    else:
+                        continue
+                    for target in targets:
+                        if not isinstance(target, ast.Name):
+                            continue
+                        attr = panel._attrs.get(target.id)
+                        if attr is not None and not attr.label:
+                            label = str(panel._name_to_label(target.id))
+                            labels.setdefault(statement.lineno, []).append(label)
+        return labels
+
+    @cached_property
+    def source(self):
+        return Path(self.path).read_text(encoding='utf-8')
+
+    @cached_property
+    def is_templatized(self):
+        # Routes extraction through a work copy, never the source file
+        return super().is_templatized or bool(self.panel_labels)
+
+    def preprocess(self):
+        if not self.panel_labels:
+            super().preprocess()
+            return
+
+        lines = self.source.split('\n')
+        for lineno, labels in self.panel_labels.items():
+            line = lines[lineno - 1]
+            indent = line[:len(line) - len(line.lstrip())]
+            calls = ''.join(f'gettext_noop({label!r}); ' for label in labels)
+            # Keep line numbers intact for gettext's source references
+            lines[lineno - 1] = indent + calls + line.lstrip()
+        Path(self.work_path).write_text('\n'.join(lines), encoding='utf-8')
+
+
+class Command(_Command):
+    build_file_class = PanelBuildFile
+
+    @cached_property
+    def panel_modules(self):
+        modules = {
+            (Path(app.path) / 'ui' / 'panels.py').resolve(): f'{app.name}.ui.panels'
+            for app in apps.get_app_configs()
+        }
+        modules[Path(getsourcefile(ObjectAttributesPanel)).resolve()] = ObjectAttributesPanel.__module__
+        return modules

+ 170 - 3
netbox/core/tests/test_management_commands.py

@@ -1,16 +1,183 @@
+import ast
 import os
+import shutil
+import sys
 import tempfile
+from contextlib import chdir
 from io import StringIO
-from types import SimpleNamespace
+from itertools import chain
+from pathlib import Path
+from textwrap import dedent
+from types import ModuleType, SimpleNamespace
+from unittest import skipUnless
 from unittest.mock import MagicMock, patch
 
 from django.core.management import call_command
 from django.core.management.base import CommandError
-from django.test import TestCase, override_settings
+from django.core.management.commands.makemessages import TranslatableFile
+from django.test import SimpleTestCase, TestCase, override_settings
+from django.utils.translation import get_language, gettext, override
 
 from core.choices import DataSourceStatusChoices
-from core.management.commands import nbshell, upgrade
+from core.management.commands import makemessages, nbshell, upgrade
 from core.management.commands.rqworker import DEFAULT_QUEUES
+from dcim.ui import panels as dcim_panels
+from netbox.ui import panels as netbox_panels
+from users.ui import panels as users_panels
+
+
+class MakeMessagesTestCase(SimpleTestCase):
+    def setUp(self):
+        directory = tempfile.TemporaryDirectory()
+        self.addCleanup(directory.cleanup)
+        self.root = Path(directory.name)
+        self.panel_modules = {}
+        self.command = makemessages.Command()
+        self.command.panel_modules = self.panel_modules
+
+    def _panel_source(self, relative_path, source):
+        path = self.root / relative_path
+        path.parent.mkdir(parents=True, exist_ok=True)
+        source = (
+            'from django.utils.translation import gettext_lazy as _\n'
+            'from netbox.ui import attrs, panels\n' + dedent(source)
+        )
+        path.write_text(source, encoding='utf-8')
+        module = ModuleType(f'makemessages_test_{len(self.panel_modules)}')
+        sys.modules[module.__name__] = module
+        self.addCleanup(sys.modules.pop, module.__name__)
+        exec(compile(source, str(path), 'exec'), module.__dict__)
+        self.panel_modules[path.resolve()] = module.__name__
+        return path
+
+    def _build_file(self, path, domain='django'):
+        translatable = TranslatableFile(str(path.parent), path.name, str(self.root / 'locale'))
+        build_file = makemessages.PanelBuildFile(self.command, domain, translatable)
+        self.addCleanup(build_file.cleanup)
+        return build_file
+
+    def _generated_labels(self, build_file):
+        build_file.preprocess()
+        tree = ast.parse(Path(build_file.work_path).read_text(encoding='utf-8'))
+        return [
+            node.args[0].value for node in ast.walk(tree)
+            if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == 'gettext_noop'
+        ]
+
+    def test_declaration_names_and_source_locations(self):
+        # A form feed ends a line for str.splitlines() only
+        path = self._panel_source('app/ui/panels.py', '''
+            def make_attribute():
+                return attrs.TextAttr('cached_weight')
+
+            class BasePanel(panels.ObjectAttributesPanel):
+                name = attrs.TextAttr('name')
+            \x0c
+            class ChildPanel(BasePanel):
+                parent_device = attrs.TextAttr(
+                    'parent_bay',
+                )
+                total_weight = make_attribute()
+                front_image: object = attrs.TextAttr('device_type.front_image')
+                shipping_address = physical_address = attrs.TextAttr('address')
+        ''')
+        original = path.read_text(encoding='utf-8')
+        build_file = self._build_file(path)
+
+        self.assertCountEqual(self._generated_labels(build_file), [
+            'Name', 'Parent device', 'Total weight', 'Front image', 'Shipping address', 'Physical address',
+        ])
+        generated = Path(build_file.work_path).read_text(encoding='utf-8')
+        self.assertEqual(generated.count('\n'), original.count('\n'))
+        self.assertEqual(path.read_text(encoding='utf-8'), original)
+        build_file.cleanup()
+        self.assertFalse(Path(build_file.work_path).exists())
+
+    def test_explicit_and_attribute_class_labels(self):
+        path = self._panel_source('app/ui/panels.py', '''
+            class LabeledAttr(attrs.TextAttr):
+                label = _('Custom default')
+
+            class ExamplePanel(panels.ObjectAttributesPanel):
+                explicit_label = attrs.TextAttr('value', label=_('Explicit label'))
+                positional_label = attrs.TextAttr('value', _('Positional label'))
+                class_label = LabeledAttr('value')
+                class_label_none = LabeledAttr('value', label=None)
+                class_label_empty = LabeledAttr('value', label='')
+                color_alias = attrs.ColorAttr('value')
+                coordinates_alias = attrs.GPSCoordinatesAttr()
+                none_label = attrs.TextAttr('value', label=None)
+                empty_label = attrs.TextAttr('value', label='')
+        ''')
+
+        self.assertCountEqual(
+            self._generated_labels(self._build_file(path)),
+            ['Class label empty', 'None label', 'Empty label'],
+        )
+
+    def test_extraction_uses_source_language(self):
+        path = self._panel_source('app/ui/panels.py', '''
+            class ExamplePanel(panels.ObjectAttributesPanel):
+                name = attrs.TextAttr('name')
+        ''')
+
+        with override('nl'):
+            self.assertNotEqual(gettext('Name'), 'Name')
+            self.assertEqual(self._generated_labels(self._build_file(path)), ['Name'])
+            self.assertEqual(get_language(), 'nl')
+
+    def test_non_panel_classes_and_javascript_are_skipped(self):
+        path = self._panel_source('app/ui/panels.py', '''
+            class Unrelated:
+                name = attrs.TextAttr('name')
+
+            class ExamplePanel(panels.ObjectAttributesPanel):
+                total_weight = attrs.TextAttr('total_weight')
+        ''')
+
+        self.assertEqual(self._generated_labels(self._build_file(path)), ['Total weight'])
+        build_file = self._build_file(path, 'djangojs')
+        self.assertEqual(self._generated_labels(build_file), [])
+        self.assertEqual(build_file.work_path, str(path))
+
+    def test_installed_app_panel_labels(self):
+        command = makemessages.Command()
+        self.assertEqual(command.panel_modules[Path(netbox_panels.__file__).resolve()], 'netbox.ui.panels')
+        labels = []
+        for module in (dcim_panels, users_panels):
+            path = Path(module.__file__)
+            translatable = TranslatableFile(str(path.parent), path.name, '')
+            build_file = makemessages.PanelBuildFile(command, 'django', translatable)
+            labels.extend(chain.from_iterable(build_file.panel_labels.values()))
+        for label in ('Total weight', 'Parent device', 'Pepper id'):
+            self.assertIn(label, labels)
+
+    @skipUnless(shutil.which('xgettext'), 'GNU gettext is not installed')
+    def test_command_extracts_derived_labels(self):
+        path = self._panel_source('app/ui/panels.py', '''
+            class ExamplePanel(panels.ObjectAttributesPanel):
+                total_weight = attrs.TextAttr('cached_weight')
+                explicit_label = attrs.TextAttr('value', label=_('Explicit label'))
+        ''')
+        original = path.read_text(encoding='utf-8')
+        (self.root / 'template.html').write_text('{% load i18n %}{% translate "Template message" %}', encoding='utf-8')
+        locale = self.root / 'translations'
+        locale.mkdir()
+
+        with (
+            chdir(self.root),
+            override_settings(LOCALE_PATHS=[str(locale)]),
+            patch.object(makemessages.Command, 'panel_modules', self.panel_modules),
+        ):
+            call_command('makemessages', locale=['en'], verbosity=0)
+
+        messages = (locale / 'en' / 'LC_MESSAGES' / 'django.po').read_text(encoding='utf-8')
+        for label in ('Total weight', 'Explicit label', 'Template message'):
+            self.assertIn(f'msgid "{label}"', messages)
+        lineno = next(i for i, line in enumerate(original.splitlines(), 1) if 'total_weight =' in line)
+        self.assertIn(f'#: app/ui/panels.py:{lineno}', messages)
+        self.assertEqual(path.read_text(encoding='utf-8'), original)
+        self.assertEqual(list(self.root.rglob('*.py.py')), [])
 
 
 class MakeMigrationsTestCase(TestCase):