可以对lua文件(能识别openresty变量)进行静态语法检测
1.安装luarocks和luacheck命令
会安装lua5.3、luarocks、luacheck
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
set -ve apt install build-essential libreadline-dev unzip -y which lua5.3 || { LUA_VER=lua-5.3.5 curl -sO http://www.lua.org/ftp/$LUA_VER.tar.gz tar zxf $LUA_VER.tar.gz rm $LUA_VER.tar.gz cd $LUA_VER/ make linux test make install cd ../ rm -r $LUA_VER/ } which luarocks || { LUAROCKS_VER=luarocks-3.4.0 curl -sOL https://luarocks.org/releases/$LUAROCKS_VER.tar.gz tar zxpf $LUAROCKS_VER.tar.gz rm $LUAROCKS_VER.tar.gz cd $LUAROCKS_VER/ ./configure --lua-version=5.3 --versioned-rocks-dir && make && make install cd ../ rm -r $LUAROCKS_VER/ } which luarocks which luacheck || { luarocks install luacheck } which luacheck && echo 'install luarocks luacheck success' |
2.luacheck命令使用
cd到程序目录,配置.luacheckrc文件,可以使用该行命令直接配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#!/bin/bash # # root@20201019 # set -ev echo 'std = "ngx_lua" unused_args = false redefined = false max_line_length = false ignore = { "542", -- An empty if branch "551", -- An empty statement } exclude_files = { "init/", }' > .luacheckrc |
luacheck your_lua_file.lua
luacheck ./
更多luacheck使用参见 https://github.com/mpeterv/luacheck//blob/76bb56736702e8651537b2a9c10ae55ab7dc1d5d/docsrc/cli.rst
3.luacheck vim插件使用
vimrc配置文件添加以下配置(https://github.com/vim-syntastic/syntastic/wiki/Lua%3A—luacheck):
1 2 3 |
let g:syntastic_check_on_open = 1 let g:syntastic_lua_checkers = ["luac", "luacheck"] let g:syntastic_lua_luacheck_args = "--no-unused-args --no-redefined --no-max-line-length --std ngx_lua --ignore 542 551" |
1 2 3 4 5 6 7 8 9 |
注解: (luacheck_args参数配置参见<a href="https://luacheck.readthedocs.io/en/stable/cli.html#patterns">https://luacheck.readthedocs.io/en/stable/cli.html#patterns</a> <a href="https://luacheck.readthedocs.io/en/stable/warnings.html">https://luacheck.readthedocs.io/en/stable/warnings.html</a>) --no-unused-args 忽略不使用的参数 --no-redefined 忽略重定义 --no-max-line-length 忽略每行最长的检测 --ignore 542 551 忽略if条件的body为空(如...elseif ret == nil then end,then和end中间没有语句);忽略空语句(如;),如果用了;则成对出现该语法检测warning 有语法错误的一行左侧栏会有S>标识,光标移动到改行,vim下发会给出提示。修改正确后保存,则该'S>'会消失。 |
4.git hook commit的使用
参见:https://moonbingbing.gitbooks.io/openresty-best-practices/content/test/static_analysis.html
把这些脚本代码加到.git/hooks/pre-commit前几行。注意第一行要是”#!/usr/bin/env bash“,/bin/sh无法识别[[]]判断符号
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#!/usr/bin/env bash lua_files=$(git status -s|awk '{if (($1=="M"||$1=="A") && $2 ~ /.lua$/)print $2;}') if [[ "$lua_files" != "" ]]; then result=$(luacheck $lua_files) if [[ "$result" =~ .*:.*:.*: ]]; then echo "$result" echo "" exec < /dev/tty read -p "Abort commit?(Y/n)" if [[ "$REPLY" == y* ]] || [[ "$REPLY" == Y* ]]; then echo "Abort commit" exit 1 fi fi fi |