Skip to contentSkip to conversation

layerindex/views: fix publishing layers with multiple branches

PATCH New Tim Orling 1 participant 2 messages Oct 8

lore
Share & tools
lore

Tim Orling

author
#0 lore raw

PATCH 1/2 layerindex/views: fix publishing layers with multiple branches

From: Michael Halstead <[email protected]>

publish_view assumed a layer had exactly one branch: get_object_or_404() on LayerBranch raised MultipleObjectsReturned (HTTP 500) for any layer with more than one, and passing the Branch object rather than its name to reverse() produced a mangled URL when the branch had a short_description.

Collect active maintainers across all of the layer's branches, keyed by email address so the greeting names and the recipient list cannot diverge and the ordering is stable between sends, and list every branch the layer is indexed on in the email body. A layer with no branches or no active maintainers is now published without an email rather than returning 404.

---
 layerindex/views.py                   | 65 ++++++++++++++++-----------
 templates/layerindex/publishemail.txt |  6 ++-
 2 files changed, 44 insertions(+), 27 deletions(-)
layerindex/views.py +39 -26
index c671cc5..4f8e64e 100644
@@ -31,7 +31,7 @@ from django.db.models.query import QuerySet
 from django.db.models.signals import pre_save
 from django.dispatch import receiver
 from django.http import Http404, HttpResponse, HttpResponseRedirect
-from django.shortcuts import get_list_or_404, get_object_or_404, render
+from django.shortcuts import get_object_or_404, render
 from django.template.loader import get_template
 from django.utils.decorators import method_decorator
 from django.utils.html import escape
@@ -376,31 +376,44 @@ def publish_view(request, name):
 
     if getattr(settings, 'SEND_PUBLISH_EMAIL', True):
         layeritem = get_object_or_404(LayerItem, name=name)
-        layerbranch = get_object_or_404(LayerBranch, layer=layeritem)
-        layer_url = request.build_absolute_uri(reverse('layer_item', args=(layerbranch.branch, layeritem.name)))
-        maintainers = get_list_or_404(LayerMaintainer, layerbranch=layerbranch)
-        from_email = settings.SUBMIT_EMAIL_FROM
-        subjecttext = get_template('layerindex/publishemailsubject.txt')
-        bodytext = get_template('layerindex/publishemail.txt')
-        maintainer_names = [m.name for m in maintainers]
-
-        # create subject from subject template
-        d = {
-            'layer_name': layeritem.name,
-            'site_name': request.META['HTTP_HOST'],
-        }
-        subject = subjecttext.render(d).rstrip()
-
-        #create body from body template
-        d = {
-            'maintainers': maintainer_names,
-            'layer_name': layeritem.name,
-            'layer_url': layer_url,
-            'help_contact': _get_help_contact(),
-        }
-        body = bodytext.render(d)
-
-        tasks.send_email.apply_async((subject, body, from_email, [m.email for m in maintainers]))
+        layerbranches = list(LayerBranch.objects.filter(layer=layeritem).select_related('branch'))
+
+        # Collect active maintainers across all branches of this layer, keyed by
+        # email so names and addresses stay in step and the order is stable.
+        maintainers = {}
+        for m in LayerMaintainer.objects.filter(layerbranch__layer=layeritem,
+                                                 status='A').order_by('name', 'email'):
+            maintainers.setdefault(m.email, m.name)
+
+        if layerbranches and maintainers:
+            branch_info = [{'branch': lb.branch.name,
+                             'url': request.build_absolute_uri(
+                                 reverse('layer_item', args=(lb.branch.name, layeritem.name)))}
+                            for lb in layerbranches]
+
+            # Prefer master as the primary link, otherwise the first branch
+            primary = next((b for b in branch_info if b['branch'] == 'master'), branch_info[0])
+
+            from_email = settings.SUBMIT_EMAIL_FROM
+            subjecttext = get_template('layerindex/publishemailsubject.txt')
+            bodytext = get_template('layerindex/publishemail.txt')
+
+            d = {
+                'layer_name': layeritem.name,
+                'site_name': request.META.get('HTTP_HOST', ''),
+            }
+            subject = subjecttext.render(d).rstrip()
+
+            d = {
+                'maintainers': list(maintainers.values()),
+                'layer_name': layeritem.name,
+                'layer_url': primary['url'],
+                'branches': branch_info,
+                'help_contact': _get_help_contact(),
+            }
+            body = bodytext.render(d)
+
+            tasks.send_email.apply_async((subject, body, from_email, list(maintainers.keys())))
 
     return _statuschange(request, name, 'P')
 
