This is an automated email from the ASF dual-hosted git repository.

sbp pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tooling-trusted-release.git


The following commit(s) were added to refs/heads/main by this push:
     new 9c252a5  Add a route checker lint script and fix the issues that it 
reported
9c252a5 is described below

commit 9c252a54c8b43e7a376edc90a9a4e1e7a5ed1986
Author: Sean B. Palmer <[email protected]>
AuthorDate: Thu Mar 27 18:40:05 2025 +0200

    Add a route checker lint script and fix the issues that it reported
---
 .pre-commit-config.yaml             |   7 ++
 atr/routes/candidate.py             |   6 ++
 atr/routes/modules.py               |  46 +++++++++++++
 atr/templates/candidate-vote.html   |   2 +-
 atr/templates/draft-tools.html      |   4 +-
 atr/templates/preview-review.html   |   2 +-
 atr/templates/release-review.html   |   4 +-
 scripts/lint/jinja_route_checker.py | 131 ++++++++++++++++++++++++++++++++++++
 8 files changed, 196 insertions(+), 6 deletions(-)

diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 862b0c7..905ad55 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -77,3 +77,10 @@ repos:
       require_serial: true
       types: [python]
       exclude: "tests"
+    - id: jinja-route-check
+      name: Jinja Route Checker
+      description: Check whether routes used in Jinja2 templates actually exist
+      entry: poetry run python scripts/lint/jinja_route_checker.py
+      language: system
+      pass_filenames: false
+      always_run: true
diff --git a/atr/routes/candidate.py b/atr/routes/candidate.py
index be62fe5..8456f71 100644
--- a/atr/routes/candidate.py
+++ b/atr/routes/candidate.py
@@ -160,6 +160,12 @@ async def create(session: routes.CommitterSession) -> 
response.Response | str:
     )
 
 
[email protected]("/candidate/delete", methods=["POST"])
+async def delete(session: routes.CommitterSession) -> response.Response:
+    """Delete a release candidate."""
+    return await session.redirect(vote, error="Not yet implemented")
+
+
 @routes.committer("/candidate/vote")
 async def vote(session: routes.CommitterSession) -> str:
     """Show all release candidates to which the user has access."""
diff --git a/atr/routes/modules.py b/atr/routes/modules.py
index 7a4f972..109814c 100644
--- a/atr/routes/modules.py
+++ b/atr/routes/modules.py
@@ -26,3 +26,49 @@ import atr.routes.preview as preview
 import atr.routes.projects as projects
 import atr.routes.release as release
 import atr.routes.root as root
+
+
+# Export data for a custom linter script
+def _export_routes() -> None:
+    import asyncio
+
+    async def _export_routes_async() -> None:
+        """Export all routes to a JSON file for static analysis."""
+        import json
+        import sys
+
+        import aiofiles
+
+        route_paths: list[str] = []
+        current_module = sys.modules[__name__]
+
+        for module_name in dir(current_module):
+            if module_name.startswith("_"):
+                # Not intended for external use
+                continue
+
+            module = getattr(current_module, module_name)
+            if not hasattr(module, "__file__"):
+                # Not a module
+                continue
+
+            # Get all callable interfaces that do not begin with an underscore
+            for attr_name in dir(module):
+                if attr_name.startswith("_"):
+                    # Not intended for external use
+                    continue
+                if not callable(getattr(module, attr_name)):
+                    # Not callable
+                    continue
+                route_path = f"{module_name}.{attr_name}"
+                route_paths.append(route_path)
+
+        async with aiofiles.open("routes.json", "w", encoding="utf-8") as f:
+            await f.write(json.dumps(route_paths, indent=2))
+
+    loop = asyncio.get_event_loop()
+    loop.run_until_complete(_export_routes_async())
+
+
+_export_routes()
+del _export_routes
diff --git a/atr/templates/candidate-vote.html 
b/atr/templates/candidate-vote.html
index ae107c2..d6a80c9 100644
--- a/atr/templates/candidate-vote.html
+++ b/atr/templates/candidate-vote.html
@@ -42,7 +42,7 @@
           </div>
           <div class="d-flex gap-3 align-items-center pt-2">
             <form method="post"
-                  action="{{ as_url(routes.release.delete) }}"
+                  action="{{ as_url(routes.candidate.delete) }}"
                   class="d-inline-block m-0">
               <input type="hidden" name="candidate_name" value="{{ 
candidate.name }}" />
               <button type="submit"
diff --git a/atr/templates/draft-tools.html b/atr/templates/draft-tools.html
index 41ea9ca..ba124b0 100644
--- a/atr/templates/draft-tools.html
+++ b/atr/templates/draft-tools.html
@@ -35,12 +35,12 @@
   </div>
   <div class="d-flex gap-2 mb-4">
     <form method="post"
-          action="{{ as_url(routes.draft.generate_hash, 
project_name=project_name, version_name=version_name, file_path=file_path) }}">
+          action="{{ as_url(routes.draft.hashgen, project_name=project_name, 
version_name=version_name, file_path=file_path) }}">
       <input type="hidden" name="hash_type" value="sha256" />
       <button type="submit" class="btn btn-outline-secondary">Generate 
SHA256</button>
     </form>
     <form method="post"
-          action="{{ as_url(routes.draft.generate_hash, 
project_name=project_name, version_name=version_name, file_path=file_path) }}">
+          action="{{ as_url(routes.draft.hashgen, project_name=project_name, 
version_name=version_name, file_path=file_path) }}">
       <input type="hidden" name="hash_type" value="sha512" />
       <button type="submit" class="btn btn-outline-secondary">Generate 
SHA512</button>
     </form>
