跳转到内容

Spectral 检查规则

本项目使用 Spectral 进行 OAS3 检查,采用双配置架构将 CI/外部工具与流水线的自定义逻辑分离。

供 GitHub Super-Linter 和任何外部 CI 工具使用。继承 spectral:oas(内置 OAS 规则集)。不包含自定义函数——这确保了与那些在无法访问 spectral/functions/ 目录的情况下运行 Spectral 的工具的兼容性。

extends:
- "spectral:oas"
rules:
path-params: "off"
operation-tags: warn
oas3-api-servers: warn
info-contact: warn
oas3-unused-component: warn
operation-operationId-unique: error
oas3-valid-schema-example: error
no-script-tags-in-markdown: warn
operation-description: info
info-description: info

spectral-pipeline.yaml — 流水线配置

Section titled “spectral-pipeline.yaml — 流水线配置”

scripts/spectral_lint.py(发现模式和门控模式)使用。继承基础配置并添加自定义 f5-path-params 函数:

extends:
- "./.spectral.yaml"
functionsDir: "./spectral/functions"
functions:
- f5-path-params
rules:
f5-path-params:
description: "Path parameters must be declared and used"
message: "{{error}}"
severity: error
given: "$.paths[*]"
then:
function: f5-path-params

Spectral 内置的 path-params 规则会错误地标记 F5 XC API 中使用点号分隔参数名(如 {metadata.namespace}{metadata.name})的情况。内置规则无法解析参数名中的点号,因此会将其报告为未声明。

自定义 f5-path-params 函数(spectral/functions/f5-path-params.js)通过将完整的 {placeholder} 内容与已声明的参数名进行匹配,正确处理了带点号的名称。它同时检查路径级别和操作级别的参数,并在两个方向上报告错误:

  • URL 路径中的占位符没有匹配的参数声明
  • 已声明的路径参数未出现在 URL 路径中

当检测到违规时,这些规则会由协调器自动修复。有关每项修复的详情,请参阅已应用的修复

规则严重级别修复方法描述
oas3-api-serverswarn_add_servers规范必须包含 servers
info-contactwarn_add_contactinfo 必须包含 contact
operation-tagswarn_add_tags每个操作必须至少有一个标签
oas3-unused-componentwarn_remove_unused_component不允许存在未引用的组件 schema
operation-operationId-uniqueerror_deduplicate_operation_id所有 operationId 必须唯一
oas3-valid-schema-exampleerror_fix_schema_example示例/默认值必须与其 schema 匹配
no-script-tags-in-markdownwarn_strip_script_tags描述中不允许包含 <script> 标签
f5-path-paramserror路径参数必须被声明和使用

这些规则被降级为 info 严重级别,因为它们无法进行有意义的自动修复:

规则严重级别描述
operation-descriptioninfo操作应包含描述
info-descriptioninfoAPI info 应包含描述

Spectral 适配器(scripts/spectral_lint.py)以两种模式运行:

Terminal window
make spectral-lint
# Equivalent to: python -m scripts.spectral_lint --mode discover

扫描 specs/original/ 并输出 reports/spectral_report.json。协调器会将此报告与验证报告一起使用。

Terminal window
make spectral-gate
# Equivalent to: python -m scripts.spectral_lint --mode gate

扫描 release/specs/ 并输出 reports/spectral_gate_report.json。如果违规数量超过配置的阈值,则返回退出码 1。

Spectral 违规会被转换为具有三种子类型的 Discrepancy 对象:

Spectral 规则类别DiscrepancyType示例规则
缺少必需元素SPECTRAL_MISSINGoas3-api-serversinfo-contactoperation-tags
现有元素无效SPECTRAL_INVALIDoas3-valid-schema-exampleno-script-tags-in-markdown
死代码SPECTRAL_UNUSEDoas3-unused-component