Forráskód Böngészése

Closes #23724: Record the synced revision on git data sources (#23730)

Jeremy Stretch 13 órája
szülő
commit
e2f6484063

+ 9 - 0
docs/models/core/datasource.md

@@ -54,3 +54,12 @@ The interval at which the data source should automatically synchronize. If not s
 ### Last Synced
 
 The date and time at which the source was most recently synchronized successfully.
+
+### Revision
+
+The revision of the data retrieved by the most recent successful synchronization, if the source's backend can determine one. For git data sources, this is the hash of the head commit. These fields are updated automatically on each synchronization and cannot be set manually.
+
+* **Revision**: The unique identifier of the revision (e.g. a git commit hash)
+* **Revision message**: The message describing the revision
+* **Revision author**: The author of the revision
+* **Revision time**: The date and time at which the revision was made

+ 2 - 0
docs/plugins/development/data-backends.md

@@ -20,4 +20,6 @@ backends = [MyDataBackend]
 !!! tip
     The path to the list of data backends can be modified by setting `data_backends` in the PluginConfig instance.
 
+A backend can optionally implement `get_revision()` to report which revision of the remote data it fetched (for example, a commit hash). NetBox records this on the data source after each synchronization.
+
 ::: netbox.data_backends.DataBackend

+ 2 - 1
netbox/core/api/serializers_/data.py

@@ -27,7 +27,8 @@ class DataSourceSerializer(PrimaryModelSerializer):
         fields = [
             'id', 'url', 'display_url', 'display', 'name', 'type', 'source_url', 'enabled', 'status', 'description',
             'sync_interval', 'parameters', 'ignore_rules', 'owner', 'comments', 'tags', 'custom_fields', 'created',
-            'last_updated', 'last_synced', 'file_count',
+            'last_updated', 'last_synced', 'revision', 'revision_message', 'revision_author', 'revision_time',
+            'file_count',
         ]
         brief_fields = ('id', 'url', 'display', 'name', 'description')
 

+ 13 - 0
netbox/core/data_backends.py

@@ -2,6 +2,7 @@ import logging
 import re
 import tempfile
 from contextlib import contextmanager
+from datetime import UTC, datetime
 from pathlib import Path, PurePosixPath
 from urllib.parse import urlparse
 
@@ -137,6 +138,18 @@ class GitBackend(DataBackend):
 
         local_path.cleanup()
 
+    def get_revision(self, local_path):
+        from dulwich.repo import Repo
+
+        with Repo(local_path) as repo:
+            commit = repo[repo.head()]
+            return {
+                'revision': commit.id.decode('utf-8'),
+                'message': commit.message.decode('utf-8', errors='replace').strip(),
+                'author': commit.author.decode('utf-8', errors='replace'),
+                'time': datetime.fromtimestamp(commit.author_time, tz=UTC),
+            }
+
 
 @register_data_backend()
 class S3Backend(DataBackend):

+ 4 - 1
netbox/core/filtersets.py

@@ -41,7 +41,10 @@ class DataSourceFilterSet(PrimaryModelFilterSet):
 
     class Meta:
         model = DataSource
-        fields = ('id', 'name', 'enabled', 'description', 'source_url', 'last_synced')
+        fields = (
+            'id', 'name', 'enabled', 'description', 'source_url', 'last_synced', 'revision', 'revision_message',
+            'revision_author', 'revision_time',
+        )
 
     def search(self, queryset, name, value):
         if not value.strip():

+ 19 - 0
netbox/core/forms/filtersets.py

@@ -32,6 +32,7 @@ class DataSourceFilterForm(PrimaryModelFilterSetForm):
     fieldsets = (
         FieldSet('q', 'filter_id', 'tag'),
         FieldSet('type', 'status', 'enabled', 'sync_interval', name=_('Data Source')),
+        FieldSet('revision', 'revision_author', 'revision_time__gte', 'revision_time__lte', name=_('Revision')),
         FieldSet('owner_group_id', 'owner_id', name=_('Ownership')),
     )
     type = forms.MultipleChoiceField(
@@ -56,6 +57,24 @@ class DataSourceFilterForm(PrimaryModelFilterSetForm):
         choices=JobIntervalChoices,
         required=False
     )
