一種實施快速風格和約定的工具,它基於現在存檔的GitHub Swift樣式指南。 Swiftlint強制執行Swift社區通常接受的樣式指南規則。這些規則在流行風格指南中得到很好的描述,例如Kodeco的Swift Style Guide。
Swiftlint掛鉤進入Clang和SourceKit,以使用源文件的AST表示,以獲得更準確的結果。
Swiftlint可以用作命令插件或構建工具插件。
添加
. package ( url : " https://github.com/SimplyDanny/SwiftLintPlugins " , from : " <version> " )
到您的Package.swift
文件以自動消耗Swiftlint的最新版本,或將依賴項固定到特定版本:
. package ( url : " https://github.com/SimplyDanny/SwiftLintPlugins " , exact : " <version> " )
在其中,將<version>
替換為所需的最小值或精確版本。
筆記
直接從Swiftlint存儲庫中食用插件帶有幾個缺點。為了避免它們並減少施加的開銷,強烈建議使用專用SwiftLintplugins存儲庫中的插件,即使Swiftlint存儲庫中的插件也絕對功能正常。如果首選來自Swiftlint的插件,只需在上面的軟件包聲明中使用url https://github.com/realm/SwiftLint
。
但是,SwiftLintPlugins促進了插件的採用。它列出了驅動插件的一些原因,而Swiftlint本身提供的插件非常麻煩。由於插件代碼和發行版保持同步,因此兩者之間的功能沒有差異,但是使用專用插件存儲庫,您可以花費大量時間和麻煩。
本文檔假設您依靠SwiftlintPlugins。
使用以下鏈接將Swiftlint作為軟件包依賴關係添加到Xcode項目:
https://github.com/SimplyDanny/SwiftLintPlugins
brew install swiftlint
將以下內容添加到您的Podfile
:
pod 'SwiftLint'
這將在Pods/
pod install
執行過程中下載Swiftlint二進製文件和依賴項,並允許您通過腳本構建階段中的${PODS_ROOT}/SwiftLint/swiftlint
調用它。
通過Cocoapods安裝還可以固定到特定版本的Swiftlint,而不僅僅是最新版本(Homebrew是這種情況)。
請注意,這將添加Swiftlint二進製文件,其依賴關係的二進製文件以及Swift二進制庫的分佈到Pods/
Directory,因此請在此目錄中檢查到SCM,例如GIT等SCM。
mint install realm/SwiftLint
將其放在您的MODULE.bazel
中。Bazel:
bazel_dep ( name = "swiftlint" , version = "0.52.4" , repo_name = "SwiftLint" )
或將其放在您的WORKSPACE
中:
load ( "@bazel_tools//tools/build_defs/repo:http.bzl" , "http_archive" )
http_archive (
name = "build_bazel_rules_apple" ,
sha256 = "390841dd5f8a85fc25776684f4793d56e21b098dfd7243cd145b9831e6ef8be6" ,
url = "https://github.com/bazelbuild/rules_apple/releases/download/2.4.1/rules_apple.2.4.1.tar.gz" ,
)
load (
"@build_bazel_rules_apple//apple:repositories.bzl" ,
"apple_rules_dependencies" ,
)
apple_rules_dependencies ()
load (
"@build_bazel_rules_swift//swift:repositories.bzl" ,
"swift_rules_dependencies" ,
)
swift_rules_dependencies ()
load (
"@build_bazel_rules_swift//swift:extras.bzl" ,
"swift_rules_extra_dependencies" ,
)
swift_rules_extra_dependencies ()
http_archive (
name = "SwiftLint" ,
sha256 = "c6ea58b9c72082cdc1ada4a2d48273ecc355896ed72204cedcc586b6ccb8aca6" ,
url = "https://github.com/realm/SwiftLint/releases/download/0.52.4/bazel.tar.gz" ,
)
load ( "@SwiftLint//bazel:repos.bzl" , "swiftlint_repos" )
swiftlint_repos ()
load ( "@SwiftLint//bazel:deps.bzl" , "swiftlint_deps" )
swiftlint_deps ()
然後,您可以使用此命令在當前目錄中運行Swiftlint:
bazel run -c opt @SwiftLint//:swiftlint
從最新的GitHub版本下載SwiftLint.pkg
並運行它。
確保安裝了構建工具Bazel和最近的Swift工具鏈,並且所有工具都可以在您的PATH
中發現。
要構建Swiftlint,請克隆此存儲庫並運行make install
。
重要的
雖然在違反皮棉時,在編譯Swift源文件之前運行Swiftlint似乎很直觀,但重要的是要了解Swiftlint旨在分析可編譯的有效源代碼。非編譯代碼很容易導致意外且令人困惑的結果,尤其是在使用--fix
/ --autocorrect
命令行參數時。
Swiftlint可以用作Swift軟件包項目和Xcode項目的構建工具插件。
構建工具插件通過在軟件包/項目目錄中找到最上方的配置文件來確定Swiftlint工作目錄。如果在其中找不到配置文件,則包裝/項目目錄用作工作目錄。
當插件無法解析SwiftLint工作目錄時,該插件會引發錯誤。例如,這將發生在XCode Projects中,該項目的SWIFT文件不在項目目錄中。
為了最大程度地提高與插件的兼容性,請避免使用--config
選項的項目結構。
筆記
需要通過Swift軟件包管理器安裝。
構建工具插件在構建每個目標時運行。當項目具有多個目標時,必須單獨將插件添加到所需的目標中。
為此,請將插件添加到目標,以伸有如下:
. target (
...
plugins : [ . plugin ( name : " SwiftLintBuildToolPlugin " , package : " SwiftLintPlugins " ) ]
) ,
筆記
需要通過Swift軟件包管理器安裝。
命令插件可以從命令行中運行Swiftlint,如下所示:
swift package plugin swiftlint
筆記
需要通過Xcode軟件包依賴項安裝。
構建工具插件作為每個目標的構建階段運行。當項目具有多個目標時,必須單獨將插件添加到所需的目標中。
為此,請將SwiftLintBuildToolPlugin
添加到Build Phases
的Run Build Tool Plug-ins
階段,以覆蓋目標。
提示
首次使用插件時,請確保在提示時信任和啟用它。如果宏存在警告,請選擇它以信任並啟用宏。
對於無人看管的使用(例如,在CI上),可以使用以下任何一個禁用軟件包插件和宏驗證:
使用xcodebuild
選項:
-skipPackagePluginValidation
-skipMacroValidation
設置XCode默認值:
defaults write com.apple.dt.Xcode IDESkipPackagePluginFingerprintValidatation -bool YES
defaults write com.apple.dt.Xcode IDESkipMacroFingerprintValidation -bool YES
重要的
無人看管的使用選項繞過Xcode的驗證對話框,並隱式信任所有插件和宏,這具有安全性。
Swiftlint的配置文件位於軟件包/項目目錄之外的項目結構未直接由構建工具插件支持。這是因為不可能通過參數來構建工具插件(例如,傳遞配置文件路徑)。
如果您的項目結構與構建工具插件不直接使用,請考慮以下選項之一:
parent_config: path/to/.swiftlint.yml
。筆記
基於所使用的安裝方法,運行腳本構建階段中的shell命令語法可能不同,也可能需要其他配置。有關更多信息,請參閱安裝說明。
如果構建工具插件不適用於您的項目設置,或者需要其他自定義設置時,可以將SwiftLint作為運行腳本構建階段添加。當項目設置依賴--config
swiftlint選項時,這很有用;或以單個swiftlint
調用在一起將所有目標貼在一起。可以在.swiftlint.yml
配置中配置文件包含和排除。
為此,在Compile Sources
階段之後,在主要應用程序目標的Build Phases
的Run Script
階段中添加自定義腳本階段。使用以下腳本實現:
if command -v swiftlint > /dev/null 2>&1
then
swiftlint
else
echo " warning: ` swiftlint ` command not found - See https://github.com/realm/SwiftLint#installation for installation instructions. "
fi
如果您在Swift軟件包中使用SwiftLintplugin,則可以通過以下方式參考swiftlint
可執行文件:
SWIFT_PACKAGE_DIR= " ${BUILD_DIR % Build /* } SourcePackages/artifacts "
SWIFTLINT_CMD= $( ls " $SWIFT_PACKAGE_DIR " /swiftlintplugins/SwiftLintBinary/SwiftLintBinary.artifactbundle/swiftlint- * /bin/swiftlint | head -n 1 )
if test -f " $SWIFTLINT_CMD " 2>&1
then
" $SWIFTLINT_CMD "
else
echo " warning: ` swiftlint ` command not found - See https://github.com/realm/SwiftLint#installation for installation instructions. "
fi
筆記
SWIFTLINT_CMD
路徑使用默認的Xcode配置,並已在Xcode 15/16上進行了測試。如果另一種配置(例如自定義Swift軟件包路徑),請相應地調整值。
提示
Based on dependency analysis
取消選中,以在所有增量構建上運行swiftlint
,從而抑制未指定的輸出警告。
Xcode 15通過設置ENABLE_USER_SCRIPT_SANDBOXING
build設置的默認值從NO
到YES
進行了重大更改。結果,Swiftlint遇到了與缺少文件權限有關的錯誤,該錯誤通常表現為error: Sandbox: swiftlint(19427) deny(1) file-read-data.
為了解決此問題,有必要手動將ENABLE_USER_SCRIPT_SANDBOXING
設置設置為Swiftlint正在配置的特定目標的NO
。
如果您在Apple Silicon上通過Homebrew安裝Swiftlint,則可能會遇到此警告:
warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint
那是因為默認情況下,蘋果矽上的自製二進製文件將二進製文件安裝到/opt/homebrew/bin
文件夾中。要指示Xcode在哪裡找到Swiftlint,您可以在構建階段中添加/opt/homebrew/bin
到PATH
環境變量:
if [[ " $( uname -m ) " == arm64 ]]
then
export PATH= " /opt/homebrew/bin: $PATH "
fi
if command -v swiftlint > /dev/null 2>&1
then
swiftlint
else
echo " warning: ` swiftlint ` command not found - See https://github.com/realm/SwiftLint#installation for installation instructions. "
fi
或者,您可以在/usr/local/bin
中創建一個指向實際二進製文件的符號鏈接:
ln -s /opt/homebrew/bin/swiftlint /usr/local/bin/swiftlint
如果您也想修復違規行為,您的腳本可以運行swiftlint --fix && swiftlint
而不僅僅是swiftlint
。這將意味著所有可更正的違規行為都是固定的,同時確保項目中出現警告,以免違規。
如果您已經通過可可錄安裝了Swiftlint,則腳本應該看起來像這樣:
" ${PODS_ROOT} /SwiftLint/swiftlint "
要將Swiftlint與Visual Studio Code集成,請從市場上安裝vscode-swiftlint
擴展。
您可以使用官方的swiftlint
Fastlane動作來運行Swiftlint,作為您的快速手術過程的一部分。
swiftlint (
mode : :lint , # SwiftLint mode: :lint (default) or :autocorrect
executable : "Pods/SwiftLint/swiftlint" , # The SwiftLint binary path (optional). Important if you've installed it via CocoaPods
path : "/path/to/lint" , # Specify path to lint (optional)
output_file : "swiftlint.result.json" , # The path of the output file (optional)
reporter : "json" , # The custom reporter to use (optional)
config_file : ".swiftlint-ci.yml" , # The path of the configuration file (optional)
files : [ # List of files to process (optional)
"AppDelegate.swift" ,
"path/to/project/Model.swift"
] ,
ignore_exit_status : true , # Allow fastlane to continue even if SwiftLint returns a non-zero exit status (Default: false)
quiet : true , # Don't print status logs like 'Linting ' & 'Done linting' (Default: false)
strict : true # Fail on warnings? (Default: false)
)
Swiftlint也可以使用Ubuntu
作為Docker映像。因此,僅首次需要使用下一個命令來拉碼頭映像:
docker pull ghcr.io/realm/swiftlint:latest
然後,隨後,您只需在Docker內部運行swiftlint
,就可以了:
docker run -it -v ` pwd ` : ` pwd ` -w ` pwd ` ghcr.io/realm/swiftlint:latest
這將在您現在所在的文件夾中執行swiftlint
( pwd
),顯示一個類似的輸出:
$ docker run -it -v ` pwd ` : ` pwd ` -w ` pwd ` ghcr.io/realm/swiftlint:latest
Linting Swift files in current working directory
Linting ' RuleDocumentation.swift ' (1/490)
...
Linting ' YamlSwiftLintTests.swift ' (490/490)
Done linting ! Found 0 violations, 0 serious in 490 files.
在這裡,您有更多有關Docker圖像使用的文檔。
$ swiftlint help
OVERVIEW: A tool to enforce Swift style and conventions.
USAGE: swiftlint <subcommand>
OPTIONS:
--version Show the version.
-h, --help Show help information.
SUBCOMMANDS:
analyze Run analysis rules
docs Open SwiftLint documentation website in the default web browser
generate-docs Generates markdown documentation for selected group of rules
lint (default) Print lint warnings and errors
baseline Operations on existing baselines
reporters Display the list of reporters and their identifiers
rules Display the list of rules and their identifiers
version Display the current version of SwiftLint
See 'swiftlint help <subcommand>' for detailed help.
在包含Swift文件的目錄中運行swiftlint
。目錄將被遞歸搜索。
在使用lint
或analyze
時指定文件列表(例如由XCode修改的文件列表,由ExtraBuildPhase
Xcode插件指定,或基於git ls-files -m
中的工作樹中修改的文件),您可以通過傳遞選項--use-script-input-files
和設置以下實例變量: SCRIPT_INPUT_FILE_COUNT
和SCRIPT_INPUT_FILE_0
, SCRIPT_INPUT_FILE_1
,..., SCRIPT_INPUT_FILE_{SCRIPT_INPUT_FILE_COUNT - 1}
。同樣,可以通過傳遞選項--use-script-input-file-lists
SCRIPT_INPUT_FILE_LIST_{SCRIPT_INPUT_FILE_LIST_COUNT - 1}
設置以下實例變量: SCRIPT_INPUT_FILE_LIST_COUNT
和SCRIPT_INPUT_FILE_LIST_0
, SCRIPT_INPUT_FILE_LIST_1
,...
這些是為輸入文件設置為自定義Xcode腳本階段的相同環境變量。
Swiftlint將鉤子掛入SourceKit,因此即使Swift進化,它仍在繼續工作!
這也可以使Swiftlint精益保持,因為它不需要與完整的Swift編譯器一起運送,它只是與您已經安裝在機器上的官方官方的官方交流。
您應該始終使用與編譯代碼相同的工具鏈運行Swiftlint。
如果您安裝了多個工具鍊或Xcodes,則可能需要覆蓋Swiftlint的默認Swift工具鏈。
這是Swiftlint確定要使用哪種Swift工具鏈的順序:
$XCODE_DEFAULT_TOOLCHAIN_OVERRIDE
$TOOLCHAIN_DIR
或$TOOLCHAINS
xcrun -find swift
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain
/Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain
~/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain
~/Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain
sourcekitd.framework
有望在上述路徑中傳遞的值的usr/lib/
subdirectory中找到。
您還可以將TOOLCHAINS
環境變量設置為標識Swift Toolchain版本的反向DNS符號:
TOOLCHAINS=com.apple.dt.toolchain.Swift_2_3 swiftlint --fix
在Linux上,預計SourceKit將位於/usr/lib/libsourcekitdInProc.so
中或由LINUX_SOURCEKIT_LIB_PATH
環境變量指定。
pre-commit
鉤子Swiftlint可以作為預先承諾的掛鉤運行。安裝後,將其添加到存儲庫的根部中的.pre-commit-config.yaml
:
repos :
- repo : https://github.com/realm/SwiftLint
rev : 0.50.3
hooks :
- id : swiftlint
將rev
調整為您選擇的Swiftlint版本。 pre-commit autoupdate
可用於更新當前版本。
可以使用entry
配置Swiftlint來應用修復程序並在錯誤上失敗:
- repo : https://github.com/realm/SwiftLint
rev : 0.50.3
hooks :
- id : swiftlint
entry : swiftlint --fix --strict
隨著時間的流逝,Swiftlint和Swift社區(就是您!)中包含200多個規則。鼓勵拉動請求。
您可以在此處找到有關規則的更新列表和更多信息。
您還可以檢查源/swiftlintbuiltinrules/規則目錄以查看其實現。
默認情況下, opt_in_rules
將被禁用(即,您必須在配置文件中明確啟用它們)。
關於何時將規則標記為選擇加入的準則:
empty_count
)force_unwrapping
)可以通過以下格式在源文件中使用註釋來禁用規則:
// swiftlint:disable <rule1> [<rule2> <rule3>...]
規則將被禁用到文件末尾或直到Linter看到匹配啟用評論之前:
// swiftlint:enable <rule1> [<rule2> <rule3>...]
例如:
// swiftlint:disable colon
let noWarning : String = " " // No warning about colons immediately after variable names!
// swiftlint:enable colon
let hasWarning : String = " " // Warning generated about colons immediately after variable names
包括all
關鍵字將禁用所有規則,直到Linter看到匹配的啟用評論:
// swiftlint:disable all
// swiftlint:enable all
例如:
// swiftlint:disable all
let noWarning : String = " " // No warning about colons immediately after variable names!
let i = " " // Also no warning about short identifier names
// swiftlint:enable all
let hasWarning : String = " " // Warning generated about colons immediately after variable names
let y = " " // Warning generated about short identifier names
也可以通過附加:previous
:this
或:next
行,也可以通過附加:上一個或:下一行修改disable
或enable
命令。
例如:
// swiftlint:disable:next force_cast
let noWarning = NSNumber ( ) as! Int
let hasWarning = NSNumber ( ) as! Int
let noWarning2 = NSNumber ( ) as! Int // swiftlint:disable:this force_cast
let noWarning3 = NSNumber ( ) as! Int
// swiftlint:disable:previous force_cast
運行swiftlint rules
以打印所有可用規則及其標識符的列表。
通過從您將從SwiftLint運行的目錄中添加.swiftlint.yml
文件來配置Swiftlint。可以配置以下參數:
規則包容:
disabled_rules
:從默認啟用設置中禁用規則。opt_in_rules
:啟用不屬於默認設置的規則。特殊的all
標識符將啟用所有OPT在Linter規則中,除了disabled_rules
中列出的規則。only_rules
:僅啟用此列表中指定的規則。不能與disabled_rules
或opt_in_rules
一起指定。analyzer_rules
:這是僅由analyze
命令運行的規則的完全獨立的列表。所有分析儀規則均可選擇加入,因此這是唯一可配置的規則列表, disabled_rules
和only_rules
沒有等效物。特殊的all
標識符也可以在此處用於啟用所有分析儀規則,除了在disabled_rules
中列出的規則。 # By default, SwiftLint uses a set of sensible default rules you can adjust:
disabled_rules : # rule identifiers turned on by default to exclude from running
- colon
- comma
- control_statement
opt_in_rules : # some rules are turned off by default, so you need to opt-in
- empty_count # find all the available rules by running: `swiftlint rules`
# Alternatively, specify all rules explicitly by uncommenting this option:
# only_rules: # delete `disabled_rules` & `opt_in_rules` if using this
# - empty_parameters
# - vertical_whitespace
analyzer_rules : # rules run by `swiftlint analyze`
- explicit_self
# Case-sensitive paths to include during linting. Directory paths supplied on the
# command line will be ignored.
included :
- Sources
excluded : # case-sensitive paths to ignore during linting. Takes precedence over `included`
- Carthage
- Pods
- Sources/ExcludedFolder
- Sources/ExcludedFile.swift
- Sources/*/ExcludedFile.swift # exclude files with a wildcard
# If true, SwiftLint will not fail if no lintable files are found.
allow_zero_lintable_files : false
# If true, SwiftLint will treat all warnings as errors.
strict : false
# If true, SwiftLint will treat all errors as warnings.
lenient : false
# The path to a baseline file, which will be used to filter out detected violations.
baseline : Baseline.json
# The path to save detected violations to as a new baseline.
write_baseline : Baseline.json
# If true, SwiftLint will check for updates after linting or analyzing.
check_for_updates : true
# configurable rules can be customized from this configuration file
# binary rules can set their severity level
force_cast : warning # implicitly
force_try :
severity : warning # explicitly
# rules that have both warning and error levels, can set just the warning level
# implicitly
line_length : 110
# they can set both implicitly with an array
type_body_length :
- 300 # warning
- 400 # error
# or they can set both explicitly
file_length :
warning : 500
error : 1200
# naming rules can set warnings/errors for min_length and max_length
# additionally they can set excluded names
type_name :
min_length : 4 # only warning
max_length : # warning and error
warning : 40
error : 50
excluded : iPhone # excluded via string
allowed_symbols : ["_"] # these are allowed in type names
identifier_name :
min_length : # only min_length
error : 4 # only error
excluded : # excluded via string array
- id
- URL
- GlobalAPIKey
reporter : " xcode " # reporter type (xcode, json, csv, checkstyle, codeclimate, junit, html, emoji, sonarqube, markdown, github-actions-logging, summary)
您還可以通過在字符串中使用${SOME_VARIABLE}
中的配置文件中的環境變量。
除了主要Swiftlint項目與使用的規則外,Swiftlint還可以運行兩種類型的自定義規則,您可以在自己的項目中定義自己:
這些規則的編寫方式與Swiftlint發貨的基於Swift的規則相同,因此它們快速,準確,可以利用SwiftSnntax,可以進行單位測試,等等。
使用這些需要如本視頻中所述,在github.com/jpsim/swiftlint-bazel-example中使用Bazel構建Swiftlint。
您可以使用以下語法在您的配置文件中定義基於自定義的正則規則:
custom_rules :
pirates_beat_ninjas : # rule identifier
included :
- " .* \ .swift " # regex that defines paths to include during linting. optional.
excluded :
- " .*Test \ .swift " # regex that defines paths to exclude during linting. optional
name : " Pirates Beat Ninjas " # rule name. optional.
regex : " ([nN]inja) " # matching pattern
capture_group : 0 # number of regex capture group to highlight the rule violation at. optional.
match_kinds : # SyntaxKinds to match. optional.
- comment
- identifier
message : " Pirates are better than ninjas. " # violation message. optional.
severity : error # violation severity. optional.
no_hiding_in_strings :
regex : " ([nN]inja) "
match_kinds : string
這就是輸出的樣子:
重要的是要注意,正則表達模式與啟用標誌s
和m
一起使用.
匹配newlines, ^
/ $
分別匹配線路的開始和結尾。如果您不想擁有.
例如,匹配新線,例如(?-s)
可以預先啟動正則。
您可以通過提供一個或多個match_kinds
來過濾匹配項,該匹配項將拒絕包括此列表中不存在的語法類型的匹配項。這是所有可能的語法類型:
argument
attribute.builtin
attribute.id
buildconfig.id
buildconfig.keyword
comment
comment.mark
comment.url
doccomment
doccomment.field
identifier
keyword
number
objectliteral
parameter
placeholder
string
string_interpolation_anchor
typeidentifier
可以提取詢問sourcekitten中摘要中使用的所有語法類型。例如, sourcekitten syntax --text "struct S {}"
提供
source.lang.swift.syntaxtype.keyword
for struct
關鍵字和source.lang.swift.syntaxtype.identifier
的S
在上面列表中與keyword
和identifier
匹配。
如果將自定義規則與only_rules
結合使用,則必須在only_rules
列表中包含字符串custom_rules
:
only_rules :
- custom_rules
custom_rules :
no_hiding_in_strings :
regex : " ([nN]inja) "
match_kinds : string
與Swift自定義規則不同,您可以使用Swiftlint官方構建(例如,來自Homebrew)來運行Regex自定義規則。
Swiftlint可以自動糾正某些違規行為。磁盤上的文件被更正的版本覆蓋。
在運行swiftlint --fix
固定,否則可能會丟失重要數據。
由於在應用更正時修改文件後,糾正措施(或其偏移)的可能性很高,因此在糾正時被禁用。
swiftlint analyze
命令可以使用完整的類型檢查AST來覆蓋Swift文件。包含清潔swiftc
構建命令調用的編譯器日誌路徑(必須失敗)通過--compiler-log-path
標誌進行analyze
。例如--compiler-log-path /path/to/xcodebuild.log
這可以通過
xcodebuild -workspace {WORKSPACE}.xcworkspace -scheme {SCHEME} > xcodebuild.log
swiftlint analyze --compiler-log-path xcodebuild.log
分析儀規則往往比棉絨規則要慢得多。
Swiftlint提供了多種包含多個配置文件的方法。多個配置文件被合併到一個單個配置中,然後將其應用於單個配置文件會被應用。
在很多用例中,使用多個配置文件可能會有所幫助:
例如,人們可以使用團隊範圍的共享Swiftlint配置,同時通過兒童配置文件允許在每個項目中覆蓋。
全隊範圍的配置:
disabled_rules :
- force_cast
特定於項目的配置:
opt_in_rules :
- force_cast
您可以在配置文件中指定child_config
和/或parent_config
引用。這些引用應該是相對於它們指定的配置文件的文件夾的本地路徑。只要沒有循環且沒有歧義,這甚至遞歸起作用。
兒童配置被視為改進,因此具有較高的優先級,而父母配置在發生衝突的情況下被認為是優先級較低的基礎。
以下是一個示例,假設您有以下文件結構:
ProjectRoot
|_ .swiftlint.yml
|_ .swiftlint_refinement.yml
|_ Base
|_ .swiftlint_base.yml
要同時包括細化和基本文件,您的.swiftlint.yml
應該看起來像:
child_config : .swiftlint_refinement.yml
parent_config : Base/.swiftlint_base.yml
合併父型和子配置時,請仔細included
和excluded
配置,以說明包含配置文件的目錄位置的差異。
就像您可以提供本地child_config
/ parent_config
參考,而不是引用本地路徑一樣,您只能將導致配置文件的URL放置。為了使Swiftlint檢測這些遠程引用,它們必須從http://
或https://
開始。
引用的遠程配置文件甚至可以遞歸地引用其他遠程配置文件,但不允許包括本地參考。
使用遠程引用,您的.swiftlint.yml
看起來像這樣:
parent_config : https://myteamserver.com/our-base-swiftlint-config.yml
每次運行Swiftlint並具有Internet連接時,Swiftlint都會嘗試獲取每個引用的每個遠程配置的新版本。如果此請求耗盡,則使用緩存版本(如果有)。如果沒有可用的緩存版本,Swiftlint會失敗 - 但不用擔心,一旦Swiftlint至少成功運行一次,則應該在那裡進行緩存的版本。
如果需要,可以使用remote_timeout
/ remote_timeout_if_cached
specifiers手動指定遠程配置獲取的超時。這些值默認為2秒或1秒。
您還可以通過命令行運行Swiftlint時僅提供一個配置文件,而是可以通過層次結構,在該層次結構中,第一個配置被視為父,而最後一個配置被視為最高優先級的孩子。
一個簡單的示例,包括兩個配置文件,如下所示:
swiftlint --config .swiftlint.yml --config .swiftlint_child.yml
除了主要配置(根文件夾中的.swiftlint.yml
文件)外,您還可以將其他配置文件命名為.swiftlint.yml
放入目錄結構中,然後將其合併為兒童配置,但僅對這些效果產生效果與配置或沒有其他配置文件的更深目錄在同一目錄內的文件。換句話說:嵌套配置無法遞歸工作 - 除了主要配置外,每個文件中最多可以使用一個嵌套配置。
.swiftlint.yml
文件僅被視為嵌套配置,如果它們尚未用於構建主配置(例如,通過child_config: Folder/.swiftlint.yml
引用的內容)。另外,嵌套配置的parent_config
/ child_config
規格也被忽略了,因為對此沒有意義。
如果通過--config
參數明確指定一個(或更多)Swiftlint文件,則該配置將被視為覆蓋,無論是否存在其他.swiftlint.yml
文件,目錄中的某個地方都存在。因此,如果要使用嵌套配置,則不能使用--config
參數。
麻省理工學院許可。
Swiftlint由Realm Inc.維護和資助。領域的名稱和徽標是Realm Inc.的商標。
我們❤️開源軟件!請參閱我們的其他開源項目,閱讀我們的博客,或在Twitter(@RealM)上打個電話。
我們感謝MacStadium提供了Mac Mini來進行我們的性能測試。