1. Project Overview & Quickstart (realm/SwiftLint)
File: README.md
SwiftLint
A tool to enforce Swift style and conventions, loosely based on the now
archived GitHub Swift Style Guide.
SwiftLint enforces the style guide rules that are generally accepted by the
Swift community. These rules are well described in popular style guides like
Kodeco's Swift Style Guide.
SwiftLint rules are predominantly based on SwiftSyntax.
Some rules still hook into Clang and
SourceKit to access type information.
This project adheres to the
Contributor Covenant Code of Conduct.
By participating, you are expected to uphold this code.
Video Introduction
To get a high-level overview of SwiftLint, we encourage you to watch this
presentation recorded January 9th, 2017 by JP Simard (transcript provided):
Installation
[Swift Package Manager](https://github.com/apple/swift-package-manager)
SwiftLint can be used as a command plugin
or a build tool plugin.
Add
.package(url: "https://github.com/SimplyDanny/SwiftLintPlugins", from: "<version>")to your Package.swift file to consume the latest release of SwiftLint
automatically or pin the dependency to a specific version:
.package(url: "https://github.com/SimplyDanny/SwiftLintPlugins", exact: "<version>")Therein, replace <version> with the desired minimum or exact version.
[!NOTE]
Consuming the plugins directly from the SwiftLint repository comes
with several drawbacks. To avoid them and reduce the overhead imposed, it's
highly recommended to consume the plugins from the dedicated
SwiftLintPlugins repository,
even though plugins from the SwiftLint repository are also absolutely
functional. If the plugins from SwiftLint are preferred, just use the URLhttps://github.com/realm/SwiftLintin the package declarations above.However, SwiftLintPlugins
facilitates plugin adoption massively. It lists some of the reasons that
drive the plugins as provided by SwiftLint itself very troublesome. Since
the plugin code and the releases are kept in sync, there is no difference
in functionality between the two, but you spare yourself a lot of time and
trouble using the dedicated plugins repository.This document assumes you're relying on SwiftLintPlugins.
[Xcode Package Dependency](https://developer.apple.com/documentation/xcode/adding-package-dependencies-to-your-app)
Use the following link to add SwiftLint as a Package Dependency to an Xcode
project:
https://github.com/SimplyDanny/SwiftLintPlugins[Homebrew](http://brew.sh)
brew install swiftlint[CocoaPods](https://cocoapods.org)
Add the following to your Podfile:
pod 'SwiftLint'This will download the SwiftLint binaries and dependencies in Pods/ during
your next pod install execution and will allow you to invoke it via${PODS_ROOT}/SwiftLint/swiftlint in your Script Build Phases.
Installing via Cocoapods also enables pinning to a specific version of
SwiftLint rather than simply the latest (which is the case with
Homebrew).
Note that this will add the SwiftLint binaries, its dependencies' binaries, and
the Swift binary library distribution to the Pods/ directory, so checking in
this directory to SCM such as Git is discouraged.
[Mint](https://github.com/yonaskolb/mint)
mint install realm/SwiftLint[Bazel](https://bazel.build)
Put this in your MODULE.bazel:
bazel_dep(name = "swiftlint", version = "0.52.4", repo_name = "SwiftLint")Or put this in your WORKSPACE:
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()Then you can run SwiftLint in the current directory with this command:
bazel run -c opt @SwiftLint//:swiftlintPre-Built Package
Download SwiftLint.pkg from the
latest GitHub release and
run it.
From Source
Make sure the build tool Bazel and a
recent Swift toolchain are
installed and all tools are discoverable in your PATH.
To build SwiftLint, clone this repository and run make install.
Setup
[!IMPORTANT]
While it may seem intuitive to run SwiftLint before compiling Swift source
files to exit a build early when there are lint violations, it is important
to understand that SwiftLint is designed to analyze valid source code that
is compilable. Non-compiling code can very easily lead to unexpected and
confusing results, especially when executing with--fix/--autocorrect
command line arguments.
Build Tool Plugins
SwiftLint can be used as a build tool plugin for both
Swift Package projects
and Xcode projects.
The build tool plugin determines the SwiftLint working directory by locating
the topmost config file within the package/project directory. If a config file
is not found therein, the package/project directory is used as the working
directory.
The plugin throws an error when it is unable to resolve the SwiftLint working
directory. For example, this will occur in Xcode projects where the target's
Swift files are not located within the project directory.
To maximize compatibility with the plugin, avoid project structures that require
the use of the --config option.
Swift Package Projects
[!NOTE]
Requires installing via Swift Package Manager.
Build tool plugins run when building each target. When a project has multiple
targets, the plugin must be added to the desired targets individually.
To do this, add the plugin to the target(s) to be linted as follows:
.target(
...
plugins: [.plugin(name: "SwiftLintBuildToolPlugin", package: "SwiftLintPlugins")]
),Swift Package Command Plugin
[!NOTE]
Requires installing via Swift Package Manager.
The command plugin enables running SwiftLint from the command line as follows:
swift package plugin swiftlintXcode Projects
[!NOTE]
Requires installing via Xcode Package Dependency.
Build tool plugins run as a build phase of each target. When a project has
multiple targets, the plugin must be added to the desired targets individually.
To do this, add the SwiftLintBuildToolPlugin to the Run Build Tool Plug-ins
phase of the Build Phases for the target(s) to be linted.
[!TIP]
When using the plugin for the first time, be sure to trust and enable
it when prompted. If a macros build warning exists, select it to trust
and enable the macros as well.
For unattended use (e.g. on CI), package plugin and macro
validations can be disabled with either of the following:
Using
xcodebuildoptions:bash-skipPackagePluginValidation -skipMacroValidationSetting Xcode defaults:
bashdefaults write com.apple.dt.Xcode IDESkipPackagePluginFingerprintValidatation -bool YES defaults write com.apple.dt.Xcode IDESkipMacroFingerprintValidation -bool YES
[!IMPORTANT]
The unattended use options bypass Xcode's validation dialogs
and implicitly trust all plugins and macros, which has security implications.
Unexpected Xcode Project Structures
Project structures where SwiftLint's configuration file is located
outside of the package/project directory are not directly supported
by the build tool plugin. This is because it isn't possible to pass
arguments to build tool plugins (e.g., passing the config file path).
If your project structure doesn't work directly with the build tool
plugin, please consider one of the following options:
- To use a config file located outside the package/project directory, a config
file may be added to that directory specifying a parent config path to the
other config file, e.g.,parent_config: path/to/.swiftlint.yml. - You can also consider the use of a
Run Script Build Phase in place of the build
tool plugin.
Xcode Run Script Build Phase
[!NOTE]
Based upon the installation method used, the shell command syntax in the
Run Script Build Phase may be different or additional configuration could
be required. Refer to the installation instructions for
more information.
If the build tool plugin does not work for your project setup or when
additional custom setup is required, SwiftLint can be added as a Run Script
Build Phase. This is useful when a project setup relies on the --config
SwiftLint option; or to lint all targets together in a single swiftlint
invocation. File inclusions and exclusions can be configured in the.swiftlint.yml configuration.
To do this, add a custom script to a Run Script phase of the Build Phases
of the primary app target, after the Compile Sources phase. Use the
following script implementation:
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."
fiIf you're using the SwiftLintPlugin in a Swift package,
you may refer to the swiftlint executable in the
following way:
SWIFT_PACKAGE_DIR="${SWIFT_PACKAGE_DIR:-${BUILD_DIR%Build/*}SourcePackages}"
SWIFTLINT_CMD="$SWIFT_PACKAGE_DIR/artifacts/swiftlintplugins/SwiftLintBinary/SwiftLintBinary.artifactbundle/macos/swiftlint"
if test -f "$SWIFTLINT_CMD" 2>&1
then
"$SWIFTLINT_CMD"
else
echo "warning: `swiftlint` command not found - See https://github.com/realm/SwiftLint#xcode-run-script-build-phase for installation instructions."
fi[!NOTE]
TheSWIFTLINT_CMDpath uses the default Xcode configuration and has been
tested on Xcode 15/16. In case of another configuration (e.g. a custom
Swift package path), please adapt the values accordingly.
If you runxcodebuildwith-clonedSourcePackagesDirPath, setSWIFT_PACKAGE_DIRto `` before running the script.
[!TIP]
UncheckBased on dependency analysisto runswiftlinton all incremental
builds, suppressing the unspecified outputs warning.
Consideration for Xcode 15.0
Xcode 15 made a significant change by setting the default value of theENABLE_USER_SCRIPT_SANDBOXING build setting from NO to YES.
As a result, SwiftLint encounters an error related to missing file permissions,
which typically manifests aserror: Sandbox: swiftlint(19427) deny(1) file-read-data.
To resolve this issue, it is necessary to manually set theENABLE_USER_SCRIPT_SANDBOXING setting to NO for the specific target that
SwiftLint is being configured for.
Consideration for Apple Silicon
If you installed SwiftLint via Homebrew on Apple Silicon, you might experience
this warning:
warning: SwiftLint not installed, download from https://github.com/realm/SwiftLintThat is because Homebrew on Apple Silicon installs the binaries into the/opt/homebrew/bin folder by default. To instruct Xcode where to find
SwiftLint, you can either add /opt/homebrew/bin to the PATH environment
variable in your build phase:
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."
fior you can create a symbolic link in /usr/local/bin pointing to the actual
binary:
ln -s /opt/homebrew/bin/swiftlint /usr/local/bin/swiftlintAdditional Considerations
If you wish to fix violations as well, your script could runswiftlint --fix && swiftlint instead of just swiftlint. This will mean
that all correctable violations are fixed while ensuring warnings show up in
your project for remaining violations.
If you've installed SwiftLint via CocoaPods the script should look like this:
"${PODS_ROOT}/SwiftLint/swiftlint"Visual Studio Code
To integrate SwiftLint with Visual Studio Code, install thevscode-swiftlint
extension from the marketplace.
Fastlane
You can use the officialswiftlint fastlane action
to run SwiftLint as part of your fastlane process.
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)
)Docker
SwiftLint is also available as a Docker image usingUbuntu. So just the first time you need to pull the docker image using the
next command:
docker pull ghcr.io/realm/swiftlint:latestThen following times, you just run swiftlint inside of the docker like:
docker run -it -v `pwd`:`pwd` -w `pwd` ghcr.io/realm/swiftlint:latestThis will execute swiftlint in the folder where you are right now (pwd),
showing an output like:
$ 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.Here you have more documentation about the usage of
Docker Images.
MegaLinter
SwiftLint is also embedded in MegaLinter, an
open-source aggregator of linters for CI. See its
SwiftLint documentation
for setup instructions.
Command Line Usage
$ 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.Run swiftlint in the directory containing the Swift files to lint. Directories
will be searched recursively.
To specify a list of files when using lint or analyze
(like the list of files modified by Xcode specified by theExtraBuildPhase Xcode
plugin, or modified files in the working tree based on git ls-files -m), you
can do so by passing the option --use-script-input-files and setting the
following instance variables: SCRIPT_INPUT_FILE_COUNT
and SCRIPT_INPUT_FILE_0, SCRIPT_INPUT_FILE_1, ...,SCRIPT_INPUT_FILE_{SCRIPT_INPUT_FILE_COUNT - 1}.
Similarly, files can be read from file lists by passing
the option --use-script-input-file-lists and setting the
following instance variables: SCRIPT_INPUT_FILE_LIST_COUNT
and SCRIPT_INPUT_FILE_LIST_0, SCRIPT_INPUT_FILE_LIST_1, ...,SCRIPT_INPUT_FILE_LIST_{SCRIPT_INPUT_FILE_LIST_COUNT - 1}.
These are same environment variables set for input files to
custom Xcode script phases.
Working With Multiple Swift Versions
SwiftLint hooks into SourceKit so it continues working even as Swift evolves!
This also keeps SwiftLint lean, as it doesn't need to ship with a full Swift
compiler, it just communicates with the official one you already have installed
on your machine.
You should always run SwiftLint with the same toolchain you use to compile your
code.
You may want to override SwiftLint's default Swift toolchain if you have
multiple toolchains or Xcodes installed.
Here's the order in which SwiftLint determines which Swift toolchain to use:
$XCODE_DEFAULT_TOOLCHAIN_OVERRIDE$TOOLCHAIN_DIRor$TOOLCHAINSxcrun -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 is expected to be found in the usr/lib/ subdirectory of
the value passed in the paths above.
You may also set the TOOLCHAINS environment variable to the reverse-DNS
notation that identifies a Swift toolchain version:
TOOLCHAINS=com.apple.dt.toolchain.Swift_2_3 swiftlint --fixOn Linux, SourceKit is expected to be located in/usr/lib/libsourcekitdInProc.so or specified by the LINUX_SOURCEKIT_LIB_PATH
environment variable.
Git `pre-commit` Hook
SwiftLint can be run as a pre-commit hook.
Once installed, add this to the.pre-commit-config.yaml in the root of your repository:
repos:
- repo: https://github.com/realm/SwiftLint
rev: 0.57.1
hooks:
- id: swiftlintAdjust rev to the SwiftLint version of your choice. pre-commit autoupdate
can be used to update to the current version.
SwiftLint can be configured using entry to apply fixes and fail on errors:
- repo: https://github.com/realm/SwiftLint
rev: 0.57.1
hooks:
- id: swiftlint
entry: swiftlint --fix --strictRules
Over 200 rules are included in SwiftLint and the Swift community (that's you!)
continues to contribute more over time.
Pull requests
are encouraged.
You can find an updated list of rules and more information about them in the
Rule Directory.
You can also check the
Source/SwiftLintBuiltInRules/Rules
directory to see their implementation.
Opt-In Rules
opt_in_rules are disabled by default (i.e., you have to explicitly enable them
in your configuration file).
Guidelines on when to mark a rule as opt-in:
- A rule that can have many false positives (e.g.
empty_count) - A rule that is too slow
- A rule that is not general consensus or is only useful in some cases
(e.g.force_unwrapping)
Disable rules in code
Rules can be disabled with a comment inside a source file with the following
format:
// swiftlint:disable <rule1> [<rule2> <rule3>...]
The rules will be disabled until the end of the file or until the linter sees a
matching enable comment:
// swiftlint:enable <rule1> [<rule2> <rule3>...]
For example:
// 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.Including the all keyword will disable all rules until the linter sees a
matching enable comment:
// swiftlint:disable all// swiftlint:enable all
For example:
// 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.It's also possible to modify a disable or enable command by appending:previous, :this or :next for only applying the command to the previous,
this (current) or next line respectively.
For example:
// 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_castRun swiftlint rules to print a list of all available rules and their
identifiers.
Configuration
Configure SwiftLint by adding a .swiftlint.yml file from the directory you'll
run SwiftLint from. The following parameters can be configured:
Rule inclusion:
disabled_rules: Disable rules from the default enabled set.opt_in_rules: Enable rules that are not part of the default set. The
specialallidentifier will enable all opt in linter rules, except the ones
listed indisabled_rules.only_rules: Only the rules specified in this list will be enabled.
Cannot be specified alongsidedisabled_rulesoropt_in_rules.analyzer_rules: This is an entirely separate list of rules that are only
run by theanalyzecommand. All analyzer rules are opt-in, so this is the
only configurable rule list, there are no equivalents fordisabled_rules
andonly_rules. The specialallidentifier can also be used here to enable
all analyzer rules, except the ones listed indisabled_rules.
/* Detailed source-code truncated for AI context efficiency. */You can also use environment variables in your configuration file,
by using ${SOME_VARIABLE} in a string.
Defining Custom Rules
In addition to the rules that the main SwiftLint project ships with, SwiftLint
can also run two types of custom rules that you can define yourself in your own
projects:
1. Swift Custom Rules
These rules are written the same way as the Swift-based rules that ship with
SwiftLint so they're fast, accurate, can leverage SwiftSyntax, can be unit
tested, and more.
Using these requires building SwiftLint with Bazel as described in
this video or its associated code in
github.com/jpsim/swiftlint-bazel-example.
2. Regex Custom Rules
You can define custom regex-based rules in your configuration file using the
following syntax:
custom_rules:
# Rule identifier.
pirates_beat_ninjas:
# Optional regex that defines paths to include during linting.
included:
- ".*\\.swift"
# Optional regex that defines paths to exclude during linting.
excluded:
- ".*Test\\.swift"
# Optional rule name.
name: "Pirates Beat Ninjas"
# Matching pattern.
regex: "([nN]inja)"
# Number of regex capture group to highlight the rule violation at. Optional, defaults to 0 (the whole match).
capture_group: 0
# SyntaxKinds to match. optional.
match_kinds:
- comment
- identifier
# Optional violation message.
message: "Pirates are better than ninjas."
# Optional violation severity.
severity: error
no_hiding_in_strings:
regex: "([nN]inja)"
# Syntax kinds to match. optional.
match_kinds: stringThis is what the output would look like:
It is important to note that the regular expression pattern is used with the
flags s and m enabled, that is .
matches newlines
and ^/$
match the start and end of lines,
respectively. If you do not want to have . match newlines, for example, the
regex can be prepended by (?-s).
You can filter the matches by providing one or more match_kinds, which will
reject matches that include syntax kinds that are not present in this list. Here
are all the possible syntax kinds:
argumentattribute.builtinattribute.idbuildconfig.idbuildconfig.keywordcommentcomment.markcomment.urldoccommentdoccomment.fieldidentifierkeywordnumberobjectliteralparameterplaceholderstringstring_interpolation_anchortypeidentifier
All syntax kinds used in a snippet of Swift code can be extracted asking
SourceKitten. For example,sourcekitten syntax --text "struct S {}" delivers
source.lang.swift.syntaxtype.keywordfor thestructkeyword andsource.lang.swift.syntaxtype.identifierfor its nameS
which match to keyword and identifier in the above list.
If using custom rules in combination with only_rules, you must include the
literal string custom_rules in the only_rules list:
only_rules:
- custom_rules
custom_rules:
no_hiding_in_strings:
regex: "([nN]inja)"
match_kinds: stringUnlike Swift custom rules, you can use official SwiftLint builds
(e.g. from Homebrew) to run regex custom rules.
Auto-correct
SwiftLint can automatically correct certain violations. Files on disk are
overwritten with a corrected version.
Please make sure to have backups of these files before runningswiftlint --fix, otherwise important data may be lost.
Standard linting is disabled while correcting because of the high likelihood of
violations (or their offsets) being incorrect after modifying a file while
applying corrections.
Analyze
The swiftlint analyze command can lint Swift files using the
full type-checked AST. The compiler log path containing the clean swiftc build
command invocation (incremental builds will fail) must be passed to analyze
via the --compiler-log-path flag.
e.g. --compiler-log-path /path/to/xcodebuild.log
This can be obtained by
- Cleaning DerivedData (incremental builds won't work with analyze)
- Running
xcodebuild -workspace {WORKSPACE}.xcworkspace -scheme {SCHEME} > xcodebuild.log - Running
swiftlint analyze --compiler-log-path xcodebuild.log
Analyzer rules tend to be considerably slower than lint rules.
Using Multiple Configuration Files
SwiftLint offers a variety of ways to include multiple configuration files.
Multiple configuration files get merged into one single configuration that is
then applied just as a single configuration file would get applied.
There are quite a lot of use cases where using multiple configuration files
could be helpful:
For instance, one could use a team-wide shared SwiftLint configuration while
allowing overrides in each project via a child configuration file.
Team-Wide Configuration:
disabled_rules:
- force_castProject-Specific Configuration:
opt_in_rules:
- force_castChild/Parent Configs (Locally)
You can specify a child_config and/or a parent_config reference within a
configuration file. These references should be local paths relative to the
folder of the configuration file they are specified in. This even works
recursively, as long as there are no cycles and no ambiguities.
A child config is treated as a refinement and thus has a higher priority,
while a parent config is considered a base with lower priority in case of
conflicts.
Here's an example, assuming you have the following file structure:
ProjectRoot
|_ .swiftlint.yml
|_ .swiftlint_refinement.yml
|_ Base
|_ .swiftlint_base.ymlTo include both the refinement and the base file, your .swiftlint.yml should
look like this:
child_config: .swiftlint_refinement.yml
parent_config: Base/.swiftlint_base.ymlWhen merging parent and child configs, included and excluded configurations
are processed carefully to account for differences in the directory location
of the containing configuration files.
Path merging follows these rules:
included/excludedentries from each config are resolved relative to that
config file's directory.- Child entries override conflicting parent entries.
- The merged path lists are computed as:
merged.included = (parent.included - child.excluded) + child.included
merged.excluded = (parent.excluded - child.included) + child.excludedThis means a child config can re-include a path excluded by its parent and can
exclude a path included by its parent.
Child/Parent Configs (Remote)
Just as you can provide local child_config/parent_config references,
instead of referencing local paths, you can just put urls that lead to
configuration files. In order for SwiftLint to detect these remote references,
they must start with http:// or https://.
The referenced remote configuration files may even recursively reference other
remote configuration files, but aren't allowed to include local references.
Using a remote reference, your .swiftlint.yml could look like this:
parent_config: https://myteamserver.com/our-base-swiftlint-config.ymlEvery time you run SwiftLint and have an Internet connection, SwiftLint tries
to get a new version of every remote configuration that is referenced. If this
request times out, a cached version is used if available. If there is no cached
version available, SwiftLint fails – but no worries, a cached version should be
there once SwiftLint has run successfully at least once.
If needed, the timeouts for the remote configuration fetching can be specified
manually via the configuration file(s) using theremote_timeout/remote_timeout_if_cached specifiers. These values default
to 2 seconds or 1 second, respectively.
Command Line
Instead of just providing one configuration file when running SwiftLint via the
command line, you can also pass a hierarchy, where the first configuration is
treated as a parent, while the last one is treated as the highest-priority
child.
A simple example including just two configuration files looks like this:
swiftlint --config .swiftlint.yml --config .swiftlint_child.yml
Nested Configurations
In addition to a main configuration (the .swiftlint.yml file in the root
folder), you can put other configuration files named .swiftlint.yml into the
directory structure. For a given file, SwiftLint walks up from that file's
directory towards the root configuration and uses the first nested.swiftlint.yml it finds as a child config.
That nested config applies only to files in its directory subtree. Files in
other subtrees continue using the main config (or their own nearest nested
config).
Because SwiftLint stops at the first match while walking up the directory tree,
at most one nested configuration is merged per file (in addition to the
main configuration).
.swiftlint.yml files are only considered as a nested configuration if they
have not been used to build the main configuration already (e. g. by having
been referenced via something like child_config: Folder/.swiftlint.yml).
Also, parent_config/child_config specifications of nested configurations
are getting ignored because there's no sense to that.
If one (or more) SwiftLint file(s) are explicitly specified via the --config
parameter, that configuration will be treated as an override, no matter whether
there exist other .swiftlint.yml files somewhere within the directory.
So if you want to use nested configurations, you can't use the --config
parameter.
License
About
SwiftLint is utterly maintained by volunteers contributing to its success
entirely in their free time. As such, SwiftLint isn't a commercial product
in any way.
Be kind to the people maintaining SwiftLint as a hobby and accept that their
time is limited. Support them by contributing to the project, reporting issues,
and helping others in the community.
Special thanks go to MacStadium for providing
physical Mac mini machines to run our performance tests.
We also thank Realm (now MongoDB) for their initial contributions and setup of
the project.
File: README_CN.md
SwiftLint
SwiftLint 是一个用于强制检查 Swift 代码风格和规定的一个工具,基本上以 Kodeco's Swift 代码风格指南为基础。
SwiftLint Hook 了 Clang 和 SourceKit 从而能够使用 AST 来表示源代码文件的更多精确结果。
该项目遵守 贡献者契约行为守则。一旦参与,你将被视为支持这一守则。请将
不可接受的行为报告给 [email protected]。
安装
使用[Swift Package Manager](https://github.com/apple/swift-package-manager)
添加
.package(url: "https://github.com/SimplyDanny/SwiftLintPlugins", from: "<version>")到你的 Package.swift 文件中,以自动获取 SwiftLint 的最新版本,或者将依赖项固定到特定版本:
.package(url: "https://github.com/SimplyDanny/SwiftLintPlugins", exact: "<version>")其中,用所需的最低版本或精确版本替换 <version>。
[Xcode Package Dependency](https://developer.apple.com/documentation/xcode/adding-package-dependencies-to-your-app)
使用以下链接将 SwiftLint 作为包依赖添加到 Xcode 项目中:
https://github.com/SimplyDanny/SwiftLintPlugins使用 [Homebrew](http://brew.sh/)
brew install swiftlint使用 [CocoaPods](https://cocoapods.org)
将如下代码添加到你的 Podfile 即可:
pod 'SwiftLint'在下一次执行 pod install 时将会把 SwiftLint 的二进制文件和依赖下载到 Pods/ 目录下并且将允许你通过 ${PODS_ROOT}/SwiftLint/swiftlint 在 Script Build Phases 中调用 SwiftLint。
自从 SwiftLint 支持安装某个特定版本后,安装一个指定版本的 SwiftLint 是目前推荐的做法相比较于简单地选择最新版本安装的话(比如通过 Homebrew 安装的话)。
请注意这会将 SwiftLint 二进制文件、所依赖的二进制文件和 Swift 二进制库安装到 Pods/ 目录下,所以不推荐将此目录添加到版本控制系统(如 git)中进行跟踪。
使用 [Mint](https://github.com/yonaskolb/mint)
mint install realm/SwiftLint使用安装包
你也可以通过从最新的 GitHub 发布地址下载 SwiftLint.pkg 然后执行的方式安装 SwiftLint。
编译源代码
你也可以通过 clone SwiftLint 的 Git 仓库到本地然后执行make install (Xcode 15.0+) 以从源代码构建及安装。
使用 Bazel
把这个放到你的 MODULE.bazel:
bazel_dep(name = "swiftlint", version = "0.50.4", repo_name = "SwiftLint")或把它放到你的 WORKSPACE:
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用法
报告
我们鼓励你观看本次报告,来获得将 SwiftLint 整合到你的项目中的推荐方式的一个高层次概括:
Xcode
整合 SwiftLint 到 Xcode 体系中去从而可以使警告和错误显示到 IDE 上,只需要在 Xcode 中添加一个新的“Run Script Phase”并且包含如下代码即可:
Xcode 15 对 Build Settings 进行了重大更改,它将 ENABLE_USER_SCRIPT_SANDBOXING 的默认值从 NO 更改为 YES。
因此,SwiftLint 会遇到与缺少文件权限相关的错误,通常报错信息为:error: Sandbox: swiftlint(19427) deny(1) file-read-data.
要解决此问题,需要手动将 ENABLE_USER_SCRIPT_SANDBOXING 设置为 NO,以针对 SwiftLint 配置的特定目标。
如果你是在搭载 Apple 芯片的 Mac 上通过 Homebrew 安装的 SwiftLint,你可能会遇到这个警告:
warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint
这是因为 Homebrew 在搭载 Apple 芯片的 Mac 上将二进制文件默认安装到了 /opt/homebrew/bin
下。如果要让 Xcode 知道 SwiftLint 在哪,你可以在 Build Phase 中将/opt/homebrew/bin 路径添加到 PATH 环境变量
if [[ "$(uname -m)" == arm64 ]]; then
export PATH="/opt/homebrew/bin:$PATH"
fi
if which swiftlint > /dev/null; then
swiftlint
else
echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"
fi或者,你可以创建一个指向在 /usr/local/bin 中实际二进制文件的符号链接:
ln -s /opt/homebrew/bin/swiftlint /usr/local/bin/swiftlint你可能希望将SwiftLint阶段直接移到'Compile Sources'
步骤之前,以便在编译之前快速检测错误。但是,SwiftLint 被设计
为在有效的 Swift 代码上运行,这些代码干净利落地完成了编译器的解析阶段。
因此,在'Compile Sources'之前运行 SwiftLint 可能会产生一些不正确的结果。
如果你也希望修正违规行为,你的脚本可以运行swiftlint --fix && swiftlint 而不是 swiftlint。 这将意味着
修复所有可纠正的违规行为,同时确保在你的项目中对剩余的违规行为显示警告。
如果你已经通过 CocoaPods 安装了 SwiftLint,脚本看起来应该像这样:
"${PODS_ROOT}/SwiftLint/swiftlint"插件支持
SwiftLint 既可以作为 Xcode 项目构建工具,也可以作为 Swift package。
由于 Swift Package Manager 插件的限制,仅推荐
在其根目录中有 SwiftLint 配置的项目使用,因为
目前没有办法将任何附加选项传递给 SwiftLint 可执行文件。
Xcode
如果你正在使用 Xcode 中的项目,你可以将 SwiftLint 集成为
Xcode 构建工具插件。
将 SwiftLint 作为依赖包添加到你的项目中,无需链接任何其他服务。
选择要添加修正的目标,打开 Build Phases 检查器。
打开 Run Build Tool Plug-ins 并选择 + 按钮。
从列表中选择 SwiftLintBuildToolPlugin 并将其添加到项目中。
对于无人值守的使用场景(例如在 CI 上),可以通过以下方式禁用软件包和宏的验证对话框
- 单独将
-skipPackagePluginValidation和-skipMacroValidation传递到xcodebuild或者 - 为那个用户使用
defaults write com.apple.dt.Xcode IDESkipPackagePluginFingerprintValidatation -bool YES进行全局设置,然后写入defaults write com.apple.dt.Xcode IDESkipMacroFingerprintValidation -bool YES
注意:这将隐含地信任所有的Xcode软件包插件,并绕过Xcode的软件包验证对话框。
这对安全有影响。
Swift Package
你可以将 SwiftLint 集成为 Swift Package Manager 插件,如果你正在使用
具有 Package.swift 清单的 Swift 包。
将 SwiftLint 作为包依赖添加到你的 Package.swift 文件中。
使用plugins参数将SwiftLint添加到目标。
.target(
...
plugins: [.plugin(name: "SwiftLintPlugin", package: "SwiftLint")]
),Visual Studio Code
如果要在vscode上使用 SwiftLint,在应用市场上安装vscode-swiftlint扩展。
fastlane
你可以用fastlane官方的SwiftLint功能来运行 SwiftLint 作为你的 Fastlane 程序的一部分。
swiftlint(
mode: :lint, # SwiftLint模式: :lint (默认) 或者 :autocorrect
executable: "Pods/SwiftLint/swiftlint", # SwiftLint的程序路径 (可选的). 对于用CocoaPods集成SwiftLint时很重要
path: "/path/to/lint", # 特殊的检查路径 (可选的)
output_file: "swiftlint.result.json", # 检查结果输出路径 (可选的)
reporter: "json", # 输出格式 (可选的)
config_file: ".swiftlint-ci.yml", # 配置文件的路径 (可选的)
files: [ # 指定检查文件列表 (可选的)
"AppDelegate.swift",
"path/to/project/Model.swift"
],
ignore_exit_status: true, # 允许fastlane可以继续执行甚至是Swiftlint返回一个非0的退出状态(默认值: false)
quiet: true, # 不输出像‘Linting’和‘Done Linting’的状态日志 (默认值: false)
strict: true # 发现警告时报错? (默认值: false)
)Docker
swiftlint 也可以在 Docker 上使用 Ubuntu 作为一个镜像使用。
因此,第一次你需要使用下面的命令调用 docker 镜像:
docker pull ghcr.io/realm/swiftlint:latest接下来,你只需在 docker 中运行swiftlint:
docker run -it -v `pwd`:`pwd` -w `pwd` ghcr.io/realm/swiftlint:latest这将在你现在所在的文件夹(pwd)中执行swiftlint,显示类似的输出:
$ 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
Available commands:
autocorrect Automatically correct warnings and errors
help Display general or command-specific help
lint Print lint warnings and errors for the Swift files in the current directory (default command)
rules Display the list of rules and their identifiers
version Display the current version of SwiftLint在包含有需要执行代码分析的 Swift 源码文件的目录下执行 swiftlint 命令,会对目录进行递归查找。
当使用 lint 或者 autocorrect 命令时,你可以通过添加 --use-script-input-files 选项并且设置以下实例变量:SCRIPT_INPUT_FILE_COUNT 和SCRIPT_INPUT_FILE_0, SCRIPT_INPUT_FILE_1... SCRIPT_INPUT_FILE_{SCRIPT_INPUT_FILE_COUNT - 1} 的方式来指定一个文件列表(就像被 Xcode 特别是 ExtraBuildPhase Xcode 插件修改的文件组成的列表,或者类似 Git 工作树中 git ls-files -m 命令显示的被修改的文件列表)。
也有类似的用来设置输入文件的环境变量以 自定义 Xcode script phases 。
使用多个 Swift 版本
SwiftLint 工作于 SourceKit 这一层,所以 Swift 版本发生变化时它也能继续工作!
这也是 SwiftLint 轻量化的原因,因为它不需要一个完整的 Swift 编译器,它只是与已经安装在你的电脑上的官方编译器进行通信。
你应该总是使用和你编译代码同样的工具集来执行 SwiftLint。
如果你有多套工具集或者安装了多个不同版本的 Xcode,你可能会需要覆盖 SwiftLint 默认的工具集。
下面这些命令可以控制 SwiftLint 使用哪一个 Swift 工具集来进行工作:
$XCODE_DEFAULT_TOOLCHAIN_OVERRIDE$TOOLCHAIN_DIR或者$TOOLCHAINSxcrun -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/ 中,上面传入的路径的子目录中。
你可能也给反向 DNS 符号设置了 TOOLCHAINS 环境变量来标记一个特定的 Swift 工具集版本:
TOOLCHAINS=com.apple.dt.toolchain.Swift_2_3 swiftlint autocorrect在 Linux 上,SourceKit 默认需要位于 /usr/lib/libsourcekitdInProc.so 或者通过 LINUX_SOURCEKIT_LIB_PATH 环境变量进行指定。
预提交
SwiftLint 可以作为一个 预提交 钩子运行。
一当 安装,把这个添加到在 root 路径中的.pre-commit-config.yaml 里:
repos:
- repo: https://github.com/realm/SwiftLint
rev: 0.50.3
hooks:
- id: swiftlint将 rev 调整为您选择的 SwiftLint 版本。可以使用 pre-commit autoupdate 来更新到当前版本。
SwiftLint 可以使用 entry 进行配置以应用修复和报错:
- repo: https://github.com/realm/SwiftLint
rev: 0.50.3
hooks:
- id: swiftlint
entry: swiftlint --fix --strict规则
SwiftLint 已经包含了超过 200 条规则,并且我们希望 Swift 社区(就是你!)会在以后有更多的贡献,我们鼓励提交 Pull Requests。
你可以在 这里 找到规则的更新列表和更多信息。
你也可以查看 Source/SwiftLintBuiltInRules/Rules 目录来查看它们的实现。
Opt-In 规则
opt_in_rules 默认是关闭的(即,你需要在你的配置文件中明确地打开它们)。
什么时候需要将一个规则设为 opt-in 的指南:
- 一个可能会有许多负面作用的规则(例如
empty_count) - 一个过慢的规则
- 一个不通用或者仅在某些特定场景下可用的规则(例如
force_unwrapping)
在代码中关闭某个规则
可以通过在一个源文件中定义一个如下格式的注释来关闭某个规则:
// swiftlint:disable <rule1> [<rule2> <rule3>...]
在该文件结束之前或者在定义如下格式的匹配注释之前,这条规则都会被禁用:
// 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: 一些规则是可选的。only_rules: 不可以和disabled_rules或者opt_in_rules并列。类似一个白名单,只有在这个列表中的规则才是开启的。
disabled_rules: # 执行时排除掉的规则
- colon
- comma
- control_statement
opt_in_rules: # 一些规则是默认关闭的,所以你需要手动启用
- empty_count # 你可以通过执行如下指令来查找所有可用的规则:`swiftlint rules`
# 或者,通过取消对该选项的注释来明确指定所有规则:
# only_rules:# 如果使用,请删除 `disabled_rules` 或 `opt_in_rules`
# - empty_parameters
# - vertical_whitespace
analyzer_rules: # `swiftlint analyze` 运行的规则
- explicit_self
included: # 执行 linting 时包含的路径。如果出现这个 `--path` 会被忽略。
- Sources
excluded: # 执行 linting 时忽略的路径。 优先级比 `included` 更高。
- Carthage
- Pods
- Sources/ExcludedFolder
- Sources/ExcludedFile.swift
# 如果值为 true,SwiftLint 将把所有警告都视为错误
strict: false
# 可配置的规则可以通过这个配置文件来自定义
# 二进制规则可以设置他们的严格程度
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)定义自定义规则
你可以用如下语法在你的配置文件里定义基于正则表达式的自定义规则:
custom_rules:
pirates_beat_ninjas: # 规则标识符
name: "Pirates Beat Ninjas" # 规则名称,可选
regex: "([nN]inja)" # 匹配的模式
match_kinds: # 需要匹配的语法类型,可选
- comment
- identifier
message: "Pirates are better than ninjas." # 提示信息,可选
severity: error # 提示的级别,可选
no_hiding_in_strings:
regex: "([nN]inja)"
match_kinds: string输出大概可能是这个样子的:
你可以通过提供一个或者多个 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
嵌套配置
SwiftLint 支持通过嵌套配置文件的方式来对代码分析过程进行更加细致的控制。
- 在你需要的目录引入
.swiftlint.yml。 - 在目录结构必要的地方引入额外的
.swiftlint.yml文件。 - 每个文件被检查时会使用在文件所在目录下的或者父目录的更深层目录下的配置文件。否则根配置文件将会生效。
excluded和included在嵌套结构中会被忽略。
自动更正
SwiftLint 可以自动修正某些错误,磁盘上的文件会被一个修正后的版本覆盖。
请确保在对文件执行 swiftlint autocorrect 之前有对它们做过备份,否则的话有可能导致重要数据的丢失。
因为在执行自动更正修改某个文件后很有可能导致之前生成的代码检查信息无效或者不正确,所以当在执行代码更正时标准的检查是无法使用的。
协议
关于
SwiftLint 是由 Realm Inc 建立和维护的。Realm 的名字和标志是属于 Realm Inc 的注册商标。
我们 :heart: 开源软件!看一下我们的其他开源项目,瞅一眼我们的博客,或者在推特上跟我们唠唠嗑(@realm)。
感谢 MacStadium 为我们的性能测试提供了一台 Mac Mini。
File: README_KR.md
SwiftLint
SwiftLint는 스위프트 스타일 및 컨벤션을 강제하기 위한 도구로, Kodeco 스위프트 스타일 가이드에 대략적인 기반을 두고 있습니다.
SwiftLint는 좀 더 정확한 결과를 위해 Clang과 SourceKit에 연결하여 소스 파일의 AST 표현을 사용합니다.
본 프로젝트는 Contributor Covenant Code of Conduct를 충실히 따릅니다. 본 프로젝트에 참여함으로써 이러한 수칙을 준수해야 합니다. 받아들일 수 없는 항목이 있다면 [email protected]로 알려주세요.
설치 방법
[Homebrew](http://brew.sh/)를 사용하는 경우
brew install swiftlint[CocoaPods](https://cocoapods.org)을 사용하는 경우
Podfile에 아래 라인을 추가하기만 하면 됩니다.
pod 'SwiftLint'이를 실행하면 다음 번 pod install 실행 시 SwiftLint 바이너리 및 Pods/에 있는 의존성들을 다운로드하고, Script Build Phases에서 ${PODS_ROOT}/SwiftLint/swiftlint 명령을 사용할 수 있게 됩니다.
CocoaPods을 사용하면 최신 버전 외에도 SwiftLint의 특정 버전을 설치할 수 있기 때문에 이 방법을 권장합니다. (Homebrew는 최신 버전만 설치 가능)
이렇게 했을 때 SwiftLint 바이너리 및 그에 종속된 바이너리들과 스위프트 바이너리까지 Pods/ 디렉터리에 추가되기 때문에, git 등의 SCM에 이런 디렉터리들을 체크인하는 것은 권장하지 않습니다.
[Mint](https://github.com/yonaskolb/mint)를 사용하는 경우
mint install realm/SwiftLint빌드된 패키지를 사용하는 경우
최신 깃허브 릴리즈에서 SwiftLint.pkg를 다운로드해서 설치하고 실행할 수 있습니다.
소스를 직접 컴파일하는 경우
본 프로젝트를 클론해서 빌드할 수도 있습니다. make install 명령을 사용합니다. (Xcode 12.5 이후 버전)
사용 방법
프레젠테이션
프로젝트에 SwiftLint를 통합하기 위한 권장 사용 방식의 전반적인 개요를 알고 싶다면, 아래 프레젠테이션 영상을 보거나 스크립트를 읽어보면 좋습니다.
Xcode
SwiftLint를 Xcode 프로젝트에 통합하여 IDE 상에 경고나 에러를 표시할 수 있습니다. 프로젝트의 파일 내비게이터에서 타겟 앱을 선택 후 "Build Phases" 탭으로 이동합니다. + 버튼을 클릭한 후 "Run Script Phase"를 선택합니다. 그 후 아래 스크립트를 추가하기만 하면 됩니다.
if which swiftlint >/dev/null; then
swiftlint
else
echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"
fi만약, 애플 실리콘 환경에서 Homebrew를 통해 SwiftLint를 설치했다면, 아마도 다음과 같은 경고를 겪었을 것입니다.
warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint
그 이유는, 애플 실리콘 기반 맥에서 Homebrew는 기본적으로 바이너리들을 /opt/homebrew/bin에 저장하기 때문입니다. SwiftLint가 어디 있는지 찾는 것을 Xcode에 알려주기 위해, build phase에서 /opt/homebrew/bin를 PATH 환경 변수에 동시에 추가하여야 합니다.
if [[ "$(uname -m)" == arm64 ]]; then
export PATH="/opt/homebrew/bin:$PATH"
fi
if which swiftlint > /dev/null; then
swiftlint
else
echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"
fi혹은 아래와 같이 /usr/local/bin에 심볼릭 링크를 생성하여 실제 바이너리가 있는 곳으로 포인팅할 수 있습니다. :
ln -s /opt/homebrew/bin/swiftlint /usr/local/bin/swiftlint당신은 SwiftLint phase를 'Compile Sources' 단계 직전으로 옮겨 컴파일 전에 에러를 빠르게 찾고 싶어 할 것입니다. 하지만, SwiftLint는 컴파일러의 구문 분석 단계를 완벽히 수행하는 유효한 Swift 코드를 실행하기 위해 설계되었습니다. 따라서, 'Compile Sources' 전에 SwiftLint를 실행하면 일부 부정확한 오류가 발생할 수도 있습니다.
만약 당신이 위반 사항(violations)을 동시에 수정하는 것을 원한다면, 스크립트에 swiftlint 대신 swiftlint --fix && swiftlint을 적어야 합니다. 이는 프로젝트의 수정 가능한 모든 위반 사항들이 수정되고 나머지 위반 사항에 대한 경고가 표시된다는 것을 의미합니다.
CocoaPods을 사용해서 설치한 경우는 아래 스크립트를 대신 사용합니다.
"${PODS_ROOT}/SwiftLint/swiftlint"Xcode 저장시 실행되는 플러그인
Xcode에서 저장시 swiftlint autocorrect를 실행하려면 Alcatraz에서 SwiftLintXcode 플러그인을 설치합니다.
⚠ ️이 플러그인은 Xcode 8에서 SIP를 비활성화하지 않으면 동작하지 않으며, 이는 권장하지 않습니다.
AppCode
AppCode에서 SwiftLint를 사용하려면 이 플러그인을 설치하고 플러그인 환경설정에서 SwiftLint가 설치된 경로를 지정해줍니다. autocorrect 액션은 ⌥⏎ 단축키로 사용할 수 있습니다.
Atom
Atom에서 SwiftLint를 사용하려면 APM에서 linter-swiftlint 패키지를 설치합니다.
fastlane
fastlane 과정에서 SwiftLint를 사용하려면 공식적인 fastlane 액션를 사용할 수 있습니다.
swiftlint(
mode: :lint, # SwiftLint 모드: :lint (디폴트) 아니면 :autocorrect
executable: "Pods/SwiftLint/swiftlint", # SwiftLint 바이너리 경로 (선택 가능). CocoaPods을 사용해서 설치한 경우는 이 옵션이 중요합니다
output_file: "swiftlint.result.json", # 결과 파일의 경로 (선택 가능)
reporter: "json", # 보고 유형 (선택 가능)
config_file: ".swiftlint-ci.yml", # 설정 파일의 경로 (선택 가능)
ignore_exit_status: true # SwiftLint 종료할 때 0이 아닌 반환한 종료 코드를 무시해서 fastlane 계속 실행합니다
)커맨드 라인
$ swiftlint help
Available commands:
autocorrect Automatically correct warnings and errors
help Display general or command-specific help
lint Print lint warnings and errors for the Swift files in the current directory (default command)
rules Display the list of rules and their identifiers
version Display the current version of SwiftLint스위프트 파일이 있는 디렉터리에서 swiftlint를 실행합니다. 디렉터리는 재귀적으로 탐색됩니다.
lint나 autocorrect를 사용할 때 여러 파일(예를 들면, ExtraBuildPhase 플러그인에 의해 Xcode가 변경한 파일들 혹은 git ls-files -m 명령으로 인해 작업 트리에서 변경된 파일들)을 지정하려면 --use-script-input-files 옵션을 넘기고 다음 인스턴스 변수들을 설정하면 됩니다. SCRIPT_INPUT_FILE_COUNT andSCRIPT_INPUT_FILE_0, SCRIPT_INPUT_FILE_1...SCRIPT_INPUT_FILE_{SCRIPT_INPUT_FILE_COUNT - 1}
이는 Xcode의 커스텀 스크립트 단계에 입력 파일로 환경 변수를 지정하는 것과 동일합니다.
스위프트 여러 버전에 대한 대응
SwiftLint는 SourceKit에 연결되어 있으므로 스위프트 언어가 변화하더라도 이상 없이 동작할 수 있습니다.
이는 전체 스위프트 컴파일러가 포함되지 않아도 되므로 SwiftLint가 간결하게 유지될 수 있습니다. SwiftLint는 데스크탑에 이미 설치되어 있는 공식 스위프트 컴파일러와 통신하기만 하면 됩니다.
SwiftLint를 실행할 때는 항상 스위프트 파일을 컴파일하는 동일한 툴체인을 사용해야 합니다.
설치된 툴체인이나 Xcode가 여러 개인 경우 혹은 스위프트 구 버전을 사용해야 하는 경우(Xcode 8에서 스위프트 2.3 버전을 사용하는 경우)에는 SwiftLint의 기본 스위프트 툴체인을 변경해야 할 수도 있습니다.
SwiftLint가 어느 스위프트 툴체인을 사용할지 결정하는 순서는 다음과 같습니다.
$XCODE_DEFAULT_TOOLCHAIN_OVERRIDE$TOOLCHAIN_DIRor$TOOLCHAINSxcrun -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/ 하위 디렉터리에 존재해야 합니다.
TOOLCHAINS 환경 변수에 스위프트 툴체인 버전을 식별할 수 있는 값을 리버스 DNS 형식으로 지정할 수도 있습니다.
TOOLCHAINS=com.apple.dt.toolchain.Swift_2_3 swiftlint autocorrect리눅스에서는 SourceKit이 /usr/lib/libsourcekitdInProc.so 혹은 LINUX_SOURCEKIT_LIB_PATH 환경변수로 지정된 경로에 존재해야 합니다.
룰
SwiftLint에는 200개가 넘는 룰들이 있고, 스위프트 커뮤니티(바로 여러분들!)는 이를 지속적으로 발전시켜 가고 있습니다. 풀 리퀘스트는 언제나 환영입니다.
현재 구현된 룰 전체를 확인하려면 Source/SwiftLintBuiltInRules/Rules를 살펴보세요.
opt_in_rules는 기본적으로 비활성화되어 있습니다. (즉, 설정 파일에서 명시적으로 해당 룰을 활성화해야 합니다.)
다음은 룰을 옵트 인으로 구현하는 경우에 대한 기준입니다.
- 잘못 판단될 가능성이 많은 룰 (예:
empty_count) - 속도가 매우 느린 룰
- 일반적으로 모든 사람이 합의하지 않거나 특정한 상황에만 유용한 룰 (예:
force_unwrapping,missing_docs)
코드에서 룰 비활성화하기
소스 파일에서 아래 형식의 주석을 사용하면 룰을 비활성화할 수 있습니다.
// swiftlint:disable <룰1> [<룰2> <룰3>...]
비활성화된 룰은 해당 파일의 마지막까지 적용되거나, 활성화 주석이 나타날 때까지 적용됩니다.
// swiftlint:enable <룰1> [<룰2> <룰3>...]
예를 들면 다음과 같습니다.
// swiftlint:disable colon
let noWarning :String = "" // 변수명 바로 뒤에 콜론이 위치하지 않는다고 경고가 뜨지 않습니다!
// swiftlint:enable colon
let hasWarning :String = "" // 변수명 바로 뒤에 콜론이 위치해야 한다는 경고가 표시됩니다.disable과 enable 명령 뒤에 :previous, :this, :next를 붙이면 각각 명령이 위치한 이전 라인, 현재 라인, 다음 라인만 룰이 적용되게 할 수 있습니다.
예를 들면 다음과 같습니다.
// 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_castswiftlint rules를 실행하면 모든 룰 목록과 룰별 식별자가 표시됩니다.
설정
SwiftLint가 실행될 디렉터리에 .swiftlint.yml 파일을 추가해서 SwiftLint를 설정할 수 있습니다. 아래 파라미터들을 설정 가능합니다.
룰 적용 여부 설정:
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: # 린트 과정에 포함할 파일 경로. 이 항목이 존재하면 `--path`는 무시됨
- Sources
excluded: # 린트 과정에서 무시할 파일 경로. `included`보다 우선순위 높음
- Carthage
- Pods
- Sources/ExcludedFolder
- Sources/ExcludedFile.swift
# 설정 가능한 룰은 이 설정 파일에서 커스터마이징 가능
# 경고나 에러 중 하나를 발생시키는 룰은 위반 수준을 설정 가능
force_cast: warning # 암시적으로 지정
force_try:
severity: warning # 명시적으로 지정
# 경고 및 에러 둘 다 존재하는 룰의 경우 값을 하나만 지정하면 암시적으로 경고 수준에 설정됨
line_length: 110
# 값을 나열해서 암시적으로 양쪽 다 지정할 수 있음
type_body_length:
- 300 # 경고
- 400 # 에러
# 둘 다 명시적으로 지정할 수도 있음
file_length:
warning: 500
error: 1200
# 네이밍 룰은 경고/에러에 min_length와 max_length를 각각 설정 가능
# 제외할 이름을 설정할 수 있음
type_name:
min_length: 4 # 경고에만 적용됨
max_length: # 경고와 에러 둘 다 적용
warning: 40
error: 50
excluded: iPhone # 제외할 문자열 값 사용
identifier_name:
min_length: # min_length에서
error: 4 # 에러만 적용
excluded: # 제외할 문자열 목록 사용
- id
- URL
- GlobalAPIKey
reporter: "xcode" # 보고 유형 (xcode, json, csv, codeclimate, checkstyle, junit, html, emoji, sonarqube, markdown, github-actions-logging)커스텀 룰 정의
아래 문법을 사용하여 설정 파일에 새로운 정규 표현식 기반의 룰을 정의할 수 있습니다.
custom_rules:
pirates_beat_ninjas: # 룰 식별자
included: ".*.swift" # 린트 실행 시 포함할 경로를 정의하는 정규표현식. 선택 가능.
name: "Pirates Beat Ninjas" # 룰 이름. 선택 가능.
regex: "([nN]inja)" # 패턴 매칭
match_kinds: # 매칭할 SyntaxKinds. 선택 가능.
- comment
- identifier
message: "Pirates are better than ninjas." # 위반 메시지. 선택 가능.
severity: error # 위반 수준. 선택 가능.
no_hiding_in_strings:
regex: "([nN]inja)"
match_kinds: string결과는 다음과 같습니다.
하나 이상의 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
중첩 구성
SwiftLint는 설정 파일을 중첩되게 구성해서 린트 과정을 더욱 세밀하게 제어할 수 있습니다.
- 디렉터리 구조에서 필요한 곳이면 어디든지
.swiftlint.yml파일을 추가할 수 있습니다. - 각 파일은 자신의 디렉터리 내에 있는 설정 파일을 사용하거나, 계층구조 상 가장 가까운 부모 디렉터리에 있는 설정 파일을 사용해서 린트됩니다. 별도로 설정 파일이 존재하지 않으면 루트에 있는 설정 파일이 사용됩니다.
- 중첩 구성에서
excluded및included는 무시됩니다.
자동 수정
SwiftLint는 일부 위반 사항들을 자동으로 수정할 수 있습니다. 디스크 상의 파일들은 수정된 버전으로 덮어 쓰여지게 됩니다.
swiftlint autocorrect를 실행하기 전에 파일들을 백업해주세요. 그렇지 않으면 중요한 데이터가 유실될 수도 있습니다.
표준 린트 검사는 자동 수정 중에는 비활성화됩니다. 위반 사항들은 파일이 자동 수정된 후에 더이상 유효하지 않을 가능성이 크기 때문입니다.
라이선스
About
SwiftLint는 Realm Inc.에 의해 만들어져서 관리되고 있습니다. Realm의 이름과 로고는 Realm Inc.의 트레이드 마크입니다.
우리는 오픈 소스 소프트웨어를 사랑합니다:heart:! Realm의 다른 오픈소스 프로젝트와 블로그들도 들러주시고, 트위터(@realm)로도 반갑게 인사 주세요.
2. Official Technical Reference & Guides (realm/realm.github.io)
Realm Open Source
A simple, static portal which outlines our open source offerings. Intentionally
themed to look like a merchant page on the directory.
Development
In an attempt to prevent unnessicary file duplication, the easiest way to develop is by build the static site and replace the index page for the site with the one from open-source. By default on realm.io repo the open-source page is ignored. Update this page on that repo to keep the footer, header, and site styles consolidated.
how to update
1) make updates to the page running the realm.io repo locally
2) build the site locally by running `bundle exec middleman build --verbose`
3) copy the contents of the `/open-source` folder into the root of this repo as well as any page specific style changes
4) replace the index in `/open-source` with the index of the repo
5) rename asset paths and URLs to reflect the new page location at the root.
6) Push to master