Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .claude/settings.json
Original file line number Diff line number Diff line change
@@ -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\""
}
]
}
]
}
}
6 changes: 6 additions & 0 deletions .github/workflows/check-workflows.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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

Expand Down
5 changes: 3 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -137,7 +139,6 @@ package-lock.json
package.json
!/scripts/package.json
!/scripts/package-lock.json
.claude/

# Local screenshot/perf bench output
/artifacts/
Expand Down
51 changes: 51 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<git common dir>/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
Expand Down
10 changes: 10 additions & 0 deletions docs/demos/common/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,16 @@
<artifactId>codenameone-maven-plugin</artifactId>

<executions>
<execution>
<!-- Added automatically: this project has SVG/Lottie
assets, and without this execution they compile to
blank 1x1 placeholders on the device. -->
<id>transcode-svg</id>
<phase>generate-sources</phase>
<goals>
<goal>transcode-svg</goal>
</goals>
</execution>
<execution>
<!-- The Python chapter's examples (src/main/python), so
the guide shows code that transpiles and compiles. -->
Expand Down
245 changes: 245 additions & 0 deletions scripts/ci/claude-pre-push-hook.py
Original file line number Diff line number Diff line change
@@ -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 <git common dir>/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"(?<![\w./-])git(?:\s+-[-\w]+(?:[ =](?:\"[^\"]*\"|'[^']*'|[^\s;&|\"'-][^\s;&|]*))?)*\s+push(?![\w-])"
r"|(?<![\w./-])gh\s+pr\s+create(?![\w-])")
LOOSE_PUSH = re.compile(r"\bpush\b|\bgh\b[\s\S]*\bcreate\b")
# Shell keywords that may precede a command in a compound: `do git push`.
KEYWORDS = {"do", "then", "else", "elif", "while", "until", "!", "{", "time"}


def pushes(command, cwd, depth=0):
"""Yield (directory, refs) for every `git push` (or `gh pr create`) in the line."""
split = segments(command)
if split is None:
if RAW_PUSH.search(strip_heredocs(command)):
yield cwd, ["HEAD"] # unparsable but looks like a push: check HEAD
return
for words in split:
if any("$(" in w or "`" in w for w in words):
# a command substitution: judge the command inside it
for k, w in enumerate(words):
if k and re.match(r"^(\$\(|`)+", w):
words = words[k:]
break
words = [w.replace("$(", "").strip("(){}`") for w in words]
words = [w for w in words if w and w not in (")", "}")]
changed = True
while words and changed:
changed = False
while words and re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", words[0]):
words, changed = words[1:], True # VAR=value prefixes
if words and words[0] in KEYWORDS:
words, changed = words[1:], True
if words and os.path.basename(words[0]) in WRAPPERS:
# The wrapper's own options may take values (`sudo -u bob`,
# `nice -n 5`), so jump to the git it runs, if any.
rest = words[1:]
at = next((k for k, w in enumerate(rest) if os.path.basename(w) == "git"), None)
words, changed = (rest[at:] if at is not None else rest), True
if not words:
continue
name = os.path.basename(words[0])
if name in SHELLS and "-c" in words[1:] and depth < 3:
idx = words.index("-c")
if idx + 1 < len(words):
for found in pushes(words[idx + 1], cwd, depth + 1):
yield found
continue
if name == "gh" and words[1:3] == ["pr", "create"]:
yield cwd, ["HEAD"] # gh offers to push the current branch
continue
if name in ("cd", "pushd") and len(words) > 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())
Loading
Loading