diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 00000000000..bee624a123e --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,15 @@ +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "Bash", + "hooks": [ + { + "type": "command", + "command": "f=\"$CLAUDE_PROJECT_DIR/scripts/ci/claude-pre-push-hook.py\"; [ ! -f \"$f\" ] || python3 \"$f\"" + } + ] + } + ] + } +} diff --git a/.github/workflows/check-workflows.yml b/.github/workflows/check-workflows.yml index 97edea55f40..6581542b0bc 100644 --- a/.github/workflows/check-workflows.yml +++ b/.github/workflows/check-workflows.yml @@ -51,6 +51,11 @@ jobs: # Those wrappers download from repo.codenameone.com, so a Maven or wrapper version # bump fails here, in one place, until the "Seed Maven distributions to R2" # workflow has copied it there -- not in every job that starts Maven. + # scripts/pre-push-gates.sh runs workflow steps BY NAME; a renamed step + # must fail here, in the PR that renames it, not in the next agent's push. + - name: Check the local pre-push gate names only steps that exist + run: bash scripts/pre-push-gates.sh --validate-steps + - name: Check R2 serves every Maven distribution the tree names run: bash maven/scripts/r2/seed-maven-distributions.sh --verify @@ -59,6 +64,7 @@ jobs: python3 scripts/ci/test_select_cn1lib_checks.py python3 scripts/ci/test_select_apple_checks.py python3 scripts/ci/test_select_ci_members.py + python3 scripts/ci/test_claude_pre_push_hook.py python3 scripts/ci/test_cn1ss_golden_plan.py node --test scripts/ci/test-cancel-stale-pr-runs.js diff --git a/.gitignore b/.gitignore index 8abbb5941e2..1ecab09ff40 100644 --- a/.gitignore +++ b/.gitignore @@ -83,7 +83,9 @@ node_modules # bundled IDE configs versioned. !maven/cn1app-archetype/src/main/resources/archetype-resources/.idea !maven/cn1app-archetype/src/main/resources/archetype-resources/.idea/** -.claude/ +# Claude Code local state; the project hooks file is shared (pre-push gate). +**/.claude/* +!/.claude/settings.json target pom.xml.versionsBackup pom.xml.releaseBackup @@ -137,7 +139,6 @@ package-lock.json package.json !/scripts/package.json !/scripts/package-lock.json -.claude/ # Local screenshot/perf bench output /artifacts/ diff --git a/CLAUDE.md b/CLAUDE.md index c3ac7d2261c..faf0e526fcb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -106,6 +106,57 @@ To use locally-built version, edit the generated `pom.xml`: - **Main JAVA_HOME (for building the framework)**: Must be JDK 8 - **Runtime JDK for simulator / desktop run**: JDK 11 through 25 is supported. The Codename One Maven plugin checks this on entry to `cn1:run` and `cn1:debug` and aborts with a friendly error when an older JDK is in use. The build-time goals (`generate-desktop-app-wrapper`, `prepare-simulator-classpath`, the `executable-jar` profile) are not gated -- they still work on JDK 8 because they only generate icons / classpath metadata. +### Before every push: `scripts/pre-push-gates.sh` + +CI is the final gate, not the QA. Most failed runs on pull requests were checks +any machine can run: inline source blocks in the guide, image alt text cut short +by a comma, a Vale or LanguageTool finding, a Playground snippet that does not +compile (javadoc in `CodenameOne/src` counts), a near-miss class name, a +copyright header, a PMD finding, a build hint named in Initializr skill text, +launcher drift, an Initializr fixture rule. So before every push: + +1. **Commit.** CI judges commits, and the selector and header gate here read + `merge-base(origin/master)..HEAD`. `git fetch origin master` if it is old. +2. **`scripts/pre-push-gates.sh`**, every time, whatever the change. +3. **Add `--full`** when the branch changes Java (SpotBugs, PMD, Checkstyle, + build hint catalog, cast semantics), the website (Hugo build) or guide Java + snippets (compiled against the demos). +4. **Push only with no `FAILED` line.** `NOT RUN` lines are not passes; name + them when you report. + +The script copies no commands. CI's own selector +(`scripts/ci/select-ci-members.py`) picks the gates, and +`scripts/ci/run-workflow-steps.py` executes the **workflow steps themselves**: +`source-gates.yml` and `check-workflows.yml` in full, and the +`developer-guide-docs.yml`, `blog-prose.yml` and `website-docs.yml` steps. They run with a real +`GITHUB_ENV`, so the step that records a Vale count feeds the step that fails on +it, as it does on the runner. Hand-run copies are how local and CI drifted: plain +`vale` exits 0 on findings CI counts, a bare `check-copyright-headers.sh` sees +only the working tree, and the guide checks without the final "Fail build on +developer guide quality issues" step judge nothing. + +- **Agents cannot push without it.** A clean pass over a clean tree records + HEAD in `/cn1-pre-push-gates`, and the Claude Code hook in + `.claude/settings.json` (`scripts/ci/claude-pre-push-hook.py`) blocks a + `git push` of any commit not recorded there, or of a Java-changing commit + recorded without `--full`. Do not hand-write that file or route around the + hook; fix what the gate reports. Humans pushing from a terminal are not + affected, and the hook allows what it cannot parse: it guards against + forgetting the gate, not against evading it. +- **Fix a mismatch by naming a workflow step**, never by pasting a command into + the script. `check-workflows.yml` runs `scripts/pre-push-gates.sh + --validate-steps`, so renaming a step the script names with `--step` fails + that PR; update the script's list in the same change. (`source-gates.yml` + and `check-workflows.yml` run with `--all-run-steps`: every step, whatever + its name.) Every selector member without a local gate is printed as NOT RUN. +- Gates that compile against Codename One (the Playground snippets, the guide + snippet compile) install the snapshots into this checkout's `maven/.m2-repo` + (`mvn install -Plocal-dev-javase` on JDK 17, never `~/.m2`). They run it + once, and again only when the branch touches what it installs. +- The script warns when local Vale or Hugo differs from the workflow's pin. +- CI alone runs the device and screenshot suites, the perf gates, the Xcode and + Android builds, the guide figure comparison and the Initializr's Windows leg. + ### Static Analysis Gates PR CI (`.github/workflows/pr.yml`, Java 8 leg) runs SpotBugs over diff --git a/docs/demos/common/pom.xml b/docs/demos/common/pom.xml index ef1efa71ad7..1090886d1c2 100644 --- a/docs/demos/common/pom.xml +++ b/docs/demos/common/pom.xml @@ -363,6 +363,16 @@ codenameone-maven-plugin + + + transcode-svg + generate-sources + + transcode-svg + + diff --git a/scripts/ci/claude-pre-push-hook.py b/scripts/ci/claude-pre-push-hook.py new file mode 100755 index 00000000000..85f298633f2 --- /dev/null +++ b/scripts/ci/claude-pre-push-hook.py @@ -0,0 +1,245 @@ +#!/usr/bin/env python3 +# +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. Codename One designates this +# particular file as subject to the "Classpath" exception as provided +# in the LICENSE file that accompanied this code. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Codename One through http://www.codenameone.com/ if you +# need additional information or have any questions. +"""Claude Code PreToolUse hook: no agent `git push` without a local gate pass. + +Wired in .claude/settings.json for the Bash tool. It reads the hook's JSON on +stdin, and when the command pushes from a Codename One checkout it requires +every commit being pushed to be recorded in /cn1-pre-push-gates, +which scripts/pre-push-gates.sh appends to after a clean pass over a clean +tree. A commit whose branch changes Java (CI's `pr` member) needs a --full pass. + +Exit 0 allows the call; exit 2 blocks it and the message on stderr is shown to +the agent. Anything this hook cannot understand is allowed, not blocked: it is +a guard against forgetting the gate, and a hook that wedges every push would be +switched off. A human pushing from a terminal is not affected. +""" +import json +import os +import re +import shlex +import subprocess +import sys + +STAMP = "cn1-pre-push-gates" +GATE = "scripts/pre-push-gates.sh" + + +def git(cwd, *args): + result = subprocess.run(("git", "-C", cwd) + args, capture_output=True, text=True) + return result.stdout.strip() if result.returncode == 0 else None + + +HEREDOC = re.compile(r"<<-?[ \t]*(['\"]?)([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n.*?\n[ \t]*\2[ \t]*(?=\n|$)", re.S) + + +def strip_heredocs(command): + """Drop heredoc bodies: a script or commit message fed on stdin is data.""" + return HEREDOC.sub(lambda m: m.group(0).split("\n", 1)[0], command) + + +def segments(command): + """Split a shell command line into simple commands at ; && || | and newlines.""" + command = strip_heredocs(command) + try: + lexer = shlex.shlex(command, posix=True, punctuation_chars=";&|\n") + lexer.whitespace = " \t\r" # a newline separates commands, as ; does + lexer.whitespace_split = True + # No comment handling: shlex would also cut `a#b` mid-word, hiding a + # later `; git push`. A push named in a comment is checked, harmlessly. + lexer.commenters = "" + tokens = list(lexer) + except ValueError: + return None + result, current = [], [] + for token in tokens: + if token and set(token) <= set(";&|\n"): + if current: + result.append(current) + current = [] + else: + current.append(token) + if current: + result.append(current) + return result + + +# Words that run the rest of the line as a command: `env git push`, `time git push`. +WRAPPERS = {"env", "command", "time", "sudo", "nice", "nohup", "exec", "xargs", "builtin"} +SHELLS = {"bash", "sh", "zsh", "dash"} +# git push options that take a separate value; the value is not the remote. +VALUED = {"-o", "--push-option", "--repo", "--receive-pack", "--exec"} +# `git [global options] push` or `gh pr create`, as words; `pre-push-gates.sh` +# or a commit message saying "push" is not one. +# Used only when the line cannot be tokenized (an unterminated quote). +RAW_PUSH = re.compile(r"(? 1: + target = os.path.join(cwd, os.path.expanduser(words[1])) + if os.path.isdir(target): + cwd = target # an unresolvable `cd "$DIR"` keeps the old directory + continue + if name != "git": + continue + i, where = 1, cwd + while i < len(words) and words[i].startswith("-"): + if words[i] == "-C" and i + 1 < len(words): + where = os.path.join(where, os.path.expanduser(words[i + 1])) + i += 2 + elif words[i] in ("-c", "--git-dir", "--work-tree") and i + 1 < len(words): + i += 2 + else: + i += 1 + if i >= len(words) or words[i] != "push": + continue + args = words[i + 1:] + positional, j = [], 0 + while j < len(args): + if args[j] in VALUED: + j += 2 + continue + if not args[j].startswith("-"): + positional.append(args[j]) + j += 1 + if any(a in ("--delete", "-d", "--dry-run", "-n", "--help", "-h") for a in args): + continue + if any(a in ("--all", "--mirror", "--branches") for a in args): + yield where, None # every branch: require all local branch tips + continue + refspecs = positional[1:] # the first is the remote + if refspecs[:1] == ["tag"]: + refspecs = ["refs/tags/" + t for t in refspecs[1:2]] + refspecs[2:] # `push origin tag v1` + yield where, refspecs or ["HEAD"] + + +def main(): + try: + data = json.load(sys.stdin) + except ValueError: + return 0 + if data.get("tool_name") != "Bash": + return 0 + command = (data.get("tool_input") or {}).get("command") or "" + if not LOOSE_PUSH.search(strip_heredocs(command)): + return 0 # cheap pre-filter; pushes() does the real parse + problems = [] + for where, refs in pushes(command, data.get("cwd") or os.getcwd()): + top = git(where, "rev-parse", "--show-toplevel") + if not top or not os.path.exists(os.path.join(top, GATE)): + continue # not a Codename One checkout (or one from before the gate) + common = git(where, "rev-parse", "--path-format=absolute", "--git-common-dir") + recorded = {} + try: + with open(os.path.join(common, STAMP), encoding="utf-8") as handle: + for line in handle: + parts = line.split() + if len(parts) == 3: + prev = recorded.get(parts[0]) + # a full pass anywhere in the file outranks a quick one + if prev is None or parts[1] == "full": + recorded[parts[0]] = (parts[1], parts[2]) + except OSError: + pass + if refs is None: + refs = (git(where, "for-each-ref", "--format=%(refname)", "refs/heads") or "").split() + checked = 0 + # HEAD is the fallback when no refspec names a local commit, and is + # always checked when a refspec is a shell expansion (`origin $b`). + expanded = any("$" in r or "`" in r for r in refs) + candidates = list(refs) + ([] if "HEAD" in refs else ["HEAD"]) + for ref in candidates: + if ref == "HEAD" and "HEAD" not in refs and checked and not expanded: + break + src = ref.lstrip("+").split(":", 1)[0] + if not src: + continue # `:branch` deletes + if src.startswith("refs/tags/") or git(where, "rev-parse", "-q", "--verify", "refs/tags/" + src): + continue # tags are cut from commits that were already gated + sha = git(where, "rev-parse", "-q", "--verify", src + "^{commit}") + if not sha: + continue # not a local revision; let git report it + checked += 1 + entry = recorded.get(sha) + if entry is None and git(where, "merge-base", "--is-ancestor", sha, "origin/master") is not None: + continue # already on master: nothing of this branch's own to gate + if entry is None: + problems.append("%s (%s) has no passing %s run" % (src, sha[:10], GATE)) + elif entry[1] == "1" and entry[0] != "full": + problems.append("%s (%s) changes Java and passed without --full" % (src, sha[:10])) + if not problems: + return 0 + sys.stderr.write( + "Push blocked: CI is the final gate, not the QA.\n - " + "\n - ".join(problems) + + "\nCommit, then run `%s` (add --full when Java changed) until it reports no FAILED line;" + " a clean pass records HEAD and the push is allowed. See \"Before every push\" in CLAUDE.md.\n" + % GATE) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/ci/run-workflow-steps.py b/scripts/ci/run-workflow-steps.py new file mode 100755 index 00000000000..02c3e87857d --- /dev/null +++ b/scripts/ci/run-workflow-steps.py @@ -0,0 +1,304 @@ +#!/usr/bin/env python3 +# +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. Codename One designates this +# particular file as subject to the "Classpath" exception as provided +# in the LICENSE file that accompanied this code. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Codename One through http://www.codenameone.com/ if you +# need additional information or have any questions. +"""Run the ``run:`` blocks of a GitHub workflow job on this machine. + +The local pre-push gate (scripts/pre-push-gates.sh) used to be a set of +hand-copied commands, and every copy drifted from the workflow it imitated: +Vale was run without the issue-count rule, the copyright check without a base, +the guide lint without the final step that turns findings into a failure. So +nothing is copied any more. This script reads the workflow YAML and executes +the job's own step scripts, in order, with the job's env, a real GITHUB_ENV +(so a step that records a status feeds the step that judges it, exactly as on +the runner), and GITHUB_OUTPUT / GITHUB_STEP_SUMMARY files. + +Steps are chosen BY NAME with --step. A name that no longer exists in the +workflow is an error, never a silent skip: renaming a CI step breaks the local +gate loudly instead of quietly dropping a check. ``uses:`` steps (setup +actions) are not run; the developer's machine supplies the tools, and +scripts/pre-push-gates.sh checks their versions against the workflow pins. + +``${{ ... }}`` expressions are resolved for the few contexts a local pull +request run has (github.event_name, base/head SHAs, runner.temp, matrix +values given with --matrix); anything else resolves to an empty string and is +reported, so a step that silently depends on one is visible. + +Deliberately stricter than the runner, never looser: step ``if:`` conditions +are ignored (a named step always runs), and every step runs under +``bash -eo pipefail`` (GitHub's default for a step without ``shell:`` is the +same since it uses ``bash -e {0}`` only for an explicit ``shell: bash``). +A local failure CI would not have is possible; a local pass CI fails is not. + + scripts/ci/run-workflow-steps.py .github/workflows/source-gates.yml \ + --job source-gates --all-run-steps --base origin/master + scripts/ci/run-workflow-steps.py .github/workflows/developer-guide-docs.yml \ + --job build --step "Run Asciidoctor lint" --step "Fail build on ..." +""" +import argparse +import os +import re +import subprocess +import sys +import tempfile +from shutil import which as shutil_which + +try: + import yaml +except ImportError: # pragma: no cover + sys.exit("run-workflow-steps: PyYAML is required (pip install pyyaml)") + +EXPR = re.compile(r"\$\{\{\s*(.*?)\s*\}\}") + + +def git(*args): + return subprocess.check_output(("git",) + args, text=True).strip() + + +class Context: + def __init__(self, base, head, temp, matrix): + self.values = { + "github.event_name": "pull_request", + "github.event.pull_request.base.sha": base, + "github.event.pull_request.head.sha": head, + "github.event.before": "", + "github.sha": head, + "github.base_ref": "master", + "github.head_ref": git("rev-parse", "--abbrev-ref", "HEAD"), + "github.ref_name": git("rev-parse", "--abbrev-ref", "HEAD"), + "github.workspace": os.getcwd(), + "github.repository": "codenameone/CodenameOne", + "runner.temp": temp, + "runner.os": "macOS" if sys.platform == "darwin" else "Linux", + } + for key, value in matrix.items(): + self.values["matrix." + key] = value + self.unresolved = set() + + def resolve(self, text): + if not isinstance(text, str): + return "" if text is None else str(text) + + def sub(match): + expr = match.group(1) + if expr in self.values: + return self.values[expr] + # `a || b` picks the first resolvable operand, as Actions does. + for part in (p.strip() for p in expr.split("||")): + if part in self.values and self.values[part]: + return self.values[part] + if part.startswith("'") and part.endswith("'"): + return part[1:-1] + self.unresolved.add(expr) + return "" + + return EXPR.sub(sub, text) + + +def find_jdk(version): + """A local JDK for a setup-java version: JAVA_HOME, else macOS java_home.""" + major = version.split(".")[0] + home = os.environ.get("JAVA%s_HOME" % major) + if home and os.path.isdir(home): + return home + if os.path.exists("/usr/libexec/java_home"): + result = subprocess.run(["/usr/libexec/java_home", "-v", "1." + major if major in ("6", "7", "8") else major], capture_output=True, text=True) + found = result.stdout.strip() + # java_home answers the nearest JDK when the exact one is absent; only take an exact match. + if result.returncode == 0 and found: + release = os.path.join(found, "release") + try: + with open(release, encoding="utf-8", errors="replace") as handle: + text = handle.read() + match = re.search(r'JAVA_VERSION="(?:1\.)?(\d+)', text) + if match and match.group(1) == major: + return found + except OSError: + return found + return None + + +def read_env_file(path, env): + """Apply a GITHUB_ENV file: KEY=VALUE lines and KEY<_HOME)" % version, 1)) + if ctx.unresolved: + print("\nrun-workflow-steps: expressions with no local value (resolved empty): %s" + % ", ".join(sorted(ctx.unresolved)), file=sys.stderr) + if failures: + print("\nrun-workflow-steps: %d step(s) failed in %s:" % (len(failures), args.workflow), + file=sys.stderr) + for name, code in failures: + print(" - %s (exit %d)" % (name, code), file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/ci/test_claude_pre_push_hook.py b/scripts/ci/test_claude_pre_push_hook.py new file mode 100644 index 00000000000..8c02b934ac0 --- /dev/null +++ b/scripts/ci/test_claude_pre_push_hook.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""Unit tests for claude-pre-push-hook.py (run by check-workflows.yml). + +The hook must see every ordinary way an agent pushes, and must NOT fire on +commands that merely mention pushing: a hook that blocks `git commit -m "push +fix"` or a heredoc'd script gets switched off, and then it guards nothing. +""" +import importlib.util +import json +import os +import subprocess +import sys +import tempfile +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +HOOK = os.path.join(HERE, "claude-pre-push-hook.py") +spec = importlib.util.spec_from_file_location("hook", HOOK) +hook = importlib.util.module_from_spec(spec) +spec.loader.exec_module(hook) + +PUSHES = [ + "git push", "git push origin HEAD", "git push -u origin topic", "git -C . push", + "/usr/bin/git push", "git -c a=b push --force-with-lease origin HEAD", + 'bash -c "git push"', "(git push)", "echo $(git push)", "env git push", + "command git push", "time git push", "git push -o ci.skip origin", + "gh pr create --fill", 'cd "$UNSET_DIR" && git push', "cat < log 2>&1", + 'git commit -qam "Pre-push gate: a, b" && scripts/pre-push-gates.sh; echo $?', + "python3 - <<'EOF'\ns = '''unterminated\nprint('git push origin x')\nEOF\necho ok", + "git commit -F - <<'EOF'\nfix: git push is gated now\nEOF", + "git push --dry-run", "git push origin --delete topic", +] + + +def run_hook(command, cwd): + data = json.dumps({"tool_name": "Bash", "tool_input": {"command": command}, "cwd": cwd}) + return subprocess.run([sys.executable, HOOK], input=data, capture_output=True, text=True).returncode + + +def git(cwd, *args): + return subprocess.check_output(("git", "-C", cwd) + args, text=True).strip() + + +class ParseTest(unittest.TestCase): + def test_pushes_are_seen(self): + for command in PUSHES: + self.assertTrue(list(hook.pushes(command, HERE)), command) + + def test_mentions_are_not_pushes(self): + for command in NOT_PUSHES: + found = list(hook.pushes(command, HERE)) if hook.LOOSE_PUSH.search(hook.strip_heredocs(command)) else [] + self.assertFalse(found, command) + + +class StampTest(unittest.TestCase): + """End to end in a scratch repository that looks like a checkout.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.repo = self.tmp.name + git(self.repo, "init", "-q", "-b", "topic") + os.makedirs(os.path.join(self.repo, "scripts")) + open(os.path.join(self.repo, hook.GATE), "w").close() + git(self.repo, "add", "-A") + git(self.repo, "-c", "user.email=t@t", "-c", "user.name=t", "-c", "commit.gpgsign=false", + "commit", "-qm", "x") + self.sha = git(self.repo, "rev-parse", "HEAD") + self.stamp = os.path.join(self.repo, ".git", hook.STAMP) + + def tearDown(self): + self.tmp.cleanup() + + def record(self, line): + with open(self.stamp, "a") as handle: + handle.write(line + "\n") + + def test_blocks_without_a_pass(self): + self.assertEqual(2, run_hook("git push origin topic", self.repo)) + + def test_allows_a_recorded_pass(self): + self.record(self.sha + " quick 0") + self.assertEqual(0, run_hook("git push -u origin topic", self.repo)) + + def test_shell_expanded_refspec_checks_head(self): + self.assertEqual(2, run_hook("git push origin $b", self.repo)) + + def test_java_needs_full(self): + self.record(self.sha + " quick 1") + self.assertEqual(2, run_hook("git push", self.repo)) + self.record(self.sha + " full 1") + self.assertEqual(0, run_hook("git push", self.repo)) + + def test_other_repositories_are_not_judged(self): + with tempfile.TemporaryDirectory() as other: + git(other, "init", "-q") + self.assertEqual(0, run_hook("cd %s && git push" % other, self.repo)) + + def test_garbage_input_is_allowed(self): + result = subprocess.run([sys.executable, HOOK], input="not json", capture_output=True, text=True) + self.assertEqual(0, result.returncode) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/developer-guide/validate-guide-snippets.py b/scripts/developer-guide/validate-guide-snippets.py index 84c9e5d6d36..c0f6a4488ec 100755 --- a/scripts/developer-guide/validate-guide-snippets.py +++ b/scripts/developer-guide/validate-guide-snippets.py @@ -296,6 +296,9 @@ def looks_like_member_snippet(code): def java_compile_classpath(): + # CI resolves the snapshots from ~/.m2; a local checkout builds into its own + # repository (-Dmaven.repo.local), which scripts/pre-push-gates.sh passes here. + repo = Path(os.environ.get("CN1_MAVEN_REPO_LOCAL") or (Path.home() / ".m2/repository")) candidates = [ Path("docs/demos/common/target/classes"), Path("maven/core/target/classes"), @@ -304,9 +307,9 @@ def java_compile_classpath(): # checkout that has not built it simply cannot use those types -- which # surfaces as the snippet failing to compile, not as it being skipped. Path("maven/flutter-runtime/target/classes"), - Path.home() / ".m2/repository/com/codenameone/codenameone-core/8.0-SNAPSHOT/codenameone-core-8.0-SNAPSHOT.jar", - Path.home() / ".m2/repository/com/codenameone/java-runtime/8.0-SNAPSHOT/java-runtime-8.0-SNAPSHOT.jar", - Path.home() / ".m2/repository/com/codenameone/codenameone-flutter-runtime/8.0-SNAPSHOT/codenameone-flutter-runtime-8.0-SNAPSHOT.jar", + repo / "com/codenameone/codenameone-core/8.0-SNAPSHOT/codenameone-core-8.0-SNAPSHOT.jar", + repo / "com/codenameone/java-runtime/8.0-SNAPSHOT/java-runtime-8.0-SNAPSHOT.jar", + repo / "com/codenameone/codenameone-flutter-runtime/8.0-SNAPSHOT/codenameone-flutter-runtime-8.0-SNAPSHOT.jar", ] return os.pathsep.join(str(p) for p in candidates if p.exists()) @@ -472,6 +475,12 @@ def write_junit_stubs(src_dir): def validate_java_snippets(java_snippets): if not java_snippets: return [] + if os.environ.get("CN1_GUIDE_SNIPPETS_NO_COMPILE") == "1": + # Set by scripts/pre-push-gates.sh when the demos are not built: the + # inline-block and include checks above still run, which is what most + # pull requests trip; CI always compiles. + print(f"CN1_GUIDE_SNIPPETS_NO_COMPILE=1: not compiling {len(java_snippets)} Java snippet(s).") + return [] javac = shutil.which("javac") if javac is None: return ["javac not found; cannot compile developer-guide Java snippets."] diff --git a/scripts/pre-push-gates.sh b/scripts/pre-push-gates.sh new file mode 100755 index 00000000000..ea515ef5d58 --- /dev/null +++ b/scripts/pre-push-gates.sh @@ -0,0 +1,345 @@ +#!/usr/bin/env bash +# +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. Codename One designates this +# particular file as subject to the "Classpath" exception as provided +# in the LICENSE file that accompanied this code. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Codename One through http://www.codenameone.com/ if you +# need additional information or have any questions. +# +# The local gate to run before EVERY push. It reproduces, on this machine, the +# CI checks that kept failing pull requests for reasons any machine can see: +# inline guide snippets, comma-cut alt text, Vale/LanguageTool counts, +# copyright headers, Playground snippets from core javadoc, launcher drift, +# Initializr fixtures, build hints, PMD/SpotBugs. +# +# It does not copy CI's commands. It decides WHAT to run with CI's own selector +# (scripts/ci/select-ci-members.py over .github/ci/ci-members.json) and runs +# the workflow steps THEMSELVES through scripts/ci/run-workflow-steps.py, so a +# check changed in a workflow changes here too, and a renamed step fails here +# loudly instead of silently disappearing. +# +# scripts/pre-push-gates.sh # every gate this branch's diff selects +# scripts/pre-push-gates.sh --full # also SpotBugs/PMD/Checkstyle, the site build +# # and the guide's Java snippet compile +# scripts/pre-push-gates.sh --all # every gate, whatever the diff +# scripts/pre-push-gates.sh --base REV # diff against REV (default origin/master) +# scripts/pre-push-gates.sh --validate-steps +# # only check that every workflow step named +# # here still exists (check-workflows.yml runs it) +# +# Gates that need Codename One built (the Playground snippets, guide snippet +# compile) install the snapshots into THIS checkout's maven/.m2-repo first +# (mvn install -Plocal-dev-javase on JDK 17) -- once, and again only when the +# diff touches the framework. Never ~/.m2: the checkouts share it. +# +# Exit status: 0 all selected gates passed, 1 a gate failed (CI will fail the +# same way), 2 bad usage. Every selected gate runs either way, so one pass +# shows everything. See "Before every push" in CLAUDE.md. +# +# A clean pass over a clean tree records HEAD in the repository's +# cn1-pre-push-gates file (git common dir, shared by worktrees). The Claude +# Code hook in .claude/settings.json (scripts/ci/claude-pre-push-hook.py) +# refuses an agent's `git push` of any commit not recorded there, and of a +# commit whose branch changes Java unless the pass was --full. + +set -uo pipefail +cd "$(git rev-parse --show-toplevel)" +ROOT="$PWD" + +BASE=origin/master +FULL=0 +ALL=0 +VALIDATE=0 +while [ $# -gt 0 ]; do + case "$1" in + --base) BASE="$2"; shift 2 ;; + --full) FULL=1; shift ;; + --all) ALL=1; FULL=1; shift ;; + --validate-steps) VALIDATE=1; ALL=1; FULL=1; shift ;; + -h|--help) sed -n '24,60p' "$0"; exit 0 ;; + *) echo "pre-push-gates: unknown argument $1" >&2; exit 2 ;; + esac +done + +RUN="python3 scripts/ci/run-workflow-steps.py" +WF=.github/workflows +FAILED=() +SKIPPED=() +note() { printf '\n=== %s\n' "$*"; } +gate() { # gate