一、安装spectral(使用yarn安装):
1.安装nodejs(版本必须>=10.8)
(1)下载
wget https://npm.taobao.org/mirrors/node/v14.15.1/node-v14.15.1-linux-x64.tar.xz
(2)解压
tar -xvf node-v14.15.1-linux-x64.tar.xz
mv node-v14.15.1-linux-x64 /usr/local/nodejs/
(3)配置环境变量
vim /etc/profile
export NODEJS_HOME=/usr/local/nodejs
export PATH=${NODEJS_HOME}/bin:${PATH}
source /etc/profile
2.安装yarn
npm install -g yarn
3.检验nodejs、npm、yarn是否安装成功
node -v
npm -v
yarn -v
4.安装spectral
yarn global add @stoplight/spectral
5.检查安装spectral是否成功
spectral --version
二、使用spectral
spectral lint 需要检测的文件
三、如何添加规则
在规则集文件的rules属性下添加规则。
规则集文件路径: /usr/local/share/.config/yarn/global/node_modules/@stoplight/spectral/dist/rulesets/oas/index.json
如果觉得现有规则集不能满足需要可以添加自定义规则,自定义规则可以使用spectral提供的核心函数(比如要求必须要有operatorId,可以使用核心函数truthy),如果核心函数对自定义规则集还不够,可以创建并使用自定义函数。自定义函数创建过程:首先在functions目录下创建.js文件,该目录应该放在规则集文件旁边,再在规则集文件里的functions数组下(在文件最上部)添加之前创建的函数文件名(不带扩展名)。
1.示例1:在规则集文件的rules属性下添加名为info-should-have-description的规则(使用核心函数):
index.json
"info-should-have-description": {
"description": "Info object should contain `description` object.",
"recommended": true,
"type": "style",
"given": "$.info",
"then": {
"field": "description",
"function": "truthy"
}
}
2. 示例2:在规则集文件的rules属性下添加名为info-title-hello的规则(创建并使用自定义函数):
index.json
"functions": [
"oasDocumentSchema",
"oasExample",
"oasOp2xxResponse",
"oasOpFormDataConsumeCheck",
"oasOpIdUnique",
"oasOpParams",
"oasOpSecurityDefined",
"oasPathParam",
"oasTagDefined",
"typedEnum",
"refSiblings",
"abc"
],
"info-title-hello": {
"description": "Info title should be `hello` .",
"recommended": true,
"type": "style",
"given": "$.info.title",
"then": {
"function": "abc"
}
}
functions/abc.js
module.exports = targetVal => {
if (targetVal !== "hello") {
return [
{
message: 'Value must equal "hello".',
},
];
}
};
四、实现在git -commit时使用spectral检测openapi文档
打开项目文件中的.git/hooks/pre-commit.sample
,去掉该文件的后缀名,并在其中使用spectral检测文档。
pre-commit
#!/bin/bash
STAGE_FILES=$(git diff --cached --name-only --diff-filter=ACM -- '*.json' '*.yaml' '*.yml')
if test ${#STAGE_FILES} -gt 0
then
echo "Start of spectral examination"
PASS=true
for FILE in $STAGE_FILES
do
spectral lint $FILE
if [ $? -eq 1 ]; then
PASS=false
fi
done
if ! $PASS; then
echo "Check failed!"
exit 1
else
echo "Check success"
fi
else
echo "There are no files to check"
fi
exit 0