+    revision = forms.CharField(
+        label=_('Revision'),
+        required=False
+    )
+    revision_author = forms.CharField(
+        label=_('Revision author'),
+        required=False
+    )
+    revision_time__gte = forms.DateTimeField(
+        label=_('Revision time after'),
+        required=False,
+        widget=DateTimePicker()
+    )
+    revision_time__lte = forms.DateTimeField(
+        label=_('Revision time before'),
+        required=False,
+        widget=DateTimePicker()
+    )
     tag = TagFilterField(model)
 
 

+ 4 - 0
netbox/core/graphql/filters.py

@@ -52,6 +52,10 @@ class DataSourceFilter(PrimaryModelFilter):
         strawberry_django.filter_field()
     )
     last_synced: DatetimeFilterLookup | None = strawberry_django.filter_field()
+    revision: StrFilterLookup | None = strawberry_django.filter_field()
+    revision_message: StrFilterLookup | None = strawberry_django.filter_field()
+    revision_author: StrFilterLookup | None = strawberry_django.filter_field()
+    revision_time: DatetimeFilterLookup | None = strawberry_django.filter_field()
     datafiles: Annotated['DataFileFilter', strawberry.lazy('core.graphql.filters')] | None = (
         strawberry_django.filter_field()
     )

+ 33 - 0
netbox/core/migrations/0029_datasource_revision.py

@@ -0,0 +1,33 @@
+# Generated by Django 6.1.3 on 2026-11-17 21:13
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('core', '0028_populate_job_access'),
+    ]
+
+    operations = [
+        migrations.AddField(
+            model_name='datasource',
+            name='revision',
+            field=models.CharField(blank=True, editable=False, max_length=64, null=True),
+        ),
+        migrations.AddField(
+            model_name='datasource',
+            name='revision_author',
+            field=models.CharField(blank=True, editable=False, max_length=200, null=True),
+        ),
+        migrations.AddField(
+            model_name='datasource',
+            name='revision_message',
+            field=models.TextField(blank=True, editable=False, null=True),
+        ),
+        migrations.AddField(
+            model_name='datasource',
+            name='revision_time',
+            field=models.DateTimeField(blank=True, editable=False, null=True),
+        ),
+    ]

+ 68 - 2
netbox/core/models/data.py

@@ -1,6 +1,7 @@
 import hashlib
 import logging
 import os
+import re
 from fnmatch import fnmatchcase
 from urllib.parse import urlparse
 
@@ -82,6 +83,33 @@ class DataSource(JobsMixin, PrimaryModel):
         null=True,
         editable=False
     )
+    revision = models.CharField(
+        verbose_name=_('revision'),
+        max_length=64,
+        blank=True,
+        null=True,
+        editable=False,
+        help_text=_("Identifier of the revision most recently synchronized (e.g. a git commit hash)")
+    )
+    revision_message = models.TextField(
+        verbose_name=_('revision message'),
+        blank=True,
+        null=True,
+        editable=False
+    )
+    revision_author = models.CharField(
+        verbose_name=_('revision author'),
+        max_length=200,
+        blank=True,
+        null=True,
+        editable=False
+    )
+    revision_time = models.DateTimeField(
+        verbose_name=_('revision time'),
+        blank=True,
+        null=True,
+        editable=False
+    )
 
     class Meta:
         ordering = ('name',)
@@ -114,6 +142,15 @@ class DataSource(JobsMixin, PrimaryModel):
     def backend_class(self):
         return registry['data_backends'].get(self.type)
 