diff --git a/atr/templates/preview-review.html 
b/atr/templates/preview-review.html
index 32985a4..c58c0ed 100644
--- a/atr/templates/preview-review.html
+++ b/atr/templates/preview-review.html
@@ -41,7 +41,7 @@
           </div>
           <!--
           <div class="d-flex gap-3 align-items-center pt-2">
-            <a class="btn btn-primary" href="[[ 
as_url(routes.preview.review_detail, preview_id=preview.id) ]]">Review 
preview</a>
+            <a class="btn btn-primary" href="[[ 
as_url{routes.preview.review_detail, preview_id=preview.id} ]]">Review 
preview</a>
           </div>
           -->
         </div>
diff --git a/atr/templates/release-review.html 
b/atr/templates/release-review.html
index 3a42ea6..5e59c75 100644
--- a/atr/templates/release-review.html
+++ b/atr/templates/release-review.html
@@ -24,7 +24,7 @@
 {% endblock stylesheets %}
 
 {% block content %}
-  <h1>Release previews</h1>
+  <h1>Releases</h1>
 
   {% if releases %}
     {% for release in releases %}
@@ -39,7 +39,7 @@
           </div>
           <!--
           <div class="d-flex gap-3 align-items-center pt-2">
-            <a class="btn btn-primary" href="[[ 
as_url(routes.release.review_detail, release_id=release.id) ]]">Review 
release</a>
+            <a class="btn btn-primary" href="[[ 
as_url{routes.release.review_detail, release_id=release.id} ]]">Review 
release</a>
           </div>
           -->
         </div>
diff --git a/scripts/lint/jinja_route_checker.py 
b/scripts/lint/jinja_route_checker.py
new file mode 100755
index 0000000..bc93d83
--- /dev/null
+++ b/scripts/lint/jinja_route_checker.py
@@ -0,0 +1,131 @@
+#!/usr/bin/env python3
+
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Script to check whether routes used in Jinja2 templates with as_url() 
actually exist."""
+
+import argparse
+import glob
+import json
+import os
+import re
+import sys
+from typing import Final
+
+_AS_URL_PATTERN: Final = re.compile(r"as_url\(routes\.([a-zA-Z0-9_.]+)")
+
+
+class JinjaRouteChecker:
+    """Check whether routes used in Jinja2 templates actually exist."""
+
+    def __init__(self) -> None:
+        self.available_routes: set[str] = set()
+        self.errors: list[tuple[str, str, int]] = []
+
+    def find_project_root(self) -> str:
+        """Find the project root directory."""
+        # Assume we're in a subdirectory somewhere
+        current_dir = os.path.dirname(os.path.abspath(__file__))
+        while current_dir != "/":
+            if os.path.exists(os.path.join(current_dir, "atr")):
+                return current_dir
+            current_dir = os.path.dirname(current_dir)
+        raise RuntimeError("Could not find project root")
+
+    def collect_available_routes(self) -> None:
+        """Collect all available routes from the routes.json file."""
+        project_root = self.find_project_root()
+        routes_file = os.path.join(project_root, "state", "routes.json")
+
+        if not os.path.exists(routes_file):
+            print(f"Note: routes file not found at {routes_file}", 
file=sys.stderr)
+            print("Run the application at least once locally to generate the 
routes file", file=sys.stderr)
+
+            # Raise no error, to avoid making this script mandatory
+            sys.exit()
+
+        with open(routes_file, encoding="utf-8") as f:
+            route_paths = json.load(f)
+        self.available_routes = set(route_paths)
+
+    def check_template_routes(self, template_file: str) -> None:
+        """Check whether routes used in a template exist."""
+        rel_path = os.path.relpath(template_file, self.find_project_root())
+
+        try:
+            with open(template_file, encoding="utf-8") as f:
+                content = f.read()
+
+            # Find all as_url calls with routes
+            for match in _AS_URL_PATTERN.finditer(content):
+                route_path = match.group(1)
+                if route_path not in self.available_routes:
+                    # Get approximate line number
+                    line_number = content[: match.start()].count("\n") + 1
+                    self.errors.append((route_path, rel_path, line_number))
+        except Exception as e:
+            print(f"Error checking {template_file}: {e}", file=sys.stderr)
+            sys.exit(1)
+
+    def check_all_templates(self) -> None:
+        """Check all Jinja2 templates for route usage."""
+        project_root = self.find_project_root()
+
+        # Find all Jinja2 templates
+        template_dir = os.path.join(project_root, "atr", "templates")
+        if not os.path.exists(template_dir):
+            raise RuntimeError(f"Template directory not found at 
{template_dir}")
+
+        template_files = glob.glob(os.path.join(template_dir, "**", "*.html"), 
recursive=True)
+        for template_file in template_files:
+            self.check_template_routes(template_file)
+
+    def report_errors(self) -> None:
+        """Report all errors found."""
+        if not self.errors:
+            print("No errors found")
+            return
+
+        for route_path, template_file, line_number in self.errors:
+            print(f"{template_file}:{line_number}: Route '{route_path}' does 
not exist")
+        print(f"\nTotal errors: {len(self.errors)}")
+
+
+def main() -> None:
+    """Run the checker."""
+    parser = argparse.ArgumentParser(description="Check whether routes used in 
Jinja2 templates exist")
+    parser.add_argument("--verbose", "-v", action="store_true", help="Show 
verbose output")
+    args = parser.parse_args()
+
+    checker = JinjaRouteChecker()
+    checker.collect_available_routes()
+
+    if args.verbose:
+        print(f"Found {len(checker.available_routes)} available routes")
+        for route in sorted(checker.available_routes):
+            print(f"  - {route}")
+
+    checker.check_all_templates()
+    checker.report_errors()
+
+    if checker.errors:
+        sys.exit(1)
+
+
+if __name__ == "__main__":
+    main()


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to