@dtapp/ci-templates 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,434 @@
1
+ #!/bin/sh
2
+ # shellcheck disable=SC3043 # local 不是 POSIX 标准,但 dash / ash / bash 都支持
3
+ #
4
+ # 生成 CNB 流水线 IM 通知正文(企业微信 / 飞书 / 钉钉共用)。
5
+ #
6
+ # 三个 workflow 各自生成通知正文的逻辑原先内嵌在 YAML heredoc 里难以维护,
7
+ # 这里统一收口为 POSIX sh 实现(替代早先的 render-ci-notice.py):
8
+ # - sechook : 读取 cnbcool/cnb-sechook 写出的 sec_overview.md(完整扫描报告)
9
+ # - review : 读取 cnbcool/code-review 写出的 code_review.json(status + issues)
10
+ # - sca : 通过 CNB OpenAPI 读取 Commit Annotation(sca.<capability>.<mode>.<field>)
11
+ #
12
+ # 每个子命令生成两份正文:
13
+ # - <name>_notice.md : markdown 版,「查看详情」为 [查看详情](URL) 超链接
14
+ # → 企业微信 fromFile、钉钉 content
15
+ # - <name>_notice.txt: 纯文本版,URL 裸写(飞书 text 消息会自动识别为链接)
16
+ # → 飞书 content
17
+ # 两份都通过 CNB set-output(base64)导出,避免多行被逐行解析。
18
+ #
19
+ # 依赖镜像:docker.cnb.cool/dtapp/alpine:latest(已预装 jq / curl / coreutils / tzdata)。
20
+ # 时间:CNB_BUILD_START_TIME(UTC)经 epoch + 8h 转北京时间(UTC+8)。
21
+ #
22
+ # 用法:
23
+ # sh scripts/ci/render-ci-notice.sh sechook [输出.md]
24
+ # sh scripts/ci/render-ci-notice.sh review [输出.md]
25
+ # sh scripts/ci/render-ci-notice.sh sca full|diff [输出.md]
26
+ # sh scripts/ci/render-ci-notice.sh --self-test
27
+ #
28
+ # ⚠️ 保持 POSIX sh 语法:CNB 的 stage 默认用 sh(dash/ash)执行。
29
+ # 不要引入 [[ ]]、数组、BASH_SOURCE、$'...' 这类 bash 专有写法。
30
+
31
+ set -eu
32
+ die() {
33
+ printf 'error: %s\n' "$*" >&2
34
+ exit 1
35
+ }
36
+ LINK_STYLE='md'
37
+ build_time_text() {
38
+ local raw="${CNB_BUILD_START_TIME:-}" norm epoch result
39
+ if [ -z "${raw}" ]; then
40
+ printf '未知'
41
+ return 0
42
+ fi
43
+ norm="$(printf '%s' "${raw}" \
44
+ | sed -E 's/T/ /; s/\.[0-9]+Z?$//; s/Z$//')"
45
+ epoch="$(date -u -d "${norm} UTC" '+%s' 2>/dev/null || true)"
46
+ if [ -z "${epoch}" ]; then
47
+ epoch="$(date -u -j -f '%Y-%m-%d %H:%M:%S' "${norm}" '+%s' 2>/dev/null || true)"
48
+ fi
49
+ if [ -z "${epoch}" ]; then
50
+ printf '%s' "${raw}"
51
+ return 0
52
+ fi
53
+ epoch=$((epoch + 8 * 3600))
54
+ result="$(date -u -d "@${epoch}" '+%Y-%m-%d %H:%M:%S' 2>/dev/null || true)"
55
+ if [ -z "${result}" ]; then
56
+ result="$(date -u -r "${epoch}" '+%Y-%m-%d %H:%M:%S' 2>/dev/null || true)"
57
+ fi
58
+ printf '%s' "${result:-${raw}}"
59
+ }
60
+ header() {
61
+ local title="$1" url="${CNB_EVENT_URL:-}"
62
+ printf '## %s\n\n' "${title}"
63
+ printf -- '- 时间: %s (UTC+8)\n' "$(build_time_text)"
64
+ printf -- '- 仓库: %s\n' "${CNB_REPO_SLUG:-}"
65
+ if [ -n "${CNB_PULL_REQUEST_TITLE:-}" ]; then
66
+ printf -- '- PR: %s\n' "${CNB_PULL_REQUEST_TITLE}"
67
+ fi
68
+ if [ -n "${CNB_PULL_REQUEST_PROPOSER:-}" ]; then
69
+ printf -- '- 发起人: %s\n' "${CNB_PULL_REQUEST_PROPOSER}"
70
+ fi
71
+ if [ "${LINK_STYLE}" = 'md' ]; then
72
+ printf '[查看详情](%s)\n\n' "${url}"
73
+ else
74
+ printf '查看详情: %s\n\n' "${url}"
75
+ fi
76
+ }
77
+ emit() {
78
+ local out_file="$1" key="$2" encoded
79
+ encoded="$(base64 -w0 <"${out_file}" 2>/dev/null || base64 <"${out_file}" | tr -d '\n')"
80
+ printf '##[set-output %s=base64,%s]\n' "${key}" "${encoded}"
81
+ }
82
+ text_path() {
83
+ printf '%s' "${1%.md}.txt"
84
+ }
85
+ feishu_post_path() {
86
+ printf '%s' "${1%.md}_feishu.json"
87
+ }
88
+ md_linkify() {
89
+ awk '
90
+ {
91
+ line = $0; out = ""
92
+ while (match(line, /https?:\/\/[^ )<>]+/)) {
93
+ pre = substr(line, 1, RSTART - 1)
94
+ url = substr(line, RSTART, RLENGTH)
95
+ line = substr(line, RSTART + RLENGTH)
96
+ if (pre ~ /\($/) {
97
+ out = out pre url
98
+ } else {
99
+ if (pre ~ /查看详情: *$/) { sub(/查看详情: *$/, "", pre); label = "查看详情" }
100
+ else if (pre ~ /报告: *$/) { sub(/报告: *$/, "", pre); label = "查看报告" }
101
+ else { label = "查看链接" }
102
+ out = out pre "[" label "](" url ")"
103
+ }
104
+ }
105
+ print out line
106
+ }
107
+ '
108
+ }
109
+ build_feishu_post() {
110
+ local title="$1" txt_file="$2" out_file="$3"
111
+ jq -n \
112
+ --arg title "${title}" \
113
+ --rawfile body "${txt_file}" \
114
+ '
115
+ def clean: sub("^## "; "") | sub("^### "; "") | sub("^- "; "");
116
+ def row:
117
+ clean as $line
118
+ | if $line == "" then []
119
+ elif ($line | startswith("查看详情: ")) then
120
+ [{ "tag": "a", "text": "查看详情", "href": ($line | sub("^查看详情: "; "")) }]
121
+ else
122
+ ([ $line | match("https?://[^ )<>]+"; "g") ]) as $ms
123
+ | if ($ms | length) == 0 then
124
+ [{ "tag": "text", "text": $line }]
125
+ else
126
+ reduce $ms[] as $m
127
+ ({ out: [], pos: 0 };
128
+ ($m.offset) as $start
129
+ | ($m.offset + ($m.string | length)) as $end
130
+ | ($line[.pos:$start]) as $seg
131
+ | (if ($seg | test("查看详情: *$")) then { pre: ($seg | sub("查看详情: *$"; "")), label: "查看详情" }
132
+ elif ($seg | test("报告: *$")) then { pre: ($seg | sub("报告: *$"; "")), label: "查看报告" }
133
+ else { pre: $seg, label: "查看链接" } end) as $h
134
+ | .out += (if ($h.pre | length) > 0 then [{ "tag": "text", "text": $h.pre }] else [] end)
135
+ | .out += [{ "tag": "a", "text": $h.label, "href": $line[$start:$end] }]
136
+ | .pos = $end)
137
+ | .out + (if .pos < ($line | length) then [{ "tag": "text", "text": $line[.pos:] }] else [] end)
138
+ end
139
+ end;
140
+ ($body | split("\n") | map(select(length > 0))) as $lines
141
+ | [ $lines[] | row ] as $rows
142
+ | { content: { post: { zh_cn: { title: $title, content: $rows } } } }
143
+ ' >"${out_file}"
144
+ }
145
+ sechook_body() {
146
+ local report="${SECHOOK_REPORT:-sec_overview.md}"
147
+ if [ -f "${report}" ]; then
148
+ cat "${report}"
149
+ else
150
+ printf '读取扫描报告失败: %s\n' "${report}"
151
+ fi
152
+ }
153
+ render_sechook() {
154
+ local md_file="$1" key="$2" txt_file feishu_file
155
+ txt_file="$(text_path "${md_file}")"
156
+ feishu_file="$(feishu_post_path "${md_file}")"
157
+ LINK_STYLE='md'
158
+ {
159
+ header '安全扫描结果'
160
+ sechook_body
161
+ } | md_linkify >"${md_file}"
162
+ LINK_STYLE='text'
163
+ {
164
+ header '安全扫描结果'
165
+ sechook_body
166
+ } >"${txt_file}"
167
+ build_feishu_post '安全扫描结果' "${txt_file}" "${feishu_file}"
168
+ emit "${md_file}" "${key}"
169
+ emit "${txt_file}" "${key}_text"
170
+ }
171
+ review_body() {
172
+ if [ "$(jq '.issues | length' code_review.json)" -gt 0 ]; then
173
+ printf '### 发现 %s 个问题\n\n' "$(jq '.issues | length' code_review.json)"
174
+ jq -r '
175
+ .issues | to_entries[] |
176
+ "**\(.key + 1). [\(.value.severity // "info")] \(.value.file // ""):\(.value.start_line // "")**",
177
+ (.value.problem // "" | gsub("\\*\\*"; "") | select(length > 0)),
178
+ (.value.suggestion // "" | gsub("\\*\\*"; "") | select(length > 0)),
179
+ ""
180
+ ' code_review.json
181
+ else
182
+ printf '未发现问题,代码质量良好。\n'
183
+ fi
184
+ }
185
+ render_review() {
186
+ local md_file="$1" key="$2" txt_file status label title
187
+ [ -f code_review.json ] || die '找不到 code_review.json(code-review 插件需设置 output: ./code_review.json)'
188
+ status="$(jq -r '.status // "unknown"' code_review.json)"
189
+ case "${status}" in
190
+ passed) label='通过' ;;
191
+ needs_modification) label='需要修改' ;;
192
+ critical) label='存在严重问题' ;;
193
+ *) label="${status}" ;;
194
+ esac
195
+ title="AI 代码评审结果: ${label}"
196
+ txt_file="$(text_path "${md_file}")"
197
+ LINK_STYLE='md'
198
+ {
199
+ header "${title}"
200
+ review_body
201
+ } | md_linkify >"${md_file}"
202
+ LINK_STYLE='text'
203
+ {
204
+ header "${title}"
205
+ review_body
206
+ } >"${txt_file}"
207
+ build_feishu_post "${title}" "${txt_file}" "$(feishu_post_path "${md_file}")"
208
+ emit "${md_file}" "${key}"
209
+ emit "${txt_file}" "${key}_text"
210
+ }
211
+ ANNOTATION_LINES=''
212
+ ann_value() {
213
+ local key="$1" line
214
+ [ -n "${ANNOTATION_LINES}" ] || return 0
215
+ line="$(grep -F "|${key}|" "${ANNOTATION_LINES}" | head -n 1 || true)"
216
+ printf '%s' "${line#*|}" | cut -d'|' -f2-
217
+ }
218
+ has_any() {
219
+ local key
220
+ for key in "$@"; do
221
+ if [ -n "$(ann_value "${key}")" ]; then
222
+ return 0
223
+ fi
224
+ done
225
+ return 1
226
+ }
227
+ sca_section() {
228
+ local title="$1" prefix="$2" fields="$3"
229
+ local pair field label value gate reporter keys=''
230
+ for pair in ${fields}; do
231
+ keys="${keys} ${prefix}${pair%%:*}"
232
+ done
233
+ if ! has_any ${keys}; then
234
+ return 0
235
+ fi
236
+ printf '### %s\n' "${title}"
237
+ for pair in ${fields}; do
238
+ field="${pair%%:*}"
239
+ label="${pair#*:}"
240
+ value="$(ann_value "${prefix}${field}")"
241
+ if [ -n "${value}" ]; then
242
+ printf -- '- %s: %s\n' "${label}" "${value}"
243
+ fi
244
+ done
245
+ gate="$(ann_value "${prefix}gate")"
246
+ if [ -n "${gate}" ]; then
247
+ if [ "${gate}" = 'gate' ]; then
248
+ gate='命中门禁'
249
+ fi
250
+ printf -- '- 门禁: %s\n' "${gate}"
251
+ fi
252
+ reporter="$(ann_value "${prefix}reporter")"
253
+ if [ -n "${reporter}" ]; then
254
+ printf -- '- 报告: %s\n' "${reporter}"
255
+ fi
256
+ printf '\n'
257
+ }
258
+ sca_body() {
259
+ local mode="$1" label
260
+ if [ "${mode}" = 'full' ]; then
261
+ label='组件总数'
262
+ else
263
+ label='变化组件数'
264
+ fi
265
+ sca_section '开源组件漏洞' "sca.vulnerability.${mode}." \
266
+ 'critical.count:Critical high.count:High medium.count:Medium low.count:Low'
267
+ sca_section 'License 风险' "sca.license.${mode}." \
268
+ 'high.count:High medium.count:Medium low.count:Low'
269
+ sca_section 'SBOM 组件' "sca.sbom.${mode}." "total.count:${label}"
270
+ if ! grep -q '^|sca\.' "${ANNOTATION_LINES}" 2>/dev/null; then
271
+ printf '未读取到扫描结果(扫描可能未执行完成)。\n'
272
+ fi
273
+ if [ -n "${SCA_ERROR:-}" ]; then
274
+ printf '读取结果失败: %s\n' "${SCA_ERROR}"
275
+ fi
276
+ }
277
+ render_sca() {
278
+ local mode="$1" md_file="$2" key="$3"
279
+ local api repo sha token url raw_json txt_file title
280
+ case "${mode}" in
281
+ full) sha="${CNB_COMMIT:-}" ;;
282
+ diff) sha="${CNB_PULL_REQUEST_SHA:-${CNB_COMMIT:-}}" ;;
283
+ *) die "sca 子命令需要 full 或 diff,收到: ${mode}" ;;
284
+ esac
285
+ ANNOTATION_LINES="$(mktemp "${TMPDIR:-/tmp}/certflow-sca.XXXXXX")"
286
+ raw_json="$(mktemp "${TMPDIR:-/tmp}/certflow-sca-json.XXXXXX")"
287
+ SCA_ERROR=''
288
+ api="${CNB_API_ENDPOINT:-}"
289
+ api="${api%/}"
290
+ repo="${CNB_REPO_SLUG:-}"
291
+ token="${CNB_TOKEN:-}"
292
+ if [ -z "${api}" ] || [ -z "${repo}" ] || [ -z "${sha}" ] || [ -z "${token}" ]; then
293
+ SCA_ERROR='缺少 CNB_API_ENDPOINT / CNB_REPO_SLUG / CNB_TOKEN / SHA'
294
+ else
295
+ url="${api}/${repo}/-/git/commit-annotations/${sha}"
296
+ if ! curl -fsS --max-time 30 \
297
+ -H "Authorization: Bearer ${token}" \
298
+ -H 'Accept: application/json' \
299
+ "${url}" -o "${raw_json}" 2>/dev/null; then
300
+ SCA_ERROR='读取 Commit Annotation 失败(OpenAPI 请求错误)'
301
+ : >"${raw_json}"
302
+ fi
303
+ fi
304
+ if [ -s "${raw_json}" ]; then
305
+ jq -r '.[] | select(.key) | "|" + .key + "|" + (.value // "")' "${raw_json}" \
306
+ >"${ANNOTATION_LINES}" 2>/dev/null || : >"${ANNOTATION_LINES}"
307
+ fi
308
+ rm -f "${raw_json}"
309
+ if [ "${mode}" = 'full' ]; then
310
+ title='SCA 全量扫描结果'
311
+ else
312
+ title='SCA 增量扫描结果'
313
+ fi
314
+ txt_file="$(text_path "${md_file}")"
315
+ LINK_STYLE='md'
316
+ {
317
+ header "${title}"
318
+ sca_body "${mode}"
319
+ } | md_linkify >"${md_file}"
320
+ LINK_STYLE='text'
321
+ {
322
+ header "${title}"
323
+ sca_body "${mode}"
324
+ } >"${txt_file}"
325
+ build_feishu_post "${title}" "${txt_file}" "$(feishu_post_path "${md_file}")"
326
+ rm -f "${ANNOTATION_LINES}"
327
+ ANNOTATION_LINES=''
328
+ emit "${md_file}" "${key}"
329
+ emit "${txt_file}" "${key}_text"
330
+ }
331
+ self_test() {
332
+ local tmp_dir cwd failures=0 out
333
+ tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/certflow-notice.XXXXXX")"
334
+ cwd="$(pwd)"
335
+ check() {
336
+ local name="$1" ok="$2" detail="${3:-}"
337
+ if [ "${ok}" = '1' ]; then
338
+ printf ' ✓ %s\n' "${name}"
339
+ else
340
+ printf ' ✗ %s%s\n' "${name}" "$([ -n "${detail}" ] && printf '(%s)' "${detail}")"
341
+ failures=$((failures + 1))
342
+ fi
343
+ }
344
+ printf '时间转换\n'
345
+ CNB_BUILD_START_TIME='2026-11-18T05:45:30.123Z'
346
+ out="$(build_time_text)"
347
+ check 'UTC 05:45:30 -> 北京 13:45:30' "$([ "${out}" = '2026-11-18 13:45:30' ] && printf 1 || printf 0)" "${out}"
348
+ CNB_BUILD_START_TIME='not-a-time'
349
+ out="$(build_time_text)"
350
+ check '非法时间原样返回' "$([ "${out}" = 'not-a-time' ] && printf 1 || printf 0)" "${out}"
351
+ CNB_BUILD_START_TIME='2026-11-18T05:45:30.123Z'
352
+ CNB_REPO_SLUG='dtapp/certflow'
353
+ CNB_PULL_REQUEST_TITLE='feat: test'
354
+ CNB_PULL_REQUEST_PROPOSER='tester'
355
+ CNB_EVENT_URL='https://cnb.cool/dtapp/certflow/-/pulls/1'
356
+ printf 'sechook\n'
357
+ printf '## 敏感信息统计\n高风险: 0\n## 漏洞统计\nCritical: 1\n' >"${tmp_dir}/sec_overview.md"
358
+ SECHOOK_REPORT="${tmp_dir}/sec_overview.md" render_sechook "${tmp_dir}/scan_notice.md" scan >/dev/null
359
+ out="$(cat "${tmp_dir}/scan_notice.md")"
360
+ check '含时间行' "$(printf '%s' "${out}" | grep -q -- '- 时间: 2026-11-18 13:45:30 (UTC+8)' && printf 1 || printf 0)"
361
+ check '含报告原文' "$(printf '%s' "${out}" | grep -q '高风险: 0' && printf 1 || printf 0)"
362
+ check 'md 版超链接' "$(printf '%s' "${out}" | grep -qF '[查看详情](https://cnb.cool/dtapp/certflow/-/pulls/1)' && printf 1 || printf 0)"
363
+ check 'md 版无裸 URL 行' "$(printf '%s' "${out}" | grep -qF '查看详情: https://' && printf 0 || printf 1)"
364
+ out="$(cat "${tmp_dir}/scan_notice.txt")"
365
+ check 'text 版裸 URL' "$(printf '%s' "${out}" | grep -qF '查看详情: https://cnb.cool/dtapp/certflow/-/pulls/1' && printf 1 || printf 0)"
366
+ check 'text 版无 markdown 链接' "$(printf '%s' "${out}" | grep -qF '[查看详情](' && printf 0 || printf 1)"
367
+ check '飞书 post 是合法 JSON' "$(jq -e '.content.post.zh_cn.title == "安全扫描结果"' "${tmp_dir}/scan_notice_feishu.json" >/dev/null 2>&1 && printf 1 || printf 0)"
368
+ check '飞书 post 含 a 标签超链接' "$(jq -e '[.content.post.zh_cn.content[][] | select(.tag == "a" and .text == "查看详情" and .href == "https://cnb.cool/dtapp/certflow/-/pulls/1")] | length > 0' "${tmp_dir}/scan_notice_feishu.json" >/dev/null 2>&1 && printf 1 || printf 0)"
369
+ printf 'review\n'
370
+ cd "${tmp_dir}"
371
+ cat >code_review.json <<'JSON'
372
+ {"status":"needs_modification","issues":[{"severity":"warning","file":"main.go","start_line":42,"problem":"**问题**: 缺少校验","suggestion":"**建议**: 增加判空"}]}
373
+ JSON
374
+ render_review review_notice.md review >/dev/null
375
+ out="$(cat review_notice.md)"
376
+ cd "${cwd}"
377
+ check '含状态中文' "$(printf '%s' "${out}" | grep -q '需要修改' && printf 1 || printf 0)"
378
+ check '含问题位置' "$(printf '%s' "${out}" | grep -q '\[warning\] main.go:42' && printf 1 || printf 0)"
379
+ check '去掉裸 **' "$(printf '%s' "${out}" | grep -q '问题: 缺少校验' && ! printf '%s' "${out}" | grep -q '\*\*问题\*\*' && printf 1 || printf 0)"
380
+ check 'md 版超链接' "$(printf '%s' "${out}" | grep -qF '[查看详情](https://cnb.cool/dtapp/certflow/-/pulls/1)' && printf 1 || printf 0)"
381
+ printf 'sca\n'
382
+ cat >"${tmp_dir}/annotations.json" <<'JSON'
383
+ [
384
+ {"key":"sca.vulnerability.full.high.count","value":"3"},
385
+ {"key":"sca.vulnerability.full.gate","value":"gate"},
386
+ {"key":"sca.vulnerability.full.reporter","value":"https://cnb.cool/report?tab=attachments"},
387
+ {"key":"sca.sbom.full.total.count","value":"128"}
388
+ ]
389
+ JSON
390
+ ANNOTATION_LINES="${tmp_dir}/ann-lines"
391
+ jq -r '.[] | select(.key) | "|" + .key + "|" + (.value // "")' "${tmp_dir}/annotations.json" >"${ANNOTATION_LINES}"
392
+ LINK_STYLE='md'
393
+ {
394
+ header 'SCA 全量扫描结果'
395
+ sca_body full
396
+ } | md_linkify >"${tmp_dir}/sca_notice.md"
397
+ out="$(cat "${tmp_dir}/sca_notice.md")"
398
+ rm -f "${ANNOTATION_LINES}"
399
+ ANNOTATION_LINES=''
400
+ check '含漏洞计数' "$(printf '%s' "${out}" | grep -q 'High: 3' && printf 1 || printf 0)"
401
+ check '门禁映射中文' "$(printf '%s' "${out}" | grep -q '命中门禁' && printf 1 || printf 0)"
402
+ check '含 SBOM 组件数' "$(printf '%s' "${out}" | grep -q '组件总数: 128' && printf 1 || printf 0)"
403
+ check 'md 版超链接' "$(printf '%s' "${out}" | grep -qF '[查看详情](https://cnb.cool/dtapp/certflow/-/pulls/1)' && printf 1 || printf 0)"
404
+ check '报告 URL 已 linkify' "$(printf '%s' "${out}" | grep -qF '[查看报告](https://cnb.cool/report?tab=attachments)' && printf 1 || printf 0)"
405
+ check '不显示完整 URL 作链接文字' "$(printf '%s' "${out}" | grep -qF '[https://' && printf 0 || printf 1)"
406
+ rm -rf "${tmp_dir}"
407
+ if [ "${failures}" -ne 0 ]; then
408
+ printf '\n自检失败: %s 项\n' "${failures}" >&2
409
+ return 1
410
+ fi
411
+ printf '\n自检通过\n'
412
+ return 0
413
+ }
414
+ usage() {
415
+ cat <<'USAGE'
416
+ 用法:
417
+ sh scripts/ci/render-ci-notice.sh sechook [输出.md]
418
+ sh scripts/ci/render-ci-notice.sh review [输出.md]
419
+ sh scripts/ci/render-ci-notice.sh sca full|diff [输出.md]
420
+ sh scripts/ci/render-ci-notice.sh --self-test
421
+ USAGE
422
+ }
423
+ case "${1:-}" in
424
+ sechook) render_sechook "${2:-scan_notice.md}" scan ;;
425
+ review) render_review "${2:-review_notice.md}" review ;;
426
+ sca) render_sca "${2:-}" "${3:-sca_notice.md}" sca ;;
427
+ --self-test) self_test ;;
428
+ -h | --help) usage ;;
429
+ '')
430
+ usage >&2
431
+ exit 2
432
+ ;;
433
+ *) die "未知子命令: ${1}" ;;
434
+ esac
@@ -0,0 +1,177 @@
1
+ #!/usr/bin/env bash
2
+ # 解析本次要发布的版本号。
3
+ #
4
+ # 基准版本(nightly 用)以「首发制品库」为准:CNB 通用 npm 制品库里的
5
+ # dist-tags.latest / versions,读不到时回退到 git tag 里最大的正式版,
6
+ # 再读不到就按 0.0.0 起算(即首版 nightly 为 0.0.1-nightly.<日期>)。
7
+ #
8
+ # 环境变量输入:
9
+ # VERSION 原始版本输入(crontab 任务的 env,或显式指定的大写变量)。
10
+ # version web_trigger 表单注入的小写输入:CNB 按 input key 原样注入环境变量,
11
+ # 所以 .cnb/web_trigger.yml 里的小写 `version` 到达脚本时是 $version,
12
+ # 而不是 $VERSION。两者同时存在时以 $VERSION 为准;都没填则默认 nightly。
13
+ # 取值之一:
14
+ # 1.2.3 正式版
15
+ # 1.2.3-rc.1 预发布(rc 渠道)
16
+ # 1.2.3-beta.1 预发布(beta 渠道)
17
+ # 1.2.3-alpha.1 预发布(alpha 渠道)
18
+ # 1.2.3-nightly.20260101 预发布(nightly 渠道)
19
+ # nightly 展开为 <最新正式版 + 1 补丁>-nightly.<日期>;
20
+ # 日期跟随调度器时区:CNB 用北京时间(内置变量
21
+ # CNB 的值为 true),GitHub Actions 用 UTC。
22
+ # NPM_REGISTRY 查基准版本用的制品库,默认 CNB 通用 npm 制品库;
23
+ # 注意不要用发布目标变量(PUBLISH_REGISTRY / NPMJS_REGISTRY)覆盖它。
24
+ # 输出(写入 $GITHUB_OUTPUT 风格的文件,默认 .version.env):
25
+ # VERSION 规范化后的 semver,不带前导 v(如 0.2.8-nightly.20261114)
26
+ # TAG git 标签名(如 v0.2.8-nightly.20261114)
27
+ # CHANNEL stable | rc | beta | alpha | nightly | prerelease 之一
28
+ # DIST_TAG npm dist-tag:正式版 latest,rc/beta/alpha/nightly 用同名渠道,
29
+ # 其它自定义预发布标识用 next
30
+ # PRERELEASE 任意预发布渠道为 true,正式版为 false
31
+ # LATEST 正式版为 true(Release 标记为 latest),预发布为 false
32
+ set -euo pipefail
33
+
34
+ case "${CI_LANG:-${LC_ALL:-${LC_MESSAGES:-${LANG:-}}}}" in
35
+ zh* | ZH*) CI_LANG=zh ;;
36
+ *) CI_LANG=en ;;
37
+ esac
38
+ msg() {
39
+ local key="$1"
40
+ shift
41
+ case "$CI_LANG:$key" in
42
+ en:cannot_determine_pkg) printf 'resolve-version: cannot determine package name (package.json or CNB_REPO_NAME_LOWERCASE)\n' ;;
43
+ zh:cannot_determine_pkg) printf 'resolve-version:无法确定包名(package.json 或 CNB_REPO_NAME_LOWERCASE)\n' ;;
44
+ en:version_required) printf "resolve-version: VERSION input is required (a semver, or the literal 'nightly')\n" ;;
45
+ zh:version_required) printf "resolve-version:缺少 VERSION 输入(需为 semver 或字面量 'nightly')\n" ;;
46
+ en:invalid_semver) printf "resolve-version: '%s' is not a semver (expected 1.2.3 or 1.2.3-rc.1, or 'nightly')\n" "$@" ;;
47
+ zh:invalid_semver) printf "resolve-version:'%s' 不是合法的 semver(应为 1.2.3、1.2.3-rc.1 或 'nightly')\n" "$@" ;;
48
+ en:resolved) printf 'resolved: version=%s tag=%s channel=%s dist-tag=%s prerelease=%s latest=%s\n' "$@" ;;
49
+ zh:resolved) printf '已解析:version=%s tag=%s channel=%s dist-tag=%s prerelease=%s latest=%s\n' "$@" ;;
50
+ esac
51
+ }
52
+ OUTPUT_FILE="${OUTPUT_FILE:-.version.env}"
53
+ PKG_NAME="${PKG_NAME:-$(node -p "require('./package.json').name" 2>/dev/null || true)}"
54
+ [ -n "$PKG_NAME" ] || PKG_NAME="@${CNB_GROUP_SLUG_LOWERCASE:-}/${CNB_REPO_NAME_LOWERCASE:-}"
55
+ [ -n "$PKG_NAME" ] || {
56
+ msg cannot_determine_pkg >&2
57
+ exit 1
58
+ }
59
+ NPM_REGISTRY="${NPM_REGISTRY:-https://npm.cnb.cool/dtapp/ci-templates/-/packages/}"
60
+ raw="${VERSION:-${version:-nightly}}"
61
+ raw="${raw#"${raw%%[![:space:]]*}"}"
62
+ raw="${raw%"${raw##*[![:space:]]}"}"
63
+ raw="${raw#v}"
64
+ SEMVER_RE='^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+(\.[0-9A-Za-z.-]+)*)?$'
65
+ channel_of() {
66
+ case "$1" in
67
+ *-rc.*) echo rc ;;
68
+ *-beta.*) echo beta ;;
69
+ *-alpha.*) echo alpha ;;
70
+ *-nightly.*) echo nightly ;;
71
+ *-*) echo prerelease ;;
72
+ *) echo stable ;;
73
+ esac
74
+ }
75
+ latest_stable() {
76
+ local registry="$1" pkg="$2" json latest
77
+ if command -v curl >/dev/null 2>&1; then
78
+ json="$(curl -fsSL --max-time 30 "${registry%/}/${pkg}" 2>/dev/null || true)"
79
+ fi
80
+ if [ -n "${json:-}" ]; then
81
+ latest="$(
82
+ printf '%s' "$json" | node -e '
83
+ let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{
84
+ try{const j=JSON.parse(s);const t=j["dist-tags"]||{};
85
+ const stable=v=>typeof v==="string"&&!/[-]/.test(v);
86
+ if(stable(t.latest))return console.log(t.latest);
87
+ const vs=Object.keys(j.versions||{}).filter(stable);
88
+ if(vs.length){vs.sort((a,b)=>{const p=x=>x.split(".").map(Number);const A=p(a),B=p(b);for(let i=0;i<3;i++)if(A[i]!==B[i])return B[i]-A[i];return 0;});return console.log(vs[0]);}
89
+ }catch{}
90
+ });'
91
+ )"
92
+ if [ -n "$latest" ]; then
93
+ echo "$latest"
94
+ return 0
95
+ fi
96
+ fi
97
+ local tags
98
+ tags="$(git tag --list 'v*' 2>/dev/null)" || tags=""
99
+ if [ -z "$tags" ]; then
100
+ tags="$(git ls-remote --tags --refs origin 'v*' 2>/dev/null | sed -n 's|.*refs/tags/||p')" || tags=""
101
+ fi
102
+ tags="$(printf '%s\n' "$tags" | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -n 1 || true)"
103
+ if [ -n "$tags" ]; then
104
+ echo "${tags#v}"
105
+ return 0
106
+ fi
107
+ echo "0.0.0"
108
+ }
109
+ bump_patch() {
110
+ local v="$1" maj min pat
111
+ maj="${v%%.*}"
112
+ v="${v#*.}"
113
+ min="${v%%.*}"
114
+ pat="${v#*.}"
115
+ pat="${pat%%-*}"
116
+ echo "${maj}.${min}.$((pat + 1))"
117
+ }
118
+ nightly_date() {
119
+ if [ "${CNB:-}" = "true" ]; then
120
+ if command -v node >/dev/null 2>&1; then
121
+ node -e 'const d=new Date(Date.now()+8*3600*1000);process.stdout.write(d.toISOString().slice(0,10).replace(/-/g,""))'
122
+ else
123
+ TZ=Asia/Shanghai date +%Y%m%d
124
+ fi
125
+ else
126
+ date -u +%Y%m%d
127
+ fi
128
+ }
129
+ if [ "$raw" = "nightly" ]; then
130
+ base="$(latest_stable "$NPM_REGISTRY" "$PKG_NAME")"
131
+ case "$base" in
132
+ *[-]*) base="$(echo "$base" | sed 's/-.*//')" ;;
133
+ esac
134
+ VERSION="$(bump_patch "$base")-nightly.$(nightly_date)"
135
+ elif [ -z "$raw" ]; then
136
+ msg version_required >&2
137
+ exit 1
138
+ elif [[ ! $raw =~ $SEMVER_RE ]]; then
139
+ msg invalid_semver "$raw" >&2
140
+ exit 1
141
+ else
142
+ VERSION="$raw"
143
+ fi
144
+ CHANNEL="$(channel_of "$VERSION")"
145
+ case "$CHANNEL" in
146
+ stable)
147
+ DIST_TAG="latest"
148
+ PRERELEASE="false"
149
+ LATEST="true"
150
+ ;;
151
+ prerelease)
152
+ DIST_TAG="next"
153
+ PRERELEASE="true"
154
+ LATEST="false"
155
+ ;;
156
+ *)
157
+ DIST_TAG="$CHANNEL"
158
+ PRERELEASE="true"
159
+ LATEST="false"
160
+ ;;
161
+ esac
162
+ TAG="v${VERSION}"
163
+ {
164
+ echo "VERSION=${VERSION}"
165
+ echo "TAG=${TAG}"
166
+ echo "CHANNEL=${CHANNEL}"
167
+ echo "DIST_TAG=${DIST_TAG}"
168
+ echo "PRERELEASE=${PRERELEASE}"
169
+ echo "LATEST=${LATEST}"
170
+ } >"$OUTPUT_FILE"
171
+ if [ "${GITHUB_ACTIONS:-}" != "true" ]; then
172
+ for key in VERSION TAG CHANNEL DIST_TAG PRERELEASE LATEST; do
173
+ echo "##[set-output ${key}=${!key}]"
174
+ done
175
+ fi
176
+ msg resolved "$VERSION" "$TAG" "$CHANNEL" "$DIST_TAG" "$PRERELEASE" "$LATEST"
177
+ cat "$OUTPUT_FILE"