+    @property
+    def short_revision(self):
+        """
+        Return the revision abbreviated to seven characters if it's a hash, otherwise unchanged.
+        """
+        if self.revision and re.fullmatch(r'[0-9a-f]{40,64}', self.revision):
+            return self.revision[:7]
+        return self.revision
+
     @property
     def ready_for_sync(self):
         return self.enabled and self.status not in (
@@ -252,19 +289,48 @@ class DataSource(JobsMixin, PrimaryModel):
             created_count = len(DataFile.objects.using(using).bulk_create(new_datafiles, batch_size=100))
             logger.debug(f"Created {created_count} data files")
 
-            # Update status & last_synced time
+            # Update status, last_synced time & revision
             last_synced = timezone.now()
+            revision = self._get_revision(backend, local_path)
             DataSource.objects.using(using).filter(pk=self.pk).update(
-                status=DataSourceStatusChoices.COMPLETED, last_synced=last_synced
+                status=DataSourceStatusChoices.COMPLETED, last_synced=last_synced, **revision
             )
 
         self.status = DataSourceStatusChoices.COMPLETED
         self.last_synced = last_synced
+        for attr, value in revision.items():
+            setattr(self, attr, value)
 
         # Emit the post_sync signal
         post_sync.send(sender=self.__class__, instance=self)
     sync.alters_data = True
 
+    def _get_revision(self, backend, local_path):
+        """
+        Return the revision field values for the data fetched to local_path, or empty values if it can't be determined.
+        """
+        fields = {
+            'revision': 'revision',
+            'revision_message': 'message',
+            'revision_author': 'author',
+            'revision_time': 'time',
+        }
+        try:
+            revision = backend.get_revision(local_path) or {}
+            values = {}
+            for field_name, key in fields.items():
+                field = self._meta.get_field(field_name)
+                value = field.to_python(revision.get(key))
+                if isinstance(value, str):
+                    # Strip NUL characters (which PostgreSQL can't store) and truncate to the field's maximum length
+                    value = value.replace('\x00', '')[:field.max_length]
+                values[field_name] = value
+        except Exception as e:
+            logger.warning(f"Unable to determine the revision of data source {self}: {e}")
+            return dict.fromkeys(fields)
+
+        return values
+
     def _walk(self, root):
         """
         Return a set of all non-excluded files within the root path.

+ 14 - 2
netbox/core/tables/data.py

@@ -5,7 +5,7 @@ from core.models import *
 from netbox.tables import NetBoxTable, PrimaryModelTable, columns
 
 from .columns import BackendTypeColumn
-from .template_code import DATA_SOURCE_SYNC_BUTTON
+from .template_code import DATA_SOURCE_REVISION, DATA_SOURCE_SYNC_BUTTON
 
 __all__ = (
     'DataFileTable',
@@ -33,6 +33,17 @@ class DataSourceTable(PrimaryModelTable):
     last_synced = tables.DateTimeColumn(
         verbose_name=_('Last Synced'),
     )
+    revision = columns.TemplateColumn(
+        verbose_name=_('Revision'),
+        template_code=DATA_SOURCE_REVISION,
+        export_raw=True,
+    )
+    revision_author = tables.Column(
+        verbose_name=_('Revision Author'),
+    )
+    revision_time = columns.DateTimeColumn(
+        verbose_name=_('Revision Time'),
+    )
     file_count = tables.Column(
         verbose_name=_('Files'),
     )
@@ -47,7 +58,8 @@ class DataSourceTable(PrimaryModelTable):
         model = DataSource
         fields = (
             'pk', 'id', 'name', 'type', 'status', 'enabled', 'source_url', 'description', 'sync_interval', 'comments',
-            'parameters', 'last_synced', 'created', 'last_updated', 'file_count',
+            'parameters', 'last_synced', 'revision', 'revision_author', 'revision_time', 'created', 'last_updated',
+            'file_count',
         )
         default_columns = ('pk', 'name', 'type', 'status', 'enabled', 'description', 'sync_interval', 'file_count')
 

+ 4 - 0
netbox/core/tables/template_code.py

@@ -37,6 +37,10 @@ PLUGIN_NAME_TEMPLATE = """
 <a href="{% url 'core:plugin' record.config_name %}">{{ record.title_long }}</a>
 """
 
+DATA_SOURCE_REVISION = """
+{% if value %}<span class="font-monospace" title="{{ value }}">{{ record.short_revision }}</span>{% endif %}
+"""
+
 DATA_SOURCE_SYNC_BUTTON = """
 {% load helpers %}
 {% load i18n %}

+ 13 - 0
netbox/core/tests/test_api.py

@@ -159,6 +159,19 @@ class DataSourceTestCase(APIViewTestCases.APIViewTestCase):
         self.assertHttpStatus(response, status.HTTP_200_OK)
         self.assertEqual(list(data_source.tags.values_list('slug', flat=True)), [])
 
+    def test_revision_fields_read_only(self):
+        """The revision fields are reported but cannot be set via the API."""
+        data_source = DataSource.objects.first()
+        DataSource.objects.filter(pk=data_source.pk).update(revision='abc123', revision_author='Jane Doe')
+        self.add_permissions('core.change_datasource')
+
+        data = {'revision': 'def456', 'revision_author': 'John Doe', 'revision_message': 'Changed'}
+        response = self.client.patch(self._get_detail_url(data_source), data, format='json', **self.header)
+        self.assertHttpStatus(response, status.HTTP_200_OK)
+        self.assertEqual(response.data['revision'], 'abc123')
+        self.assertEqual(response.data['revision_author'], 'Jane Doe')
+        self.assertIsNone(response.data['revision_message'])
+
     @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
     def test_sync(self):
         """

+ 41 - 0
netbox/core/tests/test_data_backends.py

@@ -1,4 +1,5 @@
 import tempfile
+from datetime import UTC, datetime
 from pathlib import Path
 from unittest import skipIf
 from unittest.mock import patch
@@ -119,6 +120,46 @@ class GitBackendCredentialIntegrationTestCase(TestCase):
         self.assertEqual(kwargs.get('password'), None)
 
 
+@skipIf(not DULWICH_AVAILABLE, "dulwich is not installed")
+class GitBackendRevisionTestCase(TestCase):
+
+    def setUp(self):
+        from dulwich import porcelain
+
+        temp_dir = tempfile.TemporaryDirectory()
+        self.addCleanup(temp_dir.cleanup)
+        self.repo_path = Path(temp_dir.name)
+        porcelain.init(str(self.repo_path))
+        for content, message in (('one\n', b'First commit'), ('two\n', b'Second commit\n\nAdd more detail\n')):
+            (self.repo_path / 'file.txt').write_text(content)
+            porcelain.add(str(self.repo_path), [str(self.repo_path / 'file.txt')])
+            self.commit = porcelain.commit(
+                str(self.repo_path),
+                message=message,
+                author=b'Jane Doe <jane@example.com>',
+                committer=b'John Doe <john@example.com>',
+                author_timestamp=1600000000,
+                author_timezone=3600,
+                commit_timestamp=1700000000,
+                commit_timezone=3600,
+            )
+
+    def test_get_revision(self):
+        """The revision describes the head commit of the fetched clone, as of its authoring."""
+        from core.data_backends import GitBackend
+
+        backend = GitBackend(url=self.repo_path.as_uri())
+        with backend.fetch() as local_path:
+            revision = backend.get_revision(local_path)
+
+        self.assertEqual(revision, {
+            'revision': self.commit.decode(),
+            'message': 'Second commit\n\nAdd more detail',
+            'author': 'Jane Doe <jane@example.com>',
+            'time': datetime(2020, 9, 13, 12, 26, 40, tzinfo=UTC),
+        })
+
+
 class S3BackendKeyResolutionTestCase(TestCase):
     """
     Verify that S3Backend resolves object keys to local paths safely, rejecting any

+ 33 - 1
netbox/core/tests/test_filtersets.py

@@ -38,7 +38,11 @@ class DataSourceTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
                 status=DataSourceStatusChoices.SYNCING,
                 enabled=True,
                 description='foobar2',
-                sync_interval=JobIntervalChoices.INTERVAL_DAILY
+                sync_interval=JobIntervalChoices.INTERVAL_DAILY,
+                revision='abcdef0123456789abcdef0123456789abcdef01',
+                revision_message='Add templates',
+                revision_author='John Doe <john@example.com>',
+                revision_time=datetime(2026, 1, 1, 12, 0, tzinfo=UTC),
             ),
             DataSource(
                 name='Data Source 3',
@@ -46,6 +50,10 @@ class DataSourceTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
                 source_url='https://example.com/git/source3',
                 status=DataSourceStatusChoices.COMPLETED,
                 enabled=False,
+                revision='0123456789abcdef0123456789abcdef01234567',
+                revision_message='Update templates',
+                revision_author='Jane Doe <jane@example.com>',
+                revision_time=datetime(2026, 2, 1, 12, 0, tzinfo=UTC),
             ),
         )
         DataSource.objects.bulk_create(data_sources)
