From 7acf9639f65972a66a1ec6d7db623e02832271c6 Mon Sep 17 00:00:00 2001
From: Samuel Gaist <samuel.gaist@idiap.ch>
Date: Fri, 11 Sep 2020 15:01:34 +0200
Subject: [PATCH] [ui][templatetags] Pre-commit cleanup

---
 beat/web/ui/templatetags/fingerprint.py |  12 +-
 beat/web/ui/templatetags/gravatar.py    |  21 +-
 beat/web/ui/templatetags/markup.py      |  55 ++--
 beat/web/ui/templatetags/ui_tags.py     | 358 +++++++++++++-----------
 4 files changed, 242 insertions(+), 204 deletions(-)

diff --git a/beat/web/ui/templatetags/fingerprint.py b/beat/web/ui/templatetags/fingerprint.py
index 4d0e69db7..0028cf9e8 100644
--- a/beat/web/ui/templatetags/fingerprint.py
+++ b/beat/web/ui/templatetags/fingerprint.py
@@ -26,30 +26,28 @@
 ###############################################################################
 
 from django import template
-from django.templatetags.static import StaticNode
 from django.contrib.staticfiles.storage import staticfiles_storage
+from django.templatetags.static import StaticNode
 
 from ... import __version__
 
-
 register = template.Library()
 
 
-#--------------------------------------------------
+# --------------------------------------------------
 
 
 class FingerprintedFilesNode(StaticNode):
-
     def url(self, context):
         path = self.path.resolve(context)
         url = staticfiles_storage.url(path)
-        return url + '?v' + __version__
+        return url + "?v" + __version__
 
 
-#--------------------------------------------------
+# --------------------------------------------------
 
 
-@register.tag('fingerprint')
+@register.tag("fingerprint")
 def do_fingerprint(parser, token):
     """
     A template tag that returns the URL to a file
diff --git a/beat/web/ui/templatetags/gravatar.py b/beat/web/ui/templatetags/gravatar.py
index 8eac267e5..6b50b7aae 100644
--- a/beat/web/ui/templatetags/gravatar.py
+++ b/beat/web/ui/templatetags/gravatar.py
@@ -25,17 +25,16 @@
 #                                                                             #
 ###############################################################################
 
-from django.conf import settings
-from django import template
-from django.template.defaultfilters import stringfilter
-
 import hashlib
 
+from django import template
+from django.conf import settings
+from django.template.defaultfilters import stringfilter
 
 register = template.Library()
 
 
-#--------------------------------------------------
+# --------------------------------------------------
 
 
 @stringfilter
@@ -43,13 +42,13 @@ def gravatar_hash(email):
     """ Computes the hash of an e-mail address to be recognized by gravatar.com
     """
     to_hash = email.lower().encode("utf-8")
-    return hashlib.md5(to_hash).hexdigest()
+    return hashlib.md5(to_hash).hexdigest()  # nosec: B303
 
 
-register.filter('gravatar_hash', gravatar_hash)
+register.filter("gravatar_hash", gravatar_hash)
 
 
-#--------------------------------------------------
+# --------------------------------------------------
 
 
 @stringfilter
@@ -57,9 +56,9 @@ def gravatar_url(email):
     """ Returns the Gravatar URL of an e-mail address
     """
     if settings.USE_HTTPS_GRAVATAR:
-        return 'https://secure.gravatar.com/avatar/' + gravatar_hash(email)
+        return "https://secure.gravatar.com/avatar/" + gravatar_hash(email)
     else:
-        return 'http://www.gravatar.com/avatar/' + gravatar_hash(email)
+        return "http://www.gravatar.com/avatar/" + gravatar_hash(email)
 
 
-register.filter('gravatar_url', gravatar_url)
+register.filter("gravatar_url", gravatar_url)
diff --git a/beat/web/ui/templatetags/markup.py b/beat/web/ui/templatetags/markup.py
index c37ea1e30..ca4adf130 100644
--- a/beat/web/ui/templatetags/markup.py
+++ b/beat/web/ui/templatetags/markup.py
@@ -36,18 +36,19 @@ markup syntaxes to HTML; currently there is support for:
 
 Source copied from: https://github.com/django/django/blob/stable/1.5.x/django/contrib/markup/templatetags/markup.py
 """
