You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tooling.apache.org by sb...@apache.org on 2026/09/11 13:45:59 UTC

(tooling-trusted-releases) 01/01: Align cycle patterns to RE2 and match on the server

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

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

commit 0ed47e0e00d211d4d6ce4783aa3789c4f3f4a70d
Author: Sean B. Palmer <se...@miscoranda.com>
AuthorDate: Fri Sep 11 14:43:20 2026 +0100

    Align cycle patterns to RE2 and match on the server
---
 atr/get/start.py                         |  46 +++++++++--
 atr/static/js/src/start-cycle-preview.js | 135 ++++++++-----------------------
 tests/unit/test_start_cycle_preview.py   | 124 ++++++++++++++++++++++++++++
 3 files changed, 196 insertions(+), 109 deletions(-)

diff --git a/atr/get/start.py b/atr/get/start.py
index da2dc3fa..5be33118 100644
--- a/atr/get/start.py
+++ b/atr/get/start.py
@@ -19,8 +19,11 @@ from typing import Literal
 
 import asfquart.base as base
 import htpy
+import pydantic.dataclasses as dataclasses
+import quart
 
 import atr.blueprints.get as get
+import atr.cycles as cycles
 import atr.db as db
 import atr.db.interaction as interaction
 import atr.form as form
@@ -36,6 +39,34 @@ import atr.util as util
 import atr.web as web
 
 
