@infly/libs 2.4.2 → 2.6.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.
- package/README.md +28 -3
- package/bin/cli.js +7 -4
- package/build/before-build.js +50 -0
- package/build/docker/compose-release.js +7 -9
- package/build/docker/deployment/promote-image.sh +75 -5
- package/build/docker/docker-build-push.js +11 -5
- package/build/docker/minimal-context.js +32 -1
- package/build/docker/project-install.js +170 -0
- package/build/docker/release-docker.js +2 -21
- package/build/docker/release-identity.js +22 -0
- package/build/docker/release-mode.js +7 -25
- package/build/docker/release-paths.js +30 -0
- package/build/docker/release-validation.js +204 -0
- package/build/docker/source-snapshot.js +45 -0
- package/build/docker/target-image.js +189 -0
- package/build/docker/target-release.js +527 -739
- package/jenkins/README.md +94 -0
- package/jenkins/src/com/infly/jenkins/BuildProvenance.groovy +16 -0
- package/jenkins/src/com/infly/jenkins/PipelineJson.groovy +28 -0
- package/jenkins/src/com/infly/jenkins/ReleaseNotification.groovy +86 -0
- package/jenkins/vars/inflyNotify.groovy +83 -0
- package/package.json +4 -1
- package/script/git-automation/index.js +828 -858
- package/script/git-automation/root-update.js +31 -0
package/README.md
CHANGED
|
@@ -8,9 +8,11 @@ Vue 2 专属的 Permission、Vuex store、实例 mixin、Vue CLI 预览和 webpa
|
|
|
8
8
|
|
|
9
9
|
## 发布结果通知
|
|
10
10
|
|
|
11
|
+
目标化镜像发布可在目标的 `deployment.instructions` 配置文本列表,推送成功且 `deployment.ready: true` 时显示。文本中的 `{releaseId}` 替换为本次完整发布编号,未启用唯一编号时使用提交号,`{image}` 替换为本次完整镜像引用。提示显示在最终发布系统链接之前,适合说明部署参数填写步骤。项目维护具体提示内容,公共工具只负责填入本次结果。
|
|
12
|
+
|
|
11
13
|
`@infly/libs/build/release-result.js` 的 `formatReleaseResult` / `createReleasePayload` 统一投影项目、环境、组件、状态、源码版本、镜像版本、构建号、触发人、发布说明和日志链接。输入字段分别为 `project/environment/components/status/sourceVersion/imageVersion/buildNumber/actor/note/logUrl`;不接受环境变量全集,日志 URL 去除认证及查询参数。
|
|
12
14
|
|
|
13
|
-
`infly-libs release:notification --input result.json --output payload.json` 只生成 JSON,不发送通知。Jenkins
|
|
15
|
+
`infly-libs release:notification --input result.json --output payload.json` 只生成 JSON,不发送通知。Jenkins 使用本包的 [共享通知库](jenkins/README.md),通过主仓 Git 源码加载,统一维护 Groovy 模板和发送逻辑。发送凭据由各项目的 Jenkins Credentials 注入。源码版本与镜像版本不能相互冒充,产物仓镜像应注明产物提交,knowledge 与 Go 应分别记录提交。
|
|
14
16
|
|
|
15
17
|
历史 `build/build-utils/webhook-single.js` 仅转发 `webhook.js` 的 `postVersionFileAndMsg`,单条和批量汇总共用正文格式、发送、超时、响应检查和凭据解析;两种调用路径继续兼容。可在 `extraParams.releaseResult` 传入上述结果对象采用统一正文,未传时保留原构建文案。`RELEASE_WEBHOOK_URL` / `WECOM_WEBHOOK_URL` 进程注入优先于原 `webhookUrl` 本机配置;所有跳过通知参数和环境开关共用。错误日志仅输出受限错误码,避免 Axios error/config 带出 URL 凭据。
|
|
16
18
|
|
|
@@ -409,16 +411,23 @@ targets:
|
|
|
409
411
|
|
|
410
412
|
- `files`:从组件源码仓复制到独立临时上下文,仅发送指定产物;配置后 `dockerfile` 相对临时上下文。未配置时 `context`、`dockerfile` 相对组件源码仓。
|
|
411
413
|
- `buildStrategy`:组件构建策略,默认 `artifact`,保持现有宿主机产物封装行为;设为 `source` 时自动识别 `monorepo` / `standalone`。monorepo 模式会从外层 workspace 生成只包含根安装契约、`packages/` 与当前项目的临时最小 Docker context;standalone 模式使用当前源码仓。两种模式都会自动注入 `BUILD_MODE` 与 `PROJECT_DIR` 构建参数。`source` 不能与 `files` 产物上下文同时使用;monorepo workspace 必须保持干净,并写入 `com.infly.workspace.revision` 镜像标签。
|
|
414
|
+
- `projectInstall: true`:可选的项目安装上下文,仅用于外部 `source` 构建。monorepo 下不复制父仓的 package/workspace/lockfile、pnpmfile 或治理脚本,而以业务仓自身配置、原锁及源码为基础,自动选取根公共包的实际依赖闭包,放入临时 `.infly-local-packages/`,并注入本地 workspace 映射。公共包不安装其自身开发工具;`.infly-local-manifests/` 供 Docker 依赖缓存层使用。`PROJECT_DIR` 为 `.`,`contextFiles` 同样写入项目根。Dockerfile 的 monorepo 依赖层先执行 `pnpm install --lockfile-only --no-frozen-lockfile --ignore-scripts` 生成临时锁,再 frozen 安装;源文件 COPY 后应恢复安装时生成的锁,避免原锁覆盖它。独立克隆以原锁为基线,在临时上下文固定最新 `@infly/*` npm 依赖闭包;跨 major 时停止。Dockerfile 在 `REFRESH_INTERNAL=true` 时先生成临时锁再 frozen 安装;手工直接 Docker 构建未设置该参数时仍使用原锁 frozen 安装。该模式不能与 `monorepoContextFiles` 同用;未启用时保留既有默认行为。
|
|
415
|
+
|
|
416
|
+
这种选择不保证两次无缓存构建解析到完全相同的新增第三方依赖;源码提交固定,但临时锁需要构建时解析。需要严格复现时应保存实际安装锁与镜像内容 ID。应用的 lint/test 需排除 `.infly-local-packages/**`,公共包有自己的检查范围。后续项目只需配置此选项并在 Dockerfile 接入 manifest 层,无需另写安装脚本或刷新锁文件脚本。
|
|
412
417
|
- `config`:`infly.docker` 中的外部配置路径,支持 JSON、YAML、JS;外部配置为基础,package 中的同名对象递归覆盖。循环引用和未知格式会直接失败。
|
|
413
418
|
- `compose`:组件构建配置来源,必须指定 `file` 和 `service`。工具从 Compose 服务读取镜像仓库、上下文、Dockerfile、stage 与构建参数;组件显式字段仍可覆盖解析结果。
|
|
414
419
|
- `target` / `buildArgs`:分别映射到 `docker buildx build --target` 和 `--build-arg`;使用 `compose` 时通常无需重复填写。
|
|
415
420
|
- `platform`:可选 Docker 构建平台,例如 `linux/amd64`;映射到 `docker buildx build --platform`。这里的组件字段不同于 CLI 的 `--platform` target 兼容别名。
|
|
416
|
-
- `
|
|
421
|
+
- `releaseIdentity: true`:外部源码构建可选的唯一发布标识,标签为 `<tagPrefix><40位业务提交>-r<12位随机标识>`,业务 revision 不变。临时上下文注入 `.infly-release.json`,记录业务/主仓/部署提交、目标、平台、构建参数哈希与内部包清单;Dockerfile 将其与实际安装锁及 sha256 保存到运行镜像的非 Web 目录。push 后校验 Registry digest 与已验证本地镜像 ID 一致,输出 `release_id`、`deploy_image=repository@sha256:...` 和本机 `node_modules/.cache/infly-releases/<releaseId>.json` 记录。
|
|
422
|
+
- `releaseChannel: true`:仅用于启用唯一发布标识的组件。整组镜像检查、精确标签推送及 digest 复验成功后,更新 `<tagPrefix><target>-latest` 环境入口。Jenkins 默认选择此入口并立即解析为固定 digest,后续步骤不再读取可变标签。紧急目标应关闭此选项,避免覆盖正常入口。
|
|
423
|
+
- `workspaceRef: origin/master`:`projectInstall` 主仓来源验证。镜像 CLI 在加载构建模块前复用原 `beforeBuild` 根仓更新方法,fetch 并快进远端 master;脏工作树、分叉、本地领先或并发修改均停止,不 reset/切分支。工具更新后重新启动主仓 CLI,避免混用模块。公共源码从冻结提交导出,不复制 ignored/untracked 内容;缺少必需的 `@infly/*` 源码时失败,不回退 npm。直接 API 不在构建中更新已加载代码,push 前只验证已准备的主仓与远端一致。独立克隆和 dry-run 不更新根仓。
|
|
424
|
+
- `mutableTags`:默认 `true`,保持提交版本 + latest 双标签;设为 `false` 时不生成或推送通用 latest;不影响显式启用的环境入口。
|
|
417
425
|
- `tagPrefix`:可选的提交版本标签前缀,例如 `qc-` 生成 `qc-<完整40位commit>`,供独立质量门禁通过后晋升。默认不加前缀,保持既有标签语义;只改变镜像标签,OCI revision/version、输出和返回值中的 commit 仍为裸 40 位提交号。前缀须为 1 到 88 位 Docker 标签合法字符,不能以 `.` 或 `-` 开头。隔离镜像建议同时设置 `mutableTags: false`;工具不会自动执行质量门禁或晋升。
|
|
418
426
|
- `requiredFiles`:构建前必须存在的源码仓相对路径,例如前端产物的 `index.html`;缺失时停止构建。
|
|
419
427
|
- `pushBranch` / `pushRef`:target 级可选推送门禁,必须成对配置,例如 `develop` 与 `origin/develop`。仅 `--push` 时要求当前分支匹配、主动 fetch 对应 remote/branch,并要求本地 HEAD 与远端提交相同;`--no-push` 仍允许在其他分支本地验证镜像。
|
|
420
428
|
- `requirements`:target 级可选本机工具最低版本,目前只支持 `node`、`pnpm` 和 `>=x.y.z` 格式。
|
|
421
429
|
- `preBuild`:target 级可选准备命令列表。原有命令参数数组继续表示始终执行,例如 `["pnpm", "run", "build:test"]`;需要兼容根 monorepo 与独立子仓时,可使用 `{ "when": "standalone", "command": ["pnpm", "install", "--frozen-lockfile"] }`,其中 `when` 支持 `always`、`monorepo`、`standalone`。它与 `buildStrategy` 共用同一个模式探测器,避免宿主机准备步骤和 Docker context 判断漂移。命令在干净工作树和推送门禁之后、Docker 检查与 `requiredFiles` 校验之前执行;配置具有代码执行权限,必须与源码一样评审。
|
|
430
|
+
- `sourceCheck`:组件级可选命令参数数组,例如 `["node", "scripts/check-backend-quality.cjs"]`。只对所选组件执行,在源码提交冻结后、准备镜像上下文及构建之前运行;工作目录为发布配置项目目录,环境变量 `INFLY_SOURCE_DIR`、`INFLY_SOURCE_REVISION`、`INFLY_BUILD_PLATFORM` 分别提供冻结源码绝对目录、完整提交号及组件平台(未配置时为空)。非零退出立即阻止本组后续构建与推送;执行后复核冻结源码仍干净且 HEAD 未变。检查应使用隔离副本,报告写到项目忽略的缓存目录,不能改写冻结源码。未配置时保持既有行为;`--dry-run` 不执行检查。该命令与发布配置一样具有代码执行权限。
|
|
422
431
|
- `source`:可选独立源码仓;`directory` 支持单个路径或按优先级排列的候选路径数组,路径均从项目目录解析,采用第一个包含 `.git` 的目录。同一次调用中,解析后目录与 branch 相同的组件只 fetch 一次、解析一次完整提交号并共用一个 detached worktree;worktree 直接使用冻结 SHA,不随 origin 分支后续变化,也不切换当前开发分支。所有来源在首个镜像构建之前冻结;临时目录仅在本次调用结束后清理,worktree 清理失败会保留父目录并报告恢复路径。交互终端找不到候选仓库时会列出已检查路径、展示路径示例并等待手动输入;取消或非交互环境仍明确说明未执行构建或推送,打印编号化的 clone、fetch 和重跑步骤,全部构建停止,CLI 返回 2。
|
|
423
432
|
- `targetPresets` 与 `targets.*.extends`:可选的具名公共目标配置。preset 可以继续 `extends` 另一个 preset;目标只继承显式指定的 preset,未声明 `extends` 的历史目标不受影响。同名普通对象递归合并;数组、字符串、数字、布尔值和 `null` 由下层整项替换,不按数组下标混合。未知 preset 或循环继承直接失败。本地构建、Compose 发布和部署包生成共用同一解析规则。
|
|
424
433
|
- `releaseScripts`:可选的组件重跑脚本覆盖。默认从项目 scripts 自动识别严格匹配 `release:<组件>:docker` 的脚本,例如 `release:backend:docker`;源码仓缺失时提示 `pnpm run <脚本> -- --platform ...`。只有脚本名称不遵循约定时才需要显式配置;无匹配时提示通用 `pnpm exec infly-libs release:docker` 命令。
|
|
@@ -440,10 +449,22 @@ infly-libs docker:bundle --target demo --dry-run
|
|
|
440
449
|
|
|
441
450
|
`--platform` 是 `--target` 的兼容别名;`--config` 读取 JSON、YAML 或 JS 文件,其顶层直接为 docker 配置。`docker:config` 输出合并和继承后的单行 JSON,便于不安装 YAML 插件的 Jenkins 使用。CLI 参数优先于项目配置;`--backend-dir` 仅覆盖名为 backend 的组件源码目录,并覆盖整个 `source.directory` 候选数组。
|
|
442
451
|
|
|
443
|
-
构建成功后逐组件输出完整提交版本和 `组件=仓库:<完整40位提交版本>`
|
|
452
|
+
构建成功后逐组件输出完整提交版本和 `组件=仓库:<完整40位提交版本>` 机器行,配置 `mutableTags: false` 的组件会省略 latest。全部构建结束后打印 `✅ 完成` 汇总块,区分不可变提交版本与最新推送镜像。
|
|
453
|
+
|
|
454
|
+
Jenkins 地址可在 Docker 配置顶层或单个 target 设置 `cicdUrl`。解析优先级为命令行 `--cicd-url`、目标配置、项目配置,项目可配置首页作为各目标的默认入口。普通镜像目标在 `deployment.ready=true` 时于汇总块末尾输出链接,历史 Compose 目标在构建成功后输出链接,`deployment.ready=false` 可关闭该目标的入口。dry-run 和失败流程会跳过成功链接。
|
|
455
|
+
|
|
456
|
+
链接必须是合法 HTTP/HTTPS URL,且不含用户名、密码或控制字符。输出的“发布系统”标题和 URL 分为两行,并采用 OSC 8 显式超链接,在支持该协议的终端中按 Ctrl + 鼠标左键打开。单组件推送成功、目标编码为字母数字且地址以 `/build` 结尾时,链接会预填平台与本次发布版本,兼容旧镜像版本参数。多组件构建使用原链接。
|
|
444
457
|
|
|
445
458
|
`docker:bundle` 只生成本地脚本包,不自动部署;输出须是项目内尚不存在的独立子目录。包内包含 config.sh、Compose 覆盖文件和公共 shell 脚本。Jenkins 可直接传入部署项目 `package.json` 声明的精确版本或 caret 范围获取公共包;`docker:bundle` 会在执行时输出实际解析到的 `@infly/libs` 精确版本,供 Jenkins 日志追溯。镜像不需要 Infly 专用版本标签,因此独立项目使用普通 `docker build` 生成的镜像仍可部署。Jenkins 使用既有凭据,调用 `deploy.sh component=repository:commit` 传输并执行。包内仍保留 `promote-image.sh` 供既有 qc 晋升流程兼容使用;低频定制平台直接在本地推送不可变提交标签与 `latest`,Jenkins 不再调用晋升脚本。运行部署脚本会操作服务器,必须由开发者手动触发既定任务。
|
|
446
459
|
|
|
460
|
+
`promote-image.sh <组件> <qc镜像> <正式镜像> <完整40位commit>` 拉取 QC 镜像后固定其 image ID,按该 ID 验证 revision。正式标签已存在且 revision 一致时保持幂等;revision 冲突或无法确认标签不存在(例如 Registry 鉴权失败)时停止,不额外要求 Buildx 或解析源 digest。
|
|
461
|
+
|
|
462
|
+
新建正式标签时优先使用 Buildx 的仓库端复制:把 QC 标签解析为同仓库 `repository@sha256:digest`(已传 digest 时直接校验使用),再次拉取该 digest 并确认 image ID/revision 与已核验镜像一致,然后 `imagetools create --tag`。复制仅消费冻结的 digest,不会复制后来漂移的 QC 标签;完整源索引及附加证明得以保留,也无需本地完整下载所有清单。此路径兼容 Docker 24/API 1.43 与 Buildx v0.10.5;旧 Buildx 的格式兼容处理使用 `{{printf "%s" .Manifest.Digest}}`,不使用新版 create 参数。真实 inspect/create 失败立即停止,不回退本地推送。
|
|
463
|
+
|
|
464
|
+
没有 Buildx 时保留按已核验 image ID 重新标记的兼容路径,从该 ID 读取 `OS/Architecture[/Variant]`,不假定业务镜像是 amd64。Docker CLI 提供 `push --platform`,且 Client API、Server API 与显式 `DOCKER_API_VERSION` 均至少为 1.46 时,只推送该平台清单;正式标签此时不保留源索引中的其他平台及附加证明,QC 原标签不受影响。旧 CLI/API 使用普通 push,仍可能受本地缺少索引内容影响;任何真实推送失败立即停止,不切换模式重试。
|
|
465
|
+
|
|
466
|
+
当前邮惠权益正式前后端通过 `deploy.sh` 直接部署已发布的正式镜像,不调用 `promote-image.sh`,因此不会触发该索引晋升问题,也不需要为此紧急发布公共包。仍使用旧 QC 晋升入口、且通过 npm 获取部署包的消费者,需要由开发人员发布包含修复的 npm 版本,并核对流水线实际解析版本,才能取得修复;仅修改 monorepo 包源码不会更新 Jenkins 下载的 npm 包。
|
|
467
|
+
|
|
447
468
|
`release:docker` 不是强制构建入口。独立源码仓可以直接使用 Dockerfile 或 Compose 构建,但若镜像要进入这里生成的部署流程,必须自行保证仓库名、不可变完整 40 位提交标签以及 `org.opencontainers.image.revision`、`org.opencontainers.image.version`、`com.infly.platform` 标签与目标配置一致;公共发布入口只是自动化这些校验和映射。部署侧仅为既有镜像保留旧 12 位标签兼容,新构建不再生成 12 位标签。
|
|
448
469
|
|
|
449
470
|
远端发布持锁后读取全部组件镜像基线,保存 .release-history;配置 `runtimeEnv` 时先从服务器总环境文件按白名单原子生成应用专用文件,再仅更新传入组件的服务(up -d --no-deps)。首次接入可由发布入口显式传入 `--initialize-baseline`:仅在 `deploy.env` 不存在时,从配置声明的运行中服务读取唯一且仓库匹配的 RepoDigest,保存权限受限的 `.onboarding-backup` 接入证据并原子创建基线;已有基线时拒绝覆盖,未显式初始化时仍要求基线预先存在。失败恢复镜像环境文件、应用专用环境文件及选中服务;回滚验证失败明确报错。不创建总环境文件,不创建/修改数据库,不更新未配置的基础设施。服务器不需要 npm/Node,仍需 Bash、Docker Compose 和 curl。
|
|
@@ -454,6 +475,10 @@ infly-libs docker:bundle --target demo --dry-run
|
|
|
454
475
|
|
|
455
476
|
源码仍按 source.directory/source.branch 冻结。monorepo 保留根公共包/锁文件,并用冻结快照替换业务目录;独立仓直接使用冻结源码。OCI revision 取业务提交,`com.infly.deployment.revision` 取部署仓提交,monorepo 额外包含 workspace revision。配置和源码在推送前再次验证。
|
|
456
477
|
|
|
478
|
+
source 构建组件可配置 `monorepoContextFiles: [tooling/install.cjs]`,逐项声明额外携带的主仓文件,路径相对 monorepo 根目录并保持原布局。公共工具只接受工作区内存在的普通文件,拒绝目录、通配符、越界、重复路径及指向工作区外的链接;未配置时不额外复制,standalone 模式忽略此清单。该清单不同于 `contextFiles`:后者从部署仓复制文件到业务目录。安装钩子的具体路径、技术栈和版本策略由调用方维护,公共工具不硬编码主仓脚本目录。
|
|
479
|
+
|
|
480
|
+
默认根安装文件仍包含 `.pnpmfile.cjs`;其额外支持文件需要通过上述清单声明。Dockerfile 应在依赖安装层逐项复制安装输入并保留 frozen 配置与 checksum 校验;仅复制根锁文件却忽略生成该锁文件约束的钩子,会导致依赖配置不一致。
|
|
481
|
+
|
|
457
482
|
`source.standalone: true` 可显式使用独立源码上下文,即使业务仓位于 monorepo 中也不带根公共包;适用于已有独立安装契约的紧急构建。target 的 `recordConfigurationRevision: true` 则让未注入文件的外部源码组件也记录并复核部署仓提交。两者均为可选布尔值,默认保持原有行为。
|
|
458
483
|
|
|
459
484
|
组件可声明 `health: {timeoutSeconds: 60, addHost: api:127.0.0.1}`,复用运行镜像的 HEALTHCHECK,失败不推送本组任何镜像。普通 check 仍用于语法或文件检查;不要对后端启动真实业务进程作本地镜像探针。
|
package/bin/cli.js
CHANGED
|
@@ -152,14 +152,17 @@ function resolveReleaseDockerMode(argv, packageObject = {}) {
|
|
|
152
152
|
return hasTargetConfig ? "target" : "quality";
|
|
153
153
|
}
|
|
154
154
|
|
|
155
|
-
async function runTargetReleaseCommand(args) {
|
|
155
|
+
async function runTargetReleaseCommand(args, rootSynchronization) {
|
|
156
156
|
const { parseReleaseArgs, runTargetRelease } = require("../build/docker/target-release");
|
|
157
|
-
const result = await runTargetRelease(parseReleaseArgs(args));
|
|
157
|
+
const result = await runTargetRelease(parseReleaseArgs(args), { rootSynchronization });
|
|
158
158
|
if (result.missingSources?.length) process.exitCode = 2;
|
|
159
159
|
return result;
|
|
160
160
|
}
|
|
161
161
|
|
|
162
162
|
async function main(argv = process.argv.slice(2)) {
|
|
163
|
+
// 构建入口在解析配置/加载实现前更新主仓;dry-run 和独立克隆不更新根仓。
|
|
164
|
+
const bootstrap = require("../build/before-build").bootstrapRelease({ argv, entryFile: __filename });
|
|
165
|
+
if (bootstrap.relaunched) { process.exitCode = bootstrap.status; return; }
|
|
163
166
|
const command = argv[0];
|
|
164
167
|
const commandMap = {
|
|
165
168
|
"release:notification": () => {
|
|
@@ -190,7 +193,7 @@ async function main(argv = process.argv.slice(2)) {
|
|
|
190
193
|
return result;
|
|
191
194
|
},
|
|
192
195
|
// 兼容旧脚本;新项目和生成配置统一使用 release:docker。
|
|
193
|
-
"docker:release": () => runTargetReleaseCommand(argv.slice(1)),
|
|
196
|
+
"docker:release": () => runTargetReleaseCommand(argv.slice(1), bootstrap.synchronization),
|
|
194
197
|
afterBuild: () => loadBuildDist().init(),
|
|
195
198
|
initZip: () => loadBuildDist().init(),
|
|
196
199
|
preview: () => loadPreview().init(),
|
|
@@ -210,7 +213,7 @@ async function main(argv = process.argv.slice(2)) {
|
|
|
210
213
|
"release:docker": () => {
|
|
211
214
|
const args = argv.slice(1);
|
|
212
215
|
const mode = resolveReleaseDockerMode(args, loadReleasePackage(args));
|
|
213
|
-
if (mode === "target") return runTargetReleaseCommand(args);
|
|
216
|
+
if (mode === "target") return runTargetReleaseCommand(args, bootstrap.synchronization);
|
|
214
217
|
return require("../build/docker/release-docker").releaseDocker(parseArgs(args));
|
|
215
218
|
},
|
|
216
219
|
"docker:compose": () => {
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
const fs = require("node:fs");
|
|
2
|
+
const path = require("node:path");
|
|
3
|
+
const { execFileSync, spawnSync } = require("node:child_process");
|
|
4
|
+
const { findOuterWorkspaceRoot, resolveGitWorktreeRoot } = require("../script/git-automation/git-utils");
|
|
5
|
+
const { updateRootRepository } = require("../script/git-automation/root-update");
|
|
6
|
+
|
|
7
|
+
const BUILD_COMMANDS = new Set(["release:docker", "docker:release", "build:docker", "docker:compose"]);
|
|
8
|
+
|
|
9
|
+
/** 在加载构建实现前同步根仓;更新自身代码后重启,防止进程混用新旧模块。 */
|
|
10
|
+
function bootstrapRelease({
|
|
11
|
+
argv = [],
|
|
12
|
+
entryFile,
|
|
13
|
+
cwd = process.cwd(),
|
|
14
|
+
env = process.env,
|
|
15
|
+
run = execFileSync,
|
|
16
|
+
spawn = spawnSync,
|
|
17
|
+
discoverRoot,
|
|
18
|
+
log = console.log
|
|
19
|
+
} = {}) {
|
|
20
|
+
if (!BUILD_COMMANDS.has(argv[0]) || argv.includes("--dry-run")) return {};
|
|
21
|
+
const index = argv.indexOf("--project-dir");
|
|
22
|
+
const equals = argv.find((arg) => arg.startsWith("--project-dir="));
|
|
23
|
+
if ((index >= 0 && (!argv[index + 1] || argv[index + 1].startsWith("--"))) || equals === "--project-dir=") {
|
|
24
|
+
throw new Error("--project-dir 缺少参数值");
|
|
25
|
+
}
|
|
26
|
+
const projectDir = path.resolve(cwd, equals ? equals.slice(14) : index >= 0 ? argv[index + 1] || "." : ".");
|
|
27
|
+
const workspaceRoot = discoverRoot
|
|
28
|
+
? discoverRoot(projectDir)
|
|
29
|
+
: findOuterWorkspaceRoot(resolveGitWorktreeRoot(projectDir));
|
|
30
|
+
if (!workspaceRoot) return {};
|
|
31
|
+
const synchronization = updateRootRepository(workspaceRoot, "master", { run, requireRemoteHead: true, log });
|
|
32
|
+
const { before, revision } = synchronization;
|
|
33
|
+
const rootEntry = path.join(workspaceRoot, "packages", "infly-libs", "bin", "cli.js");
|
|
34
|
+
if (before !== revision || path.resolve(entryFile) !== rootEntry) {
|
|
35
|
+
if (env.INFLY_BOOTSTRAP_RESTARTS) throw new Error("重启期间根仓再次更新,请重新执行构建命令");
|
|
36
|
+
if (!fs.existsSync(rootEntry)) throw new Error("更新后的根仓缺少公共 CLI,不能回退旧工具");
|
|
37
|
+
log("主仓已同步,使用更新后的公共工具重新启动构建。");
|
|
38
|
+
const child = spawn(process.execPath, [rootEntry, ...argv], {
|
|
39
|
+
cwd,
|
|
40
|
+
stdio: "inherit",
|
|
41
|
+
env: { ...env, INFLY_BOOTSTRAP_RESTARTS: "1" }
|
|
42
|
+
});
|
|
43
|
+
if (child.error || child.signal || child.status == null)
|
|
44
|
+
throw new Error("更新后的构建工具启动失败", { cause: child.error });
|
|
45
|
+
return { relaunched: true, status: child.status };
|
|
46
|
+
}
|
|
47
|
+
return { synchronization };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
module.exports = { bootstrapRelease };
|
|
@@ -62,7 +62,9 @@ function composeRelease(options = {}, dependencies = {}) {
|
|
|
62
62
|
const resolved = resolveComposePath(projectDir, file);
|
|
63
63
|
const original = fs.readFileSync(resolved.composePath, "utf8");
|
|
64
64
|
const updated = bumpComposeImageVersion(original, bump);
|
|
65
|
-
const
|
|
65
|
+
const commands = ["config", "build", ...(push ? ["push"] : [])]
|
|
66
|
+
.map((command) => ["compose", "-f", resolved.composePath, command]);
|
|
67
|
+
const result = { ...updated, ...resolved };
|
|
66
68
|
|
|
67
69
|
if (bump === "none") {
|
|
68
70
|
console.log(`Version fixed: ${updated.from}`);
|
|
@@ -71,24 +73,20 @@ function composeRelease(options = {}, dependencies = {}) {
|
|
|
71
73
|
}
|
|
72
74
|
|
|
73
75
|
if (dryRun) {
|
|
74
|
-
console.log(`[dry-run] docker ${
|
|
75
|
-
|
|
76
|
-
if (push) console.log(`[dry-run] docker ${[...baseArgs, "push"].join(" ")}`);
|
|
77
|
-
return { ...updated, projectDir: resolved.projectDir, composePath: resolved.composePath };
|
|
76
|
+
for (const args of commands) console.log(`[dry-run] docker ${args.join(" ")}`);
|
|
77
|
+
return result;
|
|
78
78
|
}
|
|
79
79
|
|
|
80
80
|
const versionChanged = updated.content !== original;
|
|
81
81
|
if (versionChanged) fs.writeFileSync(resolved.composePath, updated.content, "utf8");
|
|
82
82
|
try {
|
|
83
|
-
runDocker(
|
|
84
|
-
runDocker([...baseArgs, "build"], { cwd: resolved.projectDir });
|
|
85
|
-
if (push) runDocker([...baseArgs, "push"], { cwd: resolved.projectDir });
|
|
83
|
+
for (const args of commands) runDocker(args, { cwd: resolved.projectDir });
|
|
86
84
|
} catch (error) {
|
|
87
85
|
if (versionChanged) fs.writeFileSync(resolved.composePath, original, "utf8");
|
|
88
86
|
throw error;
|
|
89
87
|
}
|
|
90
88
|
|
|
91
|
-
return
|
|
89
|
+
return result;
|
|
92
90
|
}
|
|
93
91
|
|
|
94
92
|
module.exports = {
|
|
@@ -23,9 +23,44 @@ cleanup() {
|
|
|
23
23
|
}
|
|
24
24
|
trap cleanup EXIT
|
|
25
25
|
|
|
26
|
+
push_release_image() {
|
|
27
|
+
local help api_versions client_api server_api api platform_supported=true
|
|
28
|
+
help=$(docker push --help) || return 1
|
|
29
|
+
if [[ "$help" == *--platform* ]]; then
|
|
30
|
+
api_versions=$(docker version --format '{{.Client.APIVersion}} {{.Server.APIVersion}}') || return 1
|
|
31
|
+
read -r client_api server_api <<< "$api_versions"
|
|
32
|
+
for api in "$client_api" "$server_api" "${DOCKER_API_VERSION:-1.46}"; do
|
|
33
|
+
[[ "$api" =~ ^([0-9]+)\.([0-9]+)$ ]] || {
|
|
34
|
+
echo "$component 无法确定 Docker push API 兼容性" >&2
|
|
35
|
+
return 1
|
|
36
|
+
}
|
|
37
|
+
if ((10#${BASH_REMATCH[1]} < 1 || (10#${BASH_REMATCH[1]} == 1 && 10#${BASH_REMATCH[2]} < 46))); then
|
|
38
|
+
platform_supported=false
|
|
39
|
+
fi
|
|
40
|
+
done
|
|
41
|
+
else
|
|
42
|
+
platform_supported=false
|
|
43
|
+
fi
|
|
44
|
+
if [[ "$platform_supported" == true ]]; then
|
|
45
|
+
# containerd 拉取的镜像可能保留未完整下载的索引;正式标签只推送已核验镜像的平台清单。
|
|
46
|
+
# 平台来自镜像 ID,不能假定 Jenkins 主机或业务镜像使用 amd64。
|
|
47
|
+
echo "$component 按已核验平台晋升镜像: $source_platform"
|
|
48
|
+
docker push --platform "$source_platform" "$final_image"
|
|
49
|
+
else
|
|
50
|
+
# 旧 CLI/API 保留原有单镜像推送;真实推送失败立即停止,不再降级重试。
|
|
51
|
+
echo "$component Docker CLI/API 不支持指定平台推送,使用兼容的单镜像推送"
|
|
52
|
+
docker push "$final_image"
|
|
53
|
+
fi
|
|
54
|
+
}
|
|
55
|
+
|
|
26
56
|
docker manifest inspect "$source_image" >/dev/null
|
|
27
57
|
docker pull "$source_image"
|
|
28
|
-
|
|
58
|
+
source_id=$(docker image inspect --format '{{.Id}}' "$source_image")
|
|
59
|
+
[[ "$source_id" =~ ^sha256:[0-9a-f]{64}$ ]] || {
|
|
60
|
+
echo "$component qc 镜像 ID 无效" >&2
|
|
61
|
+
exit 1
|
|
62
|
+
}
|
|
63
|
+
actual_revision=$(docker image inspect --format '{{ index .Config.Labels "org.opencontainers.image.revision" }}' "$source_id")
|
|
29
64
|
if [[ "$actual_revision" != "$expected_revision" ]]; then
|
|
30
65
|
echo "$component qc 镜像完整 revision 校验失败: image=$source_image" >&2
|
|
31
66
|
exit 1
|
|
@@ -48,10 +83,45 @@ if ! grep -Eqi 'manifest unknown|no such manifest|manifest[^[:cntrl:]]*not found
|
|
|
48
83
|
exit 1
|
|
49
84
|
fi
|
|
50
85
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
86
|
+
if docker buildx version >/dev/null 2>&1; then
|
|
87
|
+
if [[ "$source_image" == *@* ]]; then
|
|
88
|
+
source_digest=${source_image##*@}
|
|
89
|
+
source_repository=${source_image%@*}
|
|
90
|
+
[[ -n "$source_repository" && "$source_repository" != *@* ]] || exit 1
|
|
91
|
+
else
|
|
92
|
+
# printf 前缀兼容 Buildx v0.10.5,避免其把以 {{.Manifest 开头的格式当成固定展示模式。
|
|
93
|
+
source_digest=$(docker buildx imagetools inspect "$source_image" --format '{{printf "%s" .Manifest.Digest}}')
|
|
94
|
+
source_repository=$source_image
|
|
95
|
+
# 只移除最后一个路径段的标签,保留 registry:port 与未显式指定标签的仓库名。
|
|
96
|
+
if [[ "${source_repository##*/}" == *:* ]]; then source_repository=${source_repository%:*}; fi
|
|
97
|
+
fi
|
|
98
|
+
[[ "$source_digest" =~ ^sha256:[0-9a-f]{64}$ ]] || {
|
|
99
|
+
echo "$component 无法冻结 qc 镜像 Registry digest" >&2
|
|
100
|
+
exit 1
|
|
101
|
+
}
|
|
102
|
+
frozen_source="$source_repository@$source_digest"
|
|
103
|
+
# 在冻结后重新拉取并校验;若 QC 标签在第一次校验后漂移,禁止复制另一个镜像。
|
|
104
|
+
docker pull "$frozen_source"
|
|
105
|
+
frozen_id=$(docker image inspect --format '{{.Id}}' "$frozen_source")
|
|
106
|
+
frozen_revision=$(docker image inspect --format '{{ index .Config.Labels "org.opencontainers.image.revision" }}' "$frozen_id")
|
|
107
|
+
if [[ "$frozen_id" != "$source_id" || "$frozen_revision" != "$expected_revision" ]]; then
|
|
108
|
+
echo "$component 冻结后的 qc 镜像与已核验镜像不一致,禁止晋升" >&2
|
|
109
|
+
exit 1
|
|
110
|
+
fi
|
|
111
|
+
echo "$component 从已冻结 Registry digest 晋升镜像: $frozen_source"
|
|
112
|
+
# 仓库端复制保留完整索引及附加证明,不依赖 Docker Engine 的 push --platform 能力。
|
|
113
|
+
# inspect/create 的真实错误立即停止,不切换到本地推送路径。
|
|
114
|
+
docker buildx imagetools create --tag "$final_image" "$frozen_source"
|
|
115
|
+
else
|
|
116
|
+
source_platform=$(docker image inspect --format '{{.Os}}/{{.Architecture}}{{if .Variant}}/{{.Variant}}{{end}}' "$source_id")
|
|
117
|
+
[[ "$source_platform" =~ ^[a-z0-9][a-z0-9_.-]*/[a-z0-9][a-z0-9_.-]*(/[a-z0-9][a-z0-9_.-]*)?$ ]] || {
|
|
118
|
+
echo "$component qc 镜像平台无效" >&2
|
|
119
|
+
exit 1
|
|
120
|
+
}
|
|
121
|
+
# 没有 Buildx 时以已核验的 ID 重标记,保留新旧 Docker CLI/API 兼容路径。
|
|
122
|
+
docker tag "$source_id" "$final_image"
|
|
123
|
+
push_release_image
|
|
124
|
+
fi
|
|
55
125
|
docker pull "$final_image"
|
|
56
126
|
final_revision=$(docker image inspect --format '{{ index .Config.Labels "org.opencontainers.image.revision" }}' "$final_image")
|
|
57
127
|
if [[ "$final_revision" != "$expected_revision" ]]; then
|
|
@@ -56,7 +56,7 @@ function formatCicdLink(value, deployParams) {
|
|
|
56
56
|
|
|
57
57
|
// 单组件推送成功后预填“平台/镜像版本”参数,新平台首次部署无需从历史选项里挑选;仅对 /build 构建入口追加。
|
|
58
58
|
if (deployParams !== undefined) {
|
|
59
|
-
const { platform, platformLabel, tag, date } = deployParams;
|
|
59
|
+
const { platform, platformLabel, tag, date, releaseVersion } = deployParams;
|
|
60
60
|
if (typeof platform !== "string" || !/^[a-z0-9]+$/.test(platform)
|
|
61
61
|
|| typeof tag !== "string" || !/^[0-9a-f]{40}$/.test(tag)
|
|
62
62
|
|| typeof date !== "string" || !/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/.test(date)) {
|
|
@@ -66,11 +66,16 @@ function formatCicdLink(value, deployParams) {
|
|
|
66
66
|
|| /[\u0000-\u001f\u007f]/.test(platformLabel))) {
|
|
67
67
|
throw new Error("发布系统深链平台名称必须是非空且不含控制字符的字符串");
|
|
68
68
|
}
|
|
69
|
+
if (releaseVersion !== undefined && !/^[0-9a-f]{40}-r[0-9a-f]{12}$/.test(releaseVersion)) {
|
|
70
|
+
throw new Error("发布系统深链发布版本无效");
|
|
71
|
+
}
|
|
69
72
|
if (parsedUrl.pathname.endsWith("/build")) {
|
|
70
73
|
// Jenkins 原生 choice 的显示文本就是提交值;传入标签时须与“中文名称 / 编码”选项完全一致。
|
|
71
74
|
const platformChoice = platformLabel === undefined ? platform : `${platformLabel.trim()} / ${platform}`;
|
|
72
75
|
const suffix = `&${encodeURIComponent("平台")}=${encodeURIComponent(platformChoice)}`
|
|
73
|
-
+
|
|
76
|
+
+ (releaseVersion
|
|
77
|
+
? `&${encodeURIComponent("发布版本")}=${encodeURIComponent(releaseVersion)}`
|
|
78
|
+
: `&${encodeURIComponent("镜像版本")}=${encodeURIComponent(`${platform} / ${tag} / ${date}`)}`);
|
|
74
79
|
parsedUrl.search = parsedUrl.search ? `${parsedUrl.search}${suffix}` : `?${suffix.slice(1)}`;
|
|
75
80
|
}
|
|
76
81
|
}
|
|
@@ -346,6 +351,7 @@ async function dockerBuildPush(options = {}, dependencies = {}) {
|
|
|
346
351
|
// 1. 检测运行模式并定位关键路径
|
|
347
352
|
const cwd = path.resolve(process.cwd());
|
|
348
353
|
const { isStandalone, contextRoot } = detectMode({ standalone });
|
|
354
|
+
const mode = isStandalone ? "standalone" : "monorepo";
|
|
349
355
|
|
|
350
356
|
const appPkgPath = path.join(cwd, "package.json");
|
|
351
357
|
if (!fs.existsSync(appPkgPath)) {
|
|
@@ -424,13 +430,13 @@ async function dockerBuildPush(options = {}, dependencies = {}) {
|
|
|
424
430
|
projectDir: cwd,
|
|
425
431
|
});
|
|
426
432
|
effectiveBuildContext = preparedContext.contextRoot;
|
|
427
|
-
console.log(`最小上下文: ${projectDirArg} + packages +
|
|
433
|
+
console.log(`最小上下文: ${projectDirArg} + packages + 根安装文件`);
|
|
428
434
|
}
|
|
429
435
|
const buildArgs = ["build", "-f", dockerfileArg];
|
|
430
436
|
tags.forEach((tag) => buildArgs.push("-t", tag));
|
|
431
437
|
buildArgs.push(
|
|
432
438
|
"--build-arg", `GIT_COMMIT=${fullCommit}`,
|
|
433
|
-
"--build-arg", `BUILD_MODE=${
|
|
439
|
+
"--build-arg", `BUILD_MODE=${mode}`,
|
|
434
440
|
"--build-arg", `PROJECT_DIR=${projectDirArg}`,
|
|
435
441
|
"--label", `org.opencontainers.image.revision=${fullCommit}`,
|
|
436
442
|
"--label", `org.opencontainers.image.version=${commitHash}`
|
|
@@ -488,7 +494,7 @@ async function dockerBuildPush(options = {}, dependencies = {}) {
|
|
|
488
494
|
}
|
|
489
495
|
console.log("");
|
|
490
496
|
|
|
491
|
-
return { mode
|
|
497
|
+
return { mode, buildContext, imageName, commitHash, tags };
|
|
492
498
|
}
|
|
493
499
|
|
|
494
500
|
module.exports = {
|
|
@@ -29,6 +29,24 @@ function shouldCopy(source) {
|
|
|
29
29
|
return !source.split(path.sep).some((segment) => EXCLUDED_DIRECTORIES.has(segment));
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
+
function normalizeMonorepoContextFiles(files = []) {
|
|
33
|
+
if (!Array.isArray(files)) throw new Error("monorepoContextFiles 必须是文件路径数组");
|
|
34
|
+
const seen = new Set();
|
|
35
|
+
return files.map((file) => {
|
|
36
|
+
if (typeof file !== "string" || !file || file.includes("\0")
|
|
37
|
+
|| path.isAbsolute(file) || path.win32.isAbsolute(file) || /^[a-z]:/i.test(file)
|
|
38
|
+
|| /[*?{}\[\]]/.test(file)) throw new Error("monorepoContextFiles 只支持根目录内的明确相对文件路径,不支持通配符");
|
|
39
|
+
const normalized = file.replace(/\\/g, "/");
|
|
40
|
+
const segments = normalized.split("/");
|
|
41
|
+
if (segments.some((segment) => !segment || segment === "." || segment === ".."
|
|
42
|
+
|| EXCLUDED_DIRECTORIES.has(segment.toLowerCase())) || seen.has(normalized)) {
|
|
43
|
+
throw new Error("monorepoContextFiles 不允许越界、排除目录或重复路径");
|
|
44
|
+
}
|
|
45
|
+
seen.add(normalized);
|
|
46
|
+
return normalized;
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
32
50
|
function copyEntry(io, workspaceRoot, contextRoot, relative) {
|
|
33
51
|
const source = path.join(workspaceRoot, relative);
|
|
34
52
|
if (!io.existsSync(source)) return false;
|
|
@@ -44,12 +62,13 @@ function copyEntry(io, workspaceRoot, contextRoot, relative) {
|
|
|
44
62
|
|
|
45
63
|
/**
|
|
46
64
|
* 为 monorepo 源码镜像准备保持原目录布局的最小上下文。
|
|
47
|
-
*
|
|
65
|
+
* 只带根安装契约及钩子、公共 packages 和当前应用,避免把其他产品线发送给 Docker。
|
|
48
66
|
*/
|
|
49
67
|
function prepareMinimalMonorepoContext({
|
|
50
68
|
workspaceRoot,
|
|
51
69
|
projectDir,
|
|
52
70
|
sourceDir,
|
|
71
|
+
additionalFiles = [],
|
|
53
72
|
io = fs,
|
|
54
73
|
temporaryRoot = os.tmpdir(),
|
|
55
74
|
} = {}) {
|
|
@@ -58,10 +77,21 @@ function prepareMinimalMonorepoContext({
|
|
|
58
77
|
if (!isInside(resolvedWorkspace, resolvedProject)) {
|
|
59
78
|
throw new Error(`项目目录不在 monorepo 根目录内: ${resolvedProject}`);
|
|
60
79
|
}
|
|
80
|
+
const explicitFiles = normalizeMonorepoContextFiles(additionalFiles);
|
|
81
|
+
for (const file of explicitFiles) {
|
|
82
|
+
const source = path.join(resolvedWorkspace, file);
|
|
83
|
+
if (!io.existsSync(source)) throw new Error(`缺少 monorepo 构建文件: ${file}`);
|
|
84
|
+
// 只允许普通文件;父目录链接也不能把读取范围带出工作区。
|
|
85
|
+
if (!io.lstatSync(source).isFile()
|
|
86
|
+
|| !isInside(io.realpathSync(resolvedWorkspace), io.realpathSync(source))) {
|
|
87
|
+
throw new Error(`monorepoContextFiles 只允许工作区内的普通文件: ${file}`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
61
90
|
const projectRelativeDir = path.relative(resolvedWorkspace, resolvedProject);
|
|
62
91
|
const contextRoot = io.mkdtempSync(path.join(temporaryRoot, "infly-docker-context-"));
|
|
63
92
|
try {
|
|
64
93
|
for (const entry of ROOT_ENTRIES) copyEntry(io, resolvedWorkspace, contextRoot, entry);
|
|
94
|
+
for (const file of explicitFiles) copyEntry(io, resolvedWorkspace, contextRoot, file);
|
|
65
95
|
if (!projectRelativeDir.startsWith(`packages${path.sep}`)) {
|
|
66
96
|
if (sourceDir) {
|
|
67
97
|
// 部署仓冻结业务源码后,以该快照替换业务目录,公共包仍来自已核验的根工作区。
|
|
@@ -82,6 +112,7 @@ function prepareMinimalMonorepoContext({
|
|
|
82
112
|
module.exports = {
|
|
83
113
|
EXCLUDED_DIRECTORIES,
|
|
84
114
|
ROOT_ENTRIES,
|
|
115
|
+
normalizeMonorepoContextFiles,
|
|
85
116
|
prepareMinimalMonorepoContext,
|
|
86
117
|
shouldCopy,
|
|
87
118
|
};
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
const fs = require("node:fs");
|
|
2
|
+
const os = require("node:os");
|
|
3
|
+
const path = require("node:path");
|
|
4
|
+
const yaml = require("yaml");
|
|
5
|
+
const { DEPENDENCY_SECTIONS, discoverWorkspacePackages } = require("../../workspace/packages");
|
|
6
|
+
const { shouldCopy } = require("./minimal-context");
|
|
7
|
+
|
|
8
|
+
const LOCAL_PACKAGES = ".infly-local-packages";
|
|
9
|
+
const LOCAL_MANIFESTS = ".infly-local-manifests";
|
|
10
|
+
const RELEASE_RECORD = ".infly-release.json";
|
|
11
|
+
|
|
12
|
+
function readJson(file) { return JSON.parse(fs.readFileSync(file, "utf8")); }
|
|
13
|
+
|
|
14
|
+
function copyTree(source, destination) {
|
|
15
|
+
fs.cpSync(source, destination, { recursive: true, filter: (file) => {
|
|
16
|
+
if (!shouldCopy(file)) return false;
|
|
17
|
+
if (fs.lstatSync(file).isSymbolicLink()) throw new Error(`构建源码不允许符号链接: ${file}`);
|
|
18
|
+
return true;
|
|
19
|
+
} });
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function manifestsIn(directory) {
|
|
23
|
+
const result = [];
|
|
24
|
+
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
|
|
25
|
+
const file = path.join(directory, entry.name);
|
|
26
|
+
if (!shouldCopy(file) || entry.isSymbolicLink()) continue;
|
|
27
|
+
if (entry.isDirectory()) result.push(...manifestsIn(file));
|
|
28
|
+
else if (entry.name === "package.json") result.push(readJson(file));
|
|
29
|
+
}
|
|
30
|
+
return result;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function prepareInstallContext({ sourceDir, temporaryRoot, prefix, reserved, pnpmfileError }, prepare) {
|
|
34
|
+
const contextRoot = fs.mkdtempSync(path.join(temporaryRoot, prefix));
|
|
35
|
+
try {
|
|
36
|
+
for (const [file, error] of reserved) {
|
|
37
|
+
if (fs.existsSync(path.join(sourceDir, file))) throw new Error(error);
|
|
38
|
+
}
|
|
39
|
+
copyTree(sourceDir, contextRoot);
|
|
40
|
+
const configFile = path.join(contextRoot, "pnpm-workspace.yaml");
|
|
41
|
+
const document = yaml.parseDocument(fs.readFileSync(configFile, "utf8"));
|
|
42
|
+
if (document.errors.length) throw document.errors[0];
|
|
43
|
+
const config = document.toJS() || {};
|
|
44
|
+
if (config.pnpmfile || fs.existsSync(path.join(contextRoot, ".pnpmfile.cjs"))) {
|
|
45
|
+
throw new Error(pnpmfileError);
|
|
46
|
+
}
|
|
47
|
+
const packages = prepare({ contextRoot, configFile, document, config });
|
|
48
|
+
return { contextRoot, projectRelativeDir: ".", packages };
|
|
49
|
+
} catch (error) {
|
|
50
|
+
fs.rmSync(contextRoot, { recursive: true, force: true });
|
|
51
|
+
throw error;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** 项目安装配置 + 按依赖闭包选取的公共源码;不读取父仓安装配置或锁文件。 */
|
|
56
|
+
function prepareProjectInstallContext({ workspaceRoot, sourceDir, temporaryRoot = os.tmpdir() }) {
|
|
57
|
+
return prepareInstallContext({
|
|
58
|
+
sourceDir, temporaryRoot, prefix: "infly-project-install-",
|
|
59
|
+
reserved: [LOCAL_PACKAGES, LOCAL_MANIFESTS, RELEASE_RECORD].map((file) => [file, `${file} 是构建保留目录`]),
|
|
60
|
+
pnpmfileError: "projectInstall 要求项目自身不使用 pnpmfile",
|
|
61
|
+
}, ({ contextRoot, configFile, document, config }) => {
|
|
62
|
+
const available = discoverWorkspacePackages(workspaceRoot);
|
|
63
|
+
const byName = new Map();
|
|
64
|
+
for (const pkg of available) {
|
|
65
|
+
if (typeof pkg.name !== "string" || !pkg.name || byName.has(pkg.name)) throw new Error("公共源码包名称缺失或重复");
|
|
66
|
+
byName.set(pkg.name, pkg);
|
|
67
|
+
}
|
|
68
|
+
const localDependencies = (manifest) => {
|
|
69
|
+
const names = new Set(DEPENDENCY_SECTIONS.flatMap((section) => Object.keys(manifest[section] || {})));
|
|
70
|
+
for (const name of names) {
|
|
71
|
+
if (name.startsWith("@infly/") && !byName.has(name)) throw new Error(`缺少公共包源码: ${name}(消费方 ${manifest.name || "未知项目"});禁止回退 npm`);
|
|
72
|
+
}
|
|
73
|
+
return [...names].filter((name) => byName.has(name));
|
|
74
|
+
};
|
|
75
|
+
const selected = new Set(manifestsIn(contextRoot).flatMap(localDependencies));
|
|
76
|
+
for (const name of selected) {
|
|
77
|
+
const pkg = byName.get(name);
|
|
78
|
+
// 公共包只参与源码消费,不安装其发布、测试等开发工具。
|
|
79
|
+
const manifest = { ...pkg.manifest };
|
|
80
|
+
delete manifest.devDependencies;
|
|
81
|
+
for (const dependency of localDependencies(manifest)) selected.add(dependency);
|
|
82
|
+
}
|
|
83
|
+
const packages = available.filter((pkg) => selected.has(pkg.name));
|
|
84
|
+
const manifestRoot = path.join(contextRoot, LOCAL_MANIFESTS);
|
|
85
|
+
fs.mkdirSync(manifestRoot, { recursive: true });
|
|
86
|
+
for (const pkg of packages) {
|
|
87
|
+
const destination = path.join(contextRoot, LOCAL_PACKAGES, pkg.dir);
|
|
88
|
+
copyTree(pkg.directoryPath, destination);
|
|
89
|
+
const manifestFile = path.join(destination, "package.json");
|
|
90
|
+
const manifest = readJson(manifestFile);
|
|
91
|
+
delete manifest.devDependencies;
|
|
92
|
+
fs.writeFileSync(manifestFile, `${JSON.stringify(manifest, null, 2)}\n`);
|
|
93
|
+
const manifestDirectory = path.join(manifestRoot, pkg.dir);
|
|
94
|
+
fs.mkdirSync(manifestDirectory, { recursive: true });
|
|
95
|
+
fs.copyFileSync(manifestFile, path.join(manifestDirectory, "package.json"));
|
|
96
|
+
}
|
|
97
|
+
config.packages = [...(config.packages || []), `${LOCAL_PACKAGES}/*`];
|
|
98
|
+
config.overrides = { ...(config.overrides || {}), ...Object.fromEntries(packages.map((pkg) => [pkg.name, "workspace:*"])) };
|
|
99
|
+
// 保留业务配置已有的注释和引号风格,只补充本地 workspace 映射。
|
|
100
|
+
document.set("packages", config.packages);
|
|
101
|
+
document.set("overrides", config.overrides);
|
|
102
|
+
fs.writeFileSync(configFile, document.toString());
|
|
103
|
+
return packages.map((pkg) => pkg.name);
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** 独立构建仅更新内部 npm 包;工作树清单与原锁均保持不变。 */
|
|
108
|
+
function prepareStandaloneInstallContext({ sourceDir, registryManifest, temporaryRoot = os.tmpdir() }) {
|
|
109
|
+
return prepareInstallContext({
|
|
110
|
+
sourceDir, temporaryRoot, prefix: "infly-standalone-install-",
|
|
111
|
+
reserved: [[RELEASE_RECORD, `${RELEASE_RECORD} 是构建保留文件`]],
|
|
112
|
+
pnpmfileError: "独立源码构建不加载 pnpmfile",
|
|
113
|
+
}, ({ contextRoot, configFile, document, config }) => {
|
|
114
|
+
const lockFile = path.join(contextRoot, "pnpm-lock.yaml");
|
|
115
|
+
const lock = yaml.parse(fs.readFileSync(lockFile, "utf8"));
|
|
116
|
+
const queue = new Map();
|
|
117
|
+
const addRequirement = (name, range) => {
|
|
118
|
+
if (!queue.has(name)) queue.set(name, new Set());
|
|
119
|
+
queue.get(name).add(String(range));
|
|
120
|
+
};
|
|
121
|
+
for (const manifest of manifestsIn(contextRoot)) {
|
|
122
|
+
for (const section of DEPENDENCY_SECTIONS) {
|
|
123
|
+
for (const [name, range] of Object.entries(manifest[section] || {})) {
|
|
124
|
+
if (name.startsWith("@infly/")) addRequirement(name, range);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
for (const importer of Object.values(lock.importers || {})) {
|
|
129
|
+
for (const section of ["dependencies", "devDependencies", "optionalDependencies"]) {
|
|
130
|
+
for (const [name, entry] of Object.entries(importer[section] || {})) {
|
|
131
|
+
if (name.startsWith("@infly/")) addRequirement(name, entry.version);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
const packages = [];
|
|
136
|
+
const versions = new Map();
|
|
137
|
+
const verifyMajor = (name, baseline, version) => {
|
|
138
|
+
const current = String(baseline).match(/^[~^<>=\s]*(\d+)(?:\.|$)/);
|
|
139
|
+
if (!current || Number(current[1]) !== Number(version.split(".")[0])) {
|
|
140
|
+
throw new Error(`需要 major 升级二次确认: ${name} ${baseline} → ${version};未修改工作树或安装依赖`);
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
for (const [name, requirements] of queue) {
|
|
144
|
+
const metadata = registryManifest(name);
|
|
145
|
+
const version = metadata.version;
|
|
146
|
+
if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version || "")) throw new Error(`${name} Registry latest 版本无效`);
|
|
147
|
+
for (const baseline of requirements) verifyMajor(name, baseline, version);
|
|
148
|
+
versions.set(name, version);
|
|
149
|
+
packages.push({ name, version });
|
|
150
|
+
for (const section of ["dependencies", "optionalDependencies", "peerDependencies"]) {
|
|
151
|
+
for (const [dependency, requirement] of Object.entries(metadata[section] || {})) {
|
|
152
|
+
if (dependency.startsWith("@infly/")) {
|
|
153
|
+
addRequirement(dependency, requirement);
|
|
154
|
+
// 后发现的 peer/传递约束同样检查,不能因包已解析而漏掉主版本冲突。
|
|
155
|
+
if (versions.has(dependency)) verifyMajor(dependency, requirement, versions.get(dependency));
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
config.overrides = { ...(config.overrides || {}), ...Object.fromEntries(packages.map(({ name, version }) => [name, version])) };
|
|
161
|
+
document.set("overrides", config.overrides);
|
|
162
|
+
fs.writeFileSync(configFile, document.toString());
|
|
163
|
+
// 只补充本次内部包约束元数据;实际锁图仍由容器内 pnpm 生成并 frozen 复验。
|
|
164
|
+
lock.overrides = config.overrides;
|
|
165
|
+
fs.writeFileSync(lockFile, yaml.stringify(lock));
|
|
166
|
+
return packages;
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
module.exports = { LOCAL_PACKAGES, prepareProjectInstallContext, prepareStandaloneInstallContext };
|