-
 from django import template
 from django.conf import settings
-from django.utils.encoding import force_bytes, force_text
-from django.utils.safestring import mark_safe
 from django.template.defaultfilters import stringfilter
+from django.utils.encoding import force_bytes
+from django.utils.encoding import force_text
+from django.utils.safestring import mark_safe
 
 register = template.Library()
 
+
 @register.filter(is_safe=True)
 @stringfilter
-def markdown(value, arg=''):
+def markdown(value, arg=""):
     """
     Runs Markdown over a given value, optionally using various
     extensions python-markdown supports.
@@ -68,31 +69,34 @@ def markdown(value, arg=''):
         import markdown
     except ImportError:
         if settings.DEBUG:
-            raise template.TemplateSyntaxError("Error in 'markdown' filter: The Python markdown library isn't installed.")
+            raise template.TemplateSyntaxError(
+                "Error in 'markdown' filter: The Python markdown library isn't installed."
+            )
         return force_text(value)
     else:
         markdown_vers = getattr(markdown, "version_info", 0)
         if markdown_vers < (2, 1):
             if settings.DEBUG:
                 raise template.TemplateSyntaxError(
-                    "Error in 'markdown' filter: Django does not support versions of the Python markdown library < 2.1.")
+                    "Error in 'markdown' filter: Django does not support versions of the Python markdown library < 2.1."
+                )
             return force_text(value)
         else:
             extensions = [e for e in arg.split(",") if e]
             if extensions and extensions[0] == "safe":
                 extensions = extensions[1:]
-                return mark_safe(markdown.markdown(
-                    force_text(value),
-                    extensions,
-                    safe_mode=True,
-                    enable_attributes=False,
-                ))
+                return mark_safe(  # nosec: B703
+                    markdown.markdown(
+                        force_text(value),
+                        extensions,
+                        safe_mode=True,
+                        enable_attributes=False,
+                    )
+                )
             else:
-                return mark_safe(markdown.markdown(
-                    force_text(value),
-                    extensions,
-                    safe_mode=False,
-                ))
+                return mark_safe(  # nosec: B703
+                    markdown.markdown(force_text(value), extensions, safe_mode=False,)
+                )
 
 
 @register.filter(is_safe=True)
@@ -102,12 +106,21 @@ def restructuredtext(value, full=False):
         from docutils.core import publish_parts
     except ImportError:
         if settings.DEBUG:
-            raise template.TemplateSyntaxError("Error in 'restructuredtext' filter: The Python docutils library isn't installed.")
+            raise template.TemplateSyntaxError(
+                "Error in 'restructuredtext' filter: The Python docutils library isn't installed."
+            )
         return force_text(value)
     else:
         docutils_settings = getattr(settings, "RESTRUCTUREDTEXT_FILTER_SETTINGS", {})
-        parts = publish_parts(source=force_bytes(value), writer_name="html4css1", settings_overrides=docutils_settings)
+        parts = publish_parts(
+            source=force_bytes(value),
+            writer_name="html4css1",
+            settings_overrides=docutils_settings,
+        )
+
         if full:
-            return mark_safe(force_text(parts["html_body"])) #with h1 title
+            text = parts["html_body"]  # with h1 title
         else:
-            return mark_safe(force_text(parts["fragment"])) #contains no title
+            text = parts["fragment"]  # contains no title
+
+        return mark_safe(force_text(text))  # nosec: B703
diff --git a/beat/web/ui/templatetags/ui_tags.py b/beat/web/ui/templatetags/ui_tags.py
index 27027d0bb..b3f10dab2 100644
--- a/beat/web/ui/templatetags/ui_tags.py
+++ b/beat/web/ui/templatetags/ui_tags.py
@@ -25,120 +25,123 @@
 #                                                                             #
 ###############################################################################
 
+import json
+from collections import OrderedDict
+
 from django import template
 from django.conf import settings
 from django.utils.html import format_html
-from ...common.texts import Messages as Texts
-from ... import __version__
-from collections import OrderedDict
 
-import json
+from ... import __version__
+from ...common.texts import Messages as Texts
 
 register = template.Library()
 
 
-#--------------------------------------------------
+# --------------------------------------------------
 
 
-@register.inclusion_tag('ui/bar.html', takes_context=True)
+@register.inclusion_tag("ui/bar.html", takes_context=True)
 def navbar(context):
     return {
-        'request': context['request'],
-        'documentation_link': settings.DOCUMENTATION_LINK,
-        'public_urls': [
-            ('experiments', 'experiments:public-list'),
-          (False, ''),
-          ('toolchains', 'toolchains:public-list'),
-          ('algorithms', 'algorithms:public-list'),
-          ('libraries', 'libraries:public-list'),
-          ('dataformats', 'dataformats:public-list'),
-          (False, ''),
-          ('attestations', 'attestations:public-list'),
-          ('reports', 'reports:public-list'),
-          ('searches', 'search:public-list'),
-          ('teams', 'teams:public-list'),
-          ('plotterparameters', 'plotters:plotterparameter-public-list'),
-          (False, ''),
-          ('databases', 'databases:list'),
-          ('environments', 'backend:list-environments'),
-          ('plotters', 'plotters:list'),
-          #('plotterparameters', 'plotters:plotterparameter-public-list'),
+        "request": context["request"],
+        "documentation_link": settings.DOCUMENTATION_LINK,
+        "public_urls": [
+            ("experiments", "experiments:public-list"),
+            (False, ""),
+            ("toolchains", "toolchains:public-list"),
+            ("algorithms", "algorithms:public-list"),
+            ("libraries", "libraries:public-list"),
+            ("dataformats", "dataformats:public-list"),
+            (False, ""),
+            ("attestations", "attestations:public-list"),
+            ("reports", "reports:public-list"),
+            ("searches", "search:public-list"),
+            ("teams", "teams:public-list"),
+            ("plotterparameters", "plotters:plotterparameter-public-list"),
+            (False, ""),
+            ("databases", "databases:list"),
+            ("environments", "backend:list-environments"),
+            ("plotters", "plotters:list"),
+            # ('plotterparameters', 'plotters:plotterparameter-public-list'),
         ],
-        'user_urls': [
-            ('experiments', 'experiments:list', True),
-          (False, '', False),
-          ('toolchains', 'toolchains:list', True),
-          ('algorithms', 'algorithms:list', True),
-          ('libraries', 'libraries:list', True),
-          ('dataformats', 'dataformats:list', True),
-          (False, '', False),
-          ('attestations', 'attestations:list', True),
-          ('reports', 'reports:list', True),
-          ('searches', 'search:list', True),
-          ('teams', 'teams:list', True),
-          ('plotterparameters', 'plotters:plotterparameter-list', True),
-          (False, '', False),
-          ('databases', 'databases:list', False),
-          ('environments', 'backend:list-environments', False),
-          ('plotters', 'plotters:list', False),
-          #('plotterparameters', 'plotters:plotterparameter-list', True),
+        "user_urls": [
+            ("experiments", "experiments:list", True),
+            (False, "", False),
+            ("toolchains", "toolchains:list", True),
+            ("algorithms", "algorithms:list", True),
+            ("libraries", "libraries:list", True),
+            ("dataformats", "dataformats:list", True),
+            (False, "", False),
+            ("attestations", "attestations:list", True),
+            ("reports", "reports:list", True),
+            ("searches", "search:list", True),
+            ("teams", "teams:list", True),
+            ("plotterparameters", "plotters:plotterparameter-list", True),
+            (False, "", False),
+            ("databases", "databases:list", False),
+            ("environments", "backend:list-environments", False),
+            ("plotters", "plotters:list", False),
+            # ('plotterparameters', 'plotters:plotterparameter-list', True),
         ],
     }
 
 
-#--------------------------------------------------
+# --------------------------------------------------
 
 
-@register.inclusion_tag('ui/contribution_breadcrumb.html', takes_context=True)
+@register.inclusion_tag("ui/contribution_breadcrumb.html", takes_context=True)
 def contribution_breadcrumb(context, obj):
     name_plural = obj.get_verbose_name_plural()
     return {
-        'request': context['request'],
-            'object': obj,
-            'name_plural': name_plural,
-            'listurl': name_plural + ':list',
-            'public_listurl': name_plural + ':public-list',
-            'viewurl': name_plural + ':view-latest',
+        "request": context["request"],
+        "object": obj,
+        "name_plural": name_plural,
+        "listurl": name_plural + ":list",
+        "public_listurl": name_plural + ":public-list",
+        "viewurl": name_plural + ":view-latest",
     }
 
 
-#--------------------------------------------------
+# --------------------------------------------------
 
 
-@register.inclusion_tag('ui/contribution_breadcrumb_plotter.html', takes_context=True)
+@register.inclusion_tag("ui/contribution_breadcrumb_plotter.html", takes_context=True)
 def contribution_breadcrumb_plotter(context, obj):
     name_plural = obj.get_verbose_name_plural()
     return {
-        'request': context['request'],
-            'object': obj,
-            'name_plural': name_plural,
-            'listurl': name_plural + ':list',
-            'public_listurl': name_plural + ':list',
-            'viewurl': name_plural + ':plotter-view-latest',
+        "request": context["request"],
+        "object": obj,
+        "name_plural": name_plural,
+        "listurl": name_plural + ":list",
+        "public_listurl": name_plural + ":list",
+        "viewurl": name_plural + ":plotter-view-latest",
     }
 
 
-#--------------------------------------------------
+# --------------------------------------------------
 
 
-@register.inclusion_tag('ui/contribution_breadcrumb_plotterparameter.html', takes_context=True)
+@register.inclusion_tag(
+    "ui/contribution_breadcrumb_plotterparameter.html", takes_context=True
+)
 def contribution_breadcrumb_plotterparameter(context, obj):
-    name_plural = 'plotterparameters'
-    name_url = 'plotters'
+    name_plural = "plotterparameters"
+    name_url = "plotters"
     return {
-        'request': context['request'],
-            'object': obj,
-            'name_plural': name_plural,
-            'listurl': name_url + ':plotterparameter-list',
-            'public_listurl': name_url + ':plotterparameter-public-list',
-            'viewurl': name_url + ':plotterparameter-view-latest',
+        "request": context["request"],
+        "object": obj,
+        "name_plural": name_plural,
+        "listurl": name_url + ":plotterparameter-list",
+        "public_listurl": name_url + ":plotterparameter-public-list",
+        "viewurl": name_url + ":plotterparameter-view-latest",
     }
 
 
-#--------------------------------------------------
+# --------------------------------------------------
 
 
-@register.inclusion_tag('ui/filter_script.html')
+@register.inclusion_tag("ui/filter_script.html")
 def filter_script(panel_id, text_filter_id, privacy_filter_id):
     return dict(
         panel_id=panel_id,
@@ -147,170 +150,192 @@ def filter_script(panel_id, text_filter_id, privacy_filter_id):
     )
 
 
-#--------------------------------------------------
+# --------------------------------------------------
 
 
-@register.inclusion_tag('ui/smart_selector.html')
+@register.inclusion_tag("ui/smart_selector.html")
 def smart_selector(id):
-    return { 'panel_id': id,
-           }
+    return {
+        "panel_id": id,
+    }
 
 
-#--------------------------------------------------
+# --------------------------------------------------
 
 
-@register.inclusion_tag('ui/tabs.html', takes_context=True)
+@register.inclusion_tag("ui/tabs.html", takes_context=True)
 def list_tabs(context, user, tab):
-    name = 'list' if not user.is_anonymous else 'public-list'
+    name = "list" if not user.is_anonymous else "public-list"
     return dict(
-        request=context['request'],
+        request=context["request"],
         user=user,
         tab=tab,
-
-        #tab name -> list url mappings
-            user_tabs=OrderedDict([
-                ('experiments', 'experiments:' + name),
-              (False, ''),
-              ('toolchains', 'toolchains:' + name),
-              ('algorithms', 'algorithms:' + name),
-              ('libraries', 'libraries:' + name),
-              ('dataformats', 'dataformats:' + name),
-              (None, ''), #note it has to be different as this is a dictionary!
-              ('attestations', 'attestations:' + name),
-              ('reports', 'reports:' + name),
-              ('searches', 'search:' + name),
-              ('teams', 'teams:' + name),
-              ('plotterparameters', 'plotters:plotterparameter-' + name),
-            ]),
-            system_tabs=OrderedDict([
-                ('databases', 'databases:list'),
-              ('environments', 'backend:list-environments'),
-              ('plotters', 'plotters:list'),
-            ]),
+        # tab name -> list url mappings
+        user_tabs=OrderedDict(
+            [
+                ("experiments", "experiments:" + name),
+                (False, ""),
+                ("toolchains", "toolchains:" + name),
+                ("algorithms", "algorithms:" + name),
+                ("libraries", "libraries:" + name),
+                ("dataformats", "dataformats:" + name),
+                (None, ""),  # note it has to be different as this is a dictionary!
+                ("attestations", "attestations:" + name),
+                ("reports", "reports:" + name),
+                ("searches", "search:" + name),
+                ("teams", "teams:" + name),
+                ("plotterparameters", "plotters:plotterparameter-" + name),
+            ]
+        ),
+        system_tabs=OrderedDict(
+            [
+                ("databases", "databases:list"),
+                ("environments", "backend:list-environments"),
+                ("plotters", "plotters:list"),
+            ]
+        ),
     )
 
 
-#--------------------------------------------------
+# --------------------------------------------------
 
 
-@register.inclusion_tag('ui/list_selector.html')
+@register.inclusion_tag("ui/list_selector.html")
 def list_selector(id):
-    return { 'panel_id': id,
-           }
+    return {
+        "panel_id": id,
+    }
 
 
-#--------------------------------------------------
+# --------------------------------------------------
 
 
-@register.inclusion_tag('ui/multiple_selector.html')
+@register.inclusion_tag("ui/multiple_selector.html")
 def multiple_selector(id):
-    return { 'panel_id': id,
-           }
+    return {
+        "panel_id": id,
+    }
 
 
-#--------------------------------------------------
+# --------------------------------------------------
 
 
-@register.inclusion_tag('ui/doc_editor.html', takes_context=True)
+@register.inclusion_tag("ui/doc_editor.html", takes_context=True)
 def doc_editor(context, obj, url_name, editable=True):
     return {
-        'request': context['request'],
-             'owner': obj.author == context['request'].user,
-             'object': obj,
-             'url_name': url_name,
-             'texts': Texts,
-             'editable': editable,
+        "request": context["request"],
+        "owner": obj.author == context["request"].user,
+        "object": obj,
+        "url_name": url_name,
+        "texts": Texts,
+        "editable": editable,
     }
 
 
-#--------------------------------------------------
+# --------------------------------------------------
 
 
-@register.inclusion_tag('ui/history.html', takes_context=True)
+@register.inclusion_tag("ui/history.html", takes_context=True)
 def history(context, plural, obj, panel_id, height):
     return {
-        'plural': plural,
-             'object': obj,
-             'history': obj.json_history(context['request'].user),
-             'panel_id': panel_id,
-             'height': height,
-             'URL_PREFIX': context['URL_PREFIX'],
+        "plural": plural,
+        "object": obj,
+        "history": obj.json_history(context["request"].user),
+        "panel_id": panel_id,
+        "height": height,
+        "URL_PREFIX": context["URL_PREFIX"],
     }
 
 
-#--------------------------------------------------
+# --------------------------------------------------
 
 
 @register.simple_tag
 def code_editor_scripts(modes):
     js = [
-        'lib/codemirror.js',
-        'addon/fold/brace-fold.js',
-        'addon/fold/foldcode.js',
-        'addon/fold/foldgutter.js',
-        'addon/fold/indent-fold.js',
-        'addon/mode/overlay.js',
-        'addon/search/search.js',
-        'addon/search/searchcursor.js',
-        'addon/dialog/dialog.js',
-        'addon/display/rulers.js',
+        "lib/codemirror.js",
+        "addon/fold/brace-fold.js",
+        "addon/fold/foldcode.js",
+        "addon/fold/foldgutter.js",
+        "addon/fold/indent-fold.js",
+        "addon/mode/overlay.js",
+        "addon/search/search.js",
+        "addon/search/searchcursor.js",
+        "addon/dialog/dialog.js",
+        "addon/display/rulers.js",
     ]
 
     # adds mode-related CodeMirror plugins
-    js += ['mode/%s/%s.js' % (k,k) for k in modes.split(',')]
+    js += ["mode/%s/%s.js" % (k, k) for k in modes.split(",")]
 
     # sets include path
-    js = ['%s/%s' % (settings.CODEMIRROR_PATH, k) for k in js]
+    js = ["%s/%s" % (settings.CODEMIRROR_PATH, k) for k in js]
 
     # inserts the CodeMirror editor defaults
     js.append("ui/js/codemirror-defaults.js")
 
-    js = ['<script src="%s%s?v%s" type="text/javascript" charset="utf-8"></script>' % (settings.STATIC_URL, k, __version__) for k in js]
+    js = [
+        '<script src="%s%s?v%s" type="text/javascript" charset="utf-8"></script>'
+        % (settings.STATIC_URL, k, __version__)
+        for k in js
+    ]
 
-    return format_html('\n'.join(js))
+    return format_html("\n".join(js))
 
 
-#--------------------------------------------------
+# --------------------------------------------------
 
 
 @register.simple_tag
 def code_editor_css():
     css = [
-        '%s/lib/codemirror.css' % settings.CODEMIRROR_PATH,
-        '%s/addon/fold/foldgutter.css' % settings.CODEMIRROR_PATH,
-        'ui/css/codemirror-overrides.css',
+        "%s/lib/codemirror.css" % settings.CODEMIRROR_PATH,
+        "%s/addon/fold/foldgutter.css" % settings.CODEMIRROR_PATH,
+        "ui/css/codemirror-overrides.css",
     ]
 
-    if settings.CODEMIRROR_THEME != 'default':
-        css.append('%s/theme/%s.css' % (settings.CODEMIRROR_PATH, settings.CODEMIRROR_THEME))
-
-    return format_html('\n'.join(map(lambda x: '<link rel="stylesheet" href="%s%s?v%s" type="text/css" media="screen" />' % (settings.STATIC_URL, x, __version__), css)))
+    if settings.CODEMIRROR_THEME != "default":
+        css.append(
+            "%s/theme/%s.css" % (settings.CODEMIRROR_PATH, settings.CODEMIRROR_THEME)
+        )
+
+    return format_html(
+        "\n".join(
+            map(
+                lambda x: '<link rel="stylesheet" href="%s%s?v%s" type="text/css" media="screen" />'
+                % (settings.STATIC_URL, x, __version__),
+                css,
+            )
+        )
+    )
 
 
-#--------------------------------------------------
+# --------------------------------------------------
 
 
-@register.inclusion_tag('ui/save_as_dialog.html')
+@register.inclusion_tag("ui/save_as_dialog.html")
 def save_as_dialog(id):
-    return { 'dialog_id': id,
-             'URL_PREFIX': settings.URL_PREFIX,
-           }
+    return {
+        "dialog_id": id,
+        "URL_PREFIX": settings.URL_PREFIX,
+    }
 
 
-#--------------------------------------------------
+# --------------------------------------------------
 
 
-@register.inclusion_tag('ui/messages.html')
+@register.inclusion_tag("ui/messages.html")
 def messages(request):
     """Sets-up the HTML for message display"""
     from django.contrib import messages as django_messages
+
     return dict(
         messages=django_messages.get_messages(request),
         DEFAULT_MESSAGE_LEVELS=django_messages.DEFAULT_LEVELS,
     )
 
 
-#--------------------------------------------------
+# --------------------------------------------------
 
 
 @register.filter
@@ -319,29 +344,32 @@ def join_by(the_list, attr_or_method):
 
     def _getval(o, n):
         attr = getattr(o, n)
-        if hasattr(attr, '__call__'): return attr()
-        else: return attr
+        if hasattr(attr, "__call__"):
+            return attr()
+        else:
+            return attr
 
-    return ", ".join(unicode(_getval(i, attr_or_method)) for i in the_list)
+    return ", ".join(str(_getval(i, attr_or_method)) for i in the_list)
 
 
-#--------------------------------------------------
+# --------------------------------------------------
 
 
 @register.filter
 def getkey(mapping, key):
     """Returns the given dictionary key (useful in templates)"""
-    return mapping.get(key, '')
+    return mapping.get(key, "")
 
 
-#--------------------------------------------------
+# --------------------------------------------------
 
 
 @register.filter
 def split_fullname(s):
-    return s.split('/')
+    return s.split("/")
+
 
-#----------------------------------------------------------------
+# ----------------------------------------------------------------
 
 
 @register.filter
@@ -352,7 +380,7 @@ def get_item(mapping, key):
         if key in data.keys():
             output_value = json.dumps(data[key])
 
-    except:
+    except Exception:
         output_value = ""
 
     return output_value
-- 
GitLab