+@dataclasses.dataclass(config={"str_strip_whitespace": True})
+class CyclePreviewQuery:
+    version: str = ""
+
+
+@get.typed
+async def cycle_preview(
+    session: web.Committer,
+    _start: Literal["start"],
+    project_key: safe.ProjectKey,
+    _preview: Literal["cycle-preview"],
+    query: CyclePreviewQuery,
+) -> web.QuartResponse:
+    await session.prevent_confusing_ui_display(project_key, flash_admin_warning=False)
+    async with db.session() as data:
+        project = await data.project(key=str(project_key), status=sql.ProjectStatus.ACTIVE, _committee=False).demand(
+            base.ASFQuartException(f"Project {project_key} not found", errorcode=404)
+        )
+
+    if util.version_key_error(query.version):
+        return quart.jsonify(cycle=None)
+    try:
+        cycle = cycles.cycle_name_for_version(project, query.version)
+    except ValueError:
+        cycle = None
+    return quart.jsonify(cycle=cycle)
+
+
 @get.typed
 async def metadata(
     session: web.Committer,
@@ -102,15 +133,14 @@ def _cycle_preview(project: sql.Project) -> htm.Element | None:
     if not project.cycle_match:
         return None
     lifecycle_url = util.as_url(projects.view, project_key=str(project.key)) + "?tab=lifecycle"
-    config = htpy.div(
-        "#start-cycle-config.d-none",
-        data_cycle_match=project.cycle_match,
-        data_lifecycle_url=lifecycle_url,
-    )
-    placeholder = htm.div("#start-cycle-preview.alert.alert-light.mt-2")[
-        "Enter a version to see which cycle it lands in."
+    return htm.div("#start-cycle-preview.alert.alert-light.mt-2")[
+        htm.span(
+            "#start-cycle-preview-text", data_preview_url=util.as_url(cycle_preview, project_key=str(project.key))
+        )["Enter a version to see which cycle it lands in."],
+        " ",
+        htm.a(href=lifecycle_url)["Lifecycle settings"],
+        ".",
     ]
-    return htm.div[config, placeholder]
 
 
 def _existing_releases(ul: htm.Block, releases: list[sql.Release], max_revisions: int = 18) -> None:
diff --git a/atr/static/js/src/start-cycle-preview.js b/atr/static/js/src/start-cycle-preview.js
index 7c2fc244..ccdc7540 100644
--- a/atr/static/js/src/start-cycle-preview.js
+++ b/atr/static/js/src/start-cycle-preview.js
@@ -17,111 +17,44 @@
  *  under the License.
  */
 
-function buildLifecycleLink(lifecycleUrl) {
-	const link = document.createElement("a");
-	link.href = lifecycleUrl;
-	link.textContent = "lifecycle settings page";
-	return link;
-}
-
-function readConfig() {
-	const config = document.getElementById("start-cycle-config");
-	if (!config) {
-		return null;
-	}
-	return {
-		cycleMatch: config.dataset.cycleMatch,
-		lifecycleUrl: config.dataset.lifecycleUrl,
+function initStartCyclePreview() {
+	const input = document.getElementById("version_key");
+	const output = document.getElementById("start-cycle-preview-text");
+	if (!input || !output) return;
+	const emptyMessage = output.textContent;
+	const url = output.dataset.previewUrl;
+
+	let timer;
+	const refresh = () => {
+		clearTimeout(timer);
+		const version = input.value;
+		if (!version.trim()) {
+			output.textContent = emptyMessage;
+			return;
+		}
+		output.textContent = "";
+		timer = setTimeout(() => updatePreview(input, output, url, version), 300);
 	};
+	input.addEventListener("input", refresh);
+	refresh();
 }
 
-function renderPreview(preview, alertClass, prefixNodes, lifecycleUrl, suffix) {
-	preview.className = `alert ${alertClass} mt-2`;
-	while (preview.firstChild) {
-		preview.firstChild.remove();
-	}
-	for (const node of prefixNodes) {
-		preview.append(node);
-	}
-	preview.append(" Visit the ");
-	preview.append(buildLifecycleLink(lifecycleUrl));
-	preview.append(suffix);
-}
-
-function updatePreview(versionInput, preview, regex, lifecycleUrl) {
-	const version = versionInput.value.trim();
-	if (!version) {
-		renderPreview(
-			preview,
-			"alert-light",
-			[
-				document.createTextNode(
-					"Enter a version to see which cycle it lands in.",
-				),
-			],
-			lifecycleUrl,
-			" to change the cycle pattern.",
-		);
-		return;
-	}
-
-	// Mirror Python's re.fullmatch by requiring the regex to consume the
-	// entire version string, and by treating an empty capture as no match.
-	const match = version.match(regex);
-	if (!match || match[0] !== version || !match[1]) {
-		renderPreview(
-			preview,
-			"alert-warning",
-			[
-				document.createTextNode(
-					"This version doesn't match the project's cycle pattern.",
-				),
-			],
-			lifecycleUrl,
-			" to adjust the pattern.",
-		);
-		return;
-	}
-
-	const cycleName = document.createElement("strong");
-	cycleName.textContent = match[1];
-	renderPreview(
-		preview,
-		"alert-info",
-		[
-			document.createTextNode("This release will be added to cycle "),
-			cycleName,
-			document.createTextNode("."),
-		],
-		lifecycleUrl,
-		" if you'd like to change which cycle this version belongs to.",
-	);
-}
-
-function initStartCyclePreview() {
-	const config = readConfig();
-	if (!config) {
-		return;
-	}
-
-	let regex;
+async function updatePreview(input, output, url, version) {
+	let message;
 	try {
-		regex = new RegExp(config.cycleMatch);
-	} catch (e) {
-		console.error("Invalid cycle_match regex:", e);
-		return;
-	}
-
-	const versionInput = document.getElementById("version_key");
-	const preview = document.getElementById("start-cycle-preview");
-	if (!versionInput || !preview) {
-		return;
-	}
-
-	const refresh = () =>
-		updatePreview(versionInput, preview, regex, config.lifecycleUrl);
-	versionInput.addEventListener("input", refresh);
-	refresh();
+		const response = await fetch(`${url}?${new URLSearchParams({ version })}`, {
+			redirect: "error",
+		});
+		if (!response.ok) throw new Error("Cycle preview unavailable");
+		const { cycle } = await response.json();
+		message =
+			cycle === null
+				? "Enter a valid version matching the project's cycle pattern."
+				: `Cycle: ${cycle}.`;
+	} catch {
+		message = "Cycle preview unavailable.";
+	}
+	if (input.value === version) output.textContent = message;
 }
 
 document.addEventListener("DOMContentLoaded", initStartCyclePreview);
diff --git a/tests/unit/test_start_cycle_preview.py b/tests/unit/test_start_cycle_preview.py
new file mode 100644
index 00000000..256dc1cd
--- /dev/null
+++ b/tests/unit/test_start_cycle_preview.py
@@ -0,0 +1,124 @@
+# 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.
+
+import contextlib
+import unittest.mock as mock
+
+import asfquart.base as base
+import pytest
+import quart
+
+import atr.get.start as start
+import atr.models.safe as safe
+import atr.models.sql as sql
+
+
+@pytest.fixture
+def preview(monkeypatch):
+    app = quart.Quart(__name__)
+    app.config["TESTING"] = True
+    app.register_error_handler(base.ASFQuartException, lambda error: ("", error.errorcode))
+    app.register_blueprint(start.get._BLUEPRINT)
+    data = mock.Mock()
+    data.project.return_value.demand = mock.AsyncMock()
+    session = mock.Mock()
+    session.prevent_confusing_ui_display = mock.AsyncMock()
+    monkeypatch.setattr(start.db, "session", lambda: contextlib.nullcontext(data))
+    monkeypatch.setattr(start.get.auth.session, "read", mock.AsyncMock(return_value=object()))
+    monkeypatch.setattr(start.get.common, "authenticate", mock.AsyncMock(return_value=session))
+    monkeypatch.setattr(start.get.log, "performance", mock.Mock())
+    return app.test_client(), data, session
+
+
+@pytest.mark.parametrize("version", ["", "a" * 129, "1.2.", "\x1e2.5.3\x1e", "\ufeff2.5.3\ufeff"])
+async def test_cycle_preview_invalid_version(preview, monkeypatch, version):
+    client, _data, _session = preview
+    resolver = mock.Mock()
+    monkeypatch.setattr(start.cycles, "cycle_name_for_version", resolver)
+    response = await client.get("/start/example/cycle-preview", query_string={"version": version})
+    assert response.status_code == 200
+    assert await response.get_json() == {"cycle": None}
+    resolver.assert_not_called()
+
+
+async def test_cycle_preview_missing_project(preview):
+    client, data, _session = preview
+    data.project.return_value.demand.side_effect = base.ASFQuartException("Missing project", errorcode=404)
+    response = await client.get("/start/example/cycle-preview?version=2.5.3")
+    assert response.status_code == 404
+
+
+async def test_cycle_preview_missing_version(preview, monkeypatch):
+    client, _data, _session = preview
+    resolver = mock.Mock()
+    monkeypatch.setattr(start.cycles, "cycle_name_for_version", resolver)
+    response = await client.get("/start/example/cycle-preview")
+    assert response.status_code == 200
+    assert await response.get_json() == {"cycle": None}
+    resolver.assert_not_called()
+
+
+@pytest.mark.parametrize(
+    ("pattern", "version", "cycle"),
+    [
+        ("(a|aa)", "aa", "aa"),
+        (r"(?P<cycle>\d+)\..*", "2.5.3", "2"),
+        ("^(a+)+$", ("a" * 30) + "X", None),
+        ("(a*)b", "b", None),
+        ("(a)?b", "b", None),
+        ("a", "a", None),
+        ("(", "a", None),
+        (None, "2.5.3", "default"),
+        (r"(\d+)\..*", " \t2.5.3\u00a0", "2"),
+        (r"(\d+)\..*", "2.5.3+build", "2"),
+    ],
+)
+async def test_cycle_preview_resolves(preview, pattern, version, cycle):
+    client, data, session = preview
+    data.project.return_value.demand.return_value = sql.Project(key="example", cycle_match=pattern)
+    response = await client.get("/start/example/cycle-preview", query_string={"version": version})
+    assert response.status_code == 200
+    assert await response.get_json() == {"cycle": cycle}
+    data.project.assert_called_once_with(key="example", status=sql.ProjectStatus.ACTIVE, _committee=False)
+    session.prevent_confusing_ui_display.assert_awaited_once_with(safe.ProjectKey("example"), flash_admin_warning=False)
+
+
+async def test_cycle_preview_unauthenticated(preview, monkeypatch):
+    client, data, _session = preview
+    monkeypatch.setattr(start.get.auth.session, "read", mock.AsyncMock(return_value=None))
+    response = await client.get("/start/example/cycle-preview?version=2.5.3")
+    assert response.status_code == 403
+    data.project.assert_not_called()
+
+
+async def test_cycle_preview_unauthorized(preview):
+    client, data, session = preview
+    session.prevent_confusing_ui_display.side_effect = base.ASFQuartException("Forbidden", errorcode=403)
+    response = await client.get("/start/example/cycle-preview?version=2.5.3")
+    assert response.status_code == 403
+    data.project.assert_not_called()
+
+
+async def test_cycle_preview_url(preview):
+    client, _data, _session = preview
+    async with client.app.test_request_context("/"):
+        html = str(start._cycle_preview(sql.Project(key="example", cycle_match="^(a+)+$")))
+    assert 'data-preview-url="/start/example/cycle-preview"' in html
+    assert "^(a+)+$" not in html
+    assert 'id="start-cycle-preview-text"' in html
+    assert "?tab=lifecycle" in html
+    assert start._cycle_preview(sql.Project(key="example", cycle_match=None)) is None


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org