Comment on page

SwiftLint

1. 安装及使用

#swiftlint #tool #Swift

1.1 安装

  • homebrew
    • 不侵入原工程
    • 安装方便
    • 不便于版本控制 ​
# 安装当前最新版本的swiftlint
brew install swiftlint
  • cocoapods
    • 通过 podfile.lock 可以控制版本
    • 修改podfile, 侵入原工程
# podfile
pod 'swiftlint'
# 执行命令
pod install
# path 检查的路径
# reporter 输出报告的格式 xcode, json, csv, checkstyle, codeclimate, junit, html, emoji, sonarqube, markdown, github-actions-logging
swiftlint lint --path <path> --reporter <reporter>

2. 配置文件 .swiftlint.yml

  • disabled_rules: 关闭某些默认开启的规则。
  • opt_in_rules: 一些规则是可选的。
  • only_rules: 不可以和 disabled_rules 或者 opt_in_rules 并列。类似一个白名单,只有在这个列表中的规则才是开启的。
disabled_rules: # 执行时排除掉的规则
- colon
- comma
- control_statement
opt_in_rules: # 一些规则仅仅是可选的
- empty_count
- missing_docs
# 可以通过执行如下指令来查找所有可用的规则:
# swiftlint rules
included: # 执行 linting 时包含的路径。如果出现这个 `--path` 会被忽略。
- Source
excluded: # 执行 linting 时忽略的路径。 优先级比 `included` 更高。
- Carthage
- Pods
- Source/ExcludedFolder
- Source/ExcludedFile.swift
# 可配置的规则可以通过这个配置文件来自定义
# 二进制规则可以设置他们的严格程度
force_cast: warning # 隐式
force_try:
severity: warning # 显式
# 同时有警告和错误等级的规则,可以只设置它的警告等级
# 隐式
line_length: 110
# 可以通过一个数组同时进行隐式设置
type_body_length:
- 300 # warning
- 400 # error
# 或者也可以同时进行显式设置
file_length:
warning: 500
error: 1200
# 命名规则可以设置最小长度和最大程度的警告/错误
# 此外它们也可以设置排除在外的名字
type_name:
min_length: 4 # 只是警告
max_length: # 警告和错误
warning: 40
error: 50
excluded: iPhone # 排除某个名字
identifier_name:
min_length: # 只有最小长度
error: 4 # 只有错误
excluded: # 排除某些名字
- id
- URL
- GlobalAPIKey
reporter: "xcode" # 报告类型 (xcode, json, csv, checkstyle, codeclimate, junit, html, emoji, sonarqube, markdown, github-actions-logging)

3. 集成方式

截屏2022-01-14 17.16.45.png

3.1 集成至Xcode中

在build phrases中创建 run script中,执行 swiftlint ​
  • 每次编译时执行
  • 直接在代码出显示warning或error
  • 一般开发直接忽略warning !
# Type a script or drag a script file from your workspace to insert its path.
echo "开始检查swiftlint安装"
if ! [ -e `which swiftlint` ]
then
echo "swiftlint未安装,开始安装swiftlint"
brew intall swiftlint
fi
changeFilesArray=(`git diff --name-only head | grep '.swift$'`)
echo "一共修改了${#changeFilesArray[*]}文件"
echo ${changeFilesArray[*]}
swiftlint lint --path ${changeFilesArray[*]}
截屏2022-01-14 16.37.32.png

3.2 githook在pre-commit

4. 参考文档