@@ -76,6 +84,30 @@ class DataSourceTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
         params = {'status': [DataSourceStatusChoices.NEW, DataSourceStatusChoices.SYNCING]}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
 
+    def test_revision(self):
+        params = {'revision': ['0123456789abcdef0123456789abcdef01234567']}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
+
+    def test_revision_message(self):
+        params = {'revision_message': 'Update templates'}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
+        params = {'revision_message__ic': 'templates'}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
+
+    def test_revision_author(self):
+        params = {'revision_author': ['Jane Doe <jane@example.com>']}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
+        params = {'revision_author__ic': ['doe']}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
+
+    def test_revision_time(self):
+        params = {'revision_time': ['2026-01-01T12:00:00Z']}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
+        params = {'revision_time__gte': ['2026-01-15T00:00:00Z']}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
+        params = {'revision_time__empty': 'true'}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
+
     def test_sync_interval(self):
         params = {'sync_interval': [JobIntervalChoices.INTERVAL_HOURLY, JobIntervalChoices.INTERVAL_DAILY]}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)

+ 96 - 1
netbox/core/tests/test_models.py

@@ -1,7 +1,7 @@
 import tempfile
 import uuid
 from contextlib import contextmanager
-from datetime import timedelta
+from datetime import UTC, datetime, timedelta
 from io import StringIO
 from pathlib import Path
 from unittest.mock import MagicMock, patch
