feat(i18n): translate UI and import messages to English with German catalogue
English is now the source language for the dashboard, forms, menu, JavaScript progress texts and all import/export messages; a complete German catalogue ships as package data. Tenant-error detection also accepts the error code and the active-language message of netbox_utilities, and no longer imports netbox_utilities when it is installed but not enabled. A test keeps the README NetBox range in sync with min_version/max_version. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
409b239fca
commit
72e04fe086
21 files changed
+713
-156
No files matched your search
@@ -219,12 +219,27 @@ conflict strategy **Abort import** still aborts on existing objects.
|
|||||||
- Encrypted credentials of NetBox-VM-Import are only usable with an identical
|
- Encrypted credentials of NetBox-VM-Import are only usable with an identical
|
||||||
Django `SECRET_KEY`; otherwise set the password again on the target.
|
Django `SECRET_KEY`; otherwise set the password again on the target.
|
||||||
|
|
||||||
|
### Language
|
||||||
|
|
||||||
|
The plugin is available in English (source) and German. Switch the display
|
||||||
|
language as usual in the user profile (**Preferences → Language**); import
|
||||||
|
reports and error messages follow it. Translations live in
|
||||||
|
`netbox_export/locale/de/LC_MESSAGES/`.
|
||||||
|
|
||||||
## Development and tests
|
## Development and tests
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python -m pytest
|
python -m pytest
|
||||||
```
|
```
|
||||||
|
|
||||||
|
After changing user-visible strings, update and compile the German catalogue:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd netbox_export
|
||||||
|
django-admin makemessages -l de --no-location
|
||||||
|
msgfmt -o locale/de/LC_MESSAGES/django.mo locale/de/LC_MESSAGES/django.po
|
||||||
|
```
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
Apache License 2.0 — see [LICENSE](LICENSE).
|
Apache License 2.0 — see [LICENSE](LICENSE).
|
||||||
+26
-25
@@ -1,26 +1,27 @@
|
|||||||
from dcim.models import Location, Region, Site
|
from dcim.models import Location, Region, Site
|
||||||
from django import forms
|
from django import forms
|
||||||
|
from django.utils.translation import gettext_lazy as _
|
||||||
from tenancy.models import Tenant, TenantGroup
|
from tenancy.models import Tenant, TenantGroup
|
||||||
|
|
||||||
|
|
||||||
class ExportForm(forms.Form):
|
class ExportForm(forms.Form):
|
||||||
scope_type = forms.ChoiceField(
|
scope_type = forms.ChoiceField(
|
||||||
label="Exportbereich",
|
label=_("Export scope"),
|
||||||
choices=(
|
choices=(
|
||||||
("tenant_group", "Mandantengruppe"),
|
("tenant_group", _("Tenant group")),
|
||||||
("tenant", "Mandant"),
|
("tenant", _("Tenant")),
|
||||||
("region", "Region"),
|
("region", _("Region")),
|
||||||
("site", "Standort"),
|
("site", _("Site")),
|
||||||
("location", "Lokation"),
|
("location", _("Location")),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
tenant_group = forms.ModelChoiceField(
|
tenant_group = forms.ModelChoiceField(
|
||||||
label="Mandantengruppe", queryset=TenantGroup.objects.all(), required=False
|
label=_("Tenant group"), queryset=TenantGroup.objects.all(), required=False
|
||||||
)
|
)
|
||||||
tenant = forms.ModelChoiceField(label="Mandant", queryset=Tenant.objects.all(), required=False)
|
tenant = forms.ModelChoiceField(label=_("Tenant"), queryset=Tenant.objects.all(), required=False)
|
||||||
region = forms.ModelChoiceField(label="Region", queryset=Region.objects.all(), required=False)
|
region = forms.ModelChoiceField(label=_("Region"), queryset=Region.objects.all(), required=False)
|
||||||
site = forms.ModelChoiceField(label="Standort", queryset=Site.objects.all(), required=False)
|
site = forms.ModelChoiceField(label=_("Site"), queryset=Site.objects.all(), required=False)
|
||||||
location = forms.ModelChoiceField(label="Lokation", queryset=Location.objects.all(), required=False)
|
location = forms.ModelChoiceField(label=_("Location"), queryset=Location.objects.all(), required=False)
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
super().__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
@@ -32,47 +33,47 @@ class ExportForm(forms.Form):
|
|||||||
scope_type = cleaned.get("scope_type")
|
scope_type = cleaned.get("scope_type")
|
||||||
selected = cleaned.get(scope_type) if scope_type else None
|
selected = cleaned.get(scope_type) if scope_type else None
|
||||||
if scope_type and selected is None:
|
if scope_type and selected is None:
|
||||||
self.add_error(scope_type, "Bitte ein Objekt für den Exportbereich auswählen.")
|
self.add_error(scope_type, _("Select an object for the export scope."))
|
||||||
cleaned["scope_object"] = selected
|
cleaned["scope_object"] = selected
|
||||||
return cleaned
|
return cleaned
|
||||||
|
|
||||||
|
|
||||||
class ImportForm(forms.Form):
|
class ImportForm(forms.Form):
|
||||||
archive = forms.FileField(
|
archive = forms.FileField(
|
||||||
label="NetBox-Export-Archiv",
|
label=_("NetBox-Export archive"),
|
||||||
widget=forms.ClearableFileInput(attrs={"accept": ".zip,application/zip"}),
|
widget=forms.ClearableFileInput(attrs={"accept": ".zip,application/zip"}),
|
||||||
)
|
)
|
||||||
conflict_strategy = forms.ChoiceField(
|
conflict_strategy = forms.ChoiceField(
|
||||||
label="Vorhandene Objekte",
|
label=_("Existing objects"),
|
||||||
choices=(
|
choices=(
|
||||||
("update", "Aktualisieren"),
|
("update", _("Update")),
|
||||||
("skip", "Überspringen"),
|
("skip", _("Skip")),
|
||||||
("fail", "Import abbrechen"),
|
("fail", _("Abort import")),
|
||||||
),
|
),
|
||||||
initial="update",
|
initial="update",
|
||||||
)
|
)
|
||||||
dry_run = forms.BooleanField(
|
dry_run = forms.BooleanField(
|
||||||
label="Nur prüfen (keine Änderungen)",
|
label=_("Check only (no changes)"),
|
||||||
required=False,
|
required=False,
|
||||||
initial=True,
|
initial=True,
|
||||||
help_text="Führt den vollständigen Import aus und setzt die Datenbanktransaktion anschließend zurück.",
|
help_text=_("Runs the complete import and then rolls back the database transaction."),
|
||||||
)
|
)
|
||||||
force = forms.BooleanField(
|
force = forms.BooleanField(
|
||||||
label="Force-Modus (Fehler überspringen)",
|
label=_("Force mode (skip errors)"),
|
||||||
required=False,
|
required=False,
|
||||||
initial=False,
|
initial=False,
|
||||||
help_text=(
|
help_text=_(
|
||||||
"Objekte, deren Import fehlschlägt, werden einzeln übersprungen, statt den gesamten Import "
|
"Objects that fail to import are skipped individually instead of rolling back the whole import. "
|
||||||
"zurückzurollen. Übersprungene Objekte werden im Bericht als Warnung aufgeführt."
|
"Skipped objects are listed as warnings in the report."
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
confirm_apply = forms.BooleanField(
|
confirm_apply = forms.BooleanField(
|
||||||
label="Ich bestätige den schreibenden Import",
|
label=_("I confirm the writing import"),
|
||||||
required=False,
|
required=False,
|
||||||
)
|
)
|
||||||
|
|
||||||
def clean(self):
|
def clean(self):
|
||||||
cleaned = super().clean()
|
cleaned = super().clean()
|
||||||
if not cleaned.get("dry_run") and not cleaned.get("confirm_apply"):
|
if not cleaned.get("dry_run") and not cleaned.get("confirm_apply"):
|
||||||
self.add_error("confirm_apply", "Für einen schreibenden Import ist die Bestätigung erforderlich.")
|
self.add_error("confirm_apply", _("Confirmation is required for a writing import."))
|
||||||
return cleaned
|
return cleaned
|
||||||
Binary file not shown.
@@ -0,0 +1,428 @@
|
|||||||
|
msgid ""
|
||||||
|
msgstr ""
|
||||||
|
"Project-Id-Version: netbox-export\n"
|
||||||
|
"Report-Msgid-Bugs-To: \n"
|
||||||
|
"POT-Creation-Date: 2026-10-26 21:17+0100\n"
|
||||||
|
"PO-Revision-Date: 2026-10-26 21:20+0100\n"
|
||||||
|
"Language-Team: German\n"
|
||||||
|
"Language: de\n"
|
||||||
|
"MIME-Version: 1.0\n"
|
||||||
|
"Content-Type: text/plain; charset=UTF-8\n"
|
||||||
|
"Content-Transfer-Encoding: 8bit\n"
|
||||||
|
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
|
||||||
|
|
||||||
|
msgid "Export scope"
|
||||||
|
msgstr "Exportbereich"
|
||||||
|
|
||||||
|
msgid "Tenant group"
|
||||||
|
msgstr "Mandantengruppe"
|
||||||
|
|
||||||
|
msgid "Tenant"
|
||||||
|
msgstr "Mandant"
|
||||||
|
|
||||||
|
msgid "Region"
|
||||||
|
msgstr "Region"
|
||||||
|
|
||||||
|
msgid "Site"
|
||||||
|
msgstr "Standort"
|
||||||
|
|
||||||
|
msgid "Location"
|
||||||
|
msgstr "Lokation"
|
||||||
|
|
||||||
|
msgid "Select an object for the export scope."
|
||||||
|
msgstr "Bitte ein Objekt für den Exportbereich auswählen."
|
||||||
|
|
||||||
|
msgid "NetBox-Export archive"
|
||||||
|
msgstr "NetBox-Export-Archiv"
|
||||||
|
|
||||||
|
msgid "Existing objects"
|
||||||
|
msgstr "Vorhandene Objekte"
|
||||||
|
|
||||||
|
msgid "Update"
|
||||||
|
msgstr "Aktualisieren"
|
||||||
|
|
||||||
|
msgid "Skip"
|
||||||
|
msgstr "Überspringen"
|
||||||
|
|
||||||
|
msgid "Abort import"
|
||||||
|
msgstr "Import abbrechen"
|
||||||
|
|
||||||
|
msgid "Check only (no changes)"
|
||||||
|
msgstr "Nur prüfen (keine Änderungen)"
|
||||||
|
|
||||||
|
msgid "Runs the complete import and then rolls back the database transaction."
|
||||||
|
msgstr ""
|
||||||
|
"Führt den vollständigen Import aus und setzt die Datenbanktransaktion "
|
||||||
|
"anschließend zurück."
|
||||||
|
|
||||||
|
msgid "Force mode (skip errors)"
|
||||||
|
msgstr "Force-Modus (Fehler überspringen)"
|
||||||
|
|
||||||
|
msgid ""
|
||||||
|
"Objects that fail to import are skipped individually instead of rolling back "
|
||||||
|
"the whole import. Skipped objects are listed as warnings in the report."
|
||||||
|
msgstr ""
|
||||||
|
"Objekte, deren Import fehlschlägt, werden einzeln übersprungen, statt den "
|
||||||
|
"gesamten Import zurückzurollen. Übersprungene Objekte werden im Bericht als "
|
||||||
|
"Warnung aufgeführt."
|
||||||
|
|
||||||
|
msgid "I confirm the writing import"
|
||||||
|
msgstr "Ich bestätige den schreibenden Import"
|
||||||
|
|
||||||
|
msgid "Confirmation is required for a writing import."
|
||||||
|
msgstr "Für einen schreibenden Import ist die Bestätigung erforderlich."
|
||||||
|
|
||||||
|
msgid "Export / Import"
|
||||||
|
msgstr "Export / Import"
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid "Duplicate file path in archive: %(path)s"
|
||||||
|
msgstr "Doppelter Dateipfad im Archiv: %(path)s"
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid "Unsafe file path in archive: %(path)s"
|
||||||
|
msgstr "Unsicherer Dateipfad im Archiv: %(path)s"
|
||||||
|
|
||||||
|
msgid "The archive exceeds the configured maximum size."
|
||||||
|
msgstr "Das Archiv überschreitet die konfigurierte Maximalgröße."
|
||||||
|
|
||||||
|
msgid "The uploaded file is not a valid ZIP archive."
|
||||||
|
msgstr "Die hochgeladene Datei ist kein gültiges ZIP-Archiv."
|
||||||
|
|
||||||
|
msgid "The archive contains too many files."
|
||||||
|
msgstr "Das Archiv enthält zu viele Dateien."
|
||||||
|
|
||||||
|
msgid "manifest.json or objects.ndjson is missing from the archive."
|
||||||
|
msgstr "manifest.json oder objects.ndjson fehlt im Archiv."
|
||||||
|
|
||||||
|
msgid "The extracted archive content is too large."
|
||||||
|
msgstr "Der entpackte Archivinhalt ist zu groß."
|
||||||
|
|
||||||
|
msgid "The archive has an impermissible compression ratio."
|
||||||
|
msgstr "Das Archiv weist ein unzulässiges Kompressionsverhältnis auf."
|
||||||
|
|
||||||
|
msgid "The archive metadata is invalid."
|
||||||
|
msgstr "Die Metadaten im Archiv sind ungültig."
|
||||||
|
|
||||||
|
msgid "The archive format or its version is not supported."
|
||||||
|
msgstr "Das Archivformat oder dessen Version wird nicht unterstützt."
|
||||||
|
|
||||||
|
msgid "The object file does not match its checksum."
|
||||||
|
msgstr "Die Objektdatei stimmt nicht mit ihrer Prüfsumme überein."
|
||||||
|
|
||||||
|
msgid "The archive signature is invalid or missing."
|
||||||
|
msgstr "Die Archivsignatur ist ungültig oder fehlt."
|
||||||
|
|
||||||
|
msgid ""
|
||||||
|
"The archive is signed but was not verified because no key is configured."
|
||||||
|
msgstr ""
|
||||||
|
"Das Archiv ist signiert, aber ohne konfigurierten Schlüssel nicht "
|
||||||
|
"verifiziert."
|
||||||
|
|
||||||
|
msgid "The archive is not signed."
|
||||||
|
msgstr "Das Archiv ist nicht signiert."
|
||||||
|
|
||||||
|
msgid "The archive contains too many objects."
|
||||||
|
msgstr "Das Archiv enthält zu viele Objekte."
|
||||||
|
|
||||||
|
msgid "objects.ndjson contains invalid JSON."
|
||||||
|
msgstr "objects.ndjson enthält ungültiges JSON."
|
||||||
|
|
||||||
|
msgid "The file list does not match the manifest."
|
||||||
|
msgstr "Die Dateiliste stimmt nicht mit dem Manifest überein."
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid "The checksum of file %(name)s is invalid."
|
||||||
|
msgstr "Die Prüfsumme der Datei %(name)s ist ungültig."
|
||||||
|
|
||||||
|
msgid "The object count does not match the manifest."
|
||||||
|
msgstr "Die Objektanzahl stimmt nicht mit dem Manifest überein."
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid ""
|
||||||
|
"The export would contain more than %(max)s objects. Narrow the scope or "
|
||||||
|
"increase max_objects."
|
||||||
|
msgstr ""
|
||||||
|
"Der Export würde mehr als %(max)s Objekte enthalten. Bitte den Bereich "
|
||||||
|
"verkleinern oder max_objects erhöhen."
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid "The model %(model)s is not installed on the target instance."
|
||||||
|
msgstr "Das Modell %(model)s ist auf der Zielinstanz nicht installiert."
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid ""
|
||||||
|
"Stored mapping for %(record)s was corrected from target ID %(old)s to target "
|
||||||
|
"ID %(new)s because the natural key %(key)s already exists."
|
||||||
|
msgstr ""
|
||||||
|
"Gespeicherte Zuordnung für %(record)s wurde von Ziel-ID %(old)s auf Ziel-ID "
|
||||||
|
"%(new)s korrigiert, da der Fachschlüssel %(key)s bereits existiert."
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid "Rack reference for %(record)s could not be resolved."
|
||||||
|
msgstr "Rack-Referenz für %(record)s konnte nicht aufgelöst werden."
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid "Rack position for %(record)s was omitted because no rack is assigned."
|
||||||
|
msgstr ""
|
||||||
|
"Rackplatz für %(record)s wurde ausgelassen, da kein Rack zugeordnet ist."
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid ""
|
||||||
|
"Rack position conflict for %(record)s: %(target)s is occupied by target "
|
||||||
|
"device(s) %(occupants)s."
|
||||||
|
msgstr ""
|
||||||
|
"Rackplatzkonflikt für %(record)s: %(target)s ist durch Zielgerät(e) "
|
||||||
|
"%(occupants)s belegt."
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid ""
|
||||||
|
"Rack position for %(record)s was skipped: %(target)s remains occupied by "
|
||||||
|
"target device(s) %(occupants)s. The imported device was saved without a rack "
|
||||||
|
"position."
|
||||||
|
msgstr ""
|
||||||
|
"Rackplatz für %(record)s wurde übersprungen: %(target)s bleibt durch "
|
||||||
|
"Zielgerät(e) %(occupants)s belegt. Das importierte Gerät wurde ohne Position"
|
||||||
|
" im Rack gespeichert."
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid ""
|
||||||
|
"Rack position conflict for %(record)s resolved: target device(s) "
|
||||||
|
"%(occupants)s were removed from %(target)s and left without a rack position."
|
||||||
|
msgstr ""
|
||||||
|
"Rackplatzkonflikt für %(record)s gelöst: Zielgerät(e) %(occupants)s wurden "
|
||||||
|
"aus %(target)s gelöst und ohne Position im Rack belassen."
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid ""
|
||||||
|
"Port mapping(s) %(ids)s were replaced by %(record)s so the front/rear port "
|
||||||
|
"cabling matches the source."
|
||||||
|
msgstr ""
|
||||||
|
"Portzuordnung(en) %(ids)s wurden durch %(record)s ersetzt, damit die "
|
||||||
|
"Front-/Rear-Port-Verkabelung der Quelle entspricht."
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid "The image exceeds the safe import limit of %(max)s pixels."
|
||||||
|
msgstr "Das Bild überschreitet die sichere Importgrenze von %(max)s Pixeln."
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid ""
|
||||||
|
"The image with %(pixels)s pixels exceeds the safe import limit of %(max)s "
|
||||||
|
"pixels."
|
||||||
|
msgstr ""
|
||||||
|
"Das Bild mit %(pixels)s Pixeln überschreitet die sichere Importgrenze von "
|
||||||
|
"%(max)s Pixeln."
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid "Image for %(record)s was downscaled from %(old)s to %(new)s pixels."
|
||||||
|
msgstr "Bild für %(record)s wurde von %(old)s auf %(new)s Pixel verkleinert."
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid "M2M reference for %(record)s could not be resolved."
|
||||||
|
msgstr "M2M-Referenz für %(record)s konnte nicht aufgelöst werden."
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid "Force mode: %(label)s was skipped because of an error: %(error)s"
|
||||||
|
msgstr ""
|
||||||
|
"Force-Modus: %(label)s wurde wegen eines Fehlers übersprungen: %(error)s"
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid ""
|
||||||
|
"Objects of type %(model)s were skipped because the related optional plugin "
|
||||||
|
"is not installed on the target instance."
|
||||||
|
msgstr ""
|
||||||
|
"Objekte vom Typ %(model)s wurden übersprungen, da das zugehörige optionale "
|
||||||
|
"Plugin auf der Zielinstanz nicht installiert ist."
|
||||||
|
|
||||||
|
msgid "Unknown conflict strategy."
|
||||||
|
msgstr "Unbekannte Konfliktstrategie."
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid ""
|
||||||
|
"NetBox versions are not compatible: source %(source)s, target %(target)s."
|
||||||
|
msgstr ""
|
||||||
|
"NetBox-Versionen sind nicht kompatibel: Quelle %(source)s, Ziel %(target)s."
|
||||||
|
|
||||||
|
msgid "The source instance ID is missing or invalid."
|
||||||
|
msgstr "Die Quellinstanz-Kennung fehlt oder ist ungültig."
|
||||||
|
|
||||||
|
msgid "An object record is incomplete."
|
||||||
|
msgstr "Ein Objektdatensatz ist unvollständig."
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid "Duplicate object ID in archive: %(record)s"
|
||||||
|
msgstr "Doppelte Objekt-ID im Archiv: %(record)s"
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid "Target object already exists: %(record)s"
|
||||||
|
msgstr "Zielobjekt existiert bereits: %(record)s"
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid ""
|
||||||
|
"Force mode: %(count)s object(s) with unresolvable references were skipped: "
|
||||||
|
"%(blocked)s"
|
||||||
|
msgstr ""
|
||||||
|
"Force-Modus: %(count)s Objekt(e) mit nicht auflösbaren Referenzen wurden "
|
||||||
|
"übersprungen: %(blocked)s"
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid "Required references could not be resolved: %(blocked)s"
|
||||||
|
msgstr "Erforderliche Referenzen konnten nicht aufgelöst werden: %(blocked)s"
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid "Reference %(name)s for %(record)s could not be resolved."
|
||||||
|
msgstr "Referenz %(name)s für %(record)s konnte nicht aufgelöst werden."
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid "Reference %(name)s for %(record)s"
|
||||||
|
msgstr "Referenz %(name)s für %(record)s"
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid "Generic reference %(name)s for %(record)s is missing."
|
||||||
|
msgstr "Generische Referenz %(name)s für %(record)s fehlt."
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid "Generic reference %(name)s for %(record)s"
|
||||||
|
msgstr "Generische Referenz %(name)s für %(record)s"
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid "Custom field reference %(name)s for %(record)s is missing."
|
||||||
|
msgstr "Custom-Field-Referenz %(name)s für %(record)s fehlt."
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid "Custom field value %(name)s for %(record)s"
|
||||||
|
msgstr "Custom-Field-Wert %(name)s für %(record)s"
|
||||||
|
|
||||||
|
msgid "Rack placement of devices"
|
||||||
|
msgstr "Rackplatzierung der Geräte"
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid "Many-to-many assignments for %(record)s"
|
||||||
|
msgstr "Mehrfachzuordnungen für %(record)s"
|
||||||
|
|
||||||
|
msgid "Recalculation of cable paths"
|
||||||
|
msgstr "Neuberechnung der Kabelpfade"
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid "The import was rolled back: %(error)s"
|
||||||
|
msgstr "Der Import wurde zurückgerollt: %(error)s"
|
||||||
|
|
||||||
|
msgid ""
|
||||||
|
"The tenant \"Auto-Import\" was used automatically as a fallback tenant for "
|
||||||
|
"the dry run; it is not created or changed permanently."
|
||||||
|
msgstr ""
|
||||||
|
"Für den Prüflauf wurde der Mandant \"Auto-Import\" automatisch als "
|
||||||
|
"Ersatzmandant verwendet; er wird nicht dauerhaft angelegt oder geändert."
|
||||||
|
|
||||||
|
msgid ""
|
||||||
|
"The tenant \"Auto-Import\" was created automatically and assigned to objects "
|
||||||
|
"without a resolvable tenant."
|
||||||
|
msgstr ""
|
||||||
|
"Der Mandant \"Auto-Import\" wurde automatisch erstellt und Objekten ohne "
|
||||||
|
"auflösbaren Mandanten zugewiesen."
|
||||||
|
|
||||||
|
msgid ""
|
||||||
|
"The existing tenant \"Auto-Import\" was selected automatically for objects "
|
||||||
|
"without a resolvable tenant."
|
||||||
|
msgstr ""
|
||||||
|
"Der vorhandene Mandant \"Auto-Import\" wurde automatisch für Objekte ohne "
|
||||||
|
"auflösbaren Mandanten ausgewählt."
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid ""
|
||||||
|
"Unique reference %(field)s was released from target object(s) %(ids)s and "
|
||||||
|
"reassigned to the imported object."
|
||||||
|
msgstr ""
|
||||||
|
"Eindeutige Referenz %(field)s wurde von Zielobjekt(en) %(ids)s gelöst und "
|
||||||
|
"dem importierten Objekt neu zugeordnet."
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid ""
|
||||||
|
"%(record)s (%(model)s) was skipped because of a missing required reference: "
|
||||||
|
"%(fields)s."
|
||||||
|
msgstr ""
|
||||||
|
"%(record)s (%(model)s) wurde wegen fehlender Pflichtreferenz übersprungen: "
|
||||||
|
"%(fields)s."
|
||||||
|
|
||||||
|
msgid "not found"
|
||||||
|
msgstr "nicht gefunden"
|
||||||
|
|
||||||
|
msgid "not unique"
|
||||||
|
msgstr "nicht eindeutig"
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid "External reference omitted: %(model)s with %(lookup)s (%(reason)s)."
|
||||||
|
msgstr "Externe Referenz ausgelassen: %(model)s mit %(lookup)s (%(reason)s)."
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid "References to the skipped object %(record)s were omitted."
|
||||||
|
msgstr "Referenzen auf das übersprungene Objekt %(record)s wurden ausgelassen."
|
||||||
|
|
||||||
|
msgid "An object reference in the archive is invalid."
|
||||||
|
msgstr "Eine Objektreferenz im Archiv ist ungültig."
|
||||||
|
|
||||||
|
msgid "Dry run successful"
|
||||||
|
msgstr "Prüflauf erfolgreich"
|
||||||
|
|
||||||
|
msgid "Import completed"
|
||||||
|
msgstr "Import abgeschlossen"
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid "%(created)s created, %(updated)s updated, %(skipped)s skipped."
|
||||||
|
msgstr ""
|
||||||
|
"%(created)s erstellt, %(updated)s aktualisiert, %(skipped)s übersprungen."
|
||||||
|
|
||||||
|
#, python-format
|
||||||
|
msgid "Source: %(label)s (%(count)s objects)."
|
||||||
|
msgstr "Quelle: %(label)s (%(count)s Objekte)."
|
||||||
|
|
||||||
|
msgid "Model"
|
||||||
|
msgstr "Modell"
|
||||||
|
|
||||||
|
msgid "Created"
|
||||||
|
msgstr "Erstellt"
|
||||||
|
|
||||||
|
msgid "Updated"
|
||||||
|
msgstr "Aktualisiert"
|
||||||
|
|
||||||
|
msgid "Skipped"
|
||||||
|
msgstr "Übersprungen"
|
||||||
|
|
||||||
|
msgid "Export"
|
||||||
|
msgstr "Export"
|
||||||
|
|
||||||
|
msgid "Preparing export ..."
|
||||||
|
msgstr "Export wird vorbereitet ..."
|
||||||
|
|
||||||
|
msgid "Export progress"
|
||||||
|
msgstr "Exportfortschritt"
|
||||||
|
|
||||||
|
msgid "Export ZIP"
|
||||||
|
msgstr "ZIP exportieren"
|
||||||
|
|
||||||
|
msgid "Import"
|
||||||
|
msgstr "Import"
|
||||||
|
|
||||||
|
msgid "Uploading archive ..."
|
||||||
|
msgstr "Archiv wird hochgeladen ..."
|
||||||
|
|
||||||
|
msgid "Import progress"
|
||||||
|
msgstr "Importfortschritt"
|
||||||
|
|
||||||
|
msgid "Process archive"
|
||||||
|
msgstr "Archiv verarbeiten"
|
||||||
|
|
||||||
|
msgid "Transferring ZIP ..."
|
||||||
|
msgstr "ZIP wird übertragen ..."
|
||||||
|
|
||||||
|
msgid "Export completed"
|
||||||
|
msgstr "Export abgeschlossen"
|
||||||
|
|
||||||
|
msgid "Export failed"
|
||||||
|
msgstr "Export fehlgeschlagen"
|
||||||
|
|
||||||
|
msgid "Checking and processing archive ..."
|
||||||
|
msgstr "Archiv wird geprüft und verarbeitet ..."
|
||||||
|
|
||||||
|
msgid "Import failed"
|
||||||
|
msgstr "Import fehlgeschlagen"
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
|
from django.utils.translation import gettext_lazy as _
|
||||||
from netbox.plugins import PluginMenuItem
|
from netbox.plugins import PluginMenuItem
|
||||||
|
|
||||||
menu_items = (
|
menu_items = (
|
||||||
PluginMenuItem(
|
PluginMenuItem(
|
||||||
link="plugins:netbox_export:dashboard",
|
link="plugins:netbox_export:dashboard",
|
||||||
link_text="Export / Import",
|
link_text=_("Export / Import"),
|
||||||
staff_only=True,
|
staff_only=True,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ from pathlib import PurePosixPath
|
|||||||
from typing import BinaryIO
|
from typing import BinaryIO
|
||||||
|
|
||||||
from django.core.serializers.json import DjangoJSONEncoder
|
from django.core.serializers.json import DjangoJSONEncoder
|
||||||
|
from django.utils.translation import gettext as _
|
||||||
|
|
||||||
from .exceptions import ArchiveValidationError
|
from .exceptions import ArchiveValidationError
|
||||||
|
|
||||||
@@ -54,7 +55,7 @@ def build_archive(manifest: dict, records: Iterable[dict], assets: dict[str, byt
|
|||||||
for path, content in assets.items():
|
for path, content in assets.items():
|
||||||
safe_path = _safe_member_name(path)
|
safe_path = _safe_member_name(path)
|
||||||
if safe_path in normalized_assets:
|
if safe_path in normalized_assets:
|
||||||
raise ArchiveValidationError(f"Doppelter Dateipfad im Archiv: {safe_path}")
|
raise ArchiveValidationError(_("Duplicate file path in archive: %(path)s") % {"path": safe_path})
|
||||||
normalized_assets[safe_path] = content
|
normalized_assets[safe_path] = content
|
||||||
assets = normalized_assets
|
assets = normalized_assets
|
||||||
object_data = b"\n".join(_json_bytes(record) for record in records) + b"\n"
|
object_data = b"\n".join(_json_bytes(record) for record in records) + b"\n"
|
||||||
@@ -94,7 +95,7 @@ def build_archive(manifest: dict, records: Iterable[dict], assets: dict[str, byt
|
|||||||
def _safe_member_name(name: str) -> str:
|
def _safe_member_name(name: str) -> str:
|
||||||
normalized = posixpath.normpath(name.replace("\\", "/"))
|
normalized = posixpath.normpath(name.replace("\\", "/"))
|
||||||
if normalized.startswith(("../", "/")) or normalized in ("", ".", ".."):
|
if normalized.startswith(("../", "/")) or normalized in ("", ".", ".."):
|
||||||
raise ArchiveValidationError(f"Unsicherer Dateipfad im Archiv: {name}")
|
raise ArchiveValidationError(_("Unsafe file path in archive: %(path)s") % {"path": name})
|
||||||
return normalized
|
return normalized
|
||||||
|
|
||||||
|
|
||||||
@@ -118,52 +119,52 @@ def read_archive(
|
|||||||
else:
|
else:
|
||||||
raw = source.read(max_size + 1)
|
raw = source.read(max_size + 1)
|
||||||
if len(raw) > max_size:
|
if len(raw) > max_size:
|
||||||
raise ArchiveValidationError("Das Archiv überschreitet die konfigurierte Maximalgröße.")
|
raise ArchiveValidationError(_("The archive exceeds the configured maximum size."))
|
||||||
|
|
||||||
try:
|
try:
|
||||||
archive = zipfile.ZipFile(io.BytesIO(raw))
|
archive = zipfile.ZipFile(io.BytesIO(raw))
|
||||||
except zipfile.BadZipFile as exc:
|
except zipfile.BadZipFile as exc:
|
||||||
raise ArchiveValidationError("Die hochgeladene Datei ist kein gültiges ZIP-Archiv.") from exc
|
raise ArchiveValidationError(_("The uploaded file is not a valid ZIP archive.")) from exc
|
||||||
|
|
||||||
with archive:
|
with archive:
|
||||||
names = {}
|
names = {}
|
||||||
for info in archive.infolist():
|
for info in archive.infolist():
|
||||||
name = _safe_member_name(info.filename)
|
name = _safe_member_name(info.filename)
|
||||||
if name in names:
|
if name in names:
|
||||||
raise ArchiveValidationError(f"Doppelter Dateipfad im Archiv: {name}")
|
raise ArchiveValidationError(_("Duplicate file path in archive: %(path)s") % {"path": name})
|
||||||
names[name] = info
|
names[name] = info
|
||||||
if len(names) > max_objects * 5 + 2:
|
if len(names) > max_objects * 5 + 2:
|
||||||
raise ArchiveValidationError("Das Archiv enthält zu viele Dateien.")
|
raise ArchiveValidationError(_("The archive contains too many files."))
|
||||||
if MANIFEST_NAME not in names or OBJECTS_NAME not in names:
|
if MANIFEST_NAME not in names or OBJECTS_NAME not in names:
|
||||||
raise ArchiveValidationError("manifest.json oder objects.ndjson fehlt im Archiv.")
|
raise ArchiveValidationError(_("manifest.json or objects.ndjson is missing from the archive."))
|
||||||
total_size = sum(info.file_size for info in names.values())
|
total_size = sum(info.file_size for info in names.values())
|
||||||
if total_size > max_size * 4:
|
if total_size > max_size * 4:
|
||||||
raise ArchiveValidationError("Der entpackte Archivinhalt ist zu groß.")
|
raise ArchiveValidationError(_("The extracted archive content is too large."))
|
||||||
if any(info.file_size > 0 and info.compress_size * 200 < info.file_size for info in names.values()):
|
if any(info.file_size > 0 and info.compress_size * 200 < info.file_size for info in names.values()):
|
||||||
raise ArchiveValidationError("Das Archiv weist ein unzulässiges Kompressionsverhältnis auf.")
|
raise ArchiveValidationError(_("The archive has an impermissible compression ratio."))
|
||||||
|
|
||||||
try:
|
try:
|
||||||
manifest = json.loads(archive.read(MANIFEST_NAME))
|
manifest = json.loads(archive.read(MANIFEST_NAME))
|
||||||
object_data = archive.read(OBJECTS_NAME)
|
object_data = archive.read(OBJECTS_NAME)
|
||||||
except (KeyError, ValueError, UnicodeDecodeError) as exc:
|
except (KeyError, ValueError, UnicodeDecodeError) as exc:
|
||||||
raise ArchiveValidationError("Die Metadaten im Archiv sind ungültig.") from exc
|
raise ArchiveValidationError(_("The archive metadata is invalid.")) from exc
|
||||||
|
|
||||||
if manifest.get("format") != FORMAT_NAME or manifest.get("format_version") != FORMAT_VERSION:
|
if manifest.get("format") != FORMAT_NAME or manifest.get("format_version") != FORMAT_VERSION:
|
||||||
raise ArchiveValidationError("Das Archivformat oder dessen Version wird nicht unterstützt.")
|
raise ArchiveValidationError(_("The archive format or its version is not supported."))
|
||||||
checksum = hashlib.sha256(object_data).hexdigest()
|
checksum = hashlib.sha256(object_data).hexdigest()
|
||||||
if not hmac.compare_digest(checksum, str(manifest.get("objects_sha256", ""))):
|
if not hmac.compare_digest(checksum, str(manifest.get("objects_sha256", ""))):
|
||||||
raise ArchiveValidationError("Die Objektdatei stimmt nicht mit ihrer Prüfsumme überein.")
|
raise ArchiveValidationError(_("The object file does not match its checksum."))
|
||||||
|
|
||||||
warnings = []
|
warnings = []
|
||||||
signature = manifest.get("signature")
|
signature = manifest.get("signature")
|
||||||
if signing_key:
|
if signing_key:
|
||||||
expected = _signature(manifest, signing_key)
|
expected = _signature(manifest, signing_key)
|
||||||
if not signature or not hmac.compare_digest(expected, signature):
|
if not signature or not hmac.compare_digest(expected, signature):
|
||||||
raise ArchiveValidationError("Die Archivsignatur ist ungültig oder fehlt.")
|
raise ArchiveValidationError(_("The archive signature is invalid or missing."))
|
||||||
elif signature:
|
elif signature:
|
||||||
warnings.append("Das Archiv ist signiert, aber ohne konfigurierten Schlüssel nicht verifiziert.")
|
warnings.append(_("The archive is signed but was not verified because no key is configured."))
|
||||||
else:
|
else:
|
||||||
warnings.append("Das Archiv ist nicht signiert.")
|
warnings.append(_("The archive is not signed."))
|
||||||
|
|
||||||
records = []
|
records = []
|
||||||
try:
|
try:
|
||||||
@@ -171,9 +172,9 @@ def read_archive(
|
|||||||
if line:
|
if line:
|
||||||
records.append(json.loads(line))
|
records.append(json.loads(line))
|
||||||
if len(records) > max_objects:
|
if len(records) > max_objects:
|
||||||
raise ArchiveValidationError("Das Archiv enthält zu viele Objekte.")
|
raise ArchiveValidationError(_("The archive contains too many objects."))
|
||||||
except (ValueError, UnicodeDecodeError) as exc:
|
except (ValueError, UnicodeDecodeError) as exc:
|
||||||
raise ArchiveValidationError("objects.ndjson enthält ungültiges JSON.") from exc
|
raise ArchiveValidationError(_("objects.ndjson contains invalid JSON.")) from exc
|
||||||
|
|
||||||
assets = {
|
assets = {
|
||||||
name: archive.read(name)
|
name: archive.read(name)
|
||||||
@@ -182,11 +183,11 @@ def read_archive(
|
|||||||
}
|
}
|
||||||
declared_assets = manifest.get("assets_sha256", {})
|
declared_assets = manifest.get("assets_sha256", {})
|
||||||
if set(declared_assets) != set(assets):
|
if set(declared_assets) != set(assets):
|
||||||
raise ArchiveValidationError("Die Dateiliste stimmt nicht mit dem Manifest überein.")
|
raise ArchiveValidationError(_("The file list does not match the manifest."))
|
||||||
for name, content in assets.items():
|
for name, content in assets.items():
|
||||||
actual = hashlib.sha256(content).hexdigest()
|
actual = hashlib.sha256(content).hexdigest()
|
||||||
if not hmac.compare_digest(actual, str(declared_assets.get(name, ""))):
|
if not hmac.compare_digest(actual, str(declared_assets.get(name, ""))):
|
||||||
raise ArchiveValidationError(f"Die Prüfsumme der Datei {name} ist ungültig.")
|
raise ArchiveValidationError(_("The checksum of file %(name)s is invalid.") % {"name": name})
|
||||||
if manifest.get("object_count") != len(records):
|
if manifest.get("object_count") != len(records):
|
||||||
raise ArchiveValidationError("Die Objektanzahl stimmt nicht mit dem Manifest überein.")
|
raise ArchiveValidationError(_("The object count does not match the manifest."))
|
||||||
return ParsedArchive(manifest=manifest, records=records, assets=assets, warnings=warnings)
|
return ParsedArchive(manifest=manifest, records=records, assets=assets, warnings=warnings)
|
||||||
@@ -6,6 +6,7 @@ from django.apps import apps
|
|||||||
from django.contrib.contenttypes.fields import GenericForeignKey
|
from django.contrib.contenttypes.fields import GenericForeignKey
|
||||||
from django.contrib.contenttypes.models import ContentType
|
from django.contrib.contenttypes.models import ContentType
|
||||||
from django.db import models
|
from django.db import models
|
||||||
|
from django.utils.translation import gettext as _
|
||||||
|
|
||||||
from .codec import object_key
|
from .codec import object_key
|
||||||
from .exceptions import GraphLimitError
|
from .exceptions import GraphLimitError
|
||||||
@@ -153,8 +154,10 @@ class ObjectGraph:
|
|||||||
object_count = len(self.members) + len(self.dependencies)
|
object_count = len(self.members) + len(self.dependencies)
|
||||||
if object_count > self.max_objects:
|
if object_count > self.max_objects:
|
||||||
raise GraphLimitError(
|
raise GraphLimitError(
|
||||||
f"Der Export würde mehr als {self.max_objects} Objekte enthalten. "
|
_(
|
||||||
"Bitte den Bereich verkleinern oder max_objects erhöhen."
|
"The export would contain more than %(max)s objects. "
|
||||||
|
"Narrow the scope or increase max_objects."
|
||||||
|
) % {"max": self.max_objects}
|
||||||
)
|
)
|
||||||
|
|
||||||
def add_member(self, obj) -> bool:
|
def add_member(self, obj) -> bool:
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ from django.contrib.contenttypes.models import ContentType
|
|||||||
from django.core.files.base import ContentFile
|
from django.core.files.base import ContentFile
|
||||||
from django.db import IntegrityError, models, transaction
|
from django.db import IntegrityError, models, transaction
|
||||||
from django.db.models import Value
|
from django.db.models import Value
|
||||||
|
from django.utils.translation import gettext as _
|
||||||
from PIL import Image as PillowImage
|
from PIL import Image as PillowImage
|
||||||
|
|
||||||
from netbox_export.models import ImportedObjectMapping
|
from netbox_export.models import ImportedObjectMapping
|
||||||
@@ -105,9 +106,9 @@ def _model_for(label: str):
|
|||||||
try:
|
try:
|
||||||
model = apps.get_model(label)
|
model = apps.get_model(label)
|
||||||
except (LookupError, ValueError) as exc:
|
except (LookupError, ValueError) as exc:
|
||||||
raise ArchiveValidationError(f"Das Modell {label} ist auf der Zielinstanz nicht installiert.") from exc
|
raise ArchiveValidationError(_("The model %(model)s is not installed on the target instance.") % {"model": label}) from exc
|
||||||
if model is None:
|
if model is None:
|
||||||
raise ArchiveValidationError(f"Das Modell {label} ist auf der Zielinstanz nicht installiert.")
|
raise ArchiveValidationError(_("The model %(model)s is not installed on the target instance.") % {"model": label})
|
||||||
return model
|
return model
|
||||||
|
|
||||||
|
|
||||||
@@ -313,8 +314,11 @@ def _find_existing(source_instance, model, record, resolver):
|
|||||||
if mapped is not None and mapped.pk != natural.pk:
|
if mapped is not None and mapped.pk != natural.pk:
|
||||||
resolver.warn(
|
resolver.warn(
|
||||||
("mapping-rebound", record["id"]),
|
("mapping-rebound", record["id"]),
|
||||||
f"Gespeicherte Zuordnung für {record['id']} wurde von Ziel-ID {mapped.pk} auf "
|
_(
|
||||||
f"Ziel-ID {natural.pk} korrigiert, da der Fachschlüssel {dict(lookup)} bereits existiert.",
|
"Stored mapping for %(record)s was corrected from target ID %(old)s to target ID %(new)s "
|
||||||
|
"because the natural key %(key)s already exists."
|
||||||
|
)
|
||||||
|
% {"record": record["id"], "old": mapped.pk, "new": natural.pk, "key": dict(lookup)},
|
||||||
)
|
)
|
||||||
return natural
|
return natural
|
||||||
|
|
||||||
@@ -418,7 +422,7 @@ def _apply_device_placements(
|
|||||||
for record_id, placement in placements:
|
for record_id, placement in placements:
|
||||||
rack, available = resolver.resolve(placement.rack_spec)
|
rack, available = resolver.resolve(placement.rack_spec)
|
||||||
if not available:
|
if not available:
|
||||||
raise ArchiveValidationError(f"Rack-Referenz für {record_id} konnte nicht aufgelöst werden.")
|
raise ArchiveValidationError(_("Rack reference for %(record)s could not be resolved.") % {"record": record_id})
|
||||||
if rack is MISSING_REFERENCE:
|
if rack is MISSING_REFERENCE:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
@@ -428,7 +432,7 @@ def _apply_device_placements(
|
|||||||
if rack is None and (position is not None or face is not None):
|
if rack is None and (position is not None or face is not None):
|
||||||
resolver.warn(
|
resolver.warn(
|
||||||
("device-placement-without-rack", record_id),
|
("device-placement-without-rack", record_id),
|
||||||
f"Rackplatz für {record_id} wurde ausgelassen, da kein Rack zugeordnet ist.",
|
_("Rack position for %(record)s was omitted because no rack is assigned.") % {"record": record_id},
|
||||||
)
|
)
|
||||||
position = None
|
position = None
|
||||||
face = None
|
face = None
|
||||||
@@ -445,14 +449,18 @@ def _apply_device_placements(
|
|||||||
occupants = _conflicting_devices(conflicts)
|
occupants = _conflicting_devices(conflicts)
|
||||||
if conflict_strategy == "fail":
|
if conflict_strategy == "fail":
|
||||||
raise ImportConflictError(
|
raise ImportConflictError(
|
||||||
f"Rackplatzkonflikt für {record_id}: {target} ist durch Zielgerät(e) {occupants} belegt."
|
_("Rack position conflict for %(record)s: %(target)s is occupied by target device(s) %(occupants)s.")
|
||||||
|
% {"record": record_id, "target": target, "occupants": occupants}
|
||||||
)
|
)
|
||||||
if conflict_strategy == "skip":
|
if conflict_strategy == "skip":
|
||||||
_save_device_placement(device, rack, None, None, compatibility)
|
_save_device_placement(device, rack, None, None, compatibility)
|
||||||
resolver.warn(
|
resolver.warn(
|
||||||
("device-placement-skipped", record_id),
|
("device-placement-skipped", record_id),
|
||||||
f"Rackplatz für {record_id} wurde übersprungen: {target} bleibt durch "
|
_(
|
||||||
f"Zielgerät(e) {occupants} belegt. Das importierte Gerät wurde ohne Position im Rack gespeichert.",
|
"Rack position for %(record)s was skipped: %(target)s remains occupied by target device(s) "
|
||||||
|
"%(occupants)s. The imported device was saved without a rack position."
|
||||||
|
)
|
||||||
|
% {"record": record_id, "target": target, "occupants": occupants},
|
||||||
)
|
)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
@@ -463,8 +471,11 @@ def _apply_device_placements(
|
|||||||
_save_device_placement(device, rack, position, face, compatibility)
|
_save_device_placement(device, rack, position, face, compatibility)
|
||||||
resolver.warn(
|
resolver.warn(
|
||||||
("device-placement-released", record_id),
|
("device-placement-released", record_id),
|
||||||
f"Rackplatzkonflikt für {record_id} gelöst: Zielgerät(e) {occupants} wurden aus {target} "
|
_(
|
||||||
"gelöst und ohne Position im Rack belassen.",
|
"Rack position conflict for %(record)s resolved: target device(s) %(occupants)s were removed "
|
||||||
|
"from %(target)s and left without a rack position."
|
||||||
|
)
|
||||||
|
% {"record": record_id, "occupants": occupants, "target": target},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -503,8 +514,10 @@ def _release_port_mapping_conflicts(obj, resolver, record_id):
|
|||||||
conflict.delete()
|
conflict.delete()
|
||||||
resolver.warn(
|
resolver.warn(
|
||||||
("port-mapping-replaced", record_id),
|
("port-mapping-replaced", record_id),
|
||||||
f"Portzuordnung(en) {conflict_ids} wurden durch {record_id} ersetzt, damit die "
|
_(
|
||||||
"Front-/Rear-Port-Verkabelung der Quelle entspricht.",
|
"Port mapping(s) %(ids)s were replaced by %(record)s so the front/rear port cabling matches the source."
|
||||||
|
)
|
||||||
|
% {"ids": conflict_ids, "record": record_id},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -640,8 +653,8 @@ def _open_image_with_bounded_override(data):
|
|||||||
except PillowImage.DecompressionBombError as exc:
|
except PillowImage.DecompressionBombError as exc:
|
||||||
stream.close()
|
stream.close()
|
||||||
raise ArchiveValidationError(
|
raise ArchiveValidationError(
|
||||||
"Das Bild überschreitet die sichere Importgrenze von "
|
_("The image exceeds the safe import limit of %(max)s pixels.")
|
||||||
f"{IMPORTED_IMAGE_SOURCE_MAX_PIXELS:,} Pixeln."
|
% {"max": f"{IMPORTED_IMAGE_SOURCE_MAX_PIXELS:,}"}
|
||||||
) from exc
|
) from exc
|
||||||
except Exception:
|
except Exception:
|
||||||
stream.close()
|
stream.close()
|
||||||
@@ -673,8 +686,8 @@ def _prepare_image_asset(data):
|
|||||||
source_pixels = width * height
|
source_pixels = width * height
|
||||||
if source_pixels > IMPORTED_IMAGE_SOURCE_MAX_PIXELS:
|
if source_pixels > IMPORTED_IMAGE_SOURCE_MAX_PIXELS:
|
||||||
raise ArchiveValidationError(
|
raise ArchiveValidationError(
|
||||||
f"Das Bild mit {source_pixels:,} Pixeln überschreitet die sichere Importgrenze von "
|
_("The image with %(pixels)s pixels exceeds the safe import limit of %(max)s pixels.")
|
||||||
f"{IMPORTED_IMAGE_SOURCE_MAX_PIXELS:,} Pixeln."
|
% {"pixels": f"{source_pixels:,}", "max": f"{IMPORTED_IMAGE_SOURCE_MAX_PIXELS:,}"}
|
||||||
)
|
)
|
||||||
if source_pixels <= NETBOX_IMAGE_MAX_PIXELS:
|
if source_pixels <= NETBOX_IMAGE_MAX_PIXELS:
|
||||||
return data, width, height, None
|
return data, width, height, None
|
||||||
@@ -714,8 +727,8 @@ def _set_files(obj, record, assets, saved_files, *, dry_run: bool, import_warnin
|
|||||||
old_width, old_height, new_width, new_height = resize_info
|
old_width, old_height, new_width, new_height = resize_info
|
||||||
record_id = record.get("id", obj._meta.label_lower)
|
record_id = record.get("id", obj._meta.label_lower)
|
||||||
import_warnings.append(
|
import_warnings.append(
|
||||||
f"Bild für {record_id} wurde von {old_width}×{old_height} auf "
|
_("Image for %(record)s was downscaled from %(old)s to %(new)s pixels.")
|
||||||
f"{new_width}×{new_height} Pixel verkleinert."
|
% {"record": record_id, "old": f"{old_width}×{old_height}", "new": f"{new_width}×{new_height}"}
|
||||||
)
|
)
|
||||||
if dry_run:
|
if dry_run:
|
||||||
continue
|
continue
|
||||||
@@ -748,7 +761,7 @@ def _apply_m2m(obj, record, resolver):
|
|||||||
for spec in specs:
|
for spec in specs:
|
||||||
value, available = resolver.resolve(spec)
|
value, available = resolver.resolve(spec)
|
||||||
if not available:
|
if not available:
|
||||||
raise ArchiveValidationError(f"M2M-Referenz für {record['id']} konnte nicht aufgelöst werden.")
|
raise ArchiveValidationError(_("M2M reference for %(record)s could not be resolved.") % {"record": record["id"]})
|
||||||
if value is MISSING_REFERENCE:
|
if value is MISSING_REFERENCE:
|
||||||
continue
|
continue
|
||||||
values.append(value)
|
values.append(value)
|
||||||
@@ -781,7 +794,7 @@ def _forced(force, warnings, label, func, *args, **kwargs):
|
|||||||
except ImportConflictError:
|
except ImportConflictError:
|
||||||
raise
|
raise
|
||||||
except Exception as exc: # noqa: BLE001 - force mode skips any failing step
|
except Exception as exc: # noqa: BLE001 - force mode skips any failing step
|
||||||
warnings.append(f"Force-Modus: {label} wurde wegen eines Fehlers übersprungen: {exc}")
|
warnings.append(_("Force mode: %(label)s was skipped because of an error: %(error)s") % {"label": label, "error": exc})
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
@@ -801,8 +814,11 @@ def _skip_uninstalled_optional_models(records, resolver, report):
|
|||||||
del records[record_id]
|
del records[record_id]
|
||||||
for label in sorted(missing_labels):
|
for label in sorted(missing_labels):
|
||||||
report.warnings.append(
|
report.warnings.append(
|
||||||
f"Objekte vom Typ {label} wurden übersprungen, da das zugehörige optionale Plugin "
|
_(
|
||||||
"auf der Zielinstanz nicht installiert ist."
|
"Objects of type %(model)s were skipped because the related optional plugin is not installed "
|
||||||
|
"on the target instance."
|
||||||
|
)
|
||||||
|
% {"model": label}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -810,24 +826,25 @@ def import_archive(
|
|||||||
parsed: ParsedArchive, *, conflict_strategy: str, dry_run: bool, force: bool = False
|
parsed: ParsedArchive, *, conflict_strategy: str, dry_run: bool, force: bool = False
|
||||||
) -> ImportReport:
|
) -> ImportReport:
|
||||||
if conflict_strategy not in ("update", "skip", "fail"):
|
if conflict_strategy not in ("update", "skip", "fail"):
|
||||||
raise ArchiveValidationError("Unbekannte Konfliktstrategie.")
|
raise ArchiveValidationError(_("Unknown conflict strategy."))
|
||||||
source_version = str(parsed.manifest.get("source_netbox_version", ""))
|
source_version = str(parsed.manifest.get("source_netbox_version", ""))
|
||||||
target_version = str(getattr(getattr(settings, "RELEASE", None), "version", ""))
|
target_version = str(getattr(getattr(settings, "RELEASE", None), "version", ""))
|
||||||
if source_version and target_version and source_version.split(".")[:2] != target_version.split(".")[:2]:
|
if source_version and target_version and source_version.split(".")[:2] != target_version.split(".")[:2]:
|
||||||
raise ArchiveValidationError(
|
raise ArchiveValidationError(
|
||||||
f"NetBox-Versionen sind nicht kompatibel: Quelle {source_version}, Ziel {target_version}."
|
_("NetBox versions are not compatible: source %(source)s, target %(target)s.")
|
||||||
|
% {"source": source_version, "target": target_version}
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
source_instance = uuid.UUID(parsed.manifest["source_instance"])
|
source_instance = uuid.UUID(parsed.manifest["source_instance"])
|
||||||
except (KeyError, TypeError, ValueError) as exc:
|
except (KeyError, TypeError, ValueError) as exc:
|
||||||
raise ArchiveValidationError("Die Quellinstanz-Kennung fehlt oder ist ungültig.") from exc
|
raise ArchiveValidationError(_("The source instance ID is missing or invalid.")) from exc
|
||||||
|
|
||||||
records = {}
|
records = {}
|
||||||
for record in parsed.records:
|
for record in parsed.records:
|
||||||
if not all(key in record for key in ("id", "model", "source_pk")):
|
if not all(key in record for key in ("id", "model", "source_pk")):
|
||||||
raise ArchiveValidationError("Ein Objektdatensatz ist unvollständig.")
|
raise ArchiveValidationError(_("An object record is incomplete."))
|
||||||
if record["id"] in records:
|
if record["id"] in records:
|
||||||
raise ArchiveValidationError(f"Doppelte Objekt-ID im Archiv: {record['id']}")
|
raise ArchiveValidationError(_("Duplicate object ID in archive: %(record)s") % {"record": record["id"]})
|
||||||
records[record["id"]] = record
|
records[record["id"]] = record
|
||||||
|
|
||||||
report = ImportReport(dry_run=dry_run, warnings=list(parsed.warnings))
|
report = ImportReport(dry_run=dry_run, warnings=list(parsed.warnings))
|
||||||
@@ -867,7 +884,7 @@ def import_archive(
|
|||||||
except IdentityNotReady:
|
except IdentityNotReady:
|
||||||
continue
|
continue
|
||||||
if existing is not None and conflict_strategy == "fail":
|
if existing is not None and conflict_strategy == "fail":
|
||||||
raise ImportConflictError(f"Zielobjekt existiert bereits: {record_id}")
|
raise ImportConflictError(_("Target object already exists: %(record)s") % {"record": record_id})
|
||||||
|
|
||||||
if existing is not None and conflict_strategy == "skip":
|
if existing is not None and conflict_strategy == "skip":
|
||||||
obj = existing
|
obj = existing
|
||||||
@@ -905,7 +922,7 @@ def import_archive(
|
|||||||
raise
|
raise
|
||||||
resolver.skipped.add(record_id)
|
resolver.skipped.add(record_id)
|
||||||
report.warnings.append(
|
report.warnings.append(
|
||||||
f"Force-Modus: {record_id} wurde wegen eines Fehlers übersprungen: {exc}"
|
_("Force mode: %(label)s was skipped because of an error: %(error)s") % {"label": record_id, "error": exc}
|
||||||
)
|
)
|
||||||
report.add(record["model"], "skipped")
|
report.add(record["model"], "skipped")
|
||||||
pending.pop(record_id)
|
pending.pop(record_id)
|
||||||
@@ -934,12 +951,12 @@ def import_archive(
|
|||||||
resolver.skipped.add(record_id)
|
resolver.skipped.add(record_id)
|
||||||
report.add(record["model"], "skipped")
|
report.add(record["model"], "skipped")
|
||||||
report.warnings.append(
|
report.warnings.append(
|
||||||
f"Force-Modus: {len(pending)} Objekt(e) mit nicht auflösbaren Referenzen "
|
_("Force mode: %(count)s object(s) with unresolvable references were skipped: %(blocked)s")
|
||||||
f"wurden übersprungen: {blocked}"
|
% {"count": len(pending), "blocked": blocked}
|
||||||
)
|
)
|
||||||
break
|
break
|
||||||
raise ArchiveValidationError(
|
raise ArchiveValidationError(
|
||||||
f"Erforderliche Referenzen konnten nicht aufgelöst werden: {blocked}"
|
_("Required references could not be resolved: %(blocked)s") % {"blocked": blocked}
|
||||||
)
|
)
|
||||||
|
|
||||||
for record_id, name, spec in deferred_relations:
|
for record_id, name, spec in deferred_relations:
|
||||||
@@ -947,13 +964,13 @@ def import_archive(
|
|||||||
continue
|
continue
|
||||||
value, available = resolver.resolve(spec)
|
value, available = resolver.resolve(spec)
|
||||||
if not available:
|
if not available:
|
||||||
raise ArchiveValidationError(f"Referenz {name} für {record_id} konnte nicht aufgelöst werden.")
|
raise ArchiveValidationError(_("Reference %(name)s for %(record)s could not be resolved.") % {"name": name, "record": record_id})
|
||||||
if value is MISSING_REFERENCE:
|
if value is MISSING_REFERENCE:
|
||||||
continue
|
continue
|
||||||
_forced(
|
_forced(
|
||||||
force,
|
force,
|
||||||
report.warnings,
|
report.warnings,
|
||||||
f"Referenz {name} für {record_id}",
|
_("Reference %(name)s for %(record)s") % {"name": name, "record": record_id},
|
||||||
_apply_deferred_relation,
|
_apply_deferred_relation,
|
||||||
resolved[record_id],
|
resolved[record_id],
|
||||||
name,
|
name,
|
||||||
@@ -966,7 +983,7 @@ def import_archive(
|
|||||||
continue
|
continue
|
||||||
value, available = resolver.resolve(spec)
|
value, available = resolver.resolve(spec)
|
||||||
if not available:
|
if not available:
|
||||||
raise ArchiveValidationError(f"Generische Referenz {name} für {record_id} fehlt.")
|
raise ArchiveValidationError(_("Generic reference %(name)s for %(record)s is missing.") % {"name": name, "record": record_id})
|
||||||
if value is MISSING_REFERENCE:
|
if value is MISSING_REFERENCE:
|
||||||
continue
|
continue
|
||||||
obj = resolved[record_id]
|
obj = resolved[record_id]
|
||||||
@@ -975,7 +992,7 @@ def import_archive(
|
|||||||
_forced(
|
_forced(
|
||||||
force,
|
force,
|
||||||
report.warnings,
|
report.warnings,
|
||||||
f"Generische Referenz {name} für {record_id}",
|
_("Generic reference %(name)s for %(record)s") % {"name": name, "record": record_id},
|
||||||
compatibility.save,
|
compatibility.save,
|
||||||
obj,
|
obj,
|
||||||
update_fields=[field.ct_field, field.fk_field],
|
update_fields=[field.ct_field, field.fk_field],
|
||||||
@@ -986,13 +1003,13 @@ def import_archive(
|
|||||||
continue
|
continue
|
||||||
value, available = _decode_archived_value(encoded, resolver)
|
value, available = _decode_archived_value(encoded, resolver)
|
||||||
if not available:
|
if not available:
|
||||||
raise ArchiveValidationError(f"Custom-Field-Referenz {name} für {record_id} fehlt.")
|
raise ArchiveValidationError(_("Custom field reference %(name)s for %(record)s is missing.") % {"name": name, "record": record_id})
|
||||||
obj = resolved[record_id]
|
obj = resolved[record_id]
|
||||||
setattr(obj, name, value)
|
setattr(obj, name, value)
|
||||||
_forced(
|
_forced(
|
||||||
force,
|
force,
|
||||||
report.warnings,
|
report.warnings,
|
||||||
f"Custom-Field-Wert {name} für {record_id}",
|
_("Custom field value %(name)s for %(record)s") % {"name": name, "record": record_id},
|
||||||
compatibility.save,
|
compatibility.save,
|
||||||
obj,
|
obj,
|
||||||
update_fields=[name],
|
update_fields=[name],
|
||||||
@@ -1001,7 +1018,7 @@ def import_archive(
|
|||||||
_forced(
|
_forced(
|
||||||
force,
|
force,
|
||||||
report.warnings,
|
report.warnings,
|
||||||
"Rackplatzierung der Geräte",
|
_("Rack placement of devices"),
|
||||||
_apply_device_placements,
|
_apply_device_placements,
|
||||||
deferred_device_placements,
|
deferred_device_placements,
|
||||||
resolved,
|
resolved,
|
||||||
@@ -1015,7 +1032,7 @@ def import_archive(
|
|||||||
_forced(
|
_forced(
|
||||||
force,
|
force,
|
||||||
report.warnings,
|
report.warnings,
|
||||||
f"Mehrfachzuordnungen für {record_id}",
|
_("Many-to-many assignments for %(record)s") % {"record": record_id},
|
||||||
_apply_m2m,
|
_apply_m2m,
|
||||||
resolved[record_id],
|
resolved[record_id],
|
||||||
record,
|
record,
|
||||||
@@ -1025,7 +1042,7 @@ def import_archive(
|
|||||||
_forced(
|
_forced(
|
||||||
force,
|
force,
|
||||||
report.warnings,
|
report.warnings,
|
||||||
"Neuberechnung der Kabelpfade",
|
_("Recalculation of cable paths"),
|
||||||
_rebuild_imported_cable_paths,
|
_rebuild_imported_cable_paths,
|
||||||
records,
|
records,
|
||||||
resolved,
|
resolved,
|
||||||
@@ -1035,11 +1052,11 @@ def import_archive(
|
|||||||
transaction.set_rollback(True)
|
transaction.set_rollback(True)
|
||||||
except (IntegrityError, ValueError, TypeError) as exc:
|
except (IntegrityError, ValueError, TypeError) as exc:
|
||||||
_cleanup_files(saved_files)
|
_cleanup_files(saved_files)
|
||||||
raise ArchiveValidationError(f"Der Import wurde zurückgerollt: {exc}") from exc
|
raise ArchiveValidationError(_("The import was rolled back: %(error)s") % {"error": exc}) from exc
|
||||||
except ExportImportError:
|
except ExportImportError:
|
||||||
_cleanup_files(saved_files)
|
_cleanup_files(saved_files)
|
||||||
raise
|
raise
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
_cleanup_files(saved_files)
|
_cleanup_files(saved_files)
|
||||||
raise ArchiveValidationError(f"Der Import wurde zurückgerollt: {exc}") from exc
|
raise ArchiveValidationError(_("The import was rolled back: %(error)s") % {"error": exc}) from exc
|
||||||
return report
|
return report
|
||||||
@@ -5,10 +5,12 @@ from functools import cache
|
|||||||
from django.apps import apps
|
from django.apps import apps
|
||||||
from django.core.exceptions import FieldDoesNotExist, ValidationError
|
from django.core.exceptions import FieldDoesNotExist, ValidationError
|
||||||
from django.db import models
|
from django.db import models
|
||||||
|
from django.utils.translation import gettext as _
|
||||||
|
|
||||||
AUTO_IMPORT_TENANT_NAME = "Auto-Import"
|
AUTO_IMPORT_TENANT_NAME = "Auto-Import"
|
||||||
AUTO_IMPORT_TENANT_SLUG = "auto-import"
|
AUTO_IMPORT_TENANT_SLUG = "auto-import"
|
||||||
MISSING_TENANT_MESSAGE = "Für dieses Objekt muss ein Mandant angegeben werden."
|
MISSING_TENANT_MESSAGE = "Für dieses Objekt muss ein Mandant angegeben werden." # netbox_utilities before i18n
|
||||||
|
MISSING_TENANT_CODE = "tenant_required"
|
||||||
# Apps of optional plugins whose data is exported when installed on the source
|
# Apps of optional plugins whose data is exported when installed on the source
|
||||||
# and skipped (instead of failing the import) when missing on the target.
|
# and skipped (instead of failing the import) when missing on the target.
|
||||||
OPTIONAL_PLUGIN_APP_LABELS = frozenset({"netbox_utilities"})
|
OPTIONAL_PLUGIN_APP_LABELS = frozenset({"netbox_utilities"})
|
||||||
@@ -20,6 +22,8 @@ def is_optional_plugin_model(label: str) -> bool:
|
|||||||
|
|
||||||
def netbox_utilities_tenant_required() -> bool:
|
def netbox_utilities_tenant_required() -> bool:
|
||||||
"""Return the effective tenant policy without requiring the optional plugin."""
|
"""Return the effective tenant policy without requiring the optional plugin."""
|
||||||
|
if not apps.is_installed("netbox_utilities"): # importing its models while disabled raises RuntimeError
|
||||||
|
return False
|
||||||
try:
|
try:
|
||||||
from netbox_utilities.runtime import tenant_required
|
from netbox_utilities.runtime import tenant_required
|
||||||
except ImportError:
|
except ImportError:
|
||||||
@@ -27,6 +31,19 @@ def netbox_utilities_tenant_required() -> bool:
|
|||||||
return bool(tenant_required())
|
return bool(tenant_required())
|
||||||
|
|
||||||
|
|
||||||
|
def netbox_utilities_tenant_messages() -> set[str]:
|
||||||
|
"""Messages netbox_utilities may raise for a missing tenant, in the active language."""
|
||||||
|
messages = {MISSING_TENANT_MESSAGE}
|
||||||
|
if not apps.is_installed("netbox_utilities"):
|
||||||
|
return messages
|
||||||
|
try:
|
||||||
|
from netbox_utilities.tenant_validation import VALIDATION_MESSAGE
|
||||||
|
except ImportError:
|
||||||
|
return messages
|
||||||
|
messages.add(str(VALIDATION_MESSAGE))
|
||||||
|
return messages
|
||||||
|
|
||||||
|
|
||||||
def is_tenant_relation(field) -> bool:
|
def is_tenant_relation(field) -> bool:
|
||||||
if field.name != "tenant":
|
if field.name != "tenant":
|
||||||
return False
|
return False
|
||||||
@@ -99,7 +116,9 @@ class PluginCompatibility:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _is_missing_tenant_error(exc: ValidationError) -> bool:
|
def _is_missing_tenant_error(exc: ValidationError) -> bool:
|
||||||
return MISSING_TENANT_MESSAGE in exc.messages
|
if any(getattr(error, "code", None) == MISSING_TENANT_CODE for error in getattr(exc, "error_list", ())):
|
||||||
|
return True
|
||||||
|
return not netbox_utilities_tenant_messages().isdisjoint(exc.messages)
|
||||||
|
|
||||||
def _auto_import_tenant(self):
|
def _auto_import_tenant(self):
|
||||||
if self._fallback_tenant is not None:
|
if self._fallback_tenant is not None:
|
||||||
@@ -118,18 +137,24 @@ class PluginCompatibility:
|
|||||||
|
|
||||||
if self.dry_run:
|
if self.dry_run:
|
||||||
message = (
|
message = (
|
||||||
'Für den Prüflauf wurde der Mandant "Auto-Import" automatisch als Ersatzmandant '
|
_(
|
||||||
"verwendet; er wird nicht dauerhaft angelegt oder geändert."
|
'The tenant "Auto-Import" was used automatically as a fallback tenant for the dry run; '
|
||||||
|
"it is not created or changed permanently."
|
||||||
|
)
|
||||||
)
|
)
|
||||||
elif created:
|
elif created:
|
||||||
message = (
|
message = (
|
||||||
'Der Mandant "Auto-Import" wurde automatisch erstellt und Objekten ohne '
|
_(
|
||||||
"auflösbaren Mandanten zugewiesen."
|
'The tenant "Auto-Import" was created automatically and assigned to objects without a '
|
||||||
|
"resolvable tenant."
|
||||||
|
)
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
message = (
|
message = (
|
||||||
'Der vorhandene Mandant "Auto-Import" wurde automatisch für Objekte ohne '
|
_(
|
||||||
"auflösbaren Mandanten ausgewählt."
|
'The existing tenant "Auto-Import" was selected automatically for objects without a '
|
||||||
|
"resolvable tenant."
|
||||||
|
)
|
||||||
)
|
)
|
||||||
self.warnings.append(message)
|
self.warnings.append(message)
|
||||||
self._fallback_tenant = tenant
|
self._fallback_tenant = tenant
|
||||||
@@ -174,6 +199,9 @@ class PluginCompatibility:
|
|||||||
type(obj)._default_manager.filter(pk__in=conflict_ids).update(**{field.attname: None})
|
type(obj)._default_manager.filter(pk__in=conflict_ids).update(**{field.attname: None})
|
||||||
identifiers = ", ".join(str(pk) for pk in conflict_ids)
|
identifiers = ", ".join(str(pk) for pk in conflict_ids)
|
||||||
self.warnings.append(
|
self.warnings.append(
|
||||||
f"Eindeutige Referenz {obj._meta.label_lower}.{field_name} wurde von Zielobjekt(en) "
|
_(
|
||||||
f"{identifiers} gelöst und dem importierten Objekt neu zugeordnet."
|
"Unique reference %(field)s was released from target object(s) %(ids)s and reassigned to the "
|
||||||
|
"imported object."
|
||||||
|
)
|
||||||
|
% {"field": f"{obj._meta.label_lower}.{field_name}", "ids": identifiers}
|
||||||
)
|
)
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from django.utils.translation import gettext as _
|
||||||
|
|
||||||
from .codec import decode_scalar
|
from .codec import decode_scalar
|
||||||
from .exceptions import ArchiveValidationError
|
from .exceptions import ArchiveValidationError
|
||||||
|
|
||||||
@@ -25,7 +27,8 @@ class ReferenceResolver:
|
|||||||
fields = ", ".join(field_names)
|
fields = ", ".join(field_names)
|
||||||
self.warn(
|
self.warn(
|
||||||
("skipped", record_id),
|
("skipped", record_id),
|
||||||
f"{record_id} ({model_label}) wurde wegen fehlender Pflichtreferenz übersprungen: {fields}.",
|
_("%(record)s (%(model)s) was skipped because of a missing required reference: %(fields)s.")
|
||||||
|
% {"record": record_id, "model": model_label, "fields": fields},
|
||||||
)
|
)
|
||||||
|
|
||||||
def _external_object(self, spec):
|
def _external_object(self, spec):
|
||||||
@@ -39,14 +42,15 @@ class ReferenceResolver:
|
|||||||
value = model._default_manager.get(**lookup)
|
value = model._default_manager.get(**lookup)
|
||||||
except model.DoesNotExist:
|
except model.DoesNotExist:
|
||||||
value = MISSING_REFERENCE
|
value = MISSING_REFERENCE
|
||||||
reason = "nicht gefunden"
|
reason = _("not found")
|
||||||
except model.MultipleObjectsReturned:
|
except model.MultipleObjectsReturned:
|
||||||
value = MISSING_REFERENCE
|
value = MISSING_REFERENCE
|
||||||
reason = "nicht eindeutig"
|
reason = _("not unique")
|
||||||
if value is MISSING_REFERENCE:
|
if value is MISSING_REFERENCE:
|
||||||
self.warn(
|
self.warn(
|
||||||
("external", cache_key),
|
("external", cache_key),
|
||||||
f"Externe Referenz ausgelassen: {spec['model']} mit {lookup} ({reason}).",
|
_("External reference omitted: %(model)s with %(lookup)s (%(reason)s).")
|
||||||
|
% {"model": spec["model"], "lookup": lookup, "reason": reason},
|
||||||
)
|
)
|
||||||
self._external_cache[cache_key] = value
|
self._external_cache[cache_key] = value
|
||||||
return value
|
return value
|
||||||
@@ -59,10 +63,10 @@ class ReferenceResolver:
|
|||||||
if record_id in self.skipped:
|
if record_id in self.skipped:
|
||||||
self.warn(
|
self.warn(
|
||||||
("internal", record_id),
|
("internal", record_id),
|
||||||
f"Referenzen auf das übersprungene Objekt {record_id} wurden ausgelassen.",
|
_("References to the skipped object %(record)s were omitted.") % {"record": record_id},
|
||||||
)
|
)
|
||||||
return MISSING_REFERENCE, True
|
return MISSING_REFERENCE, True
|
||||||
return self.resolved.get(record_id), record_id in self.resolved
|
return self.resolved.get(record_id), record_id in self.resolved
|
||||||
if "external" in spec:
|
if "external" in spec:
|
||||||
return self._external_object(spec["external"]), True
|
return self._external_object(spec["external"]), True
|
||||||
raise ArchiveValidationError("Eine Objektreferenz im Archiv ist ungültig.")
|
raise ArchiveValidationError(_("An object reference in the archive is invalid."))
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
{% extends 'base/layout.html' %}
|
{% extends 'base/layout.html' %}
|
||||||
{% load form_helpers %}
|
{% load form_helpers %}
|
||||||
|
{% load i18n %}
|
||||||
|
|
||||||
{% block title %}NetBox-Export{% endblock title %}
|
{% block title %}NetBox-Export{% endblock title %}
|
||||||
|
|
||||||
@@ -19,18 +20,22 @@
|
|||||||
{% if report %}
|
{% if report %}
|
||||||
<div class="alert {% if report.dry_run %}alert-info{% else %}alert-success{% endif %}" role="alert">
|
<div class="alert {% if report.dry_run %}alert-info{% else %}alert-success{% endif %}" role="alert">
|
||||||
<h2 class="h4 mb-2">
|
<h2 class="h4 mb-2">
|
||||||
{% if report.dry_run %}Prüflauf erfolgreich{% else %}Import abgeschlossen{% endif %}
|
{% if report.dry_run %}{% trans "Dry run successful" %}{% else %}{% trans "Import completed" %}{% endif %}
|
||||||
</h2>
|
</h2>
|
||||||
<div>
|
<div>
|
||||||
{{ report.created }} erstellt, {{ report.updated }} aktualisiert, {{ report.skipped }} übersprungen.
|
{% blocktrans trimmed with created=report.created updated=report.updated skipped=report.skipped %}
|
||||||
Quelle: {{ manifest.scope.label }} ({{ manifest.object_count }} Objekte).
|
{{ created }} created, {{ updated }} updated, {{ skipped }} skipped.
|
||||||
|
{% endblocktrans %}
|
||||||
|
{% blocktrans trimmed with label=manifest.scope.label count=manifest.object_count %}
|
||||||
|
Source: {{ label }} ({{ count }} objects).
|
||||||
|
{% endblocktrans %}
|
||||||
</div>
|
</div>
|
||||||
{% for warning in report.warnings %}<div class="mt-1">{{ warning }}</div>{% endfor %}
|
{% for warning in report.warnings %}<div class="mt-1">{{ warning }}</div>{% endfor %}
|
||||||
</div>
|
</div>
|
||||||
<div class="table-responsive mb-4">
|
<div class="table-responsive mb-4">
|
||||||
<table class="table table-sm table-hover">
|
<table class="table table-sm table-hover">
|
||||||
<thead>
|
<thead>
|
||||||
<tr><th>Modell</th><th class="text-end">Erstellt</th><th class="text-end">Aktualisiert</th><th class="text-end">Übersprungen</th></tr>
|
<tr><th>{% trans "Model" %}</th><th class="text-end">{% trans "Created" %}</th><th class="text-end">{% trans "Updated" %}</th><th class="text-end">{% trans "Skipped" %}</th></tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{% for model, counts in report.models.items %}
|
{% for model, counts in report.models.items %}
|
||||||
@@ -50,7 +55,7 @@
|
|||||||
<div class="col-12 col-xl-6">
|
<div class="col-12 col-xl-6">
|
||||||
<div class="card h-100">
|
<div class="card h-100">
|
||||||
<div class="card-header">
|
<div class="card-header">
|
||||||
<h2 class="card-title"><i class="mdi mdi-download me-1" aria-hidden="true"></i> Export</h2>
|
<h2 class="card-title"><i class="mdi mdi-download me-1" aria-hidden="true"></i> {% trans "Export" %}</h2>
|
||||||
</div>
|
</div>
|
||||||
<form method="post" id="netbox-export-form" novalidate>
|
<form method="post" id="netbox-export-form" novalidate>
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
@@ -64,15 +69,15 @@
|
|||||||
<div class="card-footer text-end">
|
<div class="card-footer text-end">
|
||||||
<div id="export-progress" class="mb-3 text-start" hidden aria-live="polite">
|
<div id="export-progress" class="mb-3 text-start" hidden aria-live="polite">
|
||||||
<div class="d-flex justify-content-between mb-1">
|
<div class="d-flex justify-content-between mb-1">
|
||||||
<span class="progress-label">Export wird vorbereitet ...</span>
|
<span class="progress-label">{% trans "Preparing export ..." %}</span>
|
||||||
<span class="progress-percent"></span>
|
<span class="progress-percent"></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="progress" role="progressbar" aria-label="Exportfortschritt" aria-valuemin="0" aria-valuemax="100">
|
<div class="progress" role="progressbar" aria-label="{% trans "Export progress" %}" aria-valuemin="0" aria-valuemax="100">
|
||||||
<div class="progress-bar progress-bar-striped progress-bar-animated" style="width: 100%"></div>
|
<div class="progress-bar progress-bar-striped progress-bar-animated" style="width: 100%"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<button type="submit" class="btn btn-primary">
|
<button type="submit" class="btn btn-primary">
|
||||||
<i class="mdi mdi-archive-arrow-down me-1" aria-hidden="true"></i> ZIP exportieren
|
<i class="mdi mdi-archive-arrow-down me-1" aria-hidden="true"></i> {% trans "Export ZIP" %}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
@@ -82,7 +87,7 @@
|
|||||||
<div class="col-12 col-xl-6">
|
<div class="col-12 col-xl-6">
|
||||||
<div class="card h-100">
|
<div class="card h-100">
|
||||||
<div class="card-header">
|
<div class="card-header">
|
||||||
<h2 class="card-title"><i class="mdi mdi-upload me-1" aria-hidden="true"></i> Import</h2>
|
<h2 class="card-title"><i class="mdi mdi-upload me-1" aria-hidden="true"></i> {% trans "Import" %}</h2>
|
||||||
</div>
|
</div>
|
||||||
<form method="post" id="netbox-import-form" enctype="multipart/form-data" novalidate>
|
<form method="post" id="netbox-import-form" enctype="multipart/form-data" novalidate>
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
@@ -96,15 +101,15 @@
|
|||||||
<div class="card-footer text-end">
|
<div class="card-footer text-end">
|
||||||
<div id="import-progress" class="mb-3 text-start" hidden aria-live="polite">
|
<div id="import-progress" class="mb-3 text-start" hidden aria-live="polite">
|
||||||
<div class="d-flex justify-content-between mb-1">
|
<div class="d-flex justify-content-between mb-1">
|
||||||
<span class="progress-label">Archiv wird hochgeladen ...</span>
|
<span class="progress-label">{% trans "Uploading archive ..." %}</span>
|
||||||
<span class="progress-percent"></span>
|
<span class="progress-percent"></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="progress" role="progressbar" aria-label="Importfortschritt" aria-valuemin="0" aria-valuemax="100">
|
<div class="progress" role="progressbar" aria-label="{% trans "Import progress" %}" aria-valuemin="0" aria-valuemax="100">
|
||||||
<div class="progress-bar progress-bar-striped progress-bar-animated" style="width: 0%"></div>
|
<div class="progress-bar progress-bar-striped progress-bar-animated" style="width: 0%"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<button type="submit" class="btn btn-primary">
|
<button type="submit" class="btn btn-primary">
|
||||||
<i class="mdi mdi-archive-arrow-up me-1" aria-hidden="true"></i> Archiv verarbeiten
|
<i class="mdi mdi-archive-arrow-up me-1" aria-hidden="true"></i> {% trans "Process archive" %}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
@@ -115,8 +120,10 @@
|
|||||||
|
|
||||||
{% block javascript %}
|
{% block javascript %}
|
||||||
{{ block.super }}
|
{{ block.super }}
|
||||||
|
{{ js_messages|json_script:"netbox-export-messages" }}
|
||||||
<script>
|
<script>
|
||||||
(() => {
|
(() => {
|
||||||
|
const msg = JSON.parse(document.getElementById('netbox-export-messages').textContent);
|
||||||
const typeSelect = document.getElementById('id_export-scope_type');
|
const typeSelect = document.getElementById('id_export-scope_type');
|
||||||
const names = ['tenant_group', 'tenant', 'region', 'site', 'location'];
|
const names = ['tenant_group', 'tenant', 'region', 'site', 'location'];
|
||||||
const refresh = () => {
|
const refresh = () => {
|
||||||
@@ -178,7 +185,7 @@
|
|||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
if (!exportForm.reportValidity()) return;
|
if (!exportForm.reportValidity()) return;
|
||||||
setBusy(exportForm, true);
|
setBusy(exportForm, true);
|
||||||
updateProgress(exportProgress, 'Export wird vorbereitet ...');
|
updateProgress(exportProgress, msg.preparing_export);
|
||||||
|
|
||||||
const request = new XMLHttpRequest();
|
const request = new XMLHttpRequest();
|
||||||
request.open('POST', formTarget(exportForm));
|
request.open('POST', formTarget(exportForm));
|
||||||
@@ -186,7 +193,7 @@
|
|||||||
request.onprogress = (progressEvent) => {
|
request.onprogress = (progressEvent) => {
|
||||||
if (!progressEvent.lengthComputable) return;
|
if (!progressEvent.lengthComputable) return;
|
||||||
const percent = Math.min(99, Math.round((progressEvent.loaded / progressEvent.total) * 100));
|
const percent = Math.min(99, Math.round((progressEvent.loaded / progressEvent.total) * 100));
|
||||||
updateProgress(exportProgress, 'ZIP wird übertragen ...', percent);
|
updateProgress(exportProgress, msg.transferring_zip, percent);
|
||||||
};
|
};
|
||||||
request.onload = async () => {
|
request.onload = async () => {
|
||||||
const contentType = request.getResponseHeader('Content-Type') || '';
|
const contentType = request.getResponseHeader('Content-Type') || '';
|
||||||
@@ -202,11 +209,11 @@
|
|||||||
link.click();
|
link.click();
|
||||||
link.remove();
|
link.remove();
|
||||||
window.setTimeout(() => URL.revokeObjectURL(downloadUrl), 1000);
|
window.setTimeout(() => URL.revokeObjectURL(downloadUrl), 1000);
|
||||||
updateProgress(exportProgress, 'Export abgeschlossen', 100, 'success');
|
updateProgress(exportProgress, msg.export_done, 100, 'success');
|
||||||
setBusy(exportForm, false);
|
setBusy(exportForm, false);
|
||||||
};
|
};
|
||||||
request.onerror = () => {
|
request.onerror = () => {
|
||||||
updateProgress(exportProgress, 'Export fehlgeschlagen', 100, 'error');
|
updateProgress(exportProgress, msg.export_failed, 100, 'error');
|
||||||
setBusy(exportForm, false);
|
setBusy(exportForm, false);
|
||||||
};
|
};
|
||||||
request.send(new FormData(exportForm));
|
request.send(new FormData(exportForm));
|
||||||
@@ -219,21 +226,21 @@
|
|||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
if (!importForm.reportValidity()) return;
|
if (!importForm.reportValidity()) return;
|
||||||
setBusy(importForm, true);
|
setBusy(importForm, true);
|
||||||
updateProgress(importProgress, 'Archiv wird hochgeladen ...', 0);
|
updateProgress(importProgress, msg.uploading, 0);
|
||||||
|
|
||||||
const request = new XMLHttpRequest();
|
const request = new XMLHttpRequest();
|
||||||
request.open('POST', formTarget(importForm));
|
request.open('POST', formTarget(importForm));
|
||||||
request.upload.onprogress = (progressEvent) => {
|
request.upload.onprogress = (progressEvent) => {
|
||||||
if (!progressEvent.lengthComputable) return;
|
if (!progressEvent.lengthComputable) return;
|
||||||
const percent = Math.min(100, Math.round((progressEvent.loaded / progressEvent.total) * 100));
|
const percent = Math.min(100, Math.round((progressEvent.loaded / progressEvent.total) * 100));
|
||||||
updateProgress(importProgress, 'Archiv wird hochgeladen ...', percent);
|
updateProgress(importProgress, msg.uploading, percent);
|
||||||
};
|
};
|
||||||
request.upload.onload = () => {
|
request.upload.onload = () => {
|
||||||
updateProgress(importProgress, 'Archiv wird geprüft und verarbeitet ...');
|
updateProgress(importProgress, msg.processing);
|
||||||
};
|
};
|
||||||
request.onload = () => replacePage(request.responseText);
|
request.onload = () => replacePage(request.responseText);
|
||||||
request.onerror = () => {
|
request.onerror = () => {
|
||||||
updateProgress(importProgress, 'Import fehlgeschlagen', 100, 'error');
|
updateProgress(importProgress, msg.import_failed, 100, 'error');
|
||||||
setBusy(importForm, false);
|
setBusy(importForm, false);
|
||||||
};
|
};
|
||||||
request.send(new FormData(importForm));
|
request.send(new FormData(importForm));
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ from django.contrib.auth.mixins import UserPassesTestMixin
|
|||||||
from django.http import HttpResponse
|
from django.http import HttpResponse
|
||||||
from django.shortcuts import render
|
from django.shortcuts import render
|
||||||
from django.utils.text import slugify
|
from django.utils.text import slugify
|
||||||
|
from django.utils.translation import gettext as _
|
||||||
from django.views import View
|
from django.views import View
|
||||||
from netbox.plugins import get_plugin_config
|
from netbox.plugins import get_plugin_config
|
||||||
|
|
||||||
@@ -25,6 +26,15 @@ class DashboardView(UserPassesTestMixin, View):
|
|||||||
"import_form": import_form or ImportForm(prefix="import"),
|
"import_form": import_form or ImportForm(prefix="import"),
|
||||||
"report": report,
|
"report": report,
|
||||||
"manifest": manifest,
|
"manifest": manifest,
|
||||||
|
"js_messages": {
|
||||||
|
"preparing_export": _("Preparing export ..."),
|
||||||
|
"transferring_zip": _("Transferring ZIP ..."),
|
||||||
|
"export_done": _("Export completed"),
|
||||||
|
"export_failed": _("Export failed"),
|
||||||
|
"uploading": _("Uploading archive ..."),
|
||||||
|
"processing": _("Checking and processing archive ..."),
|
||||||
|
"import_failed": _("Import failed"),
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
def get(self, request):
|
def get(self, request):
|
||||||
|
|||||||
+5
-1
@@ -20,7 +20,11 @@ classifiers = [
|
|||||||
include = ["netbox_export*"]
|
include = ["netbox_export*"]
|
||||||
|
|
||||||
[tool.setuptools.package-data]
|
[tool.setuptools.package-data]
|
||||||
netbox_export = ["templates/**/*.html"]
|
netbox_export = [
|
||||||
|
"templates/**/*.html",
|
||||||
|
"locale/*/LC_MESSAGES/*.po",
|
||||||
|
"locale/*/LC_MESSAGES/*.mo",
|
||||||
|
]
|
||||||
|
|
||||||
[tool.pytest.ini_options]
|
[tool.pytest.ini_options]
|
||||||
testpaths = ["tests"]
|
testpaths = ["tests"]
|
||||||
|
|||||||
@@ -34,13 +34,13 @@ def test_archive_round_trip():
|
|||||||
|
|
||||||
assert parsed.records == records()
|
assert parsed.records == records()
|
||||||
assert parsed.assets == {"assets/a.txt": b"data"}
|
assert parsed.assets == {"assets/a.txt": b"data"}
|
||||||
assert parsed.warnings == ["Das Archiv ist nicht signiert."]
|
assert parsed.warnings == ["The archive is not signed."]
|
||||||
|
|
||||||
|
|
||||||
def test_signed_archive_requires_matching_key():
|
def test_signed_archive_requires_matching_key():
|
||||||
payload = build_archive(manifest(), records(), {}, signing_key="secret-a")
|
payload = build_archive(manifest(), records(), {}, signing_key="secret-a")
|
||||||
|
|
||||||
with pytest.raises(ArchiveValidationError, match="Archivsignatur"):
|
with pytest.raises(ArchiveValidationError, match="archive signature"):
|
||||||
read_archive(payload, max_size=1024 * 1024, max_objects=10, signing_key="secret-b")
|
read_archive(payload, max_size=1024 * 1024, max_objects=10, signing_key="secret-b")
|
||||||
|
|
||||||
|
|
||||||
@@ -49,7 +49,7 @@ def test_signed_archive_without_local_key_is_not_claimed_as_verified():
|
|||||||
|
|
||||||
parsed = read_archive(payload, max_size=1024 * 1024, max_objects=10)
|
parsed = read_archive(payload, max_size=1024 * 1024, max_objects=10)
|
||||||
|
|
||||||
assert parsed.warnings == ["Das Archiv ist signiert, aber ohne konfigurierten Schlüssel nicht verifiziert."]
|
assert parsed.warnings == ["The archive is signed but was not verified because no key is configured."]
|
||||||
|
|
||||||
|
|
||||||
def test_modified_object_stream_is_rejected():
|
def test_modified_object_stream_is_rejected():
|
||||||
@@ -63,7 +63,7 @@ def test_modified_object_stream_is_rejected():
|
|||||||
content = content.replace(b"Berlin", b"Hamburg")
|
content = content.replace(b"Berlin", b"Hamburg")
|
||||||
target.writestr(info, content)
|
target.writestr(info, content)
|
||||||
|
|
||||||
with pytest.raises(ArchiveValidationError, match="Prüfsumme"):
|
with pytest.raises(ArchiveValidationError, match="checksum"):
|
||||||
read_archive(output.getvalue(), max_size=1024 * 1024, max_objects=10)
|
read_archive(output.getvalue(), max_size=1024 * 1024, max_objects=10)
|
||||||
|
|
||||||
|
|
||||||
@@ -78,7 +78,7 @@ def test_modified_asset_is_rejected():
|
|||||||
content = b"modified"
|
content = b"modified"
|
||||||
target.writestr(info, content)
|
target.writestr(info, content)
|
||||||
|
|
||||||
with pytest.raises(ArchiveValidationError, match="Prüfsumme der Datei"):
|
with pytest.raises(ArchiveValidationError, match="checksum of file"):
|
||||||
read_archive(output.getvalue(), max_size=1024 * 1024, max_objects=10)
|
read_archive(output.getvalue(), max_size=1024 * 1024, max_objects=10)
|
||||||
|
|
||||||
|
|
||||||
@@ -88,12 +88,12 @@ def test_path_traversal_is_rejected():
|
|||||||
with zipfile.ZipFile(output, "w") as archive:
|
with zipfile.ZipFile(output, "w") as archive:
|
||||||
archive.writestr("../manifest.json", json.dumps(manifest()))
|
archive.writestr("../manifest.json", json.dumps(manifest()))
|
||||||
|
|
||||||
with pytest.raises(ArchiveValidationError, match="Dateipfad"):
|
with pytest.raises(ArchiveValidationError, match="file path"):
|
||||||
read_archive(output.getvalue(), max_size=1024 * 1024, max_objects=10)
|
read_archive(output.getvalue(), max_size=1024 * 1024, max_objects=10)
|
||||||
|
|
||||||
|
|
||||||
def test_object_limit_is_enforced():
|
def test_object_limit_is_enforced():
|
||||||
payload = build_archive(manifest(), records() * 2, {})
|
payload = build_archive(manifest(), records() * 2, {})
|
||||||
|
|
||||||
with pytest.raises(ArchiveValidationError, match="zu viele Objekte"):
|
with pytest.raises(ArchiveValidationError, match="too many objects"):
|
||||||
read_archive(payload, max_size=1024 * 1024, max_objects=1)
|
read_archive(payload, max_size=1024 * 1024, max_objects=1)
|
||||||
@@ -49,7 +49,7 @@ def test_port_mapping_conflicts_are_replaced_before_save():
|
|||||||
|
|
||||||
assert deleted == [12]
|
assert deleted == [12]
|
||||||
resolver.warn.assert_called_once()
|
resolver.warn.assert_called_once()
|
||||||
assert "Front-/Rear-Port-Verkabelung" in resolver.warn.call_args.args[1]
|
assert "front/rear port cabling" in resolver.warn.call_args.args[1]
|
||||||
|
|
||||||
|
|
||||||
def test_imported_cable_terminations_trigger_netbox_path_rebuild(monkeypatch):
|
def test_imported_cable_terminations_trigger_netbox_path_rebuild(monkeypatch):
|
||||||
|
|||||||
@@ -140,7 +140,7 @@ def test_update_releases_exact_rack_occupant_and_places_imported_device(placemen
|
|||||||
assert (occupant.rack, occupant.position, occupant.face) == (rack, None, None)
|
assert (occupant.rack, occupant.position, occupant.face) == (rack, None, None)
|
||||||
assert (imported.rack, imported.position, imported.face) == (rack, Decimal("31.0"), "front")
|
assert (imported.rack, imported.position, imported.face) == (rack, Decimal("31.0"), "front")
|
||||||
assert len(warnings) == 1
|
assert len(warnings) == 1
|
||||||
assert f"Zielgerät(e) {occupant.pk} (Existing)" in warnings[0]
|
assert f"target device(s) {occupant.pk} (Existing)" in warnings[0]
|
||||||
|
|
||||||
|
|
||||||
def test_skip_keeps_occupant_and_leaves_imported_device_unpositioned(placement_schema):
|
def test_skip_keeps_occupant_and_leaves_imported_device_unpositioned(placement_schema):
|
||||||
@@ -165,7 +165,7 @@ def test_skip_keeps_occupant_and_leaves_imported_device_unpositioned(placement_s
|
|||||||
assert (occupant.rack, occupant.position, occupant.face) == (rack, Decimal("31.0"), "front")
|
assert (occupant.rack, occupant.position, occupant.face) == (rack, Decimal("31.0"), "front")
|
||||||
assert (imported.rack, imported.position, imported.face) == (rack, None, None)
|
assert (imported.rack, imported.position, imported.face) == (rack, None, None)
|
||||||
assert len(warnings) == 1
|
assert len(warnings) == 1
|
||||||
assert "wurde ohne Position im Rack gespeichert" in warnings[0]
|
assert "was saved without a rack position" in warnings[0]
|
||||||
|
|
||||||
|
|
||||||
def test_fail_reports_rack_conflict_before_database_constraint(placement_schema):
|
def test_fail_reports_rack_conflict_before_database_constraint(placement_schema):
|
||||||
@@ -177,7 +177,7 @@ def test_fail_reports_rack_conflict_before_database_constraint(placement_schema)
|
|||||||
imported = PlacementDevice.objects.create(name="Imported", device_type=device_type)
|
imported = PlacementDevice.objects.create(name="Imported", device_type=device_type)
|
||||||
record_id, resolved, _, resolver, compatibility, placement = placement_context(imported, rack)
|
record_id, resolved, _, resolver, compatibility, placement = placement_context(imported, rack)
|
||||||
|
|
||||||
with pytest.raises(ImportConflictError, match="Rackplatzkonflikt.*Rack R01"):
|
with pytest.raises(ImportConflictError, match="Rack position conflict.*Rack R01"):
|
||||||
_apply_device_placements(
|
_apply_device_placements(
|
||||||
[(record_id, placement)],
|
[(record_id, placement)],
|
||||||
resolved,
|
resolved,
|
||||||
|
|||||||
@@ -98,8 +98,8 @@ def test_oversized_image_is_resized_after_pillow_bomb_error(monkeypatch):
|
|||||||
assert stored_image.format == "PNG"
|
assert stored_image.format == "PNG"
|
||||||
assert import_warnings == [
|
assert import_warnings == [
|
||||||
(
|
(
|
||||||
f"Bild für extras.imageattachment:17 wurde von 11×10 auf "
|
f"Image for extras.imageattachment:17 was downscaled from 11×10 to "
|
||||||
f"{obj.image_width}×{obj.image_height} Pixel verkleinert."
|
f"{obj.image_width}×{obj.image_height} pixels."
|
||||||
)
|
)
|
||||||
]
|
]
|
||||||
assert Image.MAX_IMAGE_PIXELS == 50
|
assert Image.MAX_IMAGE_PIXELS == 50
|
||||||
|
|||||||
@@ -246,8 +246,8 @@ def test_existing_unique_relation_is_released_before_reassignment():
|
|||||||
assert imported_owner.primary_ip6 == address
|
assert imported_owner.primary_ip6 == address
|
||||||
assert warnings == [
|
assert warnings == [
|
||||||
(
|
(
|
||||||
"Eindeutige Referenz compat_tests.uniqueaddressowner.primary_ip6 wurde von "
|
"Unique reference compat_tests.uniqueaddressowner.primary_ip6 was released from target "
|
||||||
f"Zielobjekt(en) {previous_owner.pk} gelöst und dem importierten Objekt neu zugeordnet."
|
f"object(s) {previous_owner.pk} and reassigned to the imported object."
|
||||||
)
|
)
|
||||||
]
|
]
|
||||||
finally:
|
finally:
|
||||||
@@ -288,9 +288,9 @@ def test_natural_key_rebinds_stale_mapping_instead_of_creating_duplicate(monkeyp
|
|||||||
assert existing == natural
|
assert existing == natural
|
||||||
assert warnings == [
|
assert warnings == [
|
||||||
(
|
(
|
||||||
"Gespeicherte Zuordnung für dcim.rearport:77 wurde von Ziel-ID 999 auf "
|
"Stored mapping for dcim.rearport:77 was corrected from target ID 999 to "
|
||||||
f"Ziel-ID {natural.pk} korrigiert, da der Fachschlüssel "
|
f"target ID {natural.pk} because the natural key "
|
||||||
f"{{'device': <Device: Device object ({device.pk})>, 'name': '3-LC'}} bereits existiert."
|
f"{{'device': <Device: Device object ({device.pk})>, 'name': '3-LC'}} already exists."
|
||||||
)
|
)
|
||||||
]
|
]
|
||||||
finally:
|
finally:
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import ast
|
||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).parents[1]
|
||||||
|
|
||||||
|
|
||||||
|
def _plugin_versions():
|
||||||
|
tree = ast.parse((ROOT / "netbox_export" / "__init__.py").read_text(encoding="utf-8"))
|
||||||
|
values = {
|
||||||
|
target.id: node.value.value
|
||||||
|
for node in ast.walk(tree)
|
||||||
|
if isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant)
|
||||||
|
for target in node.targets
|
||||||
|
if isinstance(target, ast.Name)
|
||||||
|
}
|
||||||
|
return values["min_version"], values["max_version"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_readme_netbox_range_matches_plugin_config():
|
||||||
|
min_version, max_version = _plugin_versions()
|
||||||
|
major, minor, patch = max_version.split(".")
|
||||||
|
upper = f"{major}.{minor}.x" if patch == "99" else max_version # 4.7.99 is documented as 4.7.x
|
||||||
|
expected = f"`{min_version}` – `{upper}`"
|
||||||
|
readme = (ROOT / "README.md").read_text(encoding="utf-8")
|
||||||
|
|
||||||
|
assert f"| **NetBox** | {expected} |" in readme
|
||||||
|
assert f"- NetBox {expected}" in readme
|
||||||
|
|
||||||
|
|
||||||
|
def test_german_catalog_is_complete():
|
||||||
|
po = ROOT / "netbox_export" / "locale" / "de" / "LC_MESSAGES" / "django.po"
|
||||||
|
content = po.read_text(encoding="utf-8")
|
||||||
|
entries = re.findall(r'^msgid ((?:".*"\n)+)msgstr ((?:".*"\n?)+)', content, re.MULTILINE)
|
||||||
|
|
||||||
|
assert "#, fuzzy" not in content
|
||||||
|
assert [msgid for msgid, msgstr in entries[1:] if msgstr.strip() == '""'] == []
|
||||||
|
assert po.with_suffix(".mo").is_file()
|
||||||
@@ -171,8 +171,8 @@ def test_creates_and_assigns_auto_import_tenant_when_policy_is_active():
|
|||||||
assert len(manager.created) == 1
|
assert len(manager.created) == 1
|
||||||
assert warnings == [
|
assert warnings == [
|
||||||
(
|
(
|
||||||
'Der Mandant "Auto-Import" wurde automatisch erstellt und Objekten ohne '
|
'The tenant "Auto-Import" was created automatically and assigned to objects without a '
|
||||||
'auflösbaren Mandanten zugewiesen.'
|
'resolvable tenant.'
|
||||||
)
|
)
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -197,7 +197,7 @@ def test_validation_error_forces_fallback_for_older_plugin_versions():
|
|||||||
assert manager.created == []
|
assert manager.created == []
|
||||||
assert warnings == [
|
assert warnings == [
|
||||||
(
|
(
|
||||||
'Der vorhandene Mandant "Auto-Import" wurde automatisch für Objekte ohne '
|
'The existing tenant "Auto-Import" was selected automatically for objects without a '
|
||||||
'auflösbaren Mandanten ausgewählt.'
|
'resolvable tenant.'
|
||||||
)
|
)
|
||||||
]
|
]
|
||||||
@@ -49,7 +49,7 @@ def test_missing_external_reference_is_omitted_and_warned_once():
|
|||||||
assert second_available is True
|
assert second_available is True
|
||||||
assert manager.calls == 1
|
assert manager.calls == 1
|
||||||
assert warnings == [
|
assert warnings == [
|
||||||
"Externe Referenz ausgelassen: users.user mit {'username': 'lke'} (nicht gefunden)."
|
"External reference omitted: users.user with {'username': 'lke'} (not found)."
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@@ -66,7 +66,7 @@ def test_ambiguous_external_reference_is_omitted():
|
|||||||
assert value is MISSING_REFERENCE
|
assert value is MISSING_REFERENCE
|
||||||
assert available is True
|
assert available is True
|
||||||
assert warnings == [
|
assert warnings == [
|
||||||
"Externe Referenz ausgelassen: users.group mit {'name': 'NetBox'} (nicht eindeutig)."
|
"External reference omitted: users.group with {'name': 'NetBox'} (not unique)."
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@@ -84,8 +84,8 @@ def test_reference_to_skipped_record_is_omitted_and_warned_once():
|
|||||||
assert second_available is True
|
assert second_available is True
|
||||||
assert warnings == [
|
assert warnings == [
|
||||||
(
|
(
|
||||||
"dcim.rackreservation:17 (dcim.rackreservation) wurde wegen fehlender "
|
"dcim.rackreservation:17 (dcim.rackreservation) was skipped because of a missing "
|
||||||
"Pflichtreferenz übersprungen: user."
|
"required reference: user."
|
||||||
),
|
),
|
||||||
"Referenzen auf das übersprungene Objekt dcim.rackreservation:17 wurden ausgelassen.",
|
"References to the skipped object dcim.rackreservation:17 were omitted.",
|
||||||
]
|
]
|
||||||
Reference in new issue
Block a user