From 5a1759c9c7a487d8c179fc686b2fddd56fb4a3d2 Mon Sep 17 00:00:00 2001 From: ckr <15865258+chekunru@user.noreply.gitee.com> Date: Tue, 24 Nov 2026 23:41:18 +0800 Subject: [PATCH 1/3] fix(git): keep Unicode words in git extension branch names (#5553) The git extension's branch scripts still sanitized names with [^a-z0-9], so a CJK-only description produced the branch 001- while the core script created specs/001-/. Port the core scripts' UTF-8 naming policy (#4574, #4780) to the bash, PowerShell, and Python twins: - keep Unicode letters and decimal digits; lowercase ASCII letters only - keep short non-ASCII words (CJK words are often two characters) - leave {author} and {app} template tokens ASCII-only, as before - bash: classify Unicode via Python and pick a UTF-8 locale, mirroring core create-new-feature.sh; truncate to 244 bytes by whole UTF-8 characters, since MSYS/Cygwin bash's 16-bit wchar_t lets ${var%?} split characters outside the BMP - PowerShell: guard the fallback join with @() so punctuation-only input no longer throws on [string]::Join($null); drop whole surrogate pairs when truncating Bump the git extension to 1.0.10. Assisted-by: Claude Code (model: Claude Opus 5.5, supervised) --- extensions/catalog.json | 2 +- extensions/git/README.md | 2 + extensions/git/extension.yml | 2 +- .../scripts/bash/create-new-feature-branch.sh | 140 +++++++++++++-- .../powershell/create-new-feature-branch.ps1 | 54 +++++- .../python/create_new_feature_branch.py | 31 +++- tests/extensions/git/test_git_extension.py | 67 ++++++- .../git/test_git_extension_python_parity.py | 166 ++++++++++++++++-- 8 files changed, 419 insertions(+), 45 deletions(-) diff --git a/extensions/catalog.json b/extensions/catalog.json index a4bc32ceb0..34b4278970 100644 --- a/extensions/catalog.json +++ b/extensions/catalog.json @@ -51,7 +51,7 @@ "git": { "name": "Git Branching Workflow", "id": "git", - "version": "1.0.9", + "version": "1.0.10", "description": "Feature branch creation, numbering (sequential/timestamp), validation, and Git remote detection", "author": "spec-kit-core", "repository": "https://github.com/github/spec-kit", diff --git a/extensions/git/README.md b/extensions/git/README.md index c0cb7b5d00..f4831abf6e 100644 --- a/extensions/git/README.md +++ b/extensions/git/README.md @@ -84,6 +84,8 @@ auto_commit: For simple namespace-only customization, `branch_prefix` is also accepted as a shorthand and expands to `/{number}-{slug}`. +`{slug}` keeps Unicode letters and decimal digits, matching the core `specs/` directory names, so `添加待办事项` produces the branch `001-添加待办事项`. Only ASCII letters are lowercased. `{author}` and `{app}` remain ASCII-only. In Bash, a non-ASCII slug requires Python 3 and a UTF-8 locale. + ## Installation ```bash diff --git a/extensions/git/extension.yml b/extensions/git/extension.yml index 71fe05ed37..67cfdff102 100644 --- a/extensions/git/extension.yml +++ b/extensions/git/extension.yml @@ -3,7 +3,7 @@ schema_version: "1.0" extension: id: git name: "Git Branching Workflow" - version: "1.0.9" + version: "1.0.10" description: "Feature branch creation, numbering (sequential/timestamp), templating, validation, and Git remote detection" author: spec-kit-core repository: https://github.com/github/spec-kit diff --git a/extensions/git/scripts/bash/create-new-feature-branch.sh b/extensions/git/scripts/bash/create-new-feature-branch.sh index ca3101f2de..7b22e5ddaf 100755 --- a/extensions/git/scripts/bash/create-new-feature-branch.sh +++ b/extensions/git/scripts/bash/create-new-feature-branch.sh @@ -205,16 +205,101 @@ check_existing_branches() { echo $((max_num + 1)) } -# Function to clean and format a branch name -# -# Three details keep this byte-identical to the Python and PowerShell twins: -# * LC_ALL=C -- in a UTF-8 locale glibc resolves the a-z *range* through -# collation, so [^a-z0-9] keeps accented lowercase letters that -# re.sub(r"[^a-z0-9]", ...) and .NET's -replace both strip. -# * `--*` instead of the GNU-only `\+`, which POSIX/BSD sed reads as a literal -# '+', leaving repeated separators uncollapsed on macOS. -# * printf instead of echo, so a name of "-n"/"-e"/"-E" is text, not options. +# Branch names keep Unicode letters and decimal digits, mirroring the core +# create-new-feature.sh (UTF-8 feature names, #4574). +contains_non_ascii() { + LC_ALL=C grep -q '[^[:print:][:cntrl:]]' +} + +# Python classifies Unicode because POSIX [:alnum:] differs by platform. Probe +# here rather than relying on common.sh's _python3_command: this script may +# have loaded git-common.sh or an older core common.sh without it. Naming needs +# no PyYAML, so a configured override is accepted without that check. +_unicode_python_command() { + local override="${SPECKIT_PYTHON_EXECUTABLE:-${SPECKIT_PYTHON:-}}" + local candidate + for candidate in "$override" python3 python; do + if [ -n "$candidate" ] && command -v "$candidate" >/dev/null 2>&1 && + "$candidate" -c 'import sys; raise SystemExit(sys.version_info.major != 3)' >/dev/null 2>&1; then + printf '%s\n' "$candidate" + return 0 + fi + done + if command -v py >/dev/null 2>&1 && py -3 -c 'import sys' >/dev/null 2>&1; then + printf '%s\n' "py" "-3" + return 0 + fi + return 1 +} + +# ASCII-only input stays shell-only under LC_ALL=C, where glibc cannot resolve +# the a-z *range* through collation. +unicode_words() { + local name="${1//$'\n'/ }" + local separator="$2" + if printf '%s' "$name" | contains_non_ascii; then + local -a python_cmd=() + local python_line + while IFS= read -r python_line; do + python_cmd+=("$python_line") + done < <(_unicode_python_command) + if [ "${#python_cmd[@]}" -eq 0 ]; then + echo "Error: Python 3 is required to create a Unicode branch name" >&2 + return 1 + fi + printf '%s' "$name" | "${python_cmd[@]}" -c ' +import sys +value = sys.stdin.buffer.read().decode("utf-8") +lower = str.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz") +result = "".join( + char if char.isalpha() or char.isdecimal() else sys.argv[1] + for char in value.translate(lower) +) +sys.stdout.buffer.write(result.encode("utf-8")) +' "$separator" + else + printf '%s' "$name" | LC_ALL=C tr '[:upper:]' '[:lower:]' | LC_ALL=C sed "s/[^a-z0-9]/$separator/g" + fi +} + +# `--*` instead of the GNU-only `\+`, which POSIX/BSD sed reads as a literal +# '+'; printf instead of echo, so a name of "-n"/"-e"/"-E" is text. clean_branch_name() { + local name="$1" + local cleaned + cleaned=$(unicode_words "$name" '-') || return 1 + printf '%s\n' "$cleaned" | sed 's/--*/-/g' | sed 's/^-//' | sed 's/-$//' +} + +# Pick a UTF-8 locale for character-safe splitting and truncation. An explicit +# LC_ALL is honored rather than overridden, as in the core script. +UNICODE_LOCALE="" +locale_candidates=(C.UTF-8 C.utf8 en_US.UTF-8 en_US.utf8 "${LC_CTYPE:-${LANG:-}}") +if [ -n "${LC_ALL:-}" ]; then + locale_candidates=("$LC_ALL") +fi +for candidate in "${locale_candidates[@]}"; do + if [ -n "$candidate" ] && [ "$(printf 'é。' | LC_ALL="$candidate" sed 's/[^[:alnum:]]/-/g' 2>/dev/null)" = 'é-' ]; then + UNICODE_LOCALE="$candidate" + break + fi +done + +if [ -z "$UNICODE_LOCALE" ]; then + UNICODE_LOCALE=C + if [ -z "${GIT_BRANCH_NAME:-}" ] && printf '%s' "${SHORT_NAME:-$FEATURE_DESCRIPTION}" | contains_non_ascii; then + if [ -n "${LC_ALL:-}" ]; then + echo "Error: A UTF-8 locale is required to create a Unicode branch name; LC_ALL=$LC_ALL is not usable" >&2 + else + echo "Error: A UTF-8 locale is required to create a Unicode branch name" >&2 + fi + exit 1 + fi +fi + +# ASCII-only cleaning for the {author} and {app} template tokens. LC_ALL=C +# because glibc resolves the a-z *range* through collation in UTF-8 locales. +clean_ascii_token() { local name="$1" local -x LC_ALL=C printf '%s\n' "$name" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | sed 's/--*/-/g' | sed 's/^-//' | sed 's/-$//' @@ -318,7 +403,7 @@ branch_token() { local value="$1" local fallback="$2" local cleaned - cleaned=$(clean_branch_name "$value") + cleaned=$(clean_ascii_token "$value") if [ -n "$cleaned" ]; then printf '%s\n' "$cleaned" else @@ -453,21 +538,23 @@ generate_branch_name() { local stop_words="^(i|a|an|the|to|for|of|in|on|at|by|with|from|is|are|was|were|be|been|being|have|has|had|do|does|did|will|would|should|could|can|may|might|must|shall|this|that|these|those|my|your|our|their|want|need|add|get|set)$" - # LC_ALL=C for the same collation reason documented on clean_branch_name, - # and so the `grep -qw` acronym probe below uses ASCII word boundaries like + # A UTF-8 locale keeps word splitting character-safe. The stop-word and + # acronym probes pin LC_ALL=C so `grep -qw` uses ASCII word boundaries like # the Python twin's (?&2 echo "Error: GIT_BRANCH_NAME must be 244 bytes or fewer in UTF-8. Provided value is ${BRANCH_BYTE_LEN} bytes." @@ -547,7 +651,7 @@ elif [ "$BRANCH_BYTE_LEN" -gt $MAX_BRANCH_LENGTH ]; then ORIGINAL_BRANCH_NAME="$BRANCH_NAME" TRUNCATED_SUFFIX="$BRANCH_SUFFIX" while [ "$(_byte_length "$BRANCH_NAME")" -gt "$MAX_BRANCH_LENGTH" ] && [ -n "$TRUNCATED_SUFFIX" ]; do - TRUNCATED_SUFFIX="${TRUNCATED_SUFFIX%?}" + TRUNCATED_SUFFIX=$(drop_last_utf8_char "$TRUNCATED_SUFFIX") TRUNCATED_SUFFIX="${TRUNCATED_SUFFIX%-}" BRANCH_NAME=$(build_branch_name "$FEATURE_NUM" "$TRUNCATED_SUFFIX") done diff --git a/extensions/git/scripts/powershell/create-new-feature-branch.ps1 b/extensions/git/scripts/powershell/create-new-feature-branch.ps1 index 697ae9c426..91bd90bb5e 100644 --- a/extensions/git/scripts/powershell/create-new-feature-branch.ps1 +++ b/extensions/git/scripts/powershell/create-new-feature-branch.ps1 @@ -178,7 +178,39 @@ function Get-NextBranchNumber { return $maxNum + 1 } +# Branch names keep Unicode letters and decimal digits, matching the core +# create-new-feature scripts (UTF-8 feature names, #4574). Only ASCII letters +# are lowercased so no culture-specific case folding can make the twins differ. +function ConvertTo-AsciiLower { + param([string]$Name) + return [regex]::Replace($Name, '[A-Z]', { param($match) $match.Value.ToLowerInvariant() }) +} + +function ConvertTo-UnicodeWords { + param([string]$Name, [string]$Separator) + + $lowerName = ConvertTo-AsciiLower -Name $Name + # A surrogate pair is one character outside the BMP; keep it when it is a + # letter or decimal digit, as Python's str.isalpha()/isdecimal() would. + return [regex]::Replace($lowerName, '[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\p{L}\p{Nd}]', { + param($match) + if ($match.Length -eq 2) { + $category = [System.Globalization.CharUnicodeInfo]::GetUnicodeCategory($match.Value, 0) + if ($category.ToString() -match '(Letter|DecimalDigitNumber)$') { + return $match.Value + } + } + return $Separator + }) +} + function ConvertTo-CleanBranchName { + param([string]$Name) + return (ConvertTo-UnicodeWords -Name $Name -Separator '-') -replace '-{2,}', '-' -replace '^-', '' -replace '-$', '' +} + +# ASCII-only cleaning for the {author} and {app} template tokens. +function ConvertTo-AsciiToken { param([string]$Name) return $Name.ToLower() -replace '[^a-z0-9]', '-' -replace '-{2,}', '-' -replace '^-', '' -replace '-$', '' } @@ -297,7 +329,7 @@ function ConvertTo-BranchToken { [string]$Fallback ) - $cleaned = ConvertTo-CleanBranchName -Name $Value + $cleaned = ConvertTo-AsciiToken -Name $Value if ($cleaned) { return $cleaned } return $Fallback } @@ -425,13 +457,16 @@ function Get-BranchName { 'want', 'need', 'add', 'get', 'set' ) - $cleanName = $Description.ToLower() -replace '[^a-z0-9\s]', ' ' + $cleanName = ConvertTo-UnicodeWords -Name $Description -Separator ' ' $words = $cleanName -split '\s+' | Where-Object { $_ } $meaningfulWords = @() foreach ($word in $words) { - if ($stopWords -contains $word) { continue } - if ($word.Length -ge 3) { + # -ccontains: words are already ASCII-lowercased, and -contains would + # also match a stop word against Unicode case variants. + if ($stopWords -ccontains $word) { continue } + # Keep non-ASCII words even when short (CJK words are often 2 chars). + if ($word.Length -ge 3 -or $word -match '[^\x00-\x7F]') { $meaningfulWords += $word } elseif ($Description -cmatch "(? str: + """Keep Unicode letters and decimal digits; replace everything else. + + Mirrors the core create_new_feature.py naming policy (UTF-8 feature + names, #4574): only ASCII letters are lowercased, so no Unicode case + folding can make the twins disagree. + """ + return "".join( + char if char.isalpha() or char.isdecimal() else separator + for char in name.translate(_ASCII_LOWER) + ) + + def clean_branch_name(name: str) -> str: + name = re.sub(r"-+", "-", unicode_words(name, "-")) + return name.strip("-") + + +def clean_ascii_token(name: str) -> str: + """ASCII-only cleaning for the {author} and {app} template tokens.""" name = re.sub(r"[^a-z0-9]", "-", name.lower()) name = re.sub(r"-+", "-", name) return name.strip("-") @@ -331,13 +355,14 @@ def clean_branch_name(name: str) -> str: def generate_branch_name(description: str) -> str: """Generate a branch suffix from the description with stop word filtering.""" - clean_name = re.sub(r"[^a-z0-9]", " ", description.lower()) + clean_name = unicode_words(description, " ") meaningful_words = [] for word in clean_name.split(): if word in STOP_WORDS: continue - if len(word) >= 3: + # Keep non-ASCII words even when short (CJK words are often 2 chars). + if len(word) >= 3 or not word.isascii(): meaningful_words.append(word) # Keep short words only when they appear uppercased in the original # description (acronyms like "API" or "DB"). The boundaries are spelled @@ -360,7 +385,7 @@ def generate_branch_name(description: str) -> str: def branch_token(value: str, fallback: str) -> str: - cleaned = clean_branch_name(value) + cleaned = clean_ascii_token(value) return cleaned if cleaned else fallback diff --git a/tests/extensions/git/test_git_extension.py b/tests/extensions/git/test_git_extension.py index 11381566b9..bd55cc7054 100644 --- a/tests/extensions/git/test_git_extension.py +++ b/tests/extensions/git/test_git_extension.py @@ -148,11 +148,14 @@ def _run_bash(script_name: str, cwd: Path, *args: str, env_extra: dict | None = """Run an extension bash script.""" script = cwd / ".specify" / "extensions" / "git" / "scripts" / "bash" / script_name env = {**os.environ, **_GIT_ENV, **(env_extra or {})} + # bash and jq write UTF-8; the locale default (e.g. cp936) would garble + # non-ASCII branch names before a test can compare them. return subprocess.run( ["bash", str(script), *args], cwd=cwd, capture_output=True, text=True, + encoding="utf-8", env=env, ) @@ -186,7 +189,7 @@ def test_manifest_validates(self): m = ExtensionManifest(EXT_DIR / "extension.yml") assert m.id == "git" - assert m.version == "1.0.9" + assert m.version == "1.0.10" def test_manifest_commands(self): """Manifest declares expected commands.""" @@ -2352,6 +2355,68 @@ def test_create_branch_reads_branch_prefix_as_utf8(self, tmp_path: Path, exe: st "équipe/001-guided-tour" ] + @pytest.mark.parametrize( + ("args", "expected"), + [ + (("添加待办事项",), "001-添加待办事项"), + (("Ünïcödé café",), "001-Ünïcödé-café"), + (("-ShortName", "待办 事项!", "x"), "001-待办-事项"), + ], + ids=["cjk_only", "accented", "cjk_short_name"], + ) + def test_create_branch_keeps_unicode_words( + self, tmp_path: Path, exe: str, args: tuple[str, ...], expected: str + ): + """Non-Latin names keep their words, matching the core script (#5553). + + On main a CJK-only description left no ASCII words, so the fallback + passed $null to [string]::Join and the script failed (surfacing as + MethodInvocationException on 5.1) instead of creating a branch. + """ + project = _setup_project(tmp_path) + + result = _run_pwsh("create-new-feature-branch.ps1", project, *args, exe=exe) + + assert result.returncode == 0, result.stdout + result.stderr + assert self._git_lines(project, "branch", "--show-current") == [expected] + + @pytest.mark.parametrize( + ("short_name", "expected_suffix"), + [ + ("汉" * 100, "汉" * 80), + ("𠀀" * 70, "𠀀" * 60), + ("a" + "𠀀" * 70, "a" + "𠀀" * 59), + ], + ids=["bmp", "astral", "astral_after_ascii"], + ) + def test_unicode_branch_name_truncates_on_character_boundary( + self, tmp_path: Path, exe: str, short_name: str, expected_suffix: str + ): + """Truncation to 244 bytes drops whole surrogate pairs, never half of one.""" + project = _setup_project(tmp_path) + + result = _run_pwsh( + "create-new-feature-branch.ps1", project, + "-ShortName", short_name, "x", + exe=exe, + ) + + assert result.returncode == 0, result.stdout + result.stderr + branch = self._git_lines(project, "branch", "--show-current")[0] + assert branch == f"001-{expected_suffix}" + assert len(branch.encode("utf-8")) <= 244 + + def test_create_branch_without_words_does_not_throw(self, tmp_path: Path, exe: str): + """Punctuation-only input still reaches the fallback; @() keeps it safe.""" + project = _setup_project(tmp_path) + + result = _run_pwsh( + "create-new-feature-branch.ps1", project, "-Json", "-DryRun", "!!!", exe=exe, + ) + + assert result.returncode == 0, result.stdout + result.stderr + assert json.loads(result.stdout)["BRANCH_NAME"] == "001-" + # ── auto-commit.ps1 CRLF warning tests (issue #2253) ──────────────────────── diff --git a/tests/extensions/git/test_git_extension_python_parity.py b/tests/extensions/git/test_git_extension_python_parity.py index bfa2a4e5ef..e4d56b6daa 100644 --- a/tests/extensions/git/test_git_extension_python_parity.py +++ b/tests/extensions/git/test_git_extension_python_parity.py @@ -74,11 +74,14 @@ def _run_py( cwd / ".specify" / "extensions" / "git" / "scripts" / "python" / PY_SCRIPTS[script_name] ) env = {**os.environ, **_GIT_ENV, **(env_extra or {})} + # The twin writes stderr in the console code page unless PYTHONIOENCODING + # overrides it; replace undecodable bytes rather than losing the stream. return subprocess.run( [sys.executable, str(script), *args], cwd=run_cwd or cwd, capture_output=True, text=True, + errors="replace", env=env, ) @@ -93,7 +96,9 @@ def _twin_projects(tmp_path: Path, *, git: bool = True) -> tuple[Path, Path]: def _branch_state(project: Path) -> tuple[str, str]: return tuple( subprocess.run( - ["git", *args], cwd=project, check=True, capture_output=True, text=True, + # git prints ref names as UTF-8 regardless of the locale. + ["git", *args], cwd=project, check=True, capture_output=True, + text=True, encoding="utf-8", ).stdout.strip() for args in (("symbolic-ref", "--short", "HEAD"), ("for-each-ref",)) ) @@ -121,6 +126,24 @@ def _assert_parity( assert py_stderr == bash_stderr +def _assert_json_parity( + bash_result: subprocess.CompletedProcess, + py_result: subprocess.CompletedProcess, + *, + stderr: bool = True, +) -> dict: + """Parity for -Json output that may contain non-ASCII branch names. + + jq writes raw UTF-8 while the Python twin escapes non-ASCII as \\uXXXX so + its output survives legacy code-page pipes (#5474), so compare the + decoded payloads rather than the raw text. + """ + _assert_parity(bash_result, py_result, stdout=False, stderr=stderr) + payload = json.loads(bash_result.stdout) + assert json.loads(py_result.stdout) == payload + return payload + + def _without_persist_hint(stderr: str) -> str: return "".join( line @@ -251,7 +274,7 @@ def test_acronym_adjacent_to_non_ascii_matches_python( "create-new-feature-branch", py_proj, "--json", "--dry-run", description, ) - _assert_parity(b, p) + _assert_json_parity(b, p) if not HAS_PWSH: pytest.skip("pwsh not available") @@ -303,10 +326,10 @@ def test_branch_name_ignores_locale_collation( ): """The created git branch must not depend on the caller's locale. - The bash twin sanitizes with sed 's/[^a-z0-9]/-/g'. Under a locale whose - a-z range is collation-ordered that class keeps accented lowercase - letters, so bash checked out 001-ajouter-réservation-hôtelière where - the Python twin checks out 001-ajouter-servation-teli. + Under a locale whose a-z range is collation-ordered, a sed [^a-z0-9] + class keeps accented lowercase letters, so the twins used to disagree. + Branch names now keep Unicode letters (#5553), and both twins must + produce the same Unicode name regardless of the collation locale. """ locale_name = collation_range_locale() if locale_name is None: @@ -322,14 +345,16 @@ def test_branch_name_ignores_locale_collation( "create-new-feature-branch", py_proj, "--json", "--dry-run", description, env_extra=env_extra, ) - _assert_parity(b, p) - branch = json.loads(b.stdout)["BRANCH_NAME"] - assert branch.isascii(), branch + branch = _assert_json_parity(b, p)["BRANCH_NAME"] + assert branch == { + "Añadir autenticación de usuario": "001-añadir-autenticación-usuario", + "Ajouter la réservation hôtelière": "001-ajouter-réservation-hôtelière", + }[description] # The run above reaches generate_branch_name. --short-name reaches - # clean_branch_name, a separate function carrying its own LC_ALL=C, so - # exercise the accented value through both: neither copy can then - # regress on its own without a failure here. + # clean_branch_name, a separate code path, so exercise the accented + # value through both: neither can then regress on its own without a + # failure here. sn_bash_proj, sn_py_proj = _twin_projects(tmp_path / "short") sb = _run_bash( "create-new-feature-branch.sh", sn_bash_proj, @@ -341,9 +366,11 @@ def test_branch_name_ignores_locale_collation( "--json", "--dry-run", "--short-name", description, "desc", env_extra=env_extra, ) - _assert_parity(sb, sp) - short_branch = json.loads(sb.stdout)["BRANCH_NAME"] - assert short_branch.isascii(), short_branch + short_branch = _assert_json_parity(sb, sp)["BRANCH_NAME"] + assert short_branch == { + "Añadir autenticación de usuario": "001-añadir-autenticación-de-usuario", + "Ajouter la réservation hôtelière": "001-ajouter-la-réservation-hôtelière", + }[description] @pytest.mark.parametrize("short_name", ["-n", "-e", "-E"], ids=["n", "e", "E"]) def test_dash_prefixed_short_name(self, tmp_path: Path, short_name: str): @@ -363,6 +390,115 @@ def test_dash_prefixed_short_name(self, tmp_path: Path, short_name: str): expected = f"001-{short_name.lstrip('-').lower()}" assert json.loads(b.stdout)["BRANCH_NAME"] == expected + @pytest.mark.parametrize( + ("args", "expected"), + [ + (("添加待办事项",), "001-添加待办事项"), + (("支持 OAuth2 登录",), "001-支持-oauth2-登录"), + (("Add API for 用户 DB",), "001-api-用户-db"), + (("Ünïcödé café",), "001-Ünïcödé-café"), + (("--short-name", "待办 事项!", "x"), "001-待办-事项"), + ], + ids=["cjk_only", "cjk_mixed", "cjk_acronyms", "accented", "cjk_short_name"], + ) + def test_unicode_branch_names_match_core_policy( + self, tmp_path: Path, args: tuple[str, ...], expected: str + ): + """Non-Latin descriptions keep their words, as in the core scripts. + + The extension used [^a-z0-9], so a CJK-only description became the + suffix-less branch 001- while the core script created + specs/001-添加待办事项/ (#5553). + """ + bash_proj, py_proj = _twin_projects(tmp_path) + b = _run_bash("create-new-feature-branch.sh", bash_proj, "--json", "--dry-run", *args) + p = _run_py("create-new-feature-branch", py_proj, "--json", "--dry-run", *args) + assert _assert_json_parity(b, p)["BRANCH_NAME"] == expected + + def test_unicode_branch_is_created_and_checked_out(self, tmp_path: Path): + """A real run checks out the Unicode branch instead of 001-.""" + bash_proj, py_proj = _twin_projects(tmp_path) + b = _run_bash("create-new-feature-branch.sh", bash_proj, "--json", "添加待办事项") + p = _run_py("create-new-feature-branch", py_proj, "--json", "添加待办事项") + assert _assert_json_parity(b, p, stderr=False)["BRANCH_NAME"] == "001-添加待办事项" + assert _branch_state(bash_proj) == _branch_state(py_proj) + assert _branch_state(bash_proj)[0] == "001-添加待办事项" + + def test_author_and_app_tokens_stay_ascii(self, tmp_path: Path): + """Only the {slug} keeps Unicode; {author}/{app} cleaning is unchanged. + + Both twins run in a project directory named "Café 应用" so {app} is + derived from a non-ASCII name, as {author} is from git user.name. + """ + bash_proj = _setup_py_project(tmp_path / "bash" / "Café 应用") + py_proj = _setup_py_project(tmp_path / "py" / "Café 应用") + for proj in (bash_proj, py_proj): + _write_config(proj, 'branch_template: "{author}/{app}/{number}-{slug}"\n') + subprocess.run( + ["git", "config", "user.name", "Zoë 测试"], cwd=proj, check=True + ) + b = _run_bash("create-new-feature-branch.sh", bash_proj, "--json", "--dry-run", "添加待办") + p = _run_py("create-new-feature-branch", py_proj, "--json", "--dry-run", "添加待办") + assert _assert_json_parity(b, p)["BRANCH_NAME"] == "zo/caf/001-添加待办" + + @pytest.mark.parametrize("layout", ["core_common", "git_common_only", "stale_core_common"]) + def test_unicode_branch_name_finds_python_without_core_helper( + self, tmp_path: Path, layout: str + ): + """Unicode naming must not depend on core common.sh's _python3_command. + + The script falls back to git-common.sh when core is missing, and an + older core common.sh may lack _python3_command; both must still find a + system Python rather than failing with "Python 3 is required". + """ + bash_proj, py_proj = _twin_projects(tmp_path) + common_sh = bash_proj / "scripts" / "bash" / "common.sh" + if layout == "git_common_only": + common_sh.unlink() + elif layout == "stale_core_common": + text = common_sh.read_text(encoding="utf-8") + common_sh.write_text( + text.replace("_python3_command()", "_removed_python3_command()"), + encoding="utf-8", + newline="\n", + ) + env_extra = {"SPECKIT_PYTHON_EXECUTABLE": "", "SPECKIT_PYTHON": ""} + args = ("--json", "--dry-run", "Add résumé support") + b = _run_bash("create-new-feature-branch.sh", bash_proj, *args, env_extra=env_extra) + p = _run_py("create-new-feature-branch", py_proj, *args, env_extra=env_extra) + assert _assert_json_parity(b, p, stderr=False)["BRANCH_NAME"] == "001-résumé-support" + + @pytest.mark.parametrize( + ("short_name", "expected_suffix"), + [ + ("汉" * 100, "汉" * 80), + ("𠀀" * 70, "𠀀" * 60), + ("a" + "𠀀" * 70, "a" + "𠀀" * 59), + ], + ids=["bmp", "astral", "astral_after_ascii"], + ) + def test_unicode_branch_name_truncates_on_character_boundary( + self, tmp_path: Path, short_name: str, expected_suffix: str + ): + """Truncation to 244 bytes must never split a multi-byte character. + + MSYS/Cygwin bash has a 16-bit wchar_t, so a locale-aware ${var%?} + removed half of a surrogate pair once an odd-length ASCII prefix put + the astral characters out of step (astral_after_ascii). + """ + bash_proj, py_proj = _twin_projects(tmp_path) + args = ("--json", "--dry-run", "--short-name", short_name, "x") + b = _run_bash("create-new-feature-branch.sh", bash_proj, *args) + p = _run_py("create-new-feature-branch", py_proj, *args) + # The truncation warning quotes the non-ASCII name; the Python twin + # writes it in the console code page, so check its presence rather + # than comparing the raw stderr text across twins. + branch = _assert_json_parity(b, p, stderr=False)["BRANCH_NAME"] + assert branch == f"001-{expected_suffix}" + assert len(branch.encode("utf-8")) <= 244 + for result in (b, p): + assert "244-byte limit" in result.stderr + def test_numbering_from_specs_and_branches(self, tmp_path: Path): bash_proj, py_proj = _twin_projects(tmp_path) for proj in (bash_proj, py_proj): From 22299d856e1485c4e72afd6d90a97ac03d1121de Mon Sep 17 00:00:00 2001 From: ckr <15865258+chekunru@user.noreply.gitee.com> Date: Wed, 25 Nov 2026 14:38:38 +0800 Subject: [PATCH 2/3] fix(git): quote the persist hint as UTF-8 and test Unicode failure paths - bash: quote the SPECIFY_FEATURE persist hint with shell_quote, as core create-new-feature.sh does, instead of printf %q. Outside a UTF-8 locale (the macOS default) %q escaped each non-ASCII byte as $'\ooo', so stderr was not valid UTF-8 and test_unicode_branch_is_created_and_ checked_out failed on macOS CI. - Python: quote the POSIX hint with shlex.quote to stay byte-identical with the bash twin. - tests: cover Unicode names with no Python 3 available and with an explicit LC_ALL=C/POSIX (clear error, exit 1, empty stdout, refs unchanged, ASCII still succeeds), and the persist hint without a UTF-8 locale. Addresses the Copilot review. Assisted-by: Claude Code (model: Claude Opus 5.5, supervised) --- .../scripts/bash/create-new-feature-branch.sh | 17 +++- .../python/create_new_feature_branch.py | 6 +- .../git/test_git_extension_python_parity.py | 77 +++++++++++++++++++ 3 files changed, 96 insertions(+), 4 deletions(-) diff --git a/extensions/git/scripts/bash/create-new-feature-branch.sh b/extensions/git/scripts/bash/create-new-feature-branch.sh index 7b22e5ddaf..09e9c63404 100755 --- a/extensions/git/scripts/bash/create-new-feature-branch.sh +++ b/extensions/git/scripts/bash/create-new-feature-branch.sh @@ -627,6 +627,19 @@ fi MAX_BRANCH_LENGTH=244 _byte_length() { printf '%s' "$1" | LC_ALL=C wc -c | tr -d ' '; } +# Quote a value for POSIX shell reuse, as core create-new-feature.sh does. +# printf %q is not used: outside a UTF-8 locale (macOS defaults) it escapes +# each non-ASCII byte as $'\ooo', which is not valid UTF-8 text. +shell_quote() { + local value="$1" LC_ALL=C + if [[ "$value" =~ ^[A-Za-z0-9_@%+=:,./-]+$ ]]; then + printf '%s' "$value" + else + local q="'\"'\"'" + printf "'%s'" "${value//\'/$q}" + fi +} + # Drop the last UTF-8 character by bytes. A locale-aware ${var%?} is not safe: # MSYS/Cygwin bash has a 16-bit wchar_t, so it would split a character outside # the BMP and leave a broken sequence. @@ -704,7 +717,7 @@ if [ "$DRY_RUN" != true ]; then >&2 echo "[specify] Warning: Git repository not detected; skipped branch creation for $BRANCH_NAME" fi - printf '# To persist: export SPECIFY_FEATURE=%q\n' "$BRANCH_NAME" >&2 + printf '# To persist: export SPECIFY_FEATURE=%s\n' "$(shell_quote "$BRANCH_NAME")" >&2 fi if $JSON_MODE; then @@ -738,6 +751,6 @@ else echo "BRANCH_NAME: $BRANCH_NAME" echo "FEATURE_NUM: $FEATURE_NUM" if [ "$DRY_RUN" != true ]; then - printf '# To persist in your shell: export SPECIFY_FEATURE=%q\n' "$BRANCH_NAME" + printf '# To persist in your shell: export SPECIFY_FEATURE=%s\n' "$(shell_quote "$BRANCH_NAME")" fi fi diff --git a/extensions/git/scripts/python/create_new_feature_branch.py b/extensions/git/scripts/python/create_new_feature_branch.py index be03f8e6e3..e93dc1adf0 100644 --- a/extensions/git/scripts/python/create_new_feature_branch.py +++ b/extensions/git/scripts/python/create_new_feature_branch.py @@ -15,6 +15,7 @@ import json import os import re +import shlex import shutil import subprocess import sys @@ -86,8 +87,9 @@ def _persist_hint(var_name: str, value: str) -> str: if os.name == "nt": escaped_value = value.replace("'", "''") return f"$env:{var_name} = '{escaped_value}'" - escaped_value = re.sub(r"([^\w@%+=:,./-])", r"\\\1", value) - return f"export {var_name}={escaped_value}" + # shlex.quote matches the bash twin's shell_quote byte for byte, as in + # core create_new_feature.py. + return f"export {var_name}={shlex.quote(value)}" def _int64_from_digits(value: str) -> int | None: diff --git a/tests/extensions/git/test_git_extension_python_parity.py b/tests/extensions/git/test_git_extension_python_parity.py index e4d56b6daa..10b4cca1cc 100644 --- a/tests/extensions/git/test_git_extension_python_parity.py +++ b/tests/extensions/git/test_git_extension_python_parity.py @@ -441,6 +441,83 @@ def test_author_and_app_tokens_stay_ascii(self, tmp_path: Path): p = _run_py("create-new-feature-branch", py_proj, "--json", "--dry-run", "添加待办") assert _assert_json_parity(b, p)["BRANCH_NAME"] == "zo/caf/001-添加待办" + @pytest.mark.parametrize( + "args", + [("添加待办事项",), ("--short-name", "待办", "Add todo")], + ids=["description", "short_name"], + ) + def test_unicode_name_without_python_fails_cleanly( + self, tmp_path: Path, args: tuple[str, ...] + ): + """Without Python 3, a Unicode name fails before touching git; ASCII still works.""" + project = _setup_py_project(tmp_path / "proj") + shim_dir = tmp_path / "bin" + shim_dir.mkdir() + for name in ("python3", "python", "py"): + shim = shim_dir / name + shim.write_text("#!/bin/sh\nexit 1\n", encoding="utf-8", newline="\n") + shim.chmod(0o755) + env_extra = { + "PATH": f"{shim_dir}{os.pathsep}{os.environ['PATH']}", + "SPECKIT_PYTHON_EXECUTABLE": "", + "SPECKIT_PYTHON": "", + } + refs_before = _branch_state(project) + + ascii_result = _run_bash( + "create-new-feature-branch.sh", project, + "--json", "--dry-run", "Add user authentication", env_extra=env_extra, + ) + assert ascii_result.returncode == 0, ascii_result.stderr + assert json.loads(ascii_result.stdout)["BRANCH_NAME"] == "001-user-authentication" + + result = _run_bash( + "create-new-feature-branch.sh", project, "--json", *args, env_extra=env_extra, + ) + assert result.returncode == 1 + assert result.stdout == "" + assert "Error: Python 3 is required to create a Unicode branch name" in result.stderr + assert _branch_state(project) == refs_before + + @pytest.mark.parametrize("locale_name", ["C", "POSIX"]) + def test_unicode_name_under_explicit_non_utf8_lc_all_fails_cleanly( + self, tmp_path: Path, locale_name: str + ): + """An explicit non-UTF-8 LC_ALL is honored, not overridden, as in core.""" + project = _setup_py_project(tmp_path / "proj") + env_extra = {"LC_ALL": locale_name, "LANG": "C.UTF-8"} + refs_before = _branch_state(project) + + ascii_result = _run_bash( + "create-new-feature-branch.sh", project, + "--json", "--dry-run", "Add user authentication", env_extra=env_extra, + ) + assert ascii_result.returncode == 0, ascii_result.stderr + assert json.loads(ascii_result.stdout)["BRANCH_NAME"] == "001-user-authentication" + + for args in (("添加待办事项",), ("--short-name", "待办", "Add todo")): + result = _run_bash( + "create-new-feature-branch.sh", project, "--json", *args, env_extra=env_extra, + ) + assert result.returncode == 1 + assert result.stdout == "" + assert "A UTF-8 locale is required" in result.stderr + assert f"LC_ALL={locale_name}" in result.stderr + assert _branch_state(project) == refs_before + + def test_persist_hint_is_utf8_without_a_utf8_locale(self, tmp_path: Path): + """The persist hint quotes like shlex.quote instead of printf %q. + + printf %q escapes each non-ASCII byte as $'\\ooo' outside a UTF-8 + locale (the macOS default), which made the hint invalid UTF-8. + """ + bash_proj, py_proj = _twin_projects(tmp_path) + env_extra = {"LC_ALL": "", "LC_CTYPE": "", "LANG": ""} + b = _run_bash("create-new-feature-branch.sh", bash_proj, "--json", "添加待办事项", env_extra=env_extra) + p = _run_py("create-new-feature-branch", py_proj, "--json", "添加待办事项", env_extra=env_extra) + assert _assert_json_parity(b, p, stderr=False)["BRANCH_NAME"] == "001-添加待办事项" + assert "# To persist: export SPECIFY_FEATURE='001-添加待办事项'" in b.stderr + @pytest.mark.parametrize("layout", ["core_common", "git_common_only", "stale_core_common"]) def test_unicode_branch_name_finds_python_without_core_helper( self, tmp_path: Path, layout: str From 5565bde87f78feea1195cab8350bae472f519db2 Mon Sep 17 00:00:00 2001 From: ckr <15865258+chekunru@user.noreply.gitee.com> Date: Wed, 25 Nov 2026 15:28:59 +0800 Subject: [PATCH 3/3] test(git): cover Unicode number categories in git extension names MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Port core's test_unicode_number_categories_match cases to the git extension for bash, Python, and Windows PowerShell 5.1: decimal digits (x٥, x𝟘) are kept, while other number categories (x², xⅫ) become separators. Addresses the Copilot review. Assisted-by: Claude Code (model: Claude Opus 5.5, supervised) --- tests/extensions/git/test_git_extension.py | 25 +++++++++++++++++++ .../git/test_git_extension_python_parity.py | 20 +++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/tests/extensions/git/test_git_extension.py b/tests/extensions/git/test_git_extension.py index bd55cc7054..808448dc2b 100644 --- a/tests/extensions/git/test_git_extension.py +++ b/tests/extensions/git/test_git_extension.py @@ -2406,6 +2406,31 @@ def test_unicode_branch_name_truncates_on_character_boundary( assert branch == f"001-{expected_suffix}" assert len(branch.encode("utf-8")) <= 244 + @pytest.mark.parametrize( + ("short_name", "expected"), + [ + ("x²", "001-x"), + ("xⅫ", "001-x"), + ("x٥", "001-x٥"), + ("x𝟘", "001-x𝟘"), + ], + ids=["superscript_number", "roman_numeral", "decimal_digit", "supplementary_decimal"], + ) + def test_unicode_number_categories_match( + self, tmp_path: Path, exe: str, short_name: str, expected: str + ): + """Only decimal digits (Nd) are kept, including outside the BMP (x𝟘).""" + project = _setup_project(tmp_path) + + result = _run_pwsh( + "create-new-feature-branch.ps1", project, + "-Json", "-DryRun", "-ShortName", short_name, "x", + exe=exe, + ) + + assert result.returncode == 0, result.stdout + result.stderr + assert json.loads(result.stdout)["BRANCH_NAME"] == expected + def test_create_branch_without_words_does_not_throw(self, tmp_path: Path, exe: str): """Punctuation-only input still reaches the fallback; @() keeps it safe.""" project = _setup_project(tmp_path) diff --git a/tests/extensions/git/test_git_extension_python_parity.py b/tests/extensions/git/test_git_extension_python_parity.py index 10b4cca1cc..2841ff609e 100644 --- a/tests/extensions/git/test_git_extension_python_parity.py +++ b/tests/extensions/git/test_git_extension_python_parity.py @@ -415,6 +415,26 @@ def test_unicode_branch_names_match_core_policy( p = _run_py("create-new-feature-branch", py_proj, "--json", "--dry-run", *args) assert _assert_json_parity(b, p)["BRANCH_NAME"] == expected + @pytest.mark.parametrize( + ("short_name", "expected"), + [ + ("x²", "001-x"), + ("xⅫ", "001-x"), + ("x٥", "001-x٥"), + ("x𝟘", "001-x𝟘"), + ], + ids=["superscript_number", "roman_numeral", "decimal_digit", "supplementary_decimal"], + ) + def test_unicode_number_categories_match( + self, tmp_path: Path, short_name: str, expected: str + ): + """Only decimal digits (Nd) are kept, as in core; other numbers are separators.""" + bash_proj, py_proj = _twin_projects(tmp_path) + args = ("--json", "--dry-run", "--short-name", short_name, "x") + b = _run_bash("create-new-feature-branch.sh", bash_proj, *args) + p = _run_py("create-new-feature-branch", py_proj, *args) + assert _assert_json_parity(b, p)["BRANCH_NAME"] == expected + def test_unicode_branch_is_created_and_checked_out(self, tmp_path: Path): """A real run checks out the Unicode branch instead of 001-.""" bash_proj, py_proj = _twin_projects(tmp_path)