@@ -287,6 +287,101 @@ class DataSourceTestCase(TestCase):
 
         self.assertEqual(dict(self.datasource.datafiles.values_list('path', 'data')), {'a.txt': b'new\n'})
 
+    def test_sync_records_revision(self):
+        """The revision reported by the backend is saved and available to post_sync receivers."""
+        revision = {
+            'revision': '0123456789abcdef0123456789abcdef01234567',
+            'message': 'Update files',
+            'author': 'Jane Doe <jane@example.com>',
+            'time': datetime(2026, 1, 1, 12, 0, tzinfo=UTC),
+        }
+        expected = {
+            'revision': revision['revision'],
+            'revision_message': revision['message'],
+            'revision_author': revision['author'],
+            'revision_time': revision['time'],
+        }
+        received = {}
+
+        def receiver(sender, instance, **kwargs):
+            received.update({field: getattr(instance, field) for field in expected})
+
+        post_sync.connect(receiver)
+        self.addCleanup(post_sync.disconnect, receiver)
+        with patch.object(LocalBackend, 'get_revision', return_value=revision):
+            self.datasource.sync()
+
+        self.assertEqual(received, expected)
+        self.assert_files_synced()
+        for field, value in expected.items():
+            self.assertEqual(getattr(self.datasource, field), value)
+
+    def test_sync_clears_revision_when_backend_reports_none(self):
+        """A backend which reports no revision leaves the revision fields empty."""
+        DataSource.objects.filter(pk=self.datasource.pk).update(
+            revision='abc123', revision_message='Old', revision_author='Jane Doe', revision_time=timezone.now()
+        )
+
+        self.datasource.sync()
+
+        self.assert_files_synced()
+        for field in ('revision', 'revision_message', 'revision_author', 'revision_time'):
+            self.assertIsNone(getattr(self.datasource, field))
+
+    def test_sync_revision_failure_does_not_fail_sync(self):
+        """An error reading the revision is logged, and the sync completes without one."""
+        with patch.object(LocalBackend, 'get_revision', side_effect=ValueError('Simulated revision error')):
+            with self.assertLogs('netbox.core.data', level='WARNING') as logs:
+                self.datasource.sync()
+
+        self.assertIn('Simulated revision error', logs.output[0])
+        self.assert_files_synced()
+        self.assertIsNone(self.datasource.revision)
+
+    def test_sync_discards_invalid_revision(self):
+        """A revision which can't be stored is logged and discarded, and the sync completes without one."""
+        for revision in (['not', 'a', 'dict'], {'revision': 'abc123', 'time': 'not a time'}):
+            with self.subTest(revision=revision):
+                with patch.object(LocalBackend, 'get_revision', return_value=revision):
+                    with self.assertLogs('netbox.core.data', level='WARNING'):
+                        self.datasource.sync()
+
+                self.assert_files_synced()
+                self.assertIsNone(self.datasource.revision)
+
+    def test_sync_strips_nul_characters_from_revision(self):
+        """NUL characters, which PostgreSQL can't store, are removed from the revision values."""
+        revision = {'revision': 'abc\x00123', 'message': 'Update\x00 files', 'author': 'Jane\x00 Doe'}
+        with patch.object(LocalBackend, 'get_revision', return_value=revision):
+            self.datasource.sync()
+
+        self.assert_files_synced()
+        self.assertEqual(self.datasource.revision, 'abc123')
+        self.assertEqual(self.datasource.revision_message, 'Update files')
+        self.assertEqual(self.datasource.revision_author, 'Jane Doe')
+
+    def test_short_revision(self):
+        """Only hash revisions are abbreviated."""
+        for revision, expected in (
+            (None, None),
+            ('0123456789abcdef0123456789abcdef01234567', '0123456'),
+            ('0123456789abcdef' * 4, '0123456'),
+            ('release-2026-01', 'release-2026-01'),
+            ('0123456789ABCDEF0123456789ABCDEF01234567', '0123456789ABCDEF0123456789ABCDEF01234567'),
+        ):
+            with self.subTest(revision=revision):
+                self.assertEqual(DataSource(revision=revision).short_revision, expected)
+
+    def test_sync_truncates_long_revision_values(self):
+        """Revision values longer than their fields are truncated rather than failing the sync."""
+        revision = {'revision': 'a' * 100, 'author': 'b' * 300}
+        with patch.object(LocalBackend, 'get_revision', return_value=revision):
+            self.datasource.sync()
+
+        self.assert_files_synced()
+        self.assertEqual(self.datasource.revision, 'a' * 64)
+        self.assertEqual(self.datasource.revision_author, 'b' * 200)
+
     def test_sync_keeps_paths_repeating_source_root(self):
         """A file below a directory repeating the source root syncs under its full path."""
         # Repeat the whole root string below it, as /scripts/scripts_old does for /scripts

+ 26 - 0
netbox/core/tests/test_views.py

@@ -75,6 +75,32 @@ class DataSourceTestCase(ViewTestCases.PrimaryObjectViewTestCase):
             'description': 'New description',
         }
 
+    def test_revision_display(self):
+        """The detail view shows the abbreviated revision with the full value on hover, and the revision message."""
+        self.add_permissions('core.view_datasource')
+        datasource = DataSource.objects.first()
+        revision = '0123456789abcdef0123456789abcdef01234567'
+        DataSource.objects.filter(pk=datasource.pk).update(
+            revision=revision,
+            revision_message='Update files\n\nAdd more detail',
+            revision_author='Jane Doe <jane@example.com>',
+            revision_time=datetime(2026, 1, 1, 12, 0, tzinfo=UTC),
+        )
+
+        response = self.client.get(datasource.get_absolute_url())
+
+        self.assertHttpStatus(response, 200)
+        self.assertContains(response, f'<span class="font-monospace" title="{revision}">0123456</span>', html=True)
+        self.assertContains(response, 'Update files<br><br>Add more detail')
+        self.assertContains(response, 'Jane Doe &lt;jane@example.com&gt;')
+
+        # A revision which isn't a hash is shown in full
+        DataSource.objects.filter(pk=datasource.pk).update(revision='release-2026-01')
+        response = self.client.get(datasource.get_absolute_url())
+        self.assertContains(
+            response, '<span class="font-monospace" title="release-2026-01">release-2026-01</span>', html=True
+        )
+
     def test_sync_form_submission_guard(self):
         """The Sync form of a ready data source opts into the duplicate submission guard."""
         self.add_permissions('core.view_datasource', 'core.sync_datasource')