templates/layerindex/publishemail.txt +5 -1
index 5d703d8..068eca1 100644
@@ -3,7 +3,11 @@ Hi {{ maintainers|slice:":-1"|join:", "}}{% if maintainers|length > 2 %},{% endi
 You are listed as the {% if maintainers|length > 1 %}maintainers{% else %}maintainer{% endif %} for the new layer, {{ layer_name }}. This layer has now been published. You can view it at the following URL:
 
  {{ layer_url }}
-
+{% if branches|length > 1 %}
+This layer is indexed on the following branches:
+{% for b in branches %}
+ {{ b.branch }} - {{ b.url }}{% endfor %}
+{% endif %}
 If you need to make changes to this layer's entry in the index in the future, create an account (using this email address) if you haven't already, and you should then be able to click on "Edit layer" on the layer's detail page and make the desired changes. If you need any assistance please contact {% if help_contact.first_name and help_contact.last_name %}{{ help_contact.first_name }} {{ help_contact.last_name}}{% else %}{{ help_contact.username }}{% endif %} <{{ help_contact.email }}>.
 
 Thanks!
Signature · 1 line
2.56.0
author
#1 lore raw

PATCH 2/2 Add sitemap using django.contrib.sitemaps

From: Michael Halstead <[email protected]>

Serve /sitemap.xml listing the main branch views and all published, non-comparison layers.

AI-Generated: Claude Sonnet 5.5

---
 docker/settings.py     |  1 +
 layerindex/sitemaps.py | 36 ++++++++++++++++++++++++++++++++++++
 settings.py            |  1 +
 tests/test_sitemap.py  | 38 ++++++++++++++++++++++++++++++++++++++
 urls.py                |  9 +++++++++
 5 files changed, 85 insertions(+)
 create mode 100644 layerindex/sitemaps.py
 create mode 100644 tests/test_sitemap.py
docker/settings.py +1 -0
index e3ae0fd..90bc5f4 100644
@@ -148,6 +148,7 @@ INSTALLED_APPS = (
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.sites',
+    'django.contrib.sitemaps',
     'django.contrib.messages',
     'django.contrib.staticfiles',
     'django.contrib.admin',
layerindex/sitemaps.py new file +36 -0
new file mode 100644
index 0000000..7d6e0ac
@@ -0,0 +1,36 @@
+# layerindex-web - sitemap definitions
+#
+# Licensed under the MIT license, see COPYING.MIT for details
+#
+# SPDX-License-Identifier: MIT
+
+from django.contrib.sitemaps import Sitemap
+from django.urls import reverse
+
+from layerindex.models import LayerItem
+
+BRANCH_VIEWS = ('layer_list', 'recipe_search', 'machine_search', 'distro_search', 'class_search')
+
+
+class StaticViewSitemap(Sitemap):
+    changefreq = 'daily'
+    priority = 0.5
+
+    def items(self):
+        return list(BRANCH_VIEWS) + ['about', 'stats']
+
+    def location(self, item):
+        if item in BRANCH_VIEWS:
+            return reverse(item, args=('master',))
+        return reverse(item)
+
+
+class LayerSitemap(Sitemap):
+    changefreq = 'weekly'
+    priority = 0.8
+
+    def items(self):
+        return LayerItem.objects.filter(status='P', comparison=False).order_by('name')
+
+    def lastmod(self, obj):
+        return obj.updated
settings.py +1 -0
index 94b3dd1..b318687 100644
@@ -148,6 +148,7 @@ INSTALLED_APPS = (
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.sites',
+    'django.contrib.sitemaps',
     'django.contrib.messages',
     'django.contrib.staticfiles',
     'django.contrib.admin',
tests/test_sitemap.py new file +38 -0
new file mode 100644
index 0000000..12b4b87
@@ -0,0 +1,38 @@
+# layerindex-web - tests for sitemap.xml
+#
+# Licensed under the MIT license, see COPYING.MIT for details
+#
+# SPDX-License-Identifier: MIT
+
+import pytest
+from django.test import TestCase
+
+from layerindex.models import LayerItem
+
+
[email protected]_db
+class TestSitemap(TestCase):
+
+    def _layer(self, name, status='P', comparison=False):
+        return LayerItem.objects.create(
+            name=name,
+            status=status,
+            layer_type='A',
+            summary=name,
+            description=name,
+            vcs_url='git://example.com/%s.git' % name,
+            comparison=comparison,
+        )
+
+    def test_sitemap(self):
+        self._layer('meta-published')
+        self._layer('meta-new', status='N')
+        self._layer('meta-compare', comparison=True)
+
+        response = self.client.get('/sitemap.xml')
+        self.assertEqual(response.status_code, 200)
+        content = response.content.decode()
+        self.assertIn('/layerindex/branch/master/layer/meta-published/', content)
+        self.assertIn('/layerindex/about/', content)
+        self.assertNotIn('meta-new', content)
+        self.assertNotIn('meta-compare', content)
urls.py +9 -0
index 295fc0b..4bd5998 100644
@@ -12,13 +12,22 @@ from django.views.generic import RedirectView, TemplateView
 from layerindex.auth_views import CaptchaRegistrationView, CaptchaPasswordResetView, delete_account_view, \
     PasswordResetSecurityQuestions
 from django.contrib import admin
+from django.contrib.sitemaps.views import sitemap
+from layerindex.sitemaps import StaticViewSitemap, LayerSitemap
 admin.autodiscover()
 
 from django.conf import settings
 
+sitemaps = {
+    'static': StaticViewSitemap,
+    'layers': LayerSitemap,
+}
+
 urlpatterns = [
     re_path(r'^layerindex/', include('layerindex.urls')),
     re_path(r'^admin/', admin.site.urls),
+    re_path(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps},
+        name='django.contrib.sitemaps.views.sitemap'),
     re_path(r'^accounts/password_reset/$',
         CaptchaPasswordResetView.as_view(
             email_template_name='registration/password_reset_email.txt',
Signature · 1 line
2.56.0