#!/usr/bin/env python3 # -*- coding: utf-8 -*- """生成 staging-p1/tokensync.sh —— P1(暖向中性)的一键迁移件。**属于另一笔授权**, 不混进 #20 的 landing/:#20 换的是标识资产与文档,这一支改的是全站色板与阴影基色。 映射不硬编:12 组中性令牌来自 `TOKEN-MIGRATION.md`,5 组深色底面由确定性规则现算 (保持明度 L、色相统一到 33°、饱和度压到 ≤0.14)。每个值都带**期望命中数**, 任一值对不上就整批拒绝——上一轮实测的账面是 82 = 47 + 16 + 19, 其中 19 处彩性蓝**故意不动**(语义色,另案)。 """ import colorsys import io import os import re HERE = os.path.dirname(os.path.abspath(__file__)) REPO = os.path.abspath(os.path.join(HERE, '..', '..')) NEUTRAL = {'#0A0E14': '#141210', '#0F172A': '#1E1B17', '#1E293B': '#2A2621', '#334155': '#3A352E', '#475569': '#4F4A42', '#64748B': '#6E675D', '#94A3B8': '#8A8377', '#CBD5E1': '#C3BDB1', '#E2E8F0': '#EFEAE1', '#EEF2F7': '#F7F4EF', '#F1F5F9': '#FBF9F5', '#F8FAFC': '#FBF9F5', '#F6F8FA': '#FAF8F4', '#EEF1F5': '#EFEAE1'} HEXPAT = r'#[0-9a-fA-F]{6,8}(?![0-9a-fA-F])' # 生成端与脚本端共用,杜绝"两套量具" HEX = re.compile(HEXPAT) def hsl(x): v = x[1:] r, g, b = [int(v[i:i + 2], 16) / 255 for i in (0, 2, 4)] hh, l, s = colorsys.rgb_to_hls(r, g, b) return hh * 360.0, l, s def tohex(deg, l, s): return '#%02X%02X%02X' % tuple(round(c * 255) for c in colorsys.hls_to_rgb(deg / 360.0, l, s)) def dryrun(MAP): """期望值不靠算术推导,靠**真跑一遍内存里的替换**。 上一版用 total − covered 反推剩余,结果差 4:`cnt[k]` 与"替换后冷色真的少了几处" 不是一回事(同一处文本可以既是 MAP 键、又不落在 195°–235° 的冷色窗口里)。 凡是"预测一个改动会带来什么结果"的判据,都应当用被预测的那个操作本身去算, 而不是用另一套统计口径去推 —— 两套口径之间的差,最后都会变成假红或假绿。""" import re as _re HEX = _re.compile(r'#[0-9a-fA-F]{6}(?![0-9a-fA-F])') before = after = hits = 0 perkey = {} for root, ds, fs in os.walk(os.path.join(REPO, 'src')): ds[:] = [d for d in ds if d not in ('node_modules', '.next')] for f in fs: if not f.endswith(('.ts', '.tsx', '.css')): continue t = io.open(os.path.join(root, f), encoding='utf-8', errors='ignore').read() before += len([m for m in HEX.finditer(t) if 195 <= hsl(m.group(0))[0] <= 235]) for a, b in MAP.items(): for A in {a, a.lower()}: # 集合去重:纯数字十六进制的 lower() 等于自身, # 元组写法会把同一串数两次(3→6、1→2,正是那"差 4") c = t.count(A) if c: hits += c perkey[a] = perkey.get(a, 0) + c t = t.replace(A, b) after += len([m for m in HEX.finditer(t) if 195 <= hsl(m.group(0))[0] <= 235]) return before, after, hits, perkey def census(): """从真仓现状算出:每个冷色值出现多少次、哪些属"深色底面"该一起转。""" cnt, dark = {}, {} for root, ds, fs in os.walk(os.path.join(REPO, 'src')): ds[:] = [d for d in ds if d not in ('node_modules', '.next')] for f in fs: if not f.endswith(('.ts', '.tsx', '.css')): continue for m in HEX.finditer(open(os.path.join(root, f), encoding='utf-8', errors='ignore').read()): x = m.group(0).upper() deg, l, s = hsl(x) if 195 <= deg <= 235: cnt[x] = cnt.get(x, 0) + 1 if l < 0.20 and x not in NEUTRAL: dark[x] = tohex(33.0, l, min(s, 0.14)) return cnt, dark def main(): cnt, dark = census() total = sum(cnt.values()) MAP = dict(NEUTRAL) MAP.update(dark) exp = {k: cnt.get(k, 0) + cnt.get(k.lower(), 0) for k in MAP} before, after, hits, perkey = dryrun(MAP) covered, residual = hits, after total = before # 断言①的期望值改为 dry-run 的逐值命中,不再用另一套统计口径(cnt)推。 # 上一版两套口径并存,于是"逐值合计 72 / dry-run 68"这种 4 的缺口只能挂在纸上; # 同源之后它不可能再出现,而缺口本身也说明 cnt 那套把某些出现重复计了。 exp = {k: v for k, v in perkey.items() if v} if sum(exp.values()) != covered: print(' ⚠ 逐值合计 %d 与 dry-run 命中 %d 仍不等 ⇒ 停止,别生成带矛盾期望的脚本' % (sum(exp.values()), covered)) raise SystemExit(1) assert len(dark) >= 3, '深色底面只算到 %d 种 ⇒ 扫描口径不对,别生成半成品脚本' % len(dark) lines = ['#!/usr/bin/env bash', '# P1 暖向中性迁移(**另一笔授权**,不属于 #20 的 landing/)', '# 沙箱彩排:REPO_ROOT=<沙箱> bash staging-p1/tokensync.sh', 'set -euo pipefail', 'REPO_ROOT="${REPO_ROOT:?红:必须显式给出 REPO_ROOT}"', 'cd "$REPO_ROOT"', 'test -d src/app || { echo "红:找不到 src/app,不像本仓根"; exit 1; }', 'python3 - <<\'PY\''] lines += ['import io, os, sys', "ROOT = os.environ['REPO_ROOT']", 'MAP = %r' % MAP, 'EXP = %r' % exp, 'RESIDUAL_EXPECT = %d' % residual, 'CHROMA_KEEP = %r' % sorted(k for k, v in cnt.items() if k not in MAP), 'n = 0; seen = {}', 'for root, ds, fs in os.walk(os.path.join(ROOT, "src")):', ' ds[:] = [d for d in ds if d not in ("node_modules", ".next")]', ' for f in fs:', ' if not f.endswith((".ts", ".tsx", ".css")): continue', ' p = os.path.join(root, f)', ' s = io.open(p, encoding="utf-8").read(); o = s', ' for a, b in MAP.items():', ' for A in {a, a.lower()}:', ' c = s.count(A)', ' if c: seen[A.upper()] = seen.get(A.upper(), 0) + c; s = s.replace(A, b)', ' if s != o:', ' io.open(p, "w", encoding="utf-8").write(s); n += 1', 'bad = []', 'for a, want in EXP.items():', ' got = seen.get(a.upper(), 0) # 单次取值:纯数字十六进制的 lower()==upper()==自身,', ' # 旧写法 seen.get(a)+seen.get(a.lower()) 会把同一串数两次(3→6)', ' if got != want: bad.append("%s 命中 %d,期望 %d" % (a, got, want))', 'assert not bad, "逐值命中数与制备时实测不一致 ⇒ 色板已被别的改动动过,停下来问清楚:" + "; ".join(bad)', 'assert n > 0, "一个文件都没改 ⇒ 要么已打过,要么口径错"', 'print("已改 %d 个文件、%d 处色值" % (n, sum(seen.values())));', 'import re as _re, colorsys as _cs', '_HEX = _re.compile(r"#[0-9a-fA-F]{6,8}(?![0-9a-fA-F])")', 'def _cold(x):', ' v = x[1:]; r, g, bl = [int(v[i:i+2], 16) / 255 for i in (0, 2, 4)]', ' return _cs.rgb_to_hls(r, g, bl)[0] * 360.0', 'left = 0', 'for root, ds, fs in os.walk(os.path.join(ROOT, "src")):', ' ds[:] = [d for d in ds if d not in ("node_modules", ".next")]', ' for f in fs:', ' if not f.endswith((".ts", ".tsx", ".css")): continue', ' for m in _HEX.finditer(io.open(os.path.join(root, f), encoding="utf-8", errors="ignore").read()):', ' if 195 <= _cold(m.group(0)) <= 235: left += 1', 'assert left == RESIDUAL_EXPECT, (', ' "迁移后剩余冷色 %d 处,与制备时算定的 %d 处不符 ⇒ 要么映射漏了值,要么色板被动过" % (left, RESIDUAL_EXPECT))', 'print("剩余冷色 %d 处 = 彩性蓝(另案,故意不动)✓ 账面闭合" % left)'] lines += ['PY', 'echo "落库后请跑:npm run check:contrast && npm run check:brand-token(副本实测:44 组全达标)"'] out = os.path.join(HERE, 'staging-p1', 'tokensync.sh') io.open(out, 'w', encoding='utf-8').write("\n".join(lines) + "\n") os.chmod(out, 0o755) print('staging-p1/tokensync.sh 已写成(未执行)') print(' 映射 %d 组(中性令牌 %d + 现算深色底面 %d 种)| 覆盖 %d 处 | 剩余彩性蓝 %d 处 | 冷色总计 %d 处' % (len(MAP), len(NEUTRAL), len(dark), covered, residual, total)) print(' 逐值期望命中:' + ', '.join('%s×%d' % (k, exp[k]) for k in sorted(exp) if exp[k])) print(' 闭合检查:%d + %d = %d → %s' % (covered, residual, total, 'OK' if covered + residual == total else '不闭合')) if __name__ == '__main__': main()