現在アーカイブされているGitHub Swiftスタイルガイドに大まかに基づいた、Swiftのスタイルと規約を適用するためのツール。SwiftLint は、Swift コミュニティで一般的に受け入れられているスタイルガイドルールを適用します。これらのルールは、レイウェンダーリッヒのスウィフトスタイルガイドのような人気のあるスタイルガイドでよく説明されています。
SwiftLint は Clang と SourceKit にフックして AST 表現を使用します。 より正確な結果を得るためにあなたのソースファイル。
このプロジェクトは、コントリビューター規約の行動規範に準拠しています。 参加することにより、このコードを支持することが期待されます。報告してください info@realm.io 容認できない行動。
brew install swiftlint
ポッドファイルに次の行を追加するだけです。
pod 'SwiftLint'
これにより、次回の実行時にSwiftLintバイナリと依存関係がダウンロードされ、スクリプトビルドフェーズで呼び出すことができます。
Pods/
pod install
${PODS_ROOT}/SwiftLint/swiftlint
これは、SwiftLintの特定のバージョンをサポートするため、インストールするための推奨される方法です。 単に最新のものではなく、固定されたバージョンをインストールします(Homebrewの場合)。
これにより、SwiftLintバイナリ、その依存関係のバイナリ、およびSwiftバイナリが追加されることに注意してください。 ライブラリをディレクトリに配布するので、このディレクトリをSCMにチェックインします。 git はお勧めできません。
Pods/
$ mint install realm/SwiftLint
また、最新のGitHubリリースからダウンロードしてSwiftLintをインストールすることもできます。 それを実行します。
SwiftLint.pkg
このプロジェクトを複製して実行することで、ソースからビルドしてインストールすることもできます(Xcode 13.3以降)。
make install
これをあなたの中に入れてください:
MODULE.bazel
bazel_dep(name = "swiftlint", version = "0.50.4", repo_name = "SwiftLint")
またはこれをあなたの中に入れてください:
WORKSPACE
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "build_bazel_rules_apple",
sha256 = "f94e6dddf74739ef5cb30f000e13a2a613f6ebfa5e63588305a71fce8a8a9911",
url = "https://github.com/bazelbuild/rules_apple/releases/download/1.1.3/rules_apple.1.1.3.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 = "7c454ff4abeeecdd9513f6293238a6d9f803b587eb93de147f9aa1be0d8337c4",
url = "https://github.com/realm/SwiftLint/releases/download/0.49.1/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 をプロジェクトに統合するための推奨される方法の概要を取得するには、 このプレゼンテーションをご覧になるか、トランスクリプトを読むことをお勧めします。
SwiftLintをXcodeプロジェクトに統合して、警告とエラーを表示します 課題ナビゲータで。
これを行うには、ファイルナビゲーターでプロジェクトを選択し、プライマリアプリを選択します ターゲットを設定し、[ビルド フェーズ] に移動します。[+] をクリックし、[新しい実行スクリプト フェーズ] を選択します。 スクリプトとして以下を挿入します。
Appleシリコン上の自作経由でSwiftLintをインストールした場合、次の警告が表示されることがあります。
警告:SwiftLintがインストールされていません、https://github.com/realm/SwiftLint からダウンロードしてください
これは、Appleシリコン上のHomebrewがデフォルトでバイナリをフォルダーにインストールするためです。XcodeにSwiftLintの場所を指示するには、ビルドフェーズで環境変数に追加します
/opt/homebrew/bin
/opt/homebrew/bin
PATH
export PATH="$PATH:/opt/homebrew/bin"
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フェーズを「ソースのコンパイル」の直前に移動することをお勧めします。 コンパイル前にエラーをすばやく検出する手順。ただし、SwiftLintは設計されています コンパイラの解析段階を正常に完了する有効なSwiftコードで実行します。 したがって、「ソースのコンパイル」の前にSwiftLintを実行すると、誤った問題が発生する可能性があります 業績。
違反も修正したい場合は、だけでなくスクリプトを実行できます。これは意味します すべての修正可能な違反が修正され、警告が 残りの違反に対するプロジェクト。
swiftlint --fix && swiftlint
swiftlint
CocoaPods経由でSwiftLintをインストールした場合、スクリプトは次のようになります。
"${PODS_ROOT}/SwiftLint/swiftlint"
SwiftLintは、Xcodeプロジェクトと 迅速なパッケージ。
Swiftパッケージマネージャープラグインの制限により、これは ルートディレクトリに SwiftLint 設定があるプロジェクトに推奨されます。 現在、SwiftLint 実行可能ファイルに追加のオプションを渡す方法はありません。
作業している場合は、SwiftLintをXcodeビルドツールプラグインとして統合できます Xcodeのプロジェクトで。
SwiftLint をパッケージの依存関係として、リンクせずにプロジェクトに追加します。 プロダクツ。
リンティングを追加するターゲットを選択し、インスペクターを開きます。 ボタンを開いて選択します。 リストから選択し、プロジェクトに追加します。
Build Phases
Run Build Tool Plug-ins
+
SwiftLintPlugin
Swift Lindt を Swift パッケージマネージャープラグインとして統合できます。 マニフェスト付きのスウィフトパッケージ。
Package.swift
SwiftLint をパッケージの依存関係としてファイルに追加します。
パラメーターを使用してターゲットに SwiftLint を追加します。
Package.swift
plugins
.target(
...
plugins: [.plugin(name: "SwiftLintPlugin", package: "SwiftLint")]
),
SwiftLintをAppCodeと統合するには、このプラグインをインストールして構成します プラグインの設定でのSwiftLintのインストールパス。 このアクションは、 から実行できます。
fix
⌥⏎
SwiftLint を vscode と統合するには、マーケットプレイスから vscode-swiftlint
拡張機能をインストールします。
公式のスイフトリントファストレーンアクションを使用して、ファストレーンプロセスの一部として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を使用して Docker イメージとしても使用できます。 したがって、次のコマンドを使用してDockerイメージをプルする必要があるのは初めてです。
Ubuntu
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 all rules lint (default) Print lint warnings and errors 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
または (ExtraBuildPhase
Xcode で指定された Xcode によって変更されたファイルのリストなど) を使用するときにファイルのリストを指定するには
プラグイン、または )、に基づいて作業ツリー内の変更されたファイル
これは、オプションを渡して
次のインスタンス変数: と , ....
lint
analyze
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}
これらは、カスタムXcodeスクリプトフェーズへの入力ファイルに設定されたのと同じ環境変数です。
SwiftLint は SourceKit にフックするので、Swift が進化しても動作し続けます!
これにより、SwiftLintは完全なSwiftで出荷する必要がないため、無駄のない状態に保たれます。 コンパイラ、それはあなたがすでにインストールした公式のものと通信するだけです あなたのマシンで。
SwiftLintは、コンパイルに使用するのと同じツールチェーンで常に実行する必要があります。 コード。
次の場合は、SwiftLintのデフォルトのSwiftツールチェーンをオーバーライドすることをお勧めします。 複数のツールチェーンまたはXコードがインストールされています。
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/
環境変数を逆引きDNSに設定することもできます Swiftツールチェーンのバージョンを識別する表記:
TOOLCHAINS
$ TOOLCHAINS=com.apple.dt.toolchain.Swift_2_3 swiftlint --fix
Linux では、SourceKit は環境変数に配置されるか、環境変数によって指定されることが想定されます。
/usr/lib/libsourcekitdInProc.so
LINUX_SOURCEKIT_LIB_PATH
SwiftLint はコミット前のフックとして実行できます。 インストールしたら、これをリポジトリのルートに追加します。
.pre-commit-config.yaml
repos:
- repo: https://github.com/realm/SwiftLint
rev: 0.50.3
hooks:
- id: swiftlint
選択したスウィフトリントバージョンに調整します。 現在のバージョンに更新するために使用できます。
rev
pre-commit autoupdate
SwiftLintは、修正を適用し、エラーで失敗するように構成できます。
entry
- repo: https://github.com/realm/SwiftLint
rev: 0.50.3
hooks:
- id: swiftlint
entry: swiftlint --fix --strict
200以上のルールがSwiftLintとSwiftコミュニティに含まれています(それはあなたです! 時間の経過とともにより多くの貢献を続けています。プル要求が推奨されます。
更新されたルールのリストとその詳細については、こちらを参照してください。
また、Source/SwiftLintFramework/Rules ディレクトリをチェックして、その実装を確認することもできます。
opt_in_rulesはデフォルトで無効になっています(つまり、明示的に有効にする必要があります あなたの構成ファイルで)。
ルールをオプトインとしてマークするタイミングに関するガイドライン:
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
// 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
また、 または コマンドを 、または前のコマンドにのみ適用して、 この(現在の)行または次の行。
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_cast
実行して、使用可能なすべてのルールとそのルールのリストを印刷します 識別子。
swiftlint rules
SwiftLintを構成するには、ディレクトリからファイルを追加します からスウィフトリントを実行します。次のパラメータを設定できます。
.swiftlint.yml
ルールの包含:
disabled_rules: デフォルトの有効セットからルールを無効にします。
opt_in_rules: デフォルトセットの一部ではないルールを有効にします。
only_rules: このリストで指定されたルールのみが有効になります。 または と一緒に指定することはできません。
disabled_rules
opt_in_rules
analyzer_rules:これは、 コマンドによって実行されます。すべてのアナライザールールはオプトインであるため、これは 構成可能なルール リストのみで、 に相当するものはありません。
analyze
disabled_rules
only_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
included: # paths to include during linting. `--path` is ignored if present.
- Source
excluded: # paths to ignore during linting. Takes precedence over `included`.
- Carthage
- Pods
- Source/ExcludedFolder
- Source/ExcludedFile.swift
- Source/*/ExcludedFile.swift # Exclude files with a wildcard
# If true, SwiftLint will not fail if no lintable files are found.
allow_zero_lintable_files: false
# 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)
構成ファイルで環境変数を使用することもできます。 文字列で使用します。
${SOME_VARIABLE}
構成ファイルでカスタム正規表現ベースのルールを定義するには、 次の構文:
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
This is what the output would look like:
You can filter the matches by providing one or more , which will reject matches that include syntax kinds that are not present in this list. Here are all the possible syntax kinds:
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
All syntax kinds used in a snippet of Swift code can be extracted asking SourceKitten. For example, delivers
sourcekitten syntax --text "struct S {}"
source.lang.swift.syntaxtype.keywordfor the keyword and
struct
source.lang.swift.syntaxtype.identifierfor its name
S
which match to and in the above list.
keyword
identifier
If using custom rules in combination with , make sure to add as an item under .
only_rules
custom_rules
only_rules
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 running , otherwise important data may be lost.
swiftlint --fix
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.
The command can lint Swift files using the full type-checked AST. The compiler log path containing the clean build command invocation (incremental builds will fail) must be passed to via the flag. e.g.
swiftlint analyze
swiftc
analyze
--compiler-log-path
--compiler-log-path /path/to/xcodebuild.log
This can be obtained by
xcodebuild -workspace {WORKSPACE}.xcworkspace -scheme {SCHEME} > xcodebuild.log
swiftlint analyze --compiler-log-path xcodebuild.log
Analyzer rules tend to be considerably slower than lint rules.
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_cast
Project-Specific Configuration:
opt_in_rules:
- force_cast
You can specify a and / or a 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.
child_config
parent_config
A child config is treated as a refinement and therefore 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.yml
To include both the refinement and the base file, your should look like this:
.swiftlint.yml
child_config: .swiftlint_refinement.yml
parent_config: Base/.swiftlint_base.yml
When merging parent and child configs, and configurations are processed carefully to account for differences in the directory location of the containing configuration files.
included
excluded
Just as you can provide local / 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 or .
child_config
parent_config
http://
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 could look like this:
.swiftlint.yml
parent_config: https://myteamserver.com/our-base-swiftlint-config.yml
Every 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 the / specifiers. These values default to 2 / 1 second(s).
remote_timeout
remote_timeout_if_cached
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
メイン設定(ルートフォルダ内のファイル)に加えて、 という名前の他の構成ファイルをディレクトリ構造に入れることができます その後、子構成としてマージされますが、それらのファイルに対してのみ効果があります 構成と同じディレクトリ内、またはより深いディレクトリにあります。 別の構成ファイルはありません。つまり、ネストされた構成は機能しません 再帰的 – ファイルごとに最大数が 1 つのネストされた構成です )は、主構成に加えて適用してもよい。
.swiftlint.yml
.swiftlint.yml
.swiftlint.ymlファイルは、ネストされていない場合にのみネストされた構成と見なされます すでにメイン構成を構築するために使用されます(たとえば、何かを介して参照されている のように)。また、ネストされた構成の仕様は、意味がないため無視されています。
child_config: Folder/.swiftlint.yml
parent_config
child_config
1つ(または複数)のSwiftLintファイルがパラメータを介して明示的に指定されている場合、
その構成は、存在するかどうかに関係なく、オーバーライドとして扱われます
ディレクトリ内のどこかにある他のファイル。したがって、使用したい場合は
入れ子になった構成では、--config パラメーターを使用できません。
--config
.swiftlint.yml
SwiftLintはRealm Inc.によって維持され、資金提供されています。の名前とロゴ Realm は Realm Inc. の商標です。
私たちは
私たちのパフォーマンスを実行するためにMac Miniを提供してくれたMacStadiumに感謝します テスト。