+ 12 - 0
netbox/core/ui/panels.py

@@ -15,6 +15,18 @@ class DataSourcePanel(panels.ObjectAttributesPanel):
     status = attrs.ChoiceAttr('status')
     sync_interval = attrs.ChoiceAttr('sync_interval', label=_('Sync interval'))
     last_synced = attrs.DateTimeAttr('last_synced', label=_('Last synced'))
+    revision = attrs.TemplatedAttr(
+        'revision',
+        label=_('Revision'),
+        template_name='core/datasource/attrs/revision.html',
+    )
+    revision_message = attrs.TemplatedAttr(
+        'revision_message',
+        label=_('Revision message'),
+        template_name='core/datasource/attrs/revision_message.html',
+    )
+    revision_author = attrs.TextAttr('revision_author', label=_('Revision author'))
+    revision_time = attrs.DateTimeAttr('revision_time', label=_('Revision time'))
     description = attrs.TextAttr('description')
     source_url = attrs.TemplatedAttr(
         'source_url',

+ 14 - 0
netbox/netbox/data_backends.py

@@ -57,6 +57,20 @@ class DataBackend:
         """
         raise NotImplementedError()
 
+    def get_revision(self, local_path):
+        """
+        Return a dictionary describing the revision of the data fetched to `local_path`, or None if the backend has no
+        concept of revisions. Called during synchronization while the fetched data is still present at `local_path`.
+
+        The dictionary may include any of the following keys:
+
+        - `revision`: A unique identifier for the revision, such as a commit hash (max 64 characters)
+        - `message`: A message describing the revision
+        - `author`: The author of the revision (max 200 characters)
+        - `time`: A timezone-aware datetime indicating when the revision was made
+        """
+        return
+
 
 def get_data_backend_choices():
     return [

+ 5 - 0
netbox/templates/core/datasource/attrs/revision.html

@@ -0,0 +1,5 @@
+{% load i18n %}
+<span class="font-monospace" title="{{ value }}">{{ object.short_revision }}</span>
+<a class="btn btn-sm btn-primary copy-content" data-clipboard-text="{{ value }}" title="{% trans "Copy to clipboard" %}">
+  <i class="mdi mdi-content-copy"></i>
+</a>

+ 1 - 0
netbox/templates/core/datasource/attrs/revision_message.html

@@ -0,0 +1 @@
+{{ value|linebreaksbr }}