Compare commits
15 Commits
main
...
jp-swift-4
Author | SHA1 | Date |
---|---|---|
![]() |
ad90413304 | |
![]() |
0f9a0a3f52 | |
![]() |
f53383f88f | |
![]() |
0b8bb4cc3a | |
![]() |
3058fa3353 | |
![]() |
c5279f1891 | |
![]() |
5d56f2f96e | |
![]() |
70c30f181c | |
![]() |
892cd76bb0 | |
![]() |
d5380d5690 | |
![]() |
cf44bcf5c6 | |
![]() |
508723c595 | |
![]() |
d2e5b4b576 | |
![]() |
6d26dd2a05 | |
![]() |
aaed908a8b |
|
@ -1 +0,0 @@
|
|||
.build
|
15
.bazelrc
15
.bazelrc
|
@ -1,15 +0,0 @@
|
|||
common --enable_bzlmod
|
||||
|
||||
try-import %workspace%/ci.bazelrc
|
||||
try-import %workspace%/user.bazelrc
|
||||
|
||||
build --macos_minimum_os=12.0 --host_macos_minimum_os=12.0
|
||||
build --disk_cache=~/.bazel_cache
|
||||
build --experimental_remote_cache_compression
|
||||
build --experimental_remote_build_event_upload=minimal
|
||||
build --nolegacy_important_outputs
|
||||
build --swiftcopt=-warnings-as-errors
|
||||
|
||||
build:release \
|
||||
--compilation_mode=opt \
|
||||
--features=swift.opt_uses_wmo
|
|
@ -1 +0,0 @@
|
|||
6.2.0
|
|
@ -1,3 +0,0 @@
|
|||
fixedReleaser:
|
||||
login: jpsim
|
||||
email: jp@jpsim.com
|
|
@ -1,15 +0,0 @@
|
|||
{
|
||||
"homepage": "https://github.com/realm/SwiftLint",
|
||||
"maintainers": [
|
||||
{
|
||||
"email": "jp@jpsim.com",
|
||||
"github": "jpsim",
|
||||
"name": "JP Simard"
|
||||
}
|
||||
],
|
||||
"repository": [
|
||||
"github:realm/SwiftLint"
|
||||
],
|
||||
"versions": [],
|
||||
"yanked_versions": {}
|
||||
}
|
|
@ -1,24 +0,0 @@
|
|||
shell_commands: &shell_commands
|
||||
- "echo --- Downloading and extracting Swift $SWIFT_VERSION to $SWIFT_HOME"
|
||||
- "mkdir $SWIFT_HOME"
|
||||
- "curl https://download.swift.org/swift-${SWIFT_VERSION}-release/ubuntu2004/swift-${SWIFT_VERSION}-RELEASE/swift-${SWIFT_VERSION}-RELEASE-ubuntu20.04.tar.gz | tar xvz --strip-components=1 -C $SWIFT_HOME"
|
||||
|
||||
tasks:
|
||||
verify_targets_linux:
|
||||
name: Verify targets (Linux)
|
||||
platform: ubuntu2004
|
||||
environment:
|
||||
CC: "clang"
|
||||
SWIFT_VERSION: "5.7.2"
|
||||
SWIFT_HOME: "$HOME/swift-$SWIFT_VERSION"
|
||||
PATH: "$PATH:$SWIFT_HOME/usr/bin"
|
||||
shell_commands: *shell_commands
|
||||
build_flags:
|
||||
- "--action_env=PATH"
|
||||
build_targets:
|
||||
- '@SwiftLint//:swiftlint'
|
||||
verify_targets_macos:
|
||||
name: Verify targets (macOS)
|
||||
platform: macos
|
||||
build_targets:
|
||||
- '@SwiftLint//:swiftlint'
|
|
@ -1,5 +0,0 @@
|
|||
{
|
||||
"url": "https://github.com/realm/SwiftLint/releases/download/{TAG}/bazel.tar.gz",
|
||||
"integrity": "",
|
||||
"strip_prefix": ""
|
||||
}
|
|
@ -1,29 +0,0 @@
|
|||
steps:
|
||||
- label: "Bazel"
|
||||
commands:
|
||||
- echo "+++ Build"
|
||||
- bazel build :swiftlint
|
||||
- echo "+++ Test"
|
||||
- bazel test --test_output=errors //Tests/...
|
||||
- label: "SwiftPM"
|
||||
commands:
|
||||
- echo "+++ Test"
|
||||
- swift test --parallel -Xswiftc -DDISABLE_FOCUSED_EXAMPLES
|
||||
- label: "Danger"
|
||||
commands:
|
||||
- echo "--- Install Bundler"
|
||||
- gem install bundler
|
||||
- echo "--- Bundle Install"
|
||||
- bundle install
|
||||
- echo "+++ Run Danger"
|
||||
- bundle exec danger --verbose
|
||||
- label: "TSan Tests"
|
||||
commands:
|
||||
- echo "+++ Test"
|
||||
- bazel test --test_output=errors --build_tests_only --features=tsan --test_timeout=1000 //Tests/...
|
||||
- label: "Sourcery"
|
||||
commands:
|
||||
- echo "+++ Run Sourcery"
|
||||
- make --always-make sourcery
|
||||
- echo "+++ Diff Files"
|
||||
- git diff --quiet HEAD
|
|
@ -1,5 +0,0 @@
|
|||
*
|
||||
!Plugins
|
||||
!Source
|
||||
!Tests
|
||||
!Package.*
|
|
@ -1,42 +0,0 @@
|
|||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
|
||||
---
|
||||
|
||||
### New Issue Checklist
|
||||
|
||||
- [ ] Updated SwiftLint to the latest version
|
||||
- [ ] I searched for [existing GitHub issues](https://github.com/realm/SwiftLint/issues)
|
||||
|
||||
### Describe the bug
|
||||
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
##### Complete output when running SwiftLint, including the stack trace and command used
|
||||
|
||||
```bash
|
||||
$ swiftlint lint
|
||||
```
|
||||
|
||||
### Environment
|
||||
|
||||
* SwiftLint version (run `swiftlint version` to be sure)?
|
||||
* Installation method used (Homebrew, CocoaPods, building from source, etc)?
|
||||
* Paste your configuration file:
|
||||
|
||||
```yml
|
||||
# insert yaml contents here
|
||||
```
|
||||
|
||||
* Are you using [nested configurations](https://github.com/realm/SwiftLint#nested-configurations)?
|
||||
If so, paste their relative paths and respective contents.
|
||||
* Which Xcode version are you using (check `xcodebuild -version`)?
|
||||
* Do you have a sample that shows the issue? Run `echo "[string here]" | swiftlint lint --no-cache --use-stdin --enable-all-rules`
|
||||
to quickly test if your example is really demonstrating the issue. If your example is more
|
||||
complex, you can use `swiftlint lint --path [file here] --no-cache --enable-all-rules`.
|
||||
|
||||
```swift
|
||||
// This triggers a violation:
|
||||
let foo = try! bar()
|
||||
```
|
|
@ -1,22 +0,0 @@
|
|||
---
|
||||
name: Rule request
|
||||
about: Share your idea for a new rule
|
||||
|
||||
---
|
||||
|
||||
### New Issue Checklist
|
||||
|
||||
- [ ] Updated SwiftLint to the latest version
|
||||
- [ ] I searched for [existing GitHub issues](https://github.com/realm/SwiftLint/issues)
|
||||
|
||||
### New rule request
|
||||
|
||||
Please describe the rule idea, format
|
||||
this issue's title as `Rule Request: [Rule Name]` and describe:
|
||||
|
||||
1. Why should this rule be added? Share links to existing discussion about what
|
||||
the community thinks about this.
|
||||
2. Provide several examples of what _would_ and _wouldn't_ trigger violations.
|
||||
3. Should the rule be configurable, if so what parameters should be configurable?
|
||||
4. Should the rule be opt-in or enabled by default? Why?
|
||||
See [README.md](../README.md#opt-in-rules) for guidelines on when to mark a rule as opt-in.
|
|
@ -1,46 +0,0 @@
|
|||
name: docker
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
tags:
|
||||
- '*'
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-20.04
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Extract DOCKER_TAG using tag name
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
run: |
|
||||
echo "DOCKER_TAG=${GITHUB_REF/refs\/tags\//}" >> $GITHUB_ENV
|
||||
|
||||
- name: Use default DOCKER_TAG
|
||||
if: startsWith(github.ref, 'refs/tags/') != true
|
||||
run: |
|
||||
echo "DOCKER_TAG=latest" >> $GITHUB_ENV
|
||||
|
||||
- name: Set lowercase repository name
|
||||
run: |
|
||||
echo "REPOSITORY_LC=${REPOSITORY,,}" >>${GITHUB_ENV}
|
||||
env:
|
||||
REPOSITORY: '${{ github.repository }}'
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v1
|
||||
|
||||
- name: Login to Github registry
|
||||
uses: docker/login-action@v1
|
||||
with:
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
registry: ghcr.io
|
||||
|
||||
- uses: docker/build-push-action@v2
|
||||
with:
|
||||
push: true
|
||||
tags: ghcr.io/${{ env.REPOSITORY_LC }}:${{ env.DOCKER_TAG }}
|
|
@ -1,5 +1,6 @@
|
|||
# Xcode
|
||||
#
|
||||
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
|
||||
|
||||
## Build generated
|
||||
build/
|
||||
|
@ -21,7 +22,6 @@ xcuserdata
|
|||
*.moved-aside
|
||||
*.xcuserstate
|
||||
*.xcscmblueprint
|
||||
default.profraw
|
||||
|
||||
## Obj-C/Swift specific
|
||||
*.hmap
|
||||
|
@ -35,26 +35,25 @@ default.profraw
|
|||
#
|
||||
#Pods/
|
||||
|
||||
# Carthage
|
||||
#
|
||||
# Add this line if you want to avoid checking in source code from Carthage dependencies.
|
||||
# Carthage/Checkouts
|
||||
|
||||
Carthage/Build
|
||||
|
||||
# SwiftLint
|
||||
|
||||
SwiftLint.xcodeproj
|
||||
SwiftLint.pkg
|
||||
*.zip
|
||||
SwiftLintFramework.framework.zip
|
||||
benchmark_*
|
||||
portable_swiftlint.zip
|
||||
osscheck/
|
||||
docs/
|
||||
rule_docs/
|
||||
bazel.tar.gz
|
||||
bazel.tar.gz.sha256
|
||||
ci.bazelrc
|
||||
user.bazelrc
|
||||
|
||||
# Swift Package Manager
|
||||
#
|
||||
# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
|
||||
Packages/
|
||||
.build/
|
||||
.swiftpm/
|
||||
# SPM
|
||||
.build
|
||||
Packages
|
||||
Package.pins
|
||||
|
||||
# macOS
|
||||
.DS_Store
|
||||
|
@ -62,6 +61,3 @@ Packages/
|
|||
# Bundler
|
||||
.bundle/
|
||||
bundle/
|
||||
|
||||
# Bazel
|
||||
bazel-*
|
||||
|
|
|
@ -0,0 +1,21 @@
|
|||
[submodule "Carthage/Checkouts/Result"]
|
||||
path = Carthage/Checkouts/Result
|
||||
url = https://github.com/antitypical/Result.git
|
||||
[submodule "Carthage/Checkouts/SWXMLHash"]
|
||||
path = Carthage/Checkouts/SWXMLHash
|
||||
url = https://github.com/drmohundro/SWXMLHash.git
|
||||
[submodule "Carthage/Checkouts/xcconfigs"]
|
||||
path = Carthage/Checkouts/xcconfigs
|
||||
url = https://github.com/jspahrsummers/xcconfigs.git
|
||||
[submodule "Carthage/Checkouts/Commandant"]
|
||||
path = Carthage/Checkouts/Commandant
|
||||
url = https://github.com/Carthage/Commandant.git
|
||||
[submodule "Carthage/Checkouts/SourceKitten"]
|
||||
path = Carthage/Checkouts/SourceKitten
|
||||
url = https://github.com/jpsim/SourceKitten.git
|
||||
[submodule "Carthage/Checkouts/SwiftyTextTable"]
|
||||
path = Carthage/Checkouts/SwiftyTextTable
|
||||
url = https://github.com/jpsim/SwiftyTextTable.git
|
||||
[submodule "Carthage/Checkouts/Yams"]
|
||||
path = Carthage/Checkouts/Yams
|
||||
url = https://github.com/jpsim/Yams.git
|
32
.jazzy.yaml
32
.jazzy.yaml
|
@ -1,32 +0,0 @@
|
|||
module: SwiftLintCore
|
||||
author: JP Simard, SwiftLint Contributors
|
||||
author_url: https://jpsim.com
|
||||
root_url: https://realm.github.io/SwiftLint/
|
||||
github_url: https://github.com/realm/SwiftLint
|
||||
github_file_prefix: https://github.com/realm/SwiftLint/tree/main
|
||||
swift_build_tool: spm
|
||||
theme: fullwidth
|
||||
clean: true
|
||||
copyright: '© 2023 [JP Simard](https://jpsim.com) under MIT.'
|
||||
|
||||
documentation: rule_docs/*.md
|
||||
hide_unlisted_documentation: true
|
||||
custom_categories_unlisted_prefix: ''
|
||||
exclude:
|
||||
# TODO: Document extensions
|
||||
- Source/SwiftLintCore/Extensions/*.swift
|
||||
custom_categories:
|
||||
- name: Rules
|
||||
children:
|
||||
- Rule Directory
|
||||
- name: Reporters
|
||||
children:
|
||||
- CSVReporter
|
||||
- CheckstyleReporter
|
||||
- CodeClimateReporter
|
||||
- EmojiReporter
|
||||
- GitHubActionsLoggingReporter
|
||||
- HTMLReporter
|
||||
- JSONReporter
|
||||
- JUnitReporter
|
||||
- MarkdownReporter
|
|
@ -1,6 +0,0 @@
|
|||
- id: swiftlint
|
||||
name: SwiftLint
|
||||
description: "Check Swift files for issues with SwiftLint"
|
||||
entry: "swiftlint --quiet"
|
||||
language: swift
|
||||
types: [swift]
|
|
@ -1,5 +0,0 @@
|
|||
|
||||
/// The rule list containing all available rules built into SwiftLint.
|
||||
public let builtInRules: [Rule.Type] = [
|
||||
{% for rule in types.structs where rule.name|hasSuffix:"Rule" or rule.name|hasSuffix:"Rules" %} {{ rule.name }}.self{% if not forloop.last %},{% endif %}
|
||||
{% endfor %}]
|
|
@ -1,20 +0,0 @@
|
|||
@testable import SwiftLintBuiltInRules
|
||||
@_spi(TestHelper)
|
||||
@testable import SwiftLintCore
|
||||
import SwiftLintTestHelpers
|
||||
|
||||
// swiftlint:disable:next blanket_disable_command
|
||||
// swiftlint:disable file_length single_test_class type_name
|
||||
|
||||
{% for rule in types.structs %}
|
||||
{% if rule.name|hasSuffix:"Rule" %}
|
||||
class {{ rule.name }}GeneratedTests: SwiftLintTestCase {
|
||||
func testWithDefaultConfiguration() {
|
||||
verifyRule({{ rule.name }}.description)
|
||||
}
|
||||
}
|
||||
{% if not forloop.last %}
|
||||
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
{% endfor %}
|
|
@ -1,7 +0,0 @@
|
|||
|
||||
/// The reporters list containing all the reporters built into SwiftLint.
|
||||
public let reportersList: [Reporter.Type] = [
|
||||
{% for reporter in types.structs where reporter.name|hasSuffix:"Reporter" %}
|
||||
{{ reporter.name }}.self{% if not forloop.last %},{% endif %}
|
||||
{% endfor %}
|
||||
]
|
123
.swiftlint.yml
123
.swiftlint.yml
|
@ -1,108 +1,39 @@
|
|||
included:
|
||||
- Plugins
|
||||
- Source
|
||||
- Tests
|
||||
excluded:
|
||||
- Tests/SwiftLintFrameworkTests/Resources
|
||||
analyzer_rules:
|
||||
- unused_declaration
|
||||
- unused_import
|
||||
opt_in_rules:
|
||||
- all
|
||||
disabled_rules:
|
||||
- anonymous_argument_in_multiline_closure
|
||||
- anyobject_protocol
|
||||
- closure_body_length
|
||||
- conditional_returns_on_newline
|
||||
- convenience_type
|
||||
- discouraged_optional_collection
|
||||
- explicit_acl
|
||||
- explicit_enum_raw_value
|
||||
- explicit_top_level_acl
|
||||
- explicit_type_interface
|
||||
- file_types_order
|
||||
- force_unwrapping
|
||||
- function_default_parameter_at_end
|
||||
- implicit_return
|
||||
- implicitly_unwrapped_optional
|
||||
- indentation_width
|
||||
- inert_defer
|
||||
- missing_docs
|
||||
- multiline_arguments
|
||||
- multiline_arguments_brackets
|
||||
- multiline_function_chains
|
||||
- multiline_literal_brackets
|
||||
- multiline_parameters
|
||||
- multiline_parameters_brackets
|
||||
- no_extension_access_modifier
|
||||
- no_fallthrough_only
|
||||
- no_grouping_extension
|
||||
- no_magic_numbers
|
||||
- prefer_nimble
|
||||
- prefer_self_in_static_references
|
||||
- prefixed_toplevel_constant
|
||||
- redundant_self_in_closure
|
||||
- required_deinit
|
||||
- self_binding
|
||||
- sorted_enum_cases
|
||||
- strict_fileprivate
|
||||
- superfluous_else
|
||||
- switch_case_on_newline
|
||||
- todo
|
||||
- trailing_closure
|
||||
- type_contents_order
|
||||
- unused_capture_list
|
||||
- vertical_whitespace_between_cases
|
||||
- empty_count
|
||||
- file_header
|
||||
- explicit_init
|
||||
- closure_spacing
|
||||
- overridden_super_call
|
||||
- redundant_nil_coalescing
|
||||
- private_outlet
|
||||
- nimble_operator
|
||||
- attributes
|
||||
- operator_usage_whitespace
|
||||
- closure_end_indentation
|
||||
- first_where
|
||||
- sorted_imports
|
||||
- object_literal
|
||||
- number_separator
|
||||
- prohibited_super_call
|
||||
- fatal_error_message
|
||||
|
||||
attributes:
|
||||
always_on_line_above:
|
||||
- "@OptionGroup"
|
||||
file_header:
|
||||
required_pattern: |
|
||||
\/\/
|
||||
\/\/ .*?\.swift
|
||||
\/\/ SwiftLint
|
||||
\/\/
|
||||
\/\/ Created by .*? on \d{1,2}\/\d{1,2}\/\d{2}\.
|
||||
\/\/ Copyright © \d{4} Realm\. All rights reserved\.
|
||||
\/\/
|
||||
identifier_name:
|
||||
excluded:
|
||||
- id
|
||||
large_tuple: 3
|
||||
line_length: 120
|
||||
number_separator:
|
||||
minimum_length: 5
|
||||
file_name:
|
||||
excluded:
|
||||
- Exports.swift
|
||||
- GeneratedTests.swift
|
||||
- SwiftSyntax+SwiftLint.swift
|
||||
- TestHelpers.swift
|
||||
|
||||
balanced_xctest_lifecycle: &unit_test_configuration
|
||||
test_parent_classes:
|
||||
- SwiftLintTestCase
|
||||
- XCTestCase
|
||||
empty_xctest_method: *unit_test_configuration
|
||||
single_test_class: *unit_test_configuration
|
||||
|
||||
function_body_length: 60
|
||||
type_body_length: 400
|
||||
|
||||
custom_rules:
|
||||
rule_id:
|
||||
included: Source/SwiftLintBuiltInRules/Rules/.+/\w+\.swift
|
||||
name: Rule ID
|
||||
message: Rule IDs must be all lowercase, snake case and not end with `rule`
|
||||
regex: ^\s+identifier:\s*("\w+_rule"|"\S*[^a-z_]\S*")
|
||||
severity: error
|
||||
fatal_error:
|
||||
name: Fatal Error
|
||||
excluded: "Tests/*"
|
||||
message: Prefer using `queuedFatalError` over `fatalError` to avoid leaking compiler host machine paths.
|
||||
regex: \bfatalError\b
|
||||
match_kinds:
|
||||
- identifier
|
||||
severity: error
|
||||
rule_test_function:
|
||||
included: Tests/SwiftLintFrameworkTests/RulesTests.swift
|
||||
name: Rule Test Function
|
||||
message: Rule Test Function mustn't end with `rule`
|
||||
regex: func\s*test\w+(r|R)ule\(\)
|
||||
severity: error
|
||||
|
||||
unused_import:
|
||||
always_keep_imports:
|
||||
- SwiftSyntaxBuilder # we can't detect uses of string interpolation of swift syntax nodes
|
||||
- SwiftLintFramework # now that this is a wrapper around other modules, don't treat as unused
|
||||
|
|
|
@ -0,0 +1,24 @@
|
|||
language: generic
|
||||
matrix:
|
||||
include:
|
||||
- script:
|
||||
- set -o pipefail && script/cibuild | xcpretty
|
||||
- pod lib lint SwiftLintFramework.podspec
|
||||
env: JOB=Xcode
|
||||
os: osx
|
||||
osx_image: xcode8.3
|
||||
before_install:
|
||||
- pod repo update
|
||||
- script: swift test
|
||||
env: JOB=SPM
|
||||
os: osx
|
||||
osx_image: xcode8.3
|
||||
- script: make docker_test
|
||||
env: JOB=Linux3.1
|
||||
sudo: required
|
||||
services: docker
|
||||
notifications:
|
||||
email: false
|
||||
slack: realmio:vPdpsG9NLDo2DNlbqtcMAQuE
|
||||
after_success:
|
||||
- bash <(curl -s https://codecov.io/bash)
|
211
BUILD
211
BUILD
|
@ -1,211 +0,0 @@
|
|||
load("@build_bazel_rules_apple//apple:apple.bzl", "apple_universal_binary")
|
||||
load(
|
||||
"@build_bazel_rules_swift//swift:swift.bzl",
|
||||
"swift_binary",
|
||||
"swift_library",
|
||||
)
|
||||
load(
|
||||
"@rules_xcodeproj//xcodeproj:defs.bzl",
|
||||
"xcode_schemes",
|
||||
"xcodeproj",
|
||||
)
|
||||
|
||||
# Targets
|
||||
|
||||
swift_library(
|
||||
name = "SwiftLintCore",
|
||||
srcs = glob(["Source/SwiftLintCore/**/*.swift"]),
|
||||
module_name = "SwiftLintCore",
|
||||
visibility = ["//visibility:public"],
|
||||
deps = [
|
||||
"@SwiftSyntax//:SwiftIDEUtils_opt",
|
||||
"@SwiftSyntax//:SwiftOperators_opt",
|
||||
"@SwiftSyntax//:SwiftParserDiagnostics_opt",
|
||||
"@SwiftSyntax//:SwiftSyntaxBuilder_opt",
|
||||
"@SwiftSyntax//:SwiftSyntax_opt",
|
||||
"@com_github_jpsim_sourcekitten//:SourceKittenFramework",
|
||||
"@sourcekitten_com_github_jpsim_yams//:Yams",
|
||||
"@swiftlint_com_github_scottrhoyt_swifty_text_table//:SwiftyTextTable",
|
||||
] + select({
|
||||
"@platforms//os:linux": ["@com_github_krzyzanowskim_cryptoswift//:CryptoSwift"],
|
||||
"//conditions:default": [":DyldWarningWorkaround"],
|
||||
}),
|
||||
)
|
||||
|
||||
swift_library(
|
||||
name = "SwiftLintBuiltInRules",
|
||||
srcs = glob(["Source/SwiftLintBuiltInRules/**/*.swift"]),
|
||||
module_name = "SwiftLintBuiltInRules",
|
||||
visibility = ["//visibility:public"],
|
||||
deps = [
|
||||
":SwiftLintCore",
|
||||
],
|
||||
)
|
||||
|
||||
swift_library(
|
||||
name = "SwiftLintExtraRules",
|
||||
srcs = [
|
||||
"Source/SwiftLintExtraRules/Exports.swift",
|
||||
"@swiftlint_extra_rules//:extra_rules",
|
||||
],
|
||||
module_name = "SwiftLintExtraRules",
|
||||
visibility = ["//visibility:public"],
|
||||
deps = [
|
||||
":SwiftLintCore",
|
||||
],
|
||||
)
|
||||
|
||||
swift_library(
|
||||
name = "SwiftLintFramework",
|
||||
srcs = glob(
|
||||
["Source/SwiftLintFramework/**/*.swift"],
|
||||
),
|
||||
module_name = "SwiftLintFramework",
|
||||
visibility = ["//visibility:public"],
|
||||
deps = [
|
||||
":SwiftLintBuiltInRules",
|
||||
":SwiftLintCore",
|
||||
":SwiftLintExtraRules",
|
||||
],
|
||||
)
|
||||
|
||||
swift_library(
|
||||
name = "swiftlint.library",
|
||||
srcs = glob(["Source/swiftlint/**/*.swift"]),
|
||||
module_name = "swiftlint",
|
||||
visibility = ["//visibility:public"],
|
||||
deps = [
|
||||
":SwiftLintFramework",
|
||||
"@com_github_johnsundell_collectionconcurrencykit//:CollectionConcurrencyKit",
|
||||
"@sourcekitten_com_github_apple_swift_argument_parser//:ArgumentParser",
|
||||
"@swiftlint_com_github_scottrhoyt_swifty_text_table//:SwiftyTextTable",
|
||||
],
|
||||
)
|
||||
|
||||
swift_binary(
|
||||
name = "swiftlint",
|
||||
visibility = ["//visibility:public"],
|
||||
deps = [
|
||||
":swiftlint.library",
|
||||
],
|
||||
)
|
||||
|
||||
apple_universal_binary(
|
||||
name = "universal_swiftlint",
|
||||
binary = ":swiftlint",
|
||||
forced_cpus = [
|
||||
"x86_64",
|
||||
"arm64",
|
||||
],
|
||||
minimum_os_version = "12.0",
|
||||
platform_type = "macos",
|
||||
visibility = ["//visibility:public"],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
name = "DyldWarningWorkaroundSources",
|
||||
srcs = [
|
||||
"Source/DyldWarningWorkaround/DyldWarningWorkaround.c",
|
||||
"Source/DyldWarningWorkaround/include/objc_dupclass.h",
|
||||
],
|
||||
)
|
||||
|
||||
cc_library(
|
||||
name = "DyldWarningWorkaround",
|
||||
srcs = ["//:DyldWarningWorkaroundSources"],
|
||||
includes = ["Source/DyldWarningWorkaround/include"],
|
||||
alwayslink = True,
|
||||
)
|
||||
|
||||
# Linting
|
||||
|
||||
filegroup(
|
||||
name = "LintInputs",
|
||||
srcs = glob(["Source/**/*.swift"]) + [
|
||||
".swiftlint.yml",
|
||||
"//Tests:SwiftLintFrameworkTestsData",
|
||||
],
|
||||
visibility = ["//Tests:__subpackages__"],
|
||||
)
|
||||
|
||||
# Release
|
||||
|
||||
filegroup(
|
||||
name = "release_files",
|
||||
srcs = [
|
||||
"BUILD",
|
||||
"LICENSE",
|
||||
"MODULE.bazel",
|
||||
"//:DyldWarningWorkaroundSources",
|
||||
"//:LintInputs",
|
||||
"//Tests:BUILD",
|
||||
"//bazel:release_files",
|
||||
],
|
||||
)
|
||||
|
||||
# TODO: Use rules_pkg
|
||||
genrule(
|
||||
name = "release",
|
||||
srcs = [":release_files"],
|
||||
outs = [
|
||||
"bazel.tar.gz",
|
||||
"bazel.tar.gz.sha256",
|
||||
],
|
||||
cmd = """\
|
||||
set -euo pipefail
|
||||
|
||||
outs=($(OUTS))
|
||||
|
||||
COPYFILE_DISABLE=1 tar czvfh "$${outs[0]}" \
|
||||
--exclude ^bazel-out/ \
|
||||
--exclude ^external/ \
|
||||
*
|
||||
shasum -a 256 "$${outs[0]}" > "$${outs[1]}"
|
||||
""",
|
||||
)
|
||||
|
||||
# Xcode Integration
|
||||
|
||||
xcodeproj(
|
||||
name = "xcodeproj",
|
||||
project_name = "SwiftLint",
|
||||
schemes = [
|
||||
xcode_schemes.scheme(
|
||||
name = "SwiftLint",
|
||||
launch_action = xcode_schemes.launch_action(
|
||||
"swiftlint",
|
||||
args = [
|
||||
"--progress",
|
||||
],
|
||||
),
|
||||
test_action = xcode_schemes.test_action([
|
||||
"//Tests:CLITests",
|
||||
"//Tests:SwiftLintFrameworkTests",
|
||||
"//Tests:GeneratedTests",
|
||||
"//Tests:IntegrationTests",
|
||||
"//Tests:ExtraRulesTests",
|
||||
]),
|
||||
),
|
||||
],
|
||||
top_level_targets = [
|
||||
"//:swiftlint",
|
||||
"//Tests:CLITests",
|
||||
"//Tests:SwiftLintFrameworkTests",
|
||||
"//Tests:GeneratedTests",
|
||||
"//Tests:IntegrationTests",
|
||||
"//Tests:ExtraRulesTests",
|
||||
],
|
||||
)
|
||||
|
||||
# Analyze
|
||||
|
||||
sh_test(
|
||||
name = "analyze",
|
||||
srcs = ["//tools:test-analyze.sh"],
|
||||
data = [
|
||||
"Package.resolved",
|
||||
"Package.swift",
|
||||
":LintInputs",
|
||||
":swiftlint",
|
||||
],
|
||||
)
|
4742
CHANGELOG.md
4742
CHANGELOG.md
File diff suppressed because it is too large
Load Diff
108
CONTRIBUTING.md
108
CONTRIBUTING.md
|
@ -1,54 +1,20 @@
|
|||
## Tutorial
|
||||
|
||||
If you'd like to write a SwiftLint rule but aren't sure how to start,
|
||||
please watch and follow along with
|
||||
[this video tutorial](https://vimeo.com/819268038).
|
||||
|
||||
## Pull Requests
|
||||
|
||||
All changes, no matter how trivial, must be done via pull request. Commits
|
||||
should never be made directly on the `main` branch. Prefer rebasing over
|
||||
merging `main` into your PR branch to update it and resolve conflicts.
|
||||
should never be made directly on the `master` branch.
|
||||
|
||||
_If you have commit access to SwiftLint and believe your change to be trivial
|
||||
and not worth waiting for review, you may open a pull request and merge
|
||||
immediately, but this should be the exception, not the norm._
|
||||
|
||||
### Building And Running Locally
|
||||
### Submodules
|
||||
|
||||
#### Using Xcode
|
||||
This SwiftLint repository uses submodules for its dependencies.
|
||||
This means that if you decide to fork this repository to contribute to SwiftLint,
|
||||
don't forget to checkout the submodules as well when cloning, by running
|
||||
`git submodule update --init --recursive` after cloning.
|
||||
|
||||
1. `git clone https://github.com/realm/SwiftLint.git`
|
||||
1. `cd SwiftLint`
|
||||
1. `xed .`
|
||||
1. Select the "swiftlint" scheme
|
||||
1. `cmd-opt-r` open the scheme options
|
||||
1. Set the "Arguments Passed On Launch" you want in the "Arguments" tab. See
|
||||
available arguments [in the README](https://github.com/realm/SwiftLint#command-line).
|
||||
1. Set the "Working Directory" in the "Options" tab to the path where you would like
|
||||
to execute SwiftLint. A folder that contains swift source files.
|
||||
1. Hit "Run"
|
||||
|
||||
|Arguments|Options|
|
||||
|-|-|
|
||||
|||
|
||||
|
||||
Then you can use the full power of Xcode/LLDB/Instruments to develop and debug your changes to SwiftLint.
|
||||
|
||||
#### Using the command line
|
||||
|
||||
1. `git clone https://github.com/realm/SwiftLint.git`
|
||||
1. `cd SwiftLint`
|
||||
1. `swift build [-c release]`
|
||||
1. Use the produced `swiftlint` binary from the command line, either by running `swift run [-c release] [swiftlint] [arguments]` or by invoking the binary directly at `.build/[release|debug]/swiftlint`
|
||||
1. [Optional] Attach LLDB: `lldb -- .build/[release|debug]/swiftlint [arguments]`
|
||||
|
||||
### Code Generation
|
||||
|
||||
If XCTest cases or functions are added/removed/renamed, or if rules are
|
||||
added/removed/renamed, you'll need to run `make sourcery`, which requires that
|
||||
[Sourcery](https://github.com/krzysztofzablocki/Sourcery) be installed on your
|
||||
machine. This will update source files to reflect these changes.
|
||||
See more info [in the README](https://github.com/realm/SwiftLint#installation).
|
||||
|
||||
### Tests
|
||||
|
||||
|
@ -57,16 +23,20 @@ with Swift Package Manager on Linux. When contributing code changes, please
|
|||
ensure that all three supported build methods continue to work and pass tests.
|
||||
|
||||
```shell
|
||||
$ xcodebuild -scheme swiftlint test
|
||||
$ script/cibuild
|
||||
$ swift test
|
||||
$ make docker_test
|
||||
```
|
||||
|
||||
XCTest functions that are added need to be mirrored in the `allTests` static var
|
||||
in the test class extensions at the bottom of the test files.
|
||||
|
||||
## Rules
|
||||
|
||||
New rules should be added in the `Source/SwiftLintBuiltInRules/Rules` directory.
|
||||
New rules should be added in the `Source/SwiftLintFramework/Rules` directory.
|
||||
|
||||
Rules should conform to either the `Rule` or `ASTRule` protocols.
|
||||
To activate a rule, add the rule to `masterRuleList` in `MasterRuleList.swift`.
|
||||
|
||||
All new rules or changes to existing rules should be accompanied by unit tests.
|
||||
|
||||
|
@ -78,19 +48,6 @@ over time. This way adding a unit test for your new Rule is just a matter of
|
|||
adding a test case in `RulesTests.swift` which simply calls
|
||||
`verifyRule(YourNewRule.description)`.
|
||||
|
||||
For debugging purposes examples can be marked as `focused`. If there are any
|
||||
focused examples found, then only those will be run when running tests for that rule.
|
||||
```
|
||||
nonTriggeringExamples: [
|
||||
Example("let x: [Int]"),
|
||||
Example("let x: [Int: String]").focused() // only this one will be run in tests
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("let x: ↓Array<String>"),
|
||||
Example("let x: ↓Dictionary<Int, String>")
|
||||
]
|
||||
```
|
||||
|
||||
### `ConfigurationProviderRule`
|
||||
|
||||
If your rule supports user-configurable options via `.swiftlint.yml`, you can
|
||||
|
@ -104,11 +61,11 @@ configuration object via the `configuration` property:
|
|||
* If none of the provided `RuleConfiguration`s are applicable, you can create one
|
||||
specifically for your rule.
|
||||
|
||||
See [`ForceCastRule`](https://github.com/realm/SwiftLint/blob/main/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ForceCastRule.swift)
|
||||
See [`ForceCastRule`](https://github.com/realm/SwiftLint/blob/master/Source/SwiftLintFramework/Rules/ForceCastRule.swift)
|
||||
for a rule that allows severity configuration,
|
||||
[`FileLengthRule`](https://github.com/realm/SwiftLint/blob/main/Source/SwiftLintBuiltInRules/Rules/Metrics/FileLengthRule.swift)
|
||||
[`FileLengthRule`](https://github.com/realm/SwiftLint/blob/master/Source/SwiftLintFramework/Rules/FileLengthRule.swift)
|
||||
for a rule that has multiple severity levels,
|
||||
[`IdentifierNameRule`](https://github.com/realm/SwiftLint/blob/main/Source/SwiftLintBuiltInRules/Rules/Style/IdentifierNameRule.swift)
|
||||
[`IdentifierNameRule`](https://github.com/realm/SwiftLint/blob/master/Source/SwiftLintFramework/Rules/IdentifierNameRule.swift)
|
||||
for a rule that allows name evaluation configuration:
|
||||
|
||||
``` yaml
|
||||
|
@ -145,40 +102,15 @@ If your rule is configurable, but does not fit the pattern of
|
|||
|
||||
All changes should be made via pull requests on GitHub.
|
||||
|
||||
When issuing a pull request with user-facing changes, please add a
|
||||
summary of your changes to the `CHANGELOG.md` file.
|
||||
When issuing a pull request, please add a summary of your changes to
|
||||
the `CHANGELOG.md` file.
|
||||
|
||||
We follow the same syntax as CocoaPods' CHANGELOG.md:
|
||||
|
||||
1. One Markdown unnumbered list item describing the change.
|
||||
2. 2 trailing spaces on the last line describing the change (so that Markdown renders each change [on its own line](https://daringfireball.net/projects/markdown/syntax#p)).
|
||||
2. 2 trailing spaces on the last line describing the change.
|
||||
3. A list of Markdown hyperlinks to the contributors to the change. One entry
|
||||
per line. Usually just one.
|
||||
4. A list of Markdown hyperlinks to the issues the change addresses. One entry
|
||||
per line. Usually just one. If there was no issue tracking this change,
|
||||
you may instead link to the change's pull request.
|
||||
per line. Usually just one.
|
||||
5. All CHANGELOG.md content is hard-wrapped at 80 characters.
|
||||
|
||||
## CI
|
||||
|
||||
SwiftLint uses Azure Pipelines for most of its CI jobs, primarily because
|
||||
they're the only CI provider to have a free tier with 10x concurrency on macOS.
|
||||
|
||||
Some CI jobs run in GitHub Actions (e.g. Docker).
|
||||
|
||||
Some CI jobs run on Buildkite using Mac Minis from MacStadium. These are jobs
|
||||
that benefit from being run on the latest Xcode & macOS versions on bare metal.
|
||||
|
||||
### Buildkite Setup
|
||||
|
||||
To bring up a new Buildkite worker from MacStadium:
|
||||
|
||||
1. Change account password
|
||||
1. Update macOS to the latest version
|
||||
1. Install Homebrew: https://brew.sh
|
||||
1. Install Buildkite agent and other tools via Homebrew:
|
||||
`brew install aria2 bazelisk htop buildkite/buildkite/buildkite-agent robotsandpencils/made/xcodes`
|
||||
1. Install latest Xcode version: `xcodes update && xcodes install 14.0.0`
|
||||
1. Add `DANGER_GITHUB_API_TOKEN` and `HOME` to `/opt/homebrew/etc/buildkite-agent/hooks/environment`
|
||||
1. Configure and launch buildkite agent: `brew info buildkite-agent` /
|
||||
https://buildkite.com/organizations/swiftlint/agents#setup-macos
|
||||
|
|
|
@ -0,0 +1,2 @@
|
|||
github "jpsim/SourceKitten" "jp-swift-4"
|
||||
github "jpsim/SwiftyTextTable" "jp-swift-4"
|
|
@ -0,0 +1,3 @@
|
|||
github "Carthage/Commandant" "master"
|
||||
github "jspahrsummers/xcconfigs" "master"
|
||||
github "jpsim/Yams" "master"
|
|
@ -0,0 +1,7 @@
|
|||
github "Carthage/Commandant" "16bcee12f48564c87bb13830f5320d21257e15b8"
|
||||
github "antitypical/Result" "3.2.3"
|
||||
github "drmohundro/SWXMLHash" "4cb1b72d406b4309aed6e6b2f11f46aa83dacbf7"
|
||||
github "jpsim/SourceKitten" "6e60ee7d6e9885ad6e674d55a5f540b0e52def09"
|
||||
github "jpsim/SwiftyTextTable" "15f72002eea8e3b446d104d18225b6a828218d32"
|
||||
github "jpsim/Yams" "b53284ba4c8bdece9ec8aad2e0010602dac588e9"
|
||||
github "jspahrsummers/xcconfigs" "2055f18efbe18e77408f7f43947f7ad92b2d4ff0"
|
|
@ -0,0 +1 @@
|
|||
Subproject commit 16bcee12f48564c87bb13830f5320d21257e15b8
|
|
@ -0,0 +1 @@
|
|||
Subproject commit c8446185238659a2b27c0261f64ff1254291d07d
|
|
@ -0,0 +1 @@
|
|||
Subproject commit 4cb1b72d406b4309aed6e6b2f11f46aa83dacbf7
|
|
@ -0,0 +1 @@
|
|||
Subproject commit 6e60ee7d6e9885ad6e674d55a5f540b0e52def09
|
|
@ -0,0 +1 @@
|
|||
Subproject commit 15f72002eea8e3b446d104d18225b6a828218d32
|
|
@ -0,0 +1 @@
|
|||
Subproject commit b53284ba4c8bdece9ec8aad2e0010602dac588e9
|
|
@ -0,0 +1 @@
|
|||
Subproject commit 2055f18efbe18e77408f7f43947f7ad92b2d4ff0
|
77
Dangerfile
77
Dangerfile
|
@ -3,24 +3,16 @@ require 'open3'
|
|||
# Warn when there is a big PR
|
||||
warn('Big PR') if git.lines_of_code > 500
|
||||
|
||||
# Ensure a clean commit history
|
||||
if git.commits.any? { |c| c.message =~ /^Merge branch '#{github.branch_for_base}'/ }
|
||||
fail('Please rebase to get rid of the merge commits in this PR')
|
||||
end
|
||||
|
||||
modified_files = git.modified_files + git.added_files
|
||||
|
||||
# Sometimes its a README fix, or something like that - which isn't relevant for
|
||||
# including in a CHANGELOG for example
|
||||
has_app_changes = !modified_files.grep(/Source/).empty?
|
||||
has_test_changes = !modified_files.grep(/Tests/).empty?
|
||||
has_danger_changes = !modified_files.grep(/Dangerfile|tools\/oss-check|Gemfile/).empty?
|
||||
has_package_changes = !modified_files.grep(/Package\.swift/).empty?
|
||||
has_bazel_changes = !modified_files.grep(/\.bazelrc|\.bazelversion|WORKSPACE|bazel\/|BUILD|MODULE\.bazel/).empty?
|
||||
has_app_changes = !git.modified_files.grep(/Source/).empty?
|
||||
has_test_changes = !git.modified_files.grep(/Tests/).empty?
|
||||
has_danger_changes = !git.modified_files.grep(/Dangerfile|script\/oss-check|Gemfile/).empty?
|
||||
has_build_changes = !git.modified_files.grep(/Makefile|SwiftLint\.xcodeproj|SwiftLint\.xcworkspace|Package\.swift|Cartfile/).empty?
|
||||
|
||||
# Add a CHANGELOG entry for app changes
|
||||
if !modified_files.include?('CHANGELOG.md') && has_app_changes
|
||||
warn("If this is a user-facing change, please include a CHANGELOG entry to credit yourself! \nYou can find it at [CHANGELOG.md](https://github.com/realm/SwiftLint/blob/main/CHANGELOG.md).")
|
||||
if !git.modified_files.include?('CHANGELOG.md') && has_app_changes
|
||||
fail("Please include a CHANGELOG entry to credit yourself! \nYou can find it at [CHANGELOG.md](https://github.com/realm/SwiftLint/blob/master/CHANGELOG.md).")
|
||||
markdown <<-MARKDOWN
|
||||
Here's an example of your CHANGELOG entry:
|
||||
```markdown
|
||||
|
@ -32,44 +24,43 @@ Here's an example of your CHANGELOG entry:
|
|||
MARKDOWN
|
||||
end
|
||||
|
||||
return unless has_app_changes || has_danger_changes || has_package_changes || has_bazel_changes
|
||||
|
||||
# Non-trivial amounts of app changes without tests
|
||||
if git.lines_of_code > 50 && has_app_changes && !has_test_changes
|
||||
warn 'This PR may need tests.'
|
||||
end
|
||||
|
||||
# Run OSSCheck if there were app changes
|
||||
if has_app_changes || has_danger_changes || has_build_changes
|
||||
def non_empty_lines(lines)
|
||||
lines.split(/\n+/).reject(&:empty?)
|
||||
end
|
||||
|
||||
def non_empty_lines(lines)
|
||||
lines.split(/\n+/).reject(&:empty?)
|
||||
end
|
||||
def parse_line(line)
|
||||
line.split(':', 2).last.strip
|
||||
end
|
||||
|
||||
def parse_line(line)
|
||||
line.split(':', 2).last.strip
|
||||
end
|
||||
lines = nil
|
||||
file = Tempfile.new('violations')
|
||||
|
||||
file = Tempfile.new('violations')
|
||||
Open3.popen3("script/oss-check 2> #{file.path}") do |_, stdout, _, _|
|
||||
while char = stdout.getc
|
||||
print char
|
||||
end
|
||||
end
|
||||
|
||||
force_flag = has_danger_changes ? "--force" : ""
|
||||
Open3.popen3("tools/oss-check -v #{force_flag} 2> #{file.path}") do |_, stdout, _, _|
|
||||
while char = stdout.getc
|
||||
print char
|
||||
end
|
||||
end
|
||||
|
||||
lines = file.read.chomp
|
||||
file.close
|
||||
file.unlink
|
||||
|
||||
non_empty_lines(lines).each do |line|
|
||||
if line.include? 'Permanently added the RSA host key for IP address'
|
||||
# Don't report to Danger
|
||||
elsif line.start_with? 'Message:'
|
||||
message parse_line(line)
|
||||
elsif line.start_with? 'Warning:'
|
||||
warn parse_line(line)
|
||||
elsif line.start_with? 'Error:'
|
||||
fail parse_line(line)
|
||||
lines = file.read.chomp
|
||||
file.close
|
||||
file.unlink
|
||||
|
||||
non_empty_lines(lines).each do |line|
|
||||
if line.start_with? 'Permanently added the RSA host key for IP address'
|
||||
# Don't report to Danger
|
||||
elsif line.start_with? 'Message:'
|
||||
message parse_line(line)
|
||||
elsif line.start_with? 'Warning:'
|
||||
warn parse_line(line)
|
||||
elsif line.start_with? 'Error:'
|
||||
fail parse_line(line)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
39
Dockerfile
39
Dockerfile
|
@ -1,39 +0,0 @@
|
|||
# Explicitly specify `jammy` to keep the Swift & Ubuntu images in sync.
|
||||
ARG BUILDER_IMAGE=swift:jammy
|
||||
ARG RUNTIME_IMAGE=ubuntu:jammy
|
||||
|
||||
# builder image
|
||||
FROM ${BUILDER_IMAGE} AS builder
|
||||
RUN apt-get update && apt-get install -y \
|
||||
libcurl4-openssl-dev \
|
||||
libxml2-dev \
|
||||
&& rm -r /var/lib/apt/lists/*
|
||||
WORKDIR /workdir/
|
||||
COPY Plugins Plugins/
|
||||
COPY Source Source/
|
||||
COPY Tests Tests/
|
||||
COPY Package.* ./
|
||||
|
||||
RUN swift package update
|
||||
ARG SWIFT_FLAGS="-c release -Xswiftc -static-stdlib -Xlinker -lCFURLSessionInterface -Xlinker -lCFXMLInterface -Xlinker -lcurl -Xlinker -lxml2 -Xswiftc -I. -Xlinker -fuse-ld=lld -Xlinker -L/usr/lib/swift/linux"
|
||||
RUN swift build $SWIFT_FLAGS --product swiftlint
|
||||
RUN mkdir -p /executables
|
||||
RUN install -v `swift build $SWIFT_FLAGS --show-bin-path`/swiftlint /executables
|
||||
|
||||
# runtime image
|
||||
FROM ${RUNTIME_IMAGE}
|
||||
LABEL org.opencontainers.image.source https://github.com/realm/SwiftLint
|
||||
RUN apt-get update && apt-get install -y \
|
||||
libcurl4 \
|
||||
libxml2 \
|
||||
&& rm -r /var/lib/apt/lists/*
|
||||
COPY --from=builder /usr/lib/libsourcekitdInProc.so /usr/lib
|
||||
COPY --from=builder /usr/lib/swift/linux/libBlocksRuntime.so /usr/lib
|
||||
COPY --from=builder /usr/lib/swift/linux/libdispatch.so /usr/lib
|
||||
COPY --from=builder /usr/lib/swift/linux/libswiftCore.so /usr/lib
|
||||
COPY --from=builder /executables/* /usr/bin
|
||||
|
||||
RUN swiftlint version
|
||||
RUN echo "_ = 0" | swiftlint --use-stdin
|
||||
|
||||
CMD ["swiftlint"]
|
7
Gemfile
7
Gemfile
|
@ -1,5 +1,4 @@
|
|||
source 'https://rubygems.org'
|
||||
# frozen_string_literal: true
|
||||
source "https://rubygems.org"
|
||||
|
||||
gem 'cocoapods'
|
||||
gem 'danger'
|
||||
gem 'jazzy'
|
||||
gem "danger"
|
||||
|
|
167
Gemfile.lock
167
Gemfile.lock
|
@ -1,162 +1,51 @@
|
|||
GEM
|
||||
remote: https://rubygems.org/
|
||||
specs:
|
||||
CFPropertyList (3.0.6)
|
||||
rexml
|
||||
activesupport (7.0.4.3)
|
||||
concurrent-ruby (~> 1.0, >= 1.0.2)
|
||||
i18n (>= 1.6, < 2)
|
||||
minitest (>= 5.1)
|
||||
tzinfo (~> 2.0)
|
||||
addressable (2.8.4)
|
||||
public_suffix (>= 2.0.2, < 6.0)
|
||||
algoliasearch (1.27.5)
|
||||
httpclient (~> 2.8, >= 2.8.3)
|
||||
json (>= 1.5.1)
|
||||
atomos (0.1.3)
|
||||
claide (1.1.0)
|
||||
addressable (2.5.1)
|
||||
public_suffix (~> 2.0, >= 2.0.2)
|
||||
claide (1.0.1)
|
||||
claide-plugins (0.9.2)
|
||||
cork
|
||||
nap
|
||||
open4 (~> 1.3)
|
||||
cocoapods (1.12.1)
|
||||
addressable (~> 2.8)
|
||||
claide (>= 1.0.2, < 2.0)
|
||||
cocoapods-core (= 1.12.1)
|
||||
cocoapods-deintegrate (>= 1.0.3, < 2.0)
|
||||
cocoapods-downloader (>= 1.6.0, < 2.0)
|
||||
cocoapods-plugins (>= 1.0.0, < 2.0)
|
||||
cocoapods-search (>= 1.0.0, < 2.0)
|
||||
cocoapods-trunk (>= 1.6.0, < 2.0)
|
||||
cocoapods-try (>= 1.1.0, < 2.0)
|
||||
colored2 (~> 3.1)
|
||||
escape (~> 0.0.4)
|
||||
fourflusher (>= 2.3.0, < 3.0)
|
||||
gh_inspector (~> 1.0)
|
||||
molinillo (~> 0.8.0)
|
||||
nap (~> 1.0)
|
||||
ruby-macho (>= 2.3.0, < 3.0)
|
||||
xcodeproj (>= 1.21.0, < 2.0)
|
||||
cocoapods-core (1.12.1)
|
||||
activesupport (>= 5.0, < 8)
|
||||
addressable (~> 2.8)
|
||||
algoliasearch (~> 1.0)
|
||||
concurrent-ruby (~> 1.1)
|
||||
fuzzy_match (~> 2.0.4)
|
||||
nap (~> 1.0)
|
||||
netrc (~> 0.11)
|
||||
public_suffix (~> 4.0)
|
||||
typhoeus (~> 1.0)
|
||||
cocoapods-deintegrate (1.0.5)
|
||||
cocoapods-downloader (1.6.3)
|
||||
cocoapods-plugins (1.0.0)
|
||||
nap
|
||||
cocoapods-search (1.0.1)
|
||||
cocoapods-trunk (1.6.0)
|
||||
nap (>= 0.8, < 2.0)
|
||||
netrc (~> 0.11)
|
||||
cocoapods-try (1.2.0)
|
||||
colored2 (3.1.2)
|
||||
concurrent-ruby (1.2.2)
|
||||
cork (0.3.0)
|
||||
colored2 (~> 3.1)
|
||||
danger (9.2.0)
|
||||
danger (5.2.2)
|
||||
claide (~> 1.0)
|
||||
claide-plugins (>= 0.9.2)
|
||||
colored2 (~> 3.1)
|
||||
cork (~> 0.1)
|
||||
faraday (>= 0.9.0, < 3.0)
|
||||
faraday-http-cache (~> 2.0)
|
||||
git (~> 1.7)
|
||||
kramdown (~> 2.3)
|
||||
kramdown-parser-gfm (~> 1.0)
|
||||
no_proxy_fix
|
||||
octokit (~> 5.0)
|
||||
terminal-table (>= 1, < 4)
|
||||
escape (0.0.4)
|
||||
ethon (0.16.0)
|
||||
ffi (>= 1.15.0)
|
||||
faraday (2.7.4)
|
||||
faraday-net_http (>= 2.0, < 3.1)
|
||||
ruby2_keywords (>= 0.0.4)
|
||||
faraday-http-cache (2.4.1)
|
||||
faraday (>= 0.8)
|
||||
faraday-net_http (3.0.2)
|
||||
ffi (1.15.5)
|
||||
fourflusher (2.3.1)
|
||||
fuzzy_match (2.0.4)
|
||||
gh_inspector (1.1.3)
|
||||
git (1.18.0)
|
||||
addressable (~> 2.8)
|
||||
rchardet (~> 1.8)
|
||||
httpclient (2.8.3)
|
||||
i18n (1.12.0)
|
||||
concurrent-ruby (~> 1.0)
|
||||
jazzy (0.14.3)
|
||||
cocoapods (~> 1.5)
|
||||
mustache (~> 1.1)
|
||||
open4 (~> 1.3)
|
||||
redcarpet (~> 3.4)
|
||||
rexml (~> 3.2)
|
||||
rouge (>= 2.0.6, < 4.0)
|
||||
sassc (~> 2.1)
|
||||
sqlite3 (~> 1.3)
|
||||
xcinvoke (~> 0.3.0)
|
||||
json (2.6.3)
|
||||
kramdown (2.4.0)
|
||||
rexml
|
||||
kramdown-parser-gfm (1.1.0)
|
||||
kramdown (~> 2.0)
|
||||
liferaft (0.0.6)
|
||||
minitest (5.18.0)
|
||||
molinillo (0.8.0)
|
||||
mustache (1.1.1)
|
||||
nanaimo (0.3.0)
|
||||
faraday (~> 0.9)
|
||||
faraday-http-cache (~> 1.0)
|
||||
git (~> 1)
|
||||
kramdown (~> 1.5)
|
||||
octokit (~> 4.2)
|
||||
terminal-table (~> 1)
|
||||
faraday (0.12.1)
|
||||
multipart-post (>= 1.2, < 3)
|
||||
faraday-http-cache (1.3.1)
|
||||
faraday (~> 0.8)
|
||||
git (1.3.0)
|
||||
kramdown (1.13.2)
|
||||
multipart-post (2.0.0)
|
||||
nap (1.1.0)
|
||||
netrc (0.11.0)
|
||||
no_proxy_fix (0.1.2)
|
||||
octokit (5.6.1)
|
||||
faraday (>= 1, < 3)
|
||||
sawyer (~> 0.9)
|
||||
octokit (4.7.0)
|
||||
sawyer (~> 0.8.0, >= 0.5.3)
|
||||
open4 (1.3.4)
|
||||
public_suffix (4.0.7)
|
||||
rchardet (1.8.0)
|
||||
redcarpet (3.6.0)
|
||||
rexml (3.2.5)
|
||||
rouge (3.30.0)
|
||||
ruby-macho (2.5.1)
|
||||
ruby2_keywords (0.0.5)
|
||||
sassc (2.4.0)
|
||||
ffi (~> 1.9)
|
||||
sawyer (0.9.2)
|
||||
addressable (>= 2.3.5)
|
||||
faraday (>= 0.17.3, < 3)
|
||||
sqlite3 (1.6.2-arm64-darwin)
|
||||
terminal-table (3.0.2)
|
||||
unicode-display_width (>= 1.1.1, < 3)
|
||||
typhoeus (1.4.0)
|
||||
ethon (>= 0.9.0)
|
||||
tzinfo (2.0.6)
|
||||
concurrent-ruby (~> 1.0)
|
||||
unicode-display_width (2.4.2)
|
||||
xcinvoke (0.3.0)
|
||||
liferaft (~> 0.0.6)
|
||||
xcodeproj (1.22.0)
|
||||
CFPropertyList (>= 2.3.3, < 4.0)
|
||||
atomos (~> 0.1.3)
|
||||
claide (>= 1.0.2, < 2.0)
|
||||
colored2 (~> 3.1)
|
||||
nanaimo (~> 0.3.0)
|
||||
rexml (~> 3.2.4)
|
||||
public_suffix (2.0.5)
|
||||
sawyer (0.8.1)
|
||||
addressable (>= 2.3.5, < 2.6)
|
||||
faraday (~> 0.8, < 1.0)
|
||||
terminal-table (1.8.0)
|
||||
unicode-display_width (~> 1.1, >= 1.1.1)
|
||||
unicode-display_width (1.2.1)
|
||||
|
||||
PLATFORMS
|
||||
arm64-darwin-21
|
||||
arm64-darwin-22
|
||||
ruby
|
||||
|
||||
DEPENDENCIES
|
||||
cocoapods
|
||||
danger
|
||||
jazzy
|
||||
|
||||
BUNDLED WITH
|
||||
2.4.12
|
||||
1.14.6
|
||||
|
|
2
LICENSE
2
LICENSE
|
@ -1,6 +1,6 @@
|
|||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2020 Realm Inc.
|
||||
Copyright (c) 2015 Realm Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
|
27
MODULE.bazel
27
MODULE.bazel
|
@ -1,27 +0,0 @@
|
|||
module(
|
||||
name = "swiftlint",
|
||||
version = "0.52.2",
|
||||
compatibility_level = 1,
|
||||
repo_name = "SwiftLint",
|
||||
)
|
||||
|
||||
bazel_dep(name = "bazel_skylib", version = "1.4.1", dev_dependency = True)
|
||||
bazel_dep(name = "platforms", version = "0.0.6")
|
||||
bazel_dep(name = "rules_apple", version = "2.3.0", repo_name = "build_bazel_rules_apple")
|
||||
bazel_dep(name = "rules_swift", version = "1.8.0", repo_name = "build_bazel_rules_swift")
|
||||
bazel_dep(name = "rules_xcodeproj", version = "1.7.0")
|
||||
bazel_dep(name = "sourcekitten", version = "0.34.1", repo_name = "com_github_jpsim_sourcekitten")
|
||||
bazel_dep(name = "swift_argument_parser", version = "1.2.1", repo_name = "sourcekitten_com_github_apple_swift_argument_parser")
|
||||
bazel_dep(name = "yams", version = "5.0.5", repo_name = "sourcekitten_com_github_jpsim_yams")
|
||||
|
||||
swiftlint_repos = use_extension("//bazel:repos.bzl", "swiftlint_repos_bzlmod")
|
||||
use_repo(
|
||||
swiftlint_repos,
|
||||
"SwiftSyntax",
|
||||
"com_github_johnsundell_collectionconcurrencykit",
|
||||
"com_github_krzyzanowskim_cryptoswift",
|
||||
"swiftlint_com_github_scottrhoyt_swifty_text_table",
|
||||
)
|
||||
|
||||
extra_rules = use_extension("//bazel:extensions.bzl", "extra_rules")
|
||||
use_repo(extra_rules, "swiftlint_extra_rules")
|
189
Makefile
189
Makefile
|
@ -2,21 +2,14 @@ TEMPORARY_FOLDER?=/tmp/SwiftLint.dst
|
|||
PREFIX?=/usr/local
|
||||
BUILD_TOOL?=xcodebuild
|
||||
|
||||
XCODEFLAGS=-scheme 'swiftlint' \
|
||||
XCODEFLAGS=-workspace 'SwiftLint.xcworkspace' \
|
||||
-scheme 'swiftlint' \
|
||||
DSTROOT=$(TEMPORARY_FOLDER) \
|
||||
OTHER_LDFLAGS=-Wl,-headerpad_max_install_names
|
||||
|
||||
SWIFT_BUILD_FLAGS=--configuration release -Xlinker -dead_strip
|
||||
|
||||
SWIFTLINT_EXECUTABLE_PARENT=.build/universal
|
||||
SWIFTLINT_EXECUTABLE=$(SWIFTLINT_EXECUTABLE_PARENT)/swiftlint
|
||||
|
||||
ARTIFACT_BUNDLE_PATH=$(TEMPORARY_FOLDER)/SwiftLintBinary.artifactbundle
|
||||
|
||||
TSAN_LIB=$(subst bin/swift,lib/swift/clang/lib/darwin/libclang_rt.tsan_osx_dynamic.dylib,$(shell xcrun --find swift))
|
||||
TSAN_SWIFT_BUILD_FLAGS=-Xswiftc -sanitize=thread
|
||||
TSAN_TEST_BUNDLE=$(shell swift build $(TSAN_SWIFT_BUILD_FLAGS) --show-bin-path)/SwiftLintPackageTests.xctest
|
||||
TSAN_XCTEST=$(shell xcrun --find xctest)
|
||||
BUILT_BUNDLE=$(TEMPORARY_FOLDER)/Applications/swiftlint.app
|
||||
SWIFTLINTFRAMEWORK_BUNDLE=$(BUILT_BUNDLE)/Contents/Frameworks/SwiftLintFramework.framework
|
||||
SWIFTLINT_EXECUTABLE=$(BUILT_BUNDLE)/Contents/MacOS/swiftlint
|
||||
|
||||
FRAMEWORKS_FOLDER=/Library/Frameworks
|
||||
BINARIES_FOLDER=/usr/local/bin
|
||||
|
@ -24,169 +17,109 @@ LICENSE_PATH="$(shell pwd)/LICENSE"
|
|||
|
||||
OUTPUT_PACKAGE=SwiftLint.pkg
|
||||
|
||||
VERSION_STRING=$(shell ./tools/get-version)
|
||||
COMPONENTS_PLIST=Source/swiftlint/Supporting Files/Components.plist
|
||||
SWIFTLINT_PLIST=Source/swiftlint/Supporting Files/Info.plist
|
||||
SWIFTLINTFRAMEWORK_PLIST=Source/SwiftLintFramework/Supporting Files/Info.plist
|
||||
|
||||
.PHONY: all clean build install package test uninstall docs
|
||||
VERSION_STRING=$(shell /usr/libexec/PlistBuddy -c "Print :CFBundleShortVersionString" "$(SWIFTLINT_PLIST)")
|
||||
|
||||
all: build
|
||||
.PHONY: all bootstrap clean install package test uninstall
|
||||
|
||||
sourcery: Source/SwiftLintBuiltInRules/Models/BuiltInRules.swift Source/SwiftLintCore/Models/ReportersList.swift Tests/GeneratedTests/GeneratedTests.swift
|
||||
all: bootstrap
|
||||
$(BUILD_TOOL) $(XCODEFLAGS) build
|
||||
|
||||
Source/SwiftLintBuiltInRules/Models/BuiltInRules.swift: Source/SwiftLintBuiltInRules/Rules/**/*.swift .sourcery/BuiltInRules.stencil
|
||||
./tools/sourcery --sources Source/SwiftLintBuiltInRules/Rules --templates .sourcery/BuiltInRules.stencil --output .sourcery
|
||||
mv .sourcery/BuiltInRules.generated.swift Source/SwiftLintBuiltInRules/Models/BuiltInRules.swift
|
||||
bootstrap:
|
||||
script/bootstrap
|
||||
|
||||
Source/SwiftLintCore/Models/ReportersList.swift: Source/SwiftLintCore/Reporters/*.swift .sourcery/ReportersList.stencil
|
||||
./tools/sourcery --sources Source/SwiftLintCore/Reporters --templates .sourcery/ReportersList.stencil --output .sourcery
|
||||
mv .sourcery/ReportersList.generated.swift Source/SwiftLintCore/Models/ReportersList.swift
|
||||
|
||||
Tests/GeneratedTests/GeneratedTests.swift: Source/SwiftLint*/Rules/**/*.swift .sourcery/GeneratedTests.stencil
|
||||
./tools/sourcery --sources Source/SwiftLintCore/Rules --sources Source/SwiftLintBuiltInRules/Rules --templates .sourcery/GeneratedTests.stencil --output .sourcery
|
||||
mv .sourcery/GeneratedTests.generated.swift Tests/GeneratedTests/GeneratedTests.swift
|
||||
|
||||
test: clean_xcode
|
||||
test: clean bootstrap
|
||||
$(BUILD_TOOL) $(XCODEFLAGS) test
|
||||
|
||||
test_tsan:
|
||||
swift build --build-tests $(TSAN_SWIFT_BUILD_FLAGS)
|
||||
DYLD_INSERT_LIBRARIES=$(TSAN_LIB) $(TSAN_XCTEST) $(TSAN_TEST_BUNDLE)
|
||||
|
||||
write_xcodebuild_log:
|
||||
xcodebuild -scheme swiftlint clean build-for-testing -destination "platform=macOS" > xcodebuild.log
|
||||
|
||||
analyze: write_xcodebuild_log
|
||||
swift run -c release swiftlint analyze --strict --compiler-log-path xcodebuild.log
|
||||
|
||||
analyze_autocorrect: write_xcodebuild_log
|
||||
swift run -c release swiftlint analyze --autocorrect --compiler-log-path xcodebuild.log
|
||||
|
||||
clean:
|
||||
rm -f "$(OUTPUT_PACKAGE)"
|
||||
rm -rf "$(TEMPORARY_FOLDER)"
|
||||
rm -f "./*.zip" "bazel.tar.gz" "bazel.tar.gz.sha256"
|
||||
swift package clean
|
||||
|
||||
clean_xcode:
|
||||
$(BUILD_TOOL) $(XCODEFLAGS) -configuration Debug clean
|
||||
$(BUILD_TOOL) $(XCODEFLAGS) -configuration Release clean
|
||||
$(BUILD_TOOL) $(XCODEFLAGS) -configuration Test clean
|
||||
|
||||
build:
|
||||
mkdir -p "$(SWIFTLINT_EXECUTABLE_PARENT)"
|
||||
bazel build --config release universal_swiftlint
|
||||
$(eval SWIFTLINT_BINARY := $(shell bazel cquery --config release --output=files universal_swiftlint))
|
||||
mv "$(SWIFTLINT_BINARY)" "$(SWIFTLINT_EXECUTABLE)"
|
||||
chmod +w "$(SWIFTLINT_EXECUTABLE)"
|
||||
strip -rSTX "$(SWIFTLINT_EXECUTABLE)"
|
||||
|
||||
build_with_disable_sandbox:
|
||||
swift build --disable-sandbox $(SWIFT_BUILD_FLAGS)
|
||||
|
||||
install: build
|
||||
install -d "$(BINARIES_FOLDER)"
|
||||
install "$(SWIFTLINT_EXECUTABLE)" "$(BINARIES_FOLDER)"
|
||||
install: uninstall package
|
||||
sudo installer -pkg SwiftLint.pkg -target /
|
||||
|
||||
uninstall:
|
||||
rm -rf "$(FRAMEWORKS_FOLDER)/SwiftLintFramework.framework"
|
||||
rm -f "$(BINARIES_FOLDER)/swiftlint"
|
||||
|
||||
installables: build
|
||||
install -d "$(TEMPORARY_FOLDER)$(BINARIES_FOLDER)"
|
||||
install "$(SWIFTLINT_EXECUTABLE)" "$(TEMPORARY_FOLDER)$(BINARIES_FOLDER)"
|
||||
installables: clean bootstrap
|
||||
$(BUILD_TOOL) $(XCODEFLAGS) -configuration Release install
|
||||
|
||||
prefix_install: build_with_disable_sandbox
|
||||
install -d "$(PREFIX)/bin/"
|
||||
install "$(SWIFTLINT_EXECUTABLE)" "$(PREFIX)/bin/"
|
||||
mkdir -p "$(TEMPORARY_FOLDER)$(FRAMEWORKS_FOLDER)" "$(TEMPORARY_FOLDER)$(BINARIES_FOLDER)"
|
||||
mv -f "$(SWIFTLINTFRAMEWORK_BUNDLE)" "$(TEMPORARY_FOLDER)$(FRAMEWORKS_FOLDER)/SwiftLintFramework.framework"
|
||||
mv -f "$(SWIFTLINT_EXECUTABLE)" "$(TEMPORARY_FOLDER)$(BINARIES_FOLDER)/swiftlint"
|
||||
rm -rf "$(BUILT_BUNDLE)"
|
||||
install_name_tool -delete_rpath "@executable_path/../Frameworks/SwiftLintFramework.framework/Versions/Current/Frameworks" "$(TEMPORARY_FOLDER)$(BINARIES_FOLDER)/swiftlint"
|
||||
|
||||
prefix_install: installables
|
||||
mkdir -p "$(PREFIX)/Frameworks" "$(PREFIX)/bin"
|
||||
cp -Rf "$(TEMPORARY_FOLDER)$(FRAMEWORKS_FOLDER)/SwiftLintFramework.framework" "$(PREFIX)/Frameworks/"
|
||||
cp -f "$(TEMPORARY_FOLDER)$(BINARIES_FOLDER)/swiftlint" "$(PREFIX)/bin/"
|
||||
install_name_tool -rpath "/Library/Frameworks/SwiftLintFramework.framework/Versions/Current/Frameworks" "@executable_path/../Frameworks/SwiftLintFramework.framework/Versions/Current/Frameworks" "$(PREFIX)/bin/swiftlint"
|
||||
install_name_tool -rpath "/Library/Frameworks" "@executable_path/../Frameworks" "$(PREFIX)/bin/swiftlint"
|
||||
|
||||
portable_zip: installables
|
||||
cp -Rf "$(TEMPORARY_FOLDER)$(FRAMEWORKS_FOLDER)/SwiftLintFramework.framework" "$(TEMPORARY_FOLDER)"
|
||||
cp -f "$(TEMPORARY_FOLDER)$(BINARIES_FOLDER)/swiftlint" "$(TEMPORARY_FOLDER)"
|
||||
install_name_tool -rpath "/Library/Frameworks/SwiftLintFramework.framework/Versions/Current/Frameworks" "@executable_path/SwiftLintFramework.framework/Versions/Current/Frameworks" "$(TEMPORARY_FOLDER)/swiftlint"
|
||||
install_name_tool -rpath "/Library/Frameworks" "@executable_path" "$(TEMPORARY_FOLDER)/swiftlint"
|
||||
rm -f "./portable_swiftlint.zip"
|
||||
cp -f "$(LICENSE_PATH)" "$(TEMPORARY_FOLDER)"
|
||||
(cd "$(TEMPORARY_FOLDER)"; zip -yr - "swiftlint" "LICENSE") > "./portable_swiftlint.zip"
|
||||
(cd "$(TEMPORARY_FOLDER)"; zip -yr - "swiftlint" "SwiftLintFramework.framework" "LICENSE") > "./portable_swiftlint.zip"
|
||||
|
||||
spm_artifactbundle_macos: installables
|
||||
mkdir -p "$(ARTIFACT_BUNDLE_PATH)/swiftlint-$(VERSION_STRING)-macos/bin"
|
||||
sed 's/__VERSION__/$(VERSION_STRING)/g' tools/info-macos.json.template > "$(ARTIFACT_BUNDLE_PATH)/info.json"
|
||||
cp -f "$(SWIFTLINT_EXECUTABLE)" "$(ARTIFACT_BUNDLE_PATH)/swiftlint-$(VERSION_STRING)-macos/bin"
|
||||
cp -f "$(LICENSE_PATH)" "$(ARTIFACT_BUNDLE_PATH)"
|
||||
(cd "$(TEMPORARY_FOLDER)"; zip -yr - "SwiftLintBinary.artifactbundle") > "./SwiftLintBinary-macos.artifactbundle.zip"
|
||||
|
||||
zip_linux: docker_image
|
||||
$(eval TMP_FOLDER := $(shell mktemp -d))
|
||||
docker run swiftlint cat /usr/bin/swiftlint > "$(TMP_FOLDER)/swiftlint"
|
||||
chmod +x "$(TMP_FOLDER)/swiftlint"
|
||||
cp -f "$(LICENSE_PATH)" "$(TMP_FOLDER)"
|
||||
(cd "$(TMP_FOLDER)"; zip -yr - "swiftlint" "LICENSE") > "./swiftlint_linux.zip"
|
||||
|
||||
zip_linux_release:
|
||||
$(eval TMP_FOLDER := $(shell mktemp -d))
|
||||
docker run --platform linux/amd64 "ghcr.io/realm/swiftlint:$(VERSION_STRING)" cat /usr/bin/swiftlint > "$(TMP_FOLDER)/swiftlint"
|
||||
chmod +x "$(TMP_FOLDER)/swiftlint"
|
||||
cp -f "$(LICENSE_PATH)" "$(TMP_FOLDER)"
|
||||
(cd "$(TMP_FOLDER)"; zip -yr - "swiftlint" "LICENSE") > "./swiftlint_linux.zip"
|
||||
gh release upload "$(VERSION_STRING)" swiftlint_linux.zip
|
||||
|
||||
package: build
|
||||
$(eval PACKAGE_ROOT := $(shell mktemp -d))
|
||||
cp "$(SWIFTLINT_EXECUTABLE)" "$(PACKAGE_ROOT)"
|
||||
package: installables
|
||||
pkgbuild \
|
||||
--component-plist "$(COMPONENTS_PLIST)" \
|
||||
--identifier "io.realm.swiftlint" \
|
||||
--install-location "/usr/local/bin" \
|
||||
--root "$(PACKAGE_ROOT)" \
|
||||
--install-location "/" \
|
||||
--root "$(TEMPORARY_FOLDER)" \
|
||||
--version "$(VERSION_STRING)" \
|
||||
"$(OUTPUT_PACKAGE)"
|
||||
|
||||
bazel_release:
|
||||
bazel build :release
|
||||
mv bazel-bin/bazel.tar.gz bazel-bin/bazel.tar.gz.sha256 .
|
||||
archive:
|
||||
carthage build --no-skip-current --platform mac
|
||||
carthage archive SwiftLintFramework
|
||||
|
||||
docker_image:
|
||||
docker build --platform linux/amd64 --force-rm --tag swiftlint .
|
||||
release: package archive portable_zip
|
||||
|
||||
docker_test:
|
||||
docker run -v `pwd`:`pwd` -w `pwd` --name swiftlint --rm swift:5.7-focal swift test --parallel
|
||||
docker run -v `pwd`:`pwd` -w `pwd` --name swiftlint --rm norionomura/sourcekit:311 swift test
|
||||
|
||||
docker_test_4:
|
||||
docker run -v `pwd`:`pwd` -w `pwd` --name swiftlint --rm norionomura/swift:4020170524a swift test
|
||||
|
||||
docker_htop:
|
||||
docker run --platform linux/amd64 -it --rm --pid=container:swiftlint terencewestphal/htop || reset
|
||||
docker run -it --rm --pid=container:swiftlint terencewestphal/htop || reset
|
||||
|
||||
# https://irace.me/swift-profiling
|
||||
# http://irace.me/swift-profiling/
|
||||
display_compilation_time:
|
||||
$(BUILD_TOOL) $(XCODEFLAGS) OTHER_SWIFT_FLAGS="-Xfrontend -debug-time-function-bodies" clean build-for-testing | grep -E ^[1-9]{1}[0-9]*.[0-9]+ms | sort -n
|
||||
|
||||
publish:
|
||||
brew update && brew bump-formula-pr --tag=$(shell git describe --tags) --revision=$(shell git rev-parse HEAD) swiftlint
|
||||
bundle install
|
||||
bundle exec pod trunk push SwiftLint.podspec
|
||||
|
||||
docs:
|
||||
swift run swiftlint generate-docs
|
||||
bundle install
|
||||
bundle exec jazzy
|
||||
pod trunk push SwiftLintFramework.podspec
|
||||
pod trunk push SwiftLint.podspec
|
||||
|
||||
get_version:
|
||||
@echo "$(VERSION_STRING)"
|
||||
@echo $(VERSION_STRING)
|
||||
|
||||
release:
|
||||
ifneq ($(strip $(shell git status --untracked-files=no --porcelain 2>/dev/null)),)
|
||||
$(error git state is not clean)
|
||||
endif
|
||||
push_version:
|
||||
$(eval NEW_VERSION_AND_NAME := $(filter-out $@,$(MAKECMDGOALS)))
|
||||
$(eval NEW_VERSION := $(shell echo $(NEW_VERSION_AND_NAME) | sed 's/:.*//' ))
|
||||
@sed -i '' 's/## Main/## $(NEW_VERSION_AND_NAME)/g' CHANGELOG.md
|
||||
@sed 's/__VERSION__/$(NEW_VERSION)/g' tools/Version.swift.template > Source/SwiftLintCore/Models/Version.swift
|
||||
@sed -e '3s/.*/ version = "$(NEW_VERSION)",/' -i '' MODULE.bazel
|
||||
make clean
|
||||
make package
|
||||
make bazel_release
|
||||
make portable_zip
|
||||
make spm_artifactbundle_macos
|
||||
./tools/update-artifact-bundle.sh "$(NEW_VERSION)"
|
||||
@sed -i '' 's/## Master/## $(NEW_VERSION_AND_NAME)/g' CHANGELOG.md
|
||||
@sed 's/__VERSION__/$(NEW_VERSION)/g' script/Version.swift.template > Source/SwiftLintFramework/Models/Version.swift
|
||||
@/usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString $(NEW_VERSION)" "$(SWIFTLINTFRAMEWORK_PLIST)"
|
||||
@/usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString $(NEW_VERSION)" "$(SWIFTLINT_PLIST)"
|
||||
git commit -a -m "release $(NEW_VERSION)"
|
||||
git tag -a $(NEW_VERSION) -m "$(NEW_VERSION_AND_NAME)"
|
||||
git push origin HEAD
|
||||
git push origin master
|
||||
git push origin $(NEW_VERSION)
|
||||
./tools/create-github-release.sh "$(NEW_VERSION)"
|
||||
make publish
|
||||
./tools/add-new-changelog-section.sh
|
||||
git commit -a -m "Add new changelog section"
|
||||
git push origin HEAD
|
||||
|
||||
%:
|
||||
@:
|
||||
|
|
150
Package.resolved
150
Package.resolved
|
@ -1,77 +1,79 @@
|
|||
{
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "collectionconcurrencykit",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/JohnSundell/CollectionConcurrencyKit.git",
|
||||
"state" : {
|
||||
"revision" : "b4f23e24b5a1bff301efc5e70871083ca029ff95",
|
||||
"version" : "0.2.0"
|
||||
"object": {
|
||||
"pins": [
|
||||
{
|
||||
"package": "Clang_C",
|
||||
"repositoryURL": "https://github.com/norio-nomura/Clang_C.git",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "90a9574276f0fd17f02f58979423c3fd4d73b59e",
|
||||
"version": "1.0.2"
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "Commandant",
|
||||
"repositoryURL": "https://github.com/Carthage/Commandant.git",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "c281992c31c3f41c48b5036c5a38185eaec32626",
|
||||
"version": "0.12.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "Result",
|
||||
"repositoryURL": "https://github.com/antitypical/Result.git",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "c8446185238659a2b27c0261f64ff1254291d07d",
|
||||
"version": "3.2.3"
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "SourceKit",
|
||||
"repositoryURL": "https://github.com/norio-nomura/SourceKit.git",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "18eaa67ca44443bbe39646916792b9f0c98dbaa1",
|
||||
"version": "1.0.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "SourceKitten",
|
||||
"repositoryURL": "https://github.com/jpsim/SourceKitten.git",
|
||||
"state": {
|
||||
"branch": "jp-swift-4",
|
||||
"revision": "6632fb43284436ab77c709fb4c8c5e55de42f6f5",
|
||||
"version": null
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "SwiftyTextTable",
|
||||
"repositoryURL": "https://github.com/jpsim/SwiftyTextTable.git",
|
||||
"state": {
|
||||
"branch": "jp-swift-4",
|
||||
"revision": "15f72002eea8e3b446d104d18225b6a828218d32",
|
||||
"version": null
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "SWXMLHash",
|
||||
"repositoryURL": "https://github.com/drmohundro/SWXMLHash.git",
|
||||
"state": {
|
||||
"branch": "version-4.0-changes",
|
||||
"revision": "4cb1b72d406b4309aed6e6b2f11f46aa83dacbf7",
|
||||
"version": null
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "Yams",
|
||||
"repositoryURL": "https://github.com/jpsim/Yams.git",
|
||||
"state": {
|
||||
"branch": "master",
|
||||
"revision": "b53284ba4c8bdece9ec8aad2e0010602dac588e9",
|
||||
"version": null
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "cryptoswift",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/krzyzanowskim/CryptoSwift.git",
|
||||
"state" : {
|
||||
"revision" : "32f641cf24fc7abc1c591a2025e9f2f572648b0f",
|
||||
"version" : "1.7.2"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "sourcekitten",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/jpsim/SourceKitten.git",
|
||||
"state" : {
|
||||
"revision" : "b6dc09ee51dfb0c66e042d2328c017483a1a5d56",
|
||||
"version" : "0.34.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swift-argument-parser",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/apple/swift-argument-parser.git",
|
||||
"state" : {
|
||||
"revision" : "4ad606ba5d7673ea60679a61ff867cc1ff8c8e86",
|
||||
"version" : "1.2.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swift-syntax",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/apple/swift-syntax.git",
|
||||
"state" : {
|
||||
"revision" : "165fc6d22394c1168ff76ab5d951245971ef07e5",
|
||||
"version" : "509.0.0-swift-DEVELOPMENT-SNAPSHOT-2023-06-05-a"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swiftytexttable",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/scottrhoyt/SwiftyTextTable.git",
|
||||
"state" : {
|
||||
"revision" : "c6df6cf533d120716bff38f8ff9885e1ce2a4ac3",
|
||||
"version" : "0.9.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swxmlhash",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/drmohundro/SWXMLHash.git",
|
||||
"state" : {
|
||||
"revision" : "4d0f62f561458cbe1f732171e625f03195151b60",
|
||||
"version" : "7.0.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "yams",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/jpsim/Yams.git",
|
||||
"state" : {
|
||||
"revision" : "f47ba4838c30dbd59998a4e4c87ab620ff959e8a",
|
||||
"version" : "5.0.5"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 2
|
||||
]
|
||||
},
|
||||
"version": 1
|
||||
}
|
||||
|
|
152
Package.swift
152
Package.swift
|
@ -1,121 +1,39 @@
|
|||
// swift-tools-version:5.7
|
||||
// swift-tools-version:4.0
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "SwiftLint",
|
||||
platforms: [.macOS(.v12)],
|
||||
products: [
|
||||
.executable(name: "swiftlint", targets: ["swiftlint"]),
|
||||
.library(name: "SwiftLintFramework", targets: ["SwiftLintFramework"]),
|
||||
.plugin(name: "SwiftLintPlugin", targets: ["SwiftLintPlugin"])
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-argument-parser.git", .upToNextMinor(from: "1.2.1")),
|
||||
.package(url: "https://github.com/apple/swift-syntax.git", exact: "509.0.0-swift-DEVELOPMENT-SNAPSHOT-2023-06-05-a"),
|
||||
.package(url: "https://github.com/jpsim/SourceKitten.git", .upToNextMinor(from: "0.34.1")),
|
||||
.package(url: "https://github.com/jpsim/Yams.git", from: "5.0.5"),
|
||||
.package(url: "https://github.com/scottrhoyt/SwiftyTextTable.git", from: "0.9.0"),
|
||||
.package(url: "https://github.com/JohnSundell/CollectionConcurrencyKit.git", from: "0.2.0"),
|
||||
.package(url: "https://github.com/krzyzanowskim/CryptoSwift.git", .upToNextMinor(from: "1.7.2"))
|
||||
],
|
||||
targets: [
|
||||
.plugin(
|
||||
name: "SwiftLintPlugin",
|
||||
capability: .buildTool(),
|
||||
dependencies: [
|
||||
.target(name: "SwiftLintBinary", condition: .when(platforms: [.macOS])),
|
||||
.target(name: "swiftlint", condition: .when(platforms: [.linux]))
|
||||
]
|
||||
),
|
||||
.executableTarget(
|
||||
name: "swiftlint",
|
||||
dependencies: [
|
||||
.product(name: "ArgumentParser", package: "swift-argument-parser"),
|
||||
"CollectionConcurrencyKit",
|
||||
"SwiftLintFramework",
|
||||
"SwiftyTextTable",
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "CLITests",
|
||||
dependencies: [
|
||||
"swiftlint"
|
||||
]
|
||||
),
|
||||
.target(
|
||||
name: "SwiftLintCore",
|
||||
dependencies: [
|
||||
.product(name: "CryptoSwift", package: "CryptoSwift", condition: .when(platforms: [.linux])),
|
||||
.target(name: "DyldWarningWorkaround", condition: .when(platforms: [.macOS])),
|
||||
.product(name: "SourceKittenFramework", package: "SourceKitten"),
|
||||
.product(name: "SwiftIDEUtils", package: "swift-syntax"),
|
||||
.product(name: "SwiftOperators", package: "swift-syntax"),
|
||||
.product(name: "SwiftParser", package: "swift-syntax"),
|
||||
.product(name: "SwiftSyntax", package: "swift-syntax"),
|
||||
.product(name: "SwiftSyntaxBuilder", package: "swift-syntax"),
|
||||
.product(name: "SwiftyTextTable", package: "SwiftyTextTable"),
|
||||
.product(name: "Yams", package: "Yams"),
|
||||
]
|
||||
),
|
||||
.target(
|
||||
name: "SwiftLintBuiltInRules",
|
||||
dependencies: ["SwiftLintCore"]
|
||||
),
|
||||
.target(
|
||||
name: "SwiftLintExtraRules",
|
||||
dependencies: ["SwiftLintCore"]
|
||||
),
|
||||
.target(
|
||||
name: "SwiftLintFramework",
|
||||
dependencies: [
|
||||
"SwiftLintBuiltInRules",
|
||||
"SwiftLintCore",
|
||||
"SwiftLintExtraRules"
|
||||
]
|
||||
),
|
||||
.target(name: "DyldWarningWorkaround"),
|
||||
.target(
|
||||
name: "SwiftLintTestHelpers",
|
||||
dependencies: [
|
||||
"SwiftLintFramework"
|
||||
],
|
||||
path: "Tests/SwiftLintTestHelpers"
|
||||
),
|
||||
.testTarget(
|
||||
name: "SwiftLintFrameworkTests",
|
||||
dependencies: [
|
||||
"SwiftLintFramework",
|
||||
"SwiftLintTestHelpers"
|
||||
],
|
||||
exclude: [
|
||||
"Resources",
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "GeneratedTests",
|
||||
dependencies: [
|
||||
"SwiftLintFramework",
|
||||
"SwiftLintTestHelpers"
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "IntegrationTests",
|
||||
dependencies: [
|
||||
"SwiftLintFramework",
|
||||
"SwiftLintTestHelpers"
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "ExtraRulesTests",
|
||||
dependencies: [
|
||||
"SwiftLintFramework",
|
||||
"SwiftLintTestHelpers"
|
||||
]
|
||||
),
|
||||
.binaryTarget(
|
||||
name: "SwiftLintBinary",
|
||||
url: "https://github.com/realm/SwiftLint/releases/download/0.52.2/SwiftLintBinary-macos.artifactbundle.zip",
|
||||
checksum: "89651e1c87fb62faf076ef785a5b1af7f43570b2b74c6773526e0d5114e0578e"
|
||||
)
|
||||
]
|
||||
name: "SwiftLint",
|
||||
products: [
|
||||
.executable(name: "swiftlint", targets: ["swiftlint"]),
|
||||
.library(name: "SwiftLintFramework", targets: ["SwiftLintFramework"])
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/Carthage/Commandant.git", from: "0.12.0"),
|
||||
.package(url: "https://github.com/jpsim/Yams.git", .branch("master")),
|
||||
.package(url: "https://github.com/jpsim/SourceKitten.git", .branch("jp-swift-4")),
|
||||
.package(url: "https://github.com/jpsim/SwiftyTextTable.git", .branch("jp-swift-4")),
|
||||
],
|
||||
targets: [
|
||||
.target(
|
||||
name: "swiftlint",
|
||||
dependencies: [
|
||||
"Commandant",
|
||||
"SwiftLintFramework",
|
||||
"SwiftyTextTable"
|
||||
]
|
||||
),
|
||||
.target(
|
||||
name: "SwiftLintFramework",
|
||||
dependencies: [
|
||||
"SourceKittenFramework"
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "SwiftLintFrameworkTests",
|
||||
dependencies: [
|
||||
"SwiftLintFramework"
|
||||
]
|
||||
)
|
||||
],
|
||||
swiftLanguageVersions: [3, 4]
|
||||
)
|
||||
|
|
|
@ -1,42 +0,0 @@
|
|||
import Foundation
|
||||
import PackagePlugin
|
||||
|
||||
#if os(Linux)
|
||||
import Glibc
|
||||
#else
|
||||
import Darwin
|
||||
#endif
|
||||
|
||||
extension Path {
|
||||
/// Scans the receiver, then all of its parents looking for a configuration file with the name ".swiftlint.yml".
|
||||
///
|
||||
/// - returns: Path to the configuration file, or nil if one cannot be found.
|
||||
func firstConfigurationFileInParentDirectories() -> Path? {
|
||||
let defaultConfigurationFileName = ".swiftlint.yml"
|
||||
let proposedDirectory = sequence(
|
||||
first: self,
|
||||
next: { path in
|
||||
guard path.stem.count > 1 else {
|
||||
// Check we're not at the root of this filesystem, as `removingLastComponent()`
|
||||
// will continually return the root from itself.
|
||||
return nil
|
||||
}
|
||||
|
||||
return path.removingLastComponent()
|
||||
}
|
||||
).first { path in
|
||||
let potentialConfigurationFile = path.appending(subpath: defaultConfigurationFileName)
|
||||
return potentialConfigurationFile.isAccessible()
|
||||
}
|
||||
return proposedDirectory?.appending(subpath: defaultConfigurationFileName)
|
||||
}
|
||||
|
||||
/// Safe way to check if the file is accessible from within the current process sandbox.
|
||||
private func isAccessible() -> Bool {
|
||||
let result = string.withCString { pointer in
|
||||
access(pointer, R_OK)
|
||||
}
|
||||
|
||||
return result == 0
|
||||
}
|
||||
}
|
|
@ -1,76 +0,0 @@
|
|||
import Foundation
|
||||
import PackagePlugin
|
||||
|
||||
@main
|
||||
struct SwiftLintPlugin: BuildToolPlugin {
|
||||
func createBuildCommands(context: PluginContext, target: Target) async throws -> [Command] {
|
||||
guard let sourceTarget = target as? SourceModuleTarget else {
|
||||
return []
|
||||
}
|
||||
return createBuildCommands(
|
||||
inputFiles: sourceTarget.sourceFiles(withSuffix: "swift").map(\.path),
|
||||
packageDirectory: context.package.directory,
|
||||
workingDirectory: context.pluginWorkDirectory,
|
||||
tool: try context.tool(named: "swiftlint")
|
||||
)
|
||||
}
|
||||
|
||||
private func createBuildCommands(
|
||||
inputFiles: [Path],
|
||||
packageDirectory: Path,
|
||||
workingDirectory: Path,
|
||||
tool: PluginContext.Tool
|
||||
) -> [Command] {
|
||||
if inputFiles.isEmpty {
|
||||
// Don't lint anything if there are no Swift source files in this target
|
||||
return []
|
||||
}
|
||||
|
||||
var arguments = [
|
||||
"lint",
|
||||
"--quiet",
|
||||
// We always pass all of the Swift source files in the target to the tool,
|
||||
// so we need to ensure that any exclusion rules in the configuration are
|
||||
// respected.
|
||||
"--force-exclude",
|
||||
"--cache-path", "\(workingDirectory)"
|
||||
]
|
||||
|
||||
// Manually look for configuration files, to avoid issues when the plugin does not execute our tool from the
|
||||
// package source directory.
|
||||
if let configuration = packageDirectory.firstConfigurationFileInParentDirectories() {
|
||||
arguments.append(contentsOf: ["--config", "\(configuration.string)"])
|
||||
}
|
||||
arguments += inputFiles.map(\.string)
|
||||
|
||||
// We are not producing output files and this is needed only to not include cache files into bundle
|
||||
let outputFilesDirectory = workingDirectory.appending("Output")
|
||||
|
||||
return [
|
||||
.prebuildCommand(
|
||||
displayName: "SwiftLint",
|
||||
executable: tool.path,
|
||||
arguments: arguments,
|
||||
outputFilesDirectory: outputFilesDirectory
|
||||
)
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(XcodeProjectPlugin)
|
||||
import XcodeProjectPlugin
|
||||
|
||||
extension SwiftLintPlugin: XcodeBuildToolPlugin {
|
||||
func createBuildCommands(context: XcodePluginContext, target: XcodeTarget) throws -> [Command] {
|
||||
let inputFilePaths = target.inputFiles
|
||||
.filter { $0.type == .source && $0.path.extension == "swift" }
|
||||
.map(\.path)
|
||||
return createBuildCommands(
|
||||
inputFiles: inputFilePaths,
|
||||
packageDirectory: context.xcodeProject.directory,
|
||||
workingDirectory: context.pluginWorkDirectory,
|
||||
tool: try context.tool(named: "swiftlint")
|
||||
)
|
||||
}
|
||||
}
|
||||
#endif
|
589
README.md
589
README.md
|
@ -1,14 +1,15 @@
|
|||
# SwiftLint
|
||||
|
||||
A tool to enforce Swift style and conventions, loosely based on the now archived [GitHub Swift Style Guide](https://github.com/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](https://github.com/kodecocodes/swift-style-guide).
|
||||
A tool to enforce Swift style and conventions, loosely based on
|
||||
[GitHub's Swift Style Guide](https://github.com/github/swift-style-guide).
|
||||
|
||||
SwiftLint hooks into [Clang](http://clang.llvm.org) and
|
||||
[SourceKit](http://www.jpsim.com/uncovering-sourcekit) to use the
|
||||
[AST](http://clang.llvm.org/docs/IntroductionToTheClangAST.html) representation
|
||||
of your source files for more accurate results.
|
||||
|
||||
[](https://dev.azure.com/jpsim/SwiftLint/_build/latest?definitionId=4?branchName=main)
|
||||
[](https://codecov.io/github/realm/SwiftLint?branch=main)
|
||||

|
||||
[](https://codecov.io/github/realm/SwiftLint?branch=master)
|
||||
|
||||

|
||||
|
||||
|
@ -16,8 +17,6 @@ This project adheres to the [Contributor Covenant Code of Conduct](https://realm
|
|||
By participating, you are expected to uphold this code. Please report
|
||||
unacceptable behavior to [info@realm.io](mailto:info@realm.io).
|
||||
|
||||
> Language Switch: [中文](https://github.com/realm/SwiftLint/blob/main/README_CN.md), [한국어](https://github.com/realm/SwiftLint/blob/main/README_KR.md).
|
||||
|
||||
## Installation
|
||||
|
||||
### Using [Homebrew](http://brew.sh/):
|
||||
|
@ -41,93 +40,20 @@ in your Script Build Phases.
|
|||
This is the recommended way to install a specific version of SwiftLint since it supports
|
||||
installing a pinned version 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
|
||||
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.
|
||||
|
||||
### Using [Mint](https://github.com/yonaskolb/mint):
|
||||
|
||||
```
|
||||
$ mint install realm/SwiftLint
|
||||
```
|
||||
|
||||
### Using a pre-built package:
|
||||
|
||||
You can also install SwiftLint by downloading `SwiftLint.pkg` from the
|
||||
[latest GitHub release](https://github.com/realm/SwiftLint/releases/latest) and
|
||||
running it.
|
||||
|
||||
### Installing from source:
|
||||
### Compiling from source:
|
||||
|
||||
You can also build and install from source by cloning this project and running
|
||||
`make install` (Xcode 13.3 or later).
|
||||
|
||||
### Using Bazel
|
||||
|
||||
Put this in your `MODULE.bazel`:
|
||||
|
||||
```bzl
|
||||
bazel_dep(name = "swiftlint", version = "0.50.4", repo_name = "SwiftLint")
|
||||
```
|
||||
|
||||
Or put this in your `WORKSPACE`:
|
||||
|
||||
<details>
|
||||
|
||||
<summary>WORKSPACE</summary>
|
||||
|
||||
```bzl
|
||||
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()
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
Then you can run SwiftLint in the current directory with this command:
|
||||
|
||||
```console
|
||||
bazel run -c opt @SwiftLint//:swiftlint
|
||||
```
|
||||
You can also build from source by cloning this project and running
|
||||
`git submodule update --init --recursive; make install` (Xcode 8.0 or later).
|
||||
|
||||
## Usage
|
||||
|
||||
|
@ -136,195 +62,72 @@ bazel run -c opt @SwiftLint//:swiftlint
|
|||
To get a high-level overview of recommended ways to integrate SwiftLint into your project,
|
||||
we encourage you to watch this presentation or read the transcript:
|
||||
|
||||
[](https://youtu.be/9Z1nTMTejqU)
|
||||
[](https://realm.io/news/slug-jp-simard-swiftlint)
|
||||
|
||||
### Xcode
|
||||
|
||||
Integrate SwiftLint into your Xcode project to get warnings and errors displayed
|
||||
in the issue navigator.
|
||||
|
||||
To do this select the project in the file navigator, then select the primary app
|
||||
target, and go to Build Phases. Click the + and select "New Run Script Phase".
|
||||
Insert the following as the script:
|
||||
|
||||

|
||||
|
||||
If you installed SwiftLint via Homebrew on Apple Silicon, you might experience this warning:
|
||||
|
||||
> warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint
|
||||
|
||||
That 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
|
||||
Integrate SwiftLint into an Xcode scheme to get warnings and errors displayed
|
||||
in the IDE. Just add a new "Run Script Phase" with:
|
||||
|
||||
```bash
|
||||
if [[ "$(uname -m)" == arm64 ]]; then
|
||||
export PATH="/opt/homebrew/bin:$PATH"
|
||||
fi
|
||||
|
||||
if which swiftlint > /dev/null; then
|
||||
if which swiftlint >/dev/null; then
|
||||
swiftlint
|
||||
else
|
||||
echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"
|
||||
fi
|
||||
```
|
||||
|
||||
or you can create a symbolic link in `/usr/local/bin` pointing to the actual binary:
|
||||

|
||||
|
||||
```bash
|
||||
ln -s /opt/homebrew/bin/swiftlint /usr/local/bin/swiftlint
|
||||
```
|
||||
|
||||
You might want to move your SwiftLint phase directly before the 'Compile Sources'
|
||||
step to detect errors quickly before compiling. However, SwiftLint is designed
|
||||
to run on valid Swift code that cleanly completes the compiler's parsing stage.
|
||||
So running SwiftLint before 'Compile Sources' might yield some incorrect
|
||||
results.
|
||||
|
||||
If you wish to fix violations as well, your script could run
|
||||
`swiftlint --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:
|
||||
Alternatively, if you've installed SwiftLint via CocoaPods the script should look like this:
|
||||
|
||||
```bash
|
||||
"${PODS_ROOT}/SwiftLint/swiftlint"
|
||||
```
|
||||
|
||||
### Plug-in Support
|
||||
#### Format on Save Xcode Plugin
|
||||
|
||||
SwiftLint can be used as a build tool plug-in for both Xcode projects as well as
|
||||
Swift packages.
|
||||
To run `swiftlint autocorrect` on save in Xcode, install the
|
||||
[SwiftLintXcode](https://github.com/ypresto/SwiftLintXcode) plugin from Alcatraz.
|
||||
|
||||
> Due to limitations with Swift Package Manager Plug-ins this is only
|
||||
recommended for projects that have a SwiftLint configuration in their root directory as
|
||||
there is currently no way to pass any additional options to the SwiftLint executable.
|
||||
⚠ ️This plugin will not work with Xcode 8 without disabling SIP. This is not recommended.
|
||||
|
||||
#### Xcode
|
||||
### AppCode
|
||||
|
||||
You can integrate SwiftLint as an Xcode Build Tool Plug-in if you're working
|
||||
with a project in Xcode.
|
||||
To integrate SwiftLint with AppCode, install
|
||||
[this plugin](https://plugins.jetbrains.com/plugin/9175) and configure
|
||||
SwiftLint's installed path in the plugin's preferences.
|
||||
The `autocorrect` action is available via `⌥⏎`.
|
||||
|
||||
Add SwiftLint as a package dependency to your project without linking any of the
|
||||
products.
|
||||
### Atom
|
||||
|
||||
Select the target you want to add linting to and open the `Build Phases` inspector.
|
||||
Open `Run Build Tool Plug-ins` and select the `+` button.
|
||||
Select `SwiftLintPlugin` from the list and add it to the project.
|
||||
|
||||

|
||||
|
||||
For unattended use (e.g. on CI), you can disable the package validation dialog by
|
||||
|
||||
* individually passing `-skipPackagePluginValidation` to `xcodebuild` or
|
||||
* globally setting `defaults write com.apple.dt.Xcode IDESkipPackagePluginFingerprintValidatation -bool YES`
|
||||
for that user.
|
||||
|
||||
_Note: This implicitly trusts all Xcode package plugins and bypasses Xcode's package validation
|
||||
dialogs, which has security implications._
|
||||
|
||||
#### Swift Package
|
||||
|
||||
You can integrate SwiftLint as a Swift Package Manager Plug-in if you're working with
|
||||
a Swift Package with a `Package.swift` manifest.
|
||||
|
||||
Add SwiftLint as a package dependency to your `Package.swift` file.
|
||||
Add SwiftLint to a target using the `plugins` parameter.
|
||||
|
||||
```swift
|
||||
.target(
|
||||
...
|
||||
plugins: [.plugin(name: "SwiftLintPlugin", package: "SwiftLint")]
|
||||
),
|
||||
```
|
||||
|
||||
### Visual Studio Code
|
||||
|
||||
To integrate SwiftLint with [vscode](https://code.visualstudio.com), install the
|
||||
[`vscode-swiftlint`](https://marketplace.visualstudio.com/items?itemName=vknabel.vscode-swiftlint) extension from the marketplace.
|
||||
|
||||
### fastlane
|
||||
|
||||
You can use the [official swiftlint fastlane action](https://docs.fastlane.tools/actions/swiftlint) to run SwiftLint as part of your fastlane process.
|
||||
|
||||
```ruby
|
||||
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](https://www.docker.com/) image using `Ubuntu`.
|
||||
So just the first time you need to pull the docker image using the next command:
|
||||
```bash
|
||||
docker pull ghcr.io/realm/swiftlint:latest
|
||||
```
|
||||
|
||||
Then following times, you just run `swiftlint` inside of the docker like:
|
||||
```bash
|
||||
docker run -it -v `pwd`:`pwd` -w `pwd` ghcr.io/realm/swiftlint:latest
|
||||
```
|
||||
|
||||
This will execute `swiftlint` in the folder where you are right now (`pwd`), showing an output like:
|
||||
```bash
|
||||
$ 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](https://docs.docker.com/).
|
||||
To integrate SwiftLint with [Atom](https://atom.io/), install the
|
||||
[`linter-swiftlint`](https://atom.io/packages/linter-swiftlint) package from
|
||||
APM.
|
||||
|
||||
### Command Line
|
||||
|
||||
```
|
||||
$ swiftlint help
|
||||
OVERVIEW: A tool to enforce Swift style and conventions.
|
||||
Available commands:
|
||||
|
||||
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
|
||||
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.
|
||||
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
|
||||
```
|
||||
|
||||
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 the
|
||||
To specify a list of files when using `lint` or `autocorrect` (like the list of
|
||||
files modified by Xcode specified by the
|
||||
[`ExtraBuildPhase`](https://github.com/norio-nomura/ExtraBuildPhase) 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}`.
|
||||
`SCRIPT_INPUT_FILE_0`, `SCRIPT_INPUT_FILE_1`...`SCRIPT_INPUT_FILE_{SCRIPT_INPUT_FILE_COUNT}`.
|
||||
|
||||
These are same environment variables set for input files to
|
||||
[custom Xcode script phases](http://indiestack.com/2014/12/speeding-up-custom-script-phases/).
|
||||
|
@ -360,56 +163,26 @@ You may also set the `TOOLCHAINS` environment variable to the reverse-DNS
|
|||
notation that identifies a Swift toolchain version:
|
||||
|
||||
```shell
|
||||
$ TOOLCHAINS=com.apple.dt.toolchain.Swift_2_3 swiftlint --fix
|
||||
$ TOOLCHAINS=com.apple.dt.toolchain.Swift_2_3 swiftlint autocorrect
|
||||
```
|
||||
|
||||
On Linux, SourceKit is expected to be located in
|
||||
`/usr/lib/libsourcekitdInProc.so` or specified by the `LINUX_SOURCEKIT_LIB_PATH`
|
||||
environment variable.
|
||||
|
||||
### pre-commit
|
||||
|
||||
SwiftLint can be run as a [pre-commit](https://pre-commit.com/) hook.
|
||||
Once [installed](https://pre-commit.com/#install), add this to the
|
||||
`.pre-commit-config.yaml` in the root of your repository:
|
||||
|
||||
```yaml
|
||||
repos:
|
||||
- repo: https://github.com/realm/SwiftLint
|
||||
rev: 0.50.3
|
||||
hooks:
|
||||
- id: swiftlint
|
||||
```
|
||||
|
||||
Adjust `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:
|
||||
```yaml
|
||||
- repo: https://github.com/realm/SwiftLint
|
||||
rev: 0.50.3
|
||||
hooks:
|
||||
- id: swiftlint
|
||||
entry: swiftlint --fix --strict
|
||||
```
|
||||
|
||||
## Rules
|
||||
|
||||
Over 200 rules are included in SwiftLint and the Swift community (that's you!)
|
||||
Over 75 rules are included in SwiftLint and the Swift community (that's you!)
|
||||
continues to contribute more over time.
|
||||
[Pull requests](CONTRIBUTING.md) are encouraged.
|
||||
|
||||
You can find an updated list of rules and more information about them
|
||||
[here](https://realm.github.io/SwiftLint/rule-directory.html).
|
||||
|
||||
You can also check [Source/SwiftLintBuiltInRules/Rules](https://github.com/realm/SwiftLint/tree/main/Source/SwiftLintBuiltInRules/Rules)
|
||||
directory to see their implementation.
|
||||
|
||||
### Opt-In Rules
|
||||
See the [Source/SwiftLintFramework/Rules](Source/SwiftLintFramework/Rules)
|
||||
directory to see the currently implemented 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:
|
||||
Guidelines on when to implement a rule as opt-in:
|
||||
|
||||
* A rule that can have many false positives (e.g. `empty_count`)
|
||||
* A rule that is too slow
|
||||
|
@ -437,22 +210,6 @@ let noWarning :String = "" // No warning about colons immediately after variable
|
|||
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:
|
||||
|
||||
```swift
|
||||
// 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.
|
||||
|
@ -479,33 +236,20 @@ 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
|
||||
special `all` identifier will enable all opt in linter rules, except the ones
|
||||
listed in `disabled_rules`.
|
||||
* `only_rules`: Only the rules specified in this list will be enabled.
|
||||
Cannot be specified alongside `disabled_rules` or `opt_in_rules`.
|
||||
* `analyzer_rules`: This is an entirely separate list of rules that are only
|
||||
run by the `analyze` command. All analyzer rules are opt-in, so this is the
|
||||
only configurable rule list, there are no equivalents for `disabled_rules`
|
||||
`only_rules`.
|
||||
* `opt_in_rules`: Enable rules not from the default set.
|
||||
* `whitelist_rules`: Acts as a whitelist, only the rules specified in this list
|
||||
will be enabled. Can not be specified alongside `disabled_rules` or
|
||||
`opt_in_rules`.
|
||||
|
||||
```yaml
|
||||
# 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
|
||||
disabled_rules: # rule identifiers 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
|
||||
|
||||
opt_in_rules: # some rules are only opt-in
|
||||
- empty_count
|
||||
# Find all the available rules by running:
|
||||
# swiftlint rules
|
||||
included: # paths to include during linting. `--path` is ignored if present.
|
||||
- Source
|
||||
excluded: # paths to ignore during linting. Takes precedence over `included`.
|
||||
|
@ -513,10 +257,6 @@ excluded: # paths to ignore during linting. Takes precedence over `included`.
|
|||
- 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
|
||||
|
@ -542,7 +282,6 @@ type_name:
|
|||
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
|
||||
|
@ -550,50 +289,28 @@ identifier_name:
|
|||
- id
|
||||
- URL
|
||||
- GlobalAPIKey
|
||||
reporter: "xcode" # reporter type (xcode, json, csv, checkstyle, codeclimate, junit, html, emoji, sonarqube, markdown, github-actions-logging, summary)
|
||||
reporter: "xcode" # reporter type (xcode, json, csv, checkstyle, junit, html, emoji)
|
||||
```
|
||||
|
||||
You can also use environment variables in your configuration file,
|
||||
by using `${SOME_VARIABLE}` in a string.
|
||||
#### Defining Custom Rules
|
||||
|
||||
### 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](https://vimeo.com/820572803) or its associated code in
|
||||
[github.com/jpsim/swiftlint-bazel-example](https://github.com/jpsim/swiftlint-bazel-example).
|
||||
|
||||
#### 2. Regex Custom Rules
|
||||
|
||||
You can define custom regex-based rules in your configuration file using the
|
||||
You can define custom regex-based rules in you configuration file using the
|
||||
following syntax:
|
||||
|
||||
```yaml
|
||||
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
|
||||
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.
|
||||
regex: "([n,N]inja)" # matching pattern
|
||||
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)"
|
||||
regex: "([n,N]inja)"
|
||||
match_kinds: string
|
||||
```
|
||||
|
||||
|
@ -605,40 +322,38 @@ 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:
|
||||
|
||||
* `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`
|
||||
* 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](https://github.com/jpsim/SourceKitten). For example,
|
||||
`sourcekitten syntax --text "struct S {}"` delivers
|
||||
#### Nested Configurations
|
||||
|
||||
* `source.lang.swift.syntaxtype.keyword` for the `struct` keyword and
|
||||
* `source.lang.swift.syntaxtype.identifier` for its name `S`
|
||||
SwiftLint supports nesting configuration files for more granular control over
|
||||
the linting process.
|
||||
|
||||
which match to `keyword` and `identifier` in the above list.
|
||||
|
||||
If using custom rules in combination with `only_rules`, make sure to add
|
||||
`custom_rules` as an item under `only_rules`.
|
||||
|
||||
Unlike Swift custom rules, you can use official SwiftLint builds
|
||||
(e.g. from Homebrew) to run regex custom rules.
|
||||
* Include additional `.swiftlint.yml` files where necessary in your directory
|
||||
structure.
|
||||
* Each file will be linted using the configuration file that is in its
|
||||
directory or at the deepest level of its parent directories. Otherwise the
|
||||
root configuration will be used.
|
||||
* `excluded` and `included` are ignored for nested
|
||||
configurations.
|
||||
|
||||
### Auto-correct
|
||||
|
||||
|
@ -646,137 +361,12 @@ 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
|
||||
`swiftlint --fix`, otherwise important data may be lost.
|
||||
`swiftlint autocorrect`, 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
|
||||
|
||||
1. Cleaning DerivedData (incremental builds won't work with analyze)
|
||||
2. Running `xcodebuild -workspace {WORKSPACE}.xcworkspace -scheme {SCHEME} > xcodebuild.log`
|
||||
3. 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:
|
||||
|
||||
```yaml
|
||||
disabled_rules:
|
||||
- force_cast
|
||||
```
|
||||
|
||||
Project-Specific Configuration:
|
||||
|
||||
```yaml
|
||||
opt_in_rules:
|
||||
- force_cast
|
||||
```
|
||||
|
||||
### Child / 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 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 `.swiftlint.yml` should look like this:
|
||||
|
||||
```yaml
|
||||
child_config: .swiftlint_refinement.yml
|
||||
parent_config: Base/.swiftlint_base.yml
|
||||
```
|
||||
|
||||
When 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.
|
||||
|
||||
### 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:
|
||||
|
||||
```yaml
|
||||
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 `remote_timeout` / `remote_timeout_if_cached` specifiers.
|
||||
These values default to 2 / 1 second(s).
|
||||
|
||||
### 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
|
||||
that then get merged as a child config, but only with an effect for those files
|
||||
that are within the same directory as the config or in a deeper directory where
|
||||
there isn't another configuration file. In other words: Nested configurations don't work
|
||||
recursively – there's a maximum number of one nested configuration per file
|
||||
that may be applied 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
|
||||
|
||||
[MIT licensed.](LICENSE)
|
||||
|
@ -792,8 +382,3 @@ We :heart: open source software!
|
|||
See [our other open source projects](https://github.com/realm),
|
||||
read [our blog](https://realm.io/news), or say hi on twitter
|
||||
([@realm](https://twitter.com/realm)).
|
||||
|
||||
<img src="assets/macstadium.png" width="184" />
|
||||
|
||||
Our thanks to MacStadium for providing a Mac Mini to run our performance
|
||||
tests.
|
||||
|
|
160
README_CN.md
160
README_CN.md
|
@ -1,63 +1,31 @@
|
|||
# SwiftLint
|
||||
|
||||
SwiftLint 是一个用于强制检查 Swift 代码风格和规定的一个工具,基本上以 [Kodeco's Swift 代码风格指南](https://github.com/kodecocodes/swift-style-guide)为基础。
|
||||
SwiftLint 是一个用于强制检查 Swift 代码风格和规定的一个工具,基本上以 [GitHub's Swift 代码风格指南](https://github.com/github/swift-style-guide)为基础。
|
||||
|
||||
SwiftLint Hook 了 [Clang](http://clang.llvm.org) 和 [SourceKit](http://www.jpsim.com/uncovering-sourcekit) 从而能够使用 [AST](http://clang.llvm.org/docs/IntroductionToTheClangAST.html) 来表示源代码文件的更多精确结果。
|
||||
|
||||
[](https://dev.azure.com/jpsim/SwiftLint/_build/latest?definitionId=4?branchName=main)
|
||||
[](https://codecov.io/github/realm/SwiftLint?branch=main)
|
||||

|
||||
[](https://codecov.io/github/realm/SwiftLint?branch=master)
|
||||
|
||||

|
||||
|
||||
该项目遵守 [贡献者契约行为守则](https://realm.io/conduct)。一旦参与,你将被视为支持这一守则。请将
|
||||
不可接受的行为报告给 [info@realm.io](mailto:info@realm.io)。
|
||||
|
||||
## 安装
|
||||
|
||||
### 使用 [Homebrew](http://brew.sh/):
|
||||
使用 [Homebrew](http://brew.sh/)
|
||||
|
||||
```
|
||||
brew install swiftlint
|
||||
```
|
||||
|
||||
### 使用 [CocoaPods](https://cocoapods.org):
|
||||
你也可以通过从[最新的 GitHub 发布地址](https://github.com/realm/SwiftLint/releases/latest)下载`SwiftLint.pkg`然后执行的方式安装 SwiftLint。
|
||||
|
||||
将如下代码添加到你的 Podfile 即可:
|
||||
|
||||
```ruby
|
||||
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 发布地址](https://github.com/realm/SwiftLint/releases/latest)下载 `SwiftLint.pkg` 然后执行的方式安装 SwiftLint。
|
||||
|
||||
### 编译源代码:
|
||||
|
||||
你也可以通过 Clone SwiftLint 的 Git 仓库到本地然后执行 `make install` (Xcode 12.5+) 编译源代码的方式来安装。
|
||||
你也可以通过 Clone SwiftLint 的 Git 仓库到本地然后执行 `git submodule update --init --recursive; make install` (Xcode 7.1) 编译源代码的方式来安装。
|
||||
|
||||
## 用法
|
||||
|
||||
### 报告
|
||||
|
||||
我们鼓励您观看本次报告,来获得将 SwiftLint 整合到你的项目中的推荐方式的一个高层次概括:
|
||||
|
||||
[](https://academy.realm.io/posts/slug-jp-simard-swiftlint/)
|
||||
|
||||
### Xcode
|
||||
|
||||
整合 SwiftLint 到 Xcode 体系中去从而可以使警告和错误显示到 IDE 上,只需要在 Xcode 中添加一个新的“Run Script Phase”并且包含如下代码即可:
|
||||
整合 SwiftLint 到 Xcode 体系中去从而可以使警告和错误显示到 IDE 上,只需要在 Xcode 中添加一个新的"Run Script Phase"并且包含如下代码即可:
|
||||
|
||||
```bash
|
||||
if which swiftlint >/dev/null; then
|
||||
|
@ -69,47 +37,9 @@ fi
|
|||
|
||||

|
||||
|
||||
或者,脚本看起来应该像这样如果你已经通过 CocoaPods 安装了 SwiftLint:
|
||||
|
||||
```bash
|
||||
"${PODS_ROOT}/SwiftLint/swiftlint"
|
||||
```
|
||||
|
||||
#### 格式化保存 Xcode 插件
|
||||
|
||||
在 Xcode 中保存时执行 `swiftlint autocorrect`,需要从 Alcatraz 安装 [SwiftLintXcode](https://github.com/ypresto/SwiftLintXcode) 插件。
|
||||
|
||||
⚠ ️如果没有禁用 SIP 的话,这个插件在 Xcode 8 或者更新版本的 Xcode 上将不会工作。不推荐此操作。
|
||||
|
||||
### AppCode
|
||||
|
||||
在 AppCode 中使用 SwiftLint,安装[这个插件](https://plugins.jetbrains.com/plugin/9175)并且在插件设置中配置 SwiftLint 的安装路径即可。`autocorrect` 操作快捷键为 `⌥⏎`。
|
||||
|
||||
### Atom
|
||||
|
||||
整合 SwiftLint 到 [Atom](https://atom.io/) 需要从 APM 安装 [`linter-swiftlint`](https://atom.io/packages/linter-swiftlint) 包。
|
||||
|
||||
### fastlane
|
||||
|
||||
你可以用[fastlane官方的SwiftLint功能](https://docs.fastlane.tools/actions/swiftlint)来运行SwiftLint作为你的Fastlane程序的一部分
|
||||
|
||||
```ruby
|
||||
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)
|
||||
)
|
||||
```
|
||||
整合 SwiftLint 到 [Atom](https://atom.io/) 需要从 APM 安装[`linter-swiftlint`](https://atom.io/packages/linter-swiftlint)包。
|
||||
|
||||
### 命令行
|
||||
|
||||
|
@ -127,55 +57,17 @@ Available commands:
|
|||
在包含有需要执行代码分析的 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`](https://github.com/norio-nomura/ExtraBuildPhase) Xcode 插件修改的文件组成的列表,或者类似 Git 工作树中 `git ls-files -m` 命令显示的被修改的文件列表)。
|
||||
`SCRIPT_INPUT_FILE_0`, `SCRIPT_INPUT_FILE_1`... `SCRIPT_INPUT_FILE_{SCRIPT_INPUT_FILE_COUNT}` 的方式来指定一个文件列表(就像被 Xcode 特别是 [`ExtraBuildPhase`](https://github.com/norio-nomura/ExtraBuildPhase) Xcode 插件修改的文件组成的列表,或者类似 Git 工作树中 `git ls-files -m` 命令显示的被修改的文件列表)。
|
||||
|
||||
也有类似的用来设置输入文件的环境变量以 [自定义 Xcode script phases](http://indiestack.com/2014/12/speeding-up-custom-script-phases/) 。
|
||||
|
||||
### 使用多个 Swift 版本
|
||||
|
||||
SwiftLint 工作于 SourceKit 这一层,所以 Swift 版本发生变化时它也能继续工作!
|
||||
|
||||
这也是 SwiftLint 轻量化的原因,因为它不需要一个完整的 Swift 编译器,它只是与已经安装在你的电脑上的官方编译器进行通信。
|
||||
|
||||
你应该总是使用和你编译代码同样的工具集来执行 SwiftLint。
|
||||
|
||||
如果你有多套工具集或者安装了多个不同版本的 Xcode,你可能会需要覆盖 SwiftLint 默认的工具集。
|
||||
|
||||
下面这些命令可以控制 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 符号设置了 `TOOLCHAINS` 环境变量来标记一个特定的 Swift 工具集版本:
|
||||
|
||||
```shell
|
||||
$ TOOLCHAINS=com.apple.dt.toolchain.Swift_2_3 swiftlint autocorrect
|
||||
```
|
||||
|
||||
在 Linux 上,SourceKit 默认需要位于 `/usr/lib/libsourcekitdInProc.so` 或者通过 `LINUX_SOURCEKIT_LIB_PATH` 环境变量进行指定。
|
||||
|
||||
## 规则
|
||||
|
||||
SwiftLint 已经包含了超过 75 条规则,并且我们希望 Swift 社区(就是你!)会在以后有更多的贡献,我们鼓励提交 [Pull Requests](CONTRIBUTING.md)。
|
||||
现在只有很少的规则被实现了,但是我们希望 Swift 社区(就是你!)会在以后有更多的贡献,我们鼓励提交 [Pull Requests](CONTRIBUTING.md)。
|
||||
|
||||
你可以在 [Rule Directory](https://realm.github.io/SwiftLint/rule-directory.html) 找到规则的更新列表和更多信息。
|
||||
当前*正在*被实施的规则大多数只是作为一个基础,仅供参考。
|
||||
|
||||
你也可以检视 [Source/SwiftLintBuiltInRules/Rules](Source/SwiftLintBuiltInRules/Rules) 目录来查看它们的实现。
|
||||
|
||||
`opt_in_rules` 默认是关闭的(即,你需要在你的配置文件中明确地打开它们)。
|
||||
|
||||
什么时候需要将一个规则设为 opt-in 的指南:
|
||||
|
||||
* 一个可能会有许多负面作用的规则(例如 `empty_count`)
|
||||
* 一个过慢的规则
|
||||
* 一个不通用或者仅在某些特定场景下可用的规则(例如 `force_unwrapping`)
|
||||
想要查看已实现的规则可以查看 [Source/SwiftLintFramework/Rules](Source/SwiftLintFramework/Rules) 目录。
|
||||
|
||||
### 在代码中关闭某个规则
|
||||
|
||||
|
@ -187,7 +79,7 @@ SwiftLint 已经包含了超过 75 条规则,并且我们希望 Swift 社区
|
|||
|
||||
`// swiftlint:enable <rule>`
|
||||
|
||||
例如:
|
||||
例如:
|
||||
|
||||
```swift
|
||||
// swiftlint:disable colon
|
||||
|
@ -198,7 +90,7 @@ let hasWarning :String = "" // Warning generated about colons immediately after
|
|||
|
||||
也可以通过添加 `:previous`, `:this` 或者 `:next` 来使关闭或者打开某条规则的命令分别应用于前一行,当前或者后一行代码。
|
||||
|
||||
例如:
|
||||
例如:
|
||||
|
||||
```swift
|
||||
// swiftlint:disable:next force_cast
|
||||
|
@ -215,11 +107,11 @@ let noWarning3 = NSNumber() as! Int
|
|||
|
||||
可以通过在你需要执行 SwiftLint 的目录下添加一个 `.swiftlint.yml` 文件的方式来配置 SwiftLint。可以被配置的参数有:
|
||||
|
||||
包含的规则:
|
||||
包含的规则:
|
||||
|
||||
* `disabled_rules`: 关闭某些默认开启的规则。
|
||||
* `opt_in_rules`: 一些规则是可选的。
|
||||
* `only_rules`: 不可以和 `disabled_rules` 或者 `opt_in_rules` 并列。类似一个白名单,只有在这个列表中的规则才是开启的。
|
||||
* `disabled_rules`: 关闭某些默认开启的规则.
|
||||
* `opt_in_rules`: 一些规则是可选的.
|
||||
* `whitelist_rules`: 不可以和 `disabled_rules` 或者 `opt_in_rules` 并列。类似一个白名单,只有在这个列表中的规则才是开启的。
|
||||
|
||||
```yaml
|
||||
disabled_rules: # 执行时排除掉的规则
|
||||
|
@ -270,7 +162,7 @@ identifier_name:
|
|||
- id
|
||||
- URL
|
||||
- GlobalAPIKey
|
||||
reporter: "xcode" # 报告类型 (xcode, json, csv, checkstyle, codeclimate, junit, html, emoji, sonarqube, markdown, github-actions-logging)
|
||||
reporter: "xcode" # 报告类型 (xcode, json, csv, checkstyle, junit, html, emoji)
|
||||
```
|
||||
|
||||
#### 定义自定义规则
|
||||
|
@ -281,14 +173,14 @@ reporter: "xcode" # 报告类型 (xcode, json, csv, checkstyle, codeclimate, jun
|
|||
custom_rules:
|
||||
pirates_beat_ninjas: # 规则标识符
|
||||
name: "Pirates Beat Ninjas" # 规则名称,可选
|
||||
regex: "([nN]inja)" # 匹配的模式
|
||||
regex: "([n,N]inja)" # 匹配的模式
|
||||
match_kinds: # 需要匹配的语法类型,可选
|
||||
- comment
|
||||
- identifier
|
||||
message: "Pirates are better than ninjas." # 提示信息,可选
|
||||
severity: error # 提示的级别,可选
|
||||
no_hiding_in_strings:
|
||||
regex: "([nN]inja)"
|
||||
regex: "([n,N]inja)"
|
||||
match_kinds: string
|
||||
```
|
||||
|
||||
|
@ -337,12 +229,4 @@ SwiftLint 可以自动修正某些错误,磁盘上的文件会被一个修正
|
|||
|
||||
## 协议
|
||||
|
||||
[MIT 许可。](LICENSE)
|
||||
|
||||
## 关于
|
||||
|
||||
<img src="assets/realm.png" width="184" />
|
||||
|
||||
SwiftLint 是由 Realm Inc 建立和维护的。Realm 的名字和标志是属于 Realm Inc 的注册商标。
|
||||
|
||||
我们 :heart: 开源软件!看一下[我们的其他开源项目](https://github.com/realm),瞅一眼[我们的博客](https://realm.io/news),或者在推特上跟我们唠唠嗑([@realm](https://twitter.com/realm))。
|
||||
MIT 许可。
|
||||
|
|
100
README_KR.md
100
README_KR.md
|
@ -1,11 +1,11 @@
|
|||
# SwiftLint
|
||||
|
||||
SwiftLint는 스위프트 스타일 및 컨벤션을 강제하기 위한 도구로, [Kodeco 스위프트 스타일 가이드](https://github.com/kodecocodes/swift-style-guide)에 대략적인 기반을 두고 있습니다.
|
||||
SwiftLint는 스위프트 스타일 및 컨벤션을 강제하기 위한 도구로, [GitHub 스위프트 스타일 가이드](https://github.com/github/swift-style-guide)에 대략적인 기반을 두고 있습니다.
|
||||
|
||||
SwiftLint는 좀 더 정확한 결과를 위해 [Clang](http://clang.llvm.org)과 [SourceKit](http://www.jpsim.com/uncovering-sourcekit)에 연결하여 소스 파일의 [AST](http://clang.llvm.org/docs/IntroductionToTheClangAST.html) 표현을 사용합니다.
|
||||
|
||||
[](https://dev.azure.com/jpsim/SwiftLint/_build/latest?definitionId=4?branchName=main)
|
||||
[](https://codecov.io/github/realm/SwiftLint?branch=main)
|
||||

|
||||
[](https://codecov.io/github/realm/SwiftLint?branch=master)
|
||||
|
||||

|
||||
|
||||
|
@ -27,16 +27,11 @@ Podfile에 아래 라인을 추가하기만 하면 됩니다.
|
|||
pod 'SwiftLint'
|
||||
```
|
||||
|
||||
이를 실행하면 다음번 `pod install` 실행 시 SwiftLint 바이너리 및 `Pods/`에 있는 디펜던시들을 다운로드하고, Script Build Phases에서 `${PODS_ROOT}/SwiftLint/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 바이너리 및 그에 종속된 바이너리들과 스위프트 바이너리까지 `Pods/` 디렉토리에 추가되기 때문에, git 등의 SCM에 이런 디렉토리들을 체크인하는 것은 권장하지 않습니다.
|
||||
|
||||
### 빌드된 패키지를 사용하는 경우:
|
||||
|
||||
|
@ -44,7 +39,7 @@ $ mint install realm/SwiftLint
|
|||
|
||||
### 소스를 직접 컴파일하는 경우:
|
||||
|
||||
본 프로젝트를 클론해서 빌드할 수도 있습니다. `make install` 명령을 사용합니다. (Xcode 12.5 이후 버전)
|
||||
본 프로젝트를 클론해서 빌드할 수도 있습니다. `git submodule update --init --recursive; make install` 명령을 사용합니다. (Xcode 8.0 이후 버전)
|
||||
|
||||
## 사용 방법
|
||||
|
||||
|
@ -52,11 +47,11 @@ $ mint install realm/SwiftLint
|
|||
|
||||
프로젝트에 SwiftLint를 통합하기 위한 권장 사용 방식의 전반적인 개요를 알고 싶다면, 아래 프레젠테이션 영상을 보거나 스크립트를 읽어보면 좋습니다.
|
||||
|
||||
[](https://academy.realm.io/posts/slug-jp-simard-swiftlint/)
|
||||
[](https://realm.io/news/slug-jp-simard-swiftlint)
|
||||
|
||||
### Xcode
|
||||
|
||||
SwiftLint를 Xcode 프로젝트에 통합하여 IDE 상에 경고나 에러를 표시할 수 있습니다. 프로젝트의 파일 내비게이터에서 타겟 앱을 선택 후 "Build Phases" 탭으로 이동합니다. + 버튼을 클릭한 후 "Run Script Phase"를 선택합니다. 그 후 아래 스크립트를 추가하기만 하면 됩니다.
|
||||
SwiftLint를 Xcode 스킴에 통합하여 IDE 상에 경고나 에러를 표시할 수 있습니다. "Run Script Phase"를 새로 만들고 아래 스크립트를 추가하기만 하면 됩니다.
|
||||
|
||||
```bash
|
||||
if which swiftlint >/dev/null; then
|
||||
|
@ -68,34 +63,6 @@ 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` 환경 변수에 동시에 추가하여야 합니다.
|
||||
|
||||
```bash
|
||||
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`에 심볼릭 링크를 생성하여 실제 바이너리가 있는 곳으로 포인팅할 수 있습니다. :
|
||||
|
||||
```bash
|
||||
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를 사용해서 설치한 경우는 아래 스크립트를 대신 사용합니다.
|
||||
|
||||
```bash
|
||||
|
@ -116,21 +83,6 @@ AppCode에서 SwiftLint를 사용하려면 [이 플러그인](https://plugins.je
|
|||
|
||||
[Atom](https://atom.io/)에서 SwiftLint를 사용하려면 APM에서 [`linter-swiftlint`](https://atom.io/packages/linter-swiftlint) 패키지를 설치합니다.
|
||||
|
||||
### fastlane
|
||||
|
||||
fastlane 과정에서 SwiftLint를 사용하려면 [공식적인 fastlane 액션](https://docs.fastlane.tools/actions/swiftlint)를 사용할 수 있습니다.
|
||||
|
||||
```ruby
|
||||
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 계속 실행합니다
|
||||
)
|
||||
```
|
||||
|
||||
### 커맨드 라인
|
||||
|
||||
```
|
||||
|
@ -144,16 +96,16 @@ Available commands:
|
|||
version Display the current version of SwiftLint
|
||||
```
|
||||
|
||||
스위프트 파일이 있는 디렉터리에서 `swiftlint`를 실행합니다. 디렉터리는 재귀적으로 탐색됩니다.
|
||||
스위프트 파일이 있는 디렉토리에서 `swiftlint`를 실행합니다. 디렉토리는 재귀적으로 탐색됩니다.
|
||||
|
||||
`lint`나 `autocorrect`를 사용할 때 여러 파일(예를 들면, [`ExtraBuildPhase`](https://github.com/norio-nomura/ExtraBuildPhase) 플러그인에 의해 Xcode가 변경한 파일들 혹은 `git ls-files -m` 명령으로 인해 작업 트리에서 변경된 파일들)을 지정하려면 `--use-script-input-files` 옵션을 넘기고 다음 인스턴스 변수들을 설정하면 됩니다. `SCRIPT_INPUT_FILE_COUNT` and
|
||||
`SCRIPT_INPUT_FILE_0`, `SCRIPT_INPUT_FILE_1`...`SCRIPT_INPUT_FILE_{SCRIPT_INPUT_FILE_COUNT - 1}`
|
||||
`SCRIPT_INPUT_FILE_0`, `SCRIPT_INPUT_FILE_1`...`SCRIPT_INPUT_FILE_{SCRIPT_INPUT_FILE_COUNT}`
|
||||
|
||||
이는 [Xcode의 커스텀 스크립트 단계](http://indiestack.com/2014/12/speeding-up-custom-script-phases/)에 입력 파일로 환경 변수를 지정하는 것과 동일합니다.
|
||||
|
||||
### 스위프트 여러 버전에 대한 대응
|
||||
|
||||
SwiftLint는 SourceKit에 연결되어 있으므로 스위프트 언어가 변화하더라도 이상 없이 동작할 수 있습니다.
|
||||
SwiftLint는 SourceKit에 연결되어 있으므로 스위프트 언어가 변화하더라도 이상없이 동작할 수 있습니다.
|
||||
|
||||
이는 전체 스위프트 컴파일러가 포함되지 않아도 되므로 SwiftLint가 간결하게 유지될 수 있습니다. SwiftLint는 데스크탑에 이미 설치되어 있는 공식 스위프트 컴파일러와 통신하기만 하면 됩니다.
|
||||
|
||||
|
@ -171,7 +123,7 @@ SwiftLint가 어느 스위프트 툴체인을 사용할지 결정하는 순서
|
|||
* `~/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain`
|
||||
* `~/Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain`
|
||||
|
||||
`sourcekitd.framework`은 위에서 선택된 경로의 `usr/lib/` 하위 디렉터리에 존재해야 합니다.
|
||||
`sourcekitd.framework`은 위에서 선택된 경로의 `usr/lib/` 하위 디렉토리에 존재해야 합니다.
|
||||
|
||||
`TOOLCHAINS` 환경 변수에 스위프트 툴체인 버전을 식별할 수 있는 값을 리버스 DNS 형식으로 지정할 수도 있습니다.
|
||||
|
||||
|
@ -183,9 +135,9 @@ $ TOOLCHAINS=com.apple.dt.toolchain.Swift_2_3 swiftlint autocorrect
|
|||
|
||||
## 룰
|
||||
|
||||
SwiftLint에는 200개가 넘는 룰들이 있고, 스위프트 커뮤니티(바로 여러분들!)는 이를 지속적으로 발전시켜 가고 있습니다. [풀 리퀘스트](CONTRIBUTING.md)는 언제나 환영입니다.
|
||||
SwiftLint에는 75개가 넘는 룰들이 있고, 스위프트 커뮤니티(바로 여러분들!)는 이를 지속적으로 발전시켜 가고 있습니다. [풀 리퀘스트](CONTRIBUTING.md)는 언제나 환영입니다.
|
||||
|
||||
현재 구현된 룰 전체를 확인하려면 [Source/SwiftLintBuiltInRules/Rules](Source/SwiftLintBuiltInRules/Rules)를 살펴보세요.
|
||||
현재 구현된 룰 전체를 확인하려면 [Source/SwiftLintFramework/Rules](Source/SwiftLintFramework/Rules)를 살펴보세요.
|
||||
|
||||
`opt_in_rules`는 기본적으로 비활성화되어 있습니다. (즉, 설정 파일에서 명시적으로 해당 룰을 활성화해야 합니다.)
|
||||
|
||||
|
@ -197,11 +149,11 @@ SwiftLint에는 200개가 넘는 룰들이 있고, 스위프트 커뮤니티(바
|
|||
|
||||
### 코드에서 룰 비활성화하기
|
||||
|
||||
소스 파일에서 아래 형식의 주석을 사용하면 룰을 비활성화할 수 있습니다.
|
||||
소스 파일에서 아래 형식의 주석을 사용하면 룰을 비활성화 할 수 있습니다.
|
||||
|
||||
`// swiftlint:disable <룰1> [<룰2> <룰3>...]`
|
||||
|
||||
비활성화된 룰은 해당 파일의 마지막까지 적용되거나, 활성화 주석이 나타날 때까지 적용됩니다.
|
||||
비활성화 된 룰은 해당 파일의 마지막까지 적용되거나, 활성화 주석이 나타날 때까지 적용됩니다.
|
||||
|
||||
`// swiftlint:enable <룰1> [<룰2> <룰3>...]`
|
||||
|
||||
|
@ -231,13 +183,13 @@ let noWarning3 = NSNumber() as! Int
|
|||
|
||||
### 설정
|
||||
|
||||
SwiftLint가 실행될 디렉터리에 `.swiftlint.yml` 파일을 추가해서 SwiftLint를 설정할 수 있습니다. 아래 파라미터들을 설정 가능합니다.
|
||||
SwiftLint가 실행될 디렉토리에 `.swiftlint.yml` 파일을 추가해서 SwiftLint를 설정할 수 있습니다. 아래 파라미터들을 설정 가능합니다.
|
||||
|
||||
룰 적용여부 설정:
|
||||
|
||||
* `disabled_rules`: 기본 활성화된 룰 중에 비활성화할 룰들을 지정합니다.
|
||||
* `opt_in_rules`: 기본 룰이 아닌 룰들을 활성화합니다.
|
||||
* `only_rules`: 지정한 룰들만 활성화되도록 화이트리스트로 지정합니다. `disabled_rules` 및 `opt_in_rules`과는 같이 사용할 수 없습니다.
|
||||
* `whitelist_rules`: 지정한 룰들만 활성화되도록 화이트리스트로 지정합니다. `disabled_rules` 및 `opt_in_rules`과는 같이 사용할 수 없습니다.
|
||||
|
||||
```yaml
|
||||
disabled_rules: # 실행에서 제외할 룰 식별자들
|
||||
|
@ -286,7 +238,7 @@ identifier_name:
|
|||
- id
|
||||
- URL
|
||||
- GlobalAPIKey
|
||||
reporter: "xcode" # 보고 유형 (xcode, json, csv, codeclimate, checkstyle, junit, html, emoji, sonarqube, markdown, github-actions-logging)
|
||||
reporter: "xcode" # 보고 유형 (xcode, json, csv, checkstyle, junit, html, emoji)
|
||||
```
|
||||
|
||||
#### 커스텀 룰 정의
|
||||
|
@ -296,16 +248,16 @@ reporter: "xcode" # 보고 유형 (xcode, json, csv, codeclimate, checkstyle, ju
|
|||
```yaml
|
||||
custom_rules:
|
||||
pirates_beat_ninjas: # 룰 식별자
|
||||
included: ".*.swift" # 린트 실행 시 포함할 경로를 정의하는 정규표현식. 선택 가능.
|
||||
included: ".*.swift" # 린트 실행시 포함할 경로를 정의하는 정규표현식. 선택 가능.
|
||||
name: "Pirates Beat Ninjas" # 룰 이름. 선택 가능.
|
||||
regex: "([nN]inja)" # 패턴 매칭
|
||||
regex: "([n,N]inja)" # 패턴 매칭
|
||||
match_kinds: # 매칭할 SyntaxKinds. 선택 가능.
|
||||
- comment
|
||||
- identifier
|
||||
message: "Pirates are better than ninjas." # 위반 메시지. 선택 가능.
|
||||
severity: error # 위반 수준. 선택 가능.
|
||||
no_hiding_in_strings:
|
||||
regex: "([nN]inja)"
|
||||
regex: "([n,N]inja)"
|
||||
match_kinds: string
|
||||
```
|
||||
|
||||
|
@ -313,7 +265,7 @@ custom_rules:
|
|||
|
||||

|
||||
|
||||
하나 이상의 `match_kinds`를 사용해서 매칭된 결과를 필터링할 수 있습니다. 이 목록에 들어있지 않은 구문 유형이 포함된 결과는 매칭에서 제외됩니다. 사용 가능한 모든 구문 유형은 다음과 같습니다.
|
||||
하나 이상의 `match_kinds`를 사용해서 매칭된 결과를 필터링 할 수 있습니다. 이 목록에 들어있지 않은 구문 유형이 포함된 결과는 매칭에서 제외됩니다. 사용 가능한 모든 구문 유형은 다음과 같습니다.
|
||||
|
||||
* argument
|
||||
* attribute.builtin
|
||||
|
@ -339,13 +291,13 @@ custom_rules:
|
|||
|
||||
SwiftLint는 설정 파일을 중첩되게 구성해서 린트 과정을 더욱 세밀하게 제어할 수 있습니다.
|
||||
|
||||
* 디렉터리 구조에서 필요한 곳이면 어디든지 `.swiftlint.yml` 파일을 추가할 수 있습니다.
|
||||
* 각 파일은 자신의 디렉터리 내에 있는 설정 파일을 사용하거나, 계층구조 상 가장 가까운 부모 디렉터리에 있는 설정 파일을 사용해서 린트됩니다. 별도로 설정 파일이 존재하지 않으면 루트에 있는 설정 파일이 사용됩니다.
|
||||
* 디렉토리 구조에서 필요한 곳이면 어디든지 `.swiftlint.yml` 파일을 추가할 수 있습니다.
|
||||
* 각 파일은 자신의 디렉토리 내에 있는 설정 파일을 사용하거나, 계층구조 상 가장 가까운 부모 디렉토리에 있는 설정 파일을 사용해서 린트됩니다. 별도로 설정 파일이 존재하지 않으면 루트에 있는 설정 파일이 사용됩니다.
|
||||
* 중첩 구성에서 `excluded` 및 `included`는 무시됩니다.
|
||||
|
||||
### 자동 수정
|
||||
|
||||
SwiftLint는 일부 위반 사항들을 자동으로 수정할 수 있습니다. 디스크 상의 파일들은 수정된 버전으로 덮어 쓰여지게 됩니다.
|
||||
SwiftLint는 일부 위반 사항들을 자동으로 수정할 수 있습니다. 디스크상의 파일들은 수정된 버전으로 덮어 쓰여지게 됩니다.
|
||||
|
||||
`swiftlint autocorrect`를 실행하기 전에 파일들을 백업해주세요. 그렇지 않으면 중요한 데이터가 유실될 수도 있습니다.
|
||||
|
||||
|
|
18
Releasing.md
18
Releasing.md
|
@ -7,8 +7,16 @@ For SwiftLint contributors, follow these steps to cut a release:
|
|||
* FabricSoftenerRule
|
||||
* Top Loading
|
||||
* Fresh Out Of The Dryer
|
||||
1. Make sure you have the latest stable Xcode version installed and
|
||||
`xcode-select`ed
|
||||
1. Release new version: `make release "0.2.0: Tumble Dry"`
|
||||
1. Wait for the Docker CI job to finish then run: `make zip_linux_release`
|
||||
1. Celebrate. :tada:
|
||||
2. Push new version: `make push_version "0.2.0: Tumble Dry"`
|
||||
3. Make sure you have the latest stable Xcode version installed and
|
||||
`xcode-select`ed.
|
||||
4. Create the pkg installer, framework zip, and portable zip: `make release`
|
||||
5. Create a GitHub release: https://github.com/realm/SwiftLint/releases/new
|
||||
* Specify the tag you just pushed from the dropdown.
|
||||
* Set the release title to the new version number & release name.
|
||||
* Add the changelog section to the release description text box.
|
||||
* Upload the pkg installer, framework zip, and portable zip you just built
|
||||
to the GitHub release binaries.
|
||||
* Click "Publish release".
|
||||
6. Publish to Homebrew and CocoaPods trunk: `make publish`
|
||||
7. Celebrate. :tada:
|
||||
|
|
1
Rules.md
1
Rules.md
|
@ -1 +0,0 @@
|
|||
Rule documentation has moved [here](https://realm.github.io/SwiftLint/rule-directory.html).
|
|
@ -1,15 +0,0 @@
|
|||
#ifdef __APPLE__
|
||||
|
||||
#include "objc_dupclass.h"
|
||||
|
||||
OBJC_DUPCLASS(_TtC11SwiftSyntax11SyntaxArena);
|
||||
OBJC_DUPCLASS(_TtC11SwiftSyntax13SyntaxVisitor);
|
||||
OBJC_DUPCLASS(_TtC11SwiftSyntax14SyntaxRewriter);
|
||||
OBJC_DUPCLASS(_TtC11SwiftSyntax16BumpPtrAllocator);
|
||||
OBJC_DUPCLASS(_TtC11SwiftSyntax16SyntaxAnyVisitor);
|
||||
OBJC_DUPCLASS(_TtC11SwiftSyntax18ParsingSyntaxArena);
|
||||
OBJC_DUPCLASS(_TtC11SwiftSyntax23SourceLocationConverter);
|
||||
OBJC_DUPCLASS(_TtC11SwiftSyntax26IncrementalParseTransition);
|
||||
OBJC_DUPCLASS(_TtC11SwiftSyntax35IncrementalParseReusedNodeCollector);
|
||||
|
||||
#endif // __APPLE__
|
|
@ -1,19 +0,0 @@
|
|||
// https://github.com/keith/objc_dupclass
|
||||
#include <stdint.h>
|
||||
|
||||
// TODO: This isn't entirely accurate, but I'm not sure how to more accurately determine
|
||||
#if (defined(__arm64__) || defined(DUPCLASS_FORCE_DATA_CONST)) && !defined(DUPCLASS_FORCE_DATA)
|
||||
#define SECTION "__DATA_CONST"
|
||||
#else
|
||||
#define SECTION "__DATA"
|
||||
#endif
|
||||
|
||||
// Struct layout from https://github.com/apple-oss-distributions/objc4/blob/8701d5672d3fd3cd817aeb84db1077aafe1a1604/runtime/objc-abi.h#L175-L183
|
||||
#define OBJC_DUPCLASS(kclass) \
|
||||
__attribute__((used)) __attribute__((visibility("hidden"))) \
|
||||
static struct { uint32_t version; uint32_t flags; const char name[64]; } \
|
||||
const __duplicate_class_##kclass = { 0, 0, #kclass }; \
|
||||
\
|
||||
__attribute__((used)) __attribute__((visibility("hidden"))) \
|
||||
__attribute__((section (SECTION",__objc_dupclass"))) \
|
||||
const void* __set___objc_dupclass_sym___duplicate_class_##kclass = &__duplicate_class_##kclass
|
|
@ -1 +0,0 @@
|
|||
@_exported import SwiftLintCore
|
|
@ -1,187 +0,0 @@
|
|||
import SourceKittenFramework
|
||||
|
||||
/// Struct to represent SwiftUI ViewModifiers for the purpose of finding modifiers in a substructure.
|
||||
struct SwiftUIModifier {
|
||||
/// Name of the modifier.
|
||||
let name: String
|
||||
|
||||
/// List of arguments to check for in the modifier.
|
||||
let arguments: [Argument]
|
||||
|
||||
struct Argument {
|
||||
/// Name of the argument we want to find. For single unnamed arguments, use the empty string.
|
||||
let name: String
|
||||
|
||||
/// Whether or not the argument is required. If the argument is present, value checks are enforced.
|
||||
/// Allows for better handling of modifiers with default values for certain arguments where we want
|
||||
/// to ensure that the default value is used.
|
||||
let required: Bool
|
||||
|
||||
/// List of possible values for the argument. Typically should just be a list with a single element,
|
||||
/// but allows for the flexibility of checking for multiple possible values. To only check for the presence
|
||||
/// of the modifier and not enforce any certain values, pass an empty array. All values are parsed as
|
||||
/// Strings; for other types (boolean, numeric, optional, etc) types you can check for "true", "5", "nil", etc.
|
||||
let values: [String]
|
||||
|
||||
/// Success criteria used for matching values (prefix, suffix, substring, exact match, or none).
|
||||
let matchType: MatchType
|
||||
|
||||
init(name: String, required: Bool = true, values: [String], matchType: MatchType = .exactMatch) {
|
||||
self.name = name
|
||||
self.required = required
|
||||
self.values = values
|
||||
self.matchType = matchType
|
||||
}
|
||||
}
|
||||
|
||||
enum MatchType {
|
||||
case prefix, suffix, substring, exactMatch
|
||||
|
||||
/// Compares the parsed argument value to a target value for the given match type
|
||||
/// and returns true is a match is found.
|
||||
func matches(argumentValue: String, targetValue: String) -> Bool {
|
||||
switch self {
|
||||
case .prefix:
|
||||
return argumentValue.hasPrefix(targetValue)
|
||||
case .suffix:
|
||||
return argumentValue.hasSuffix(targetValue)
|
||||
case .substring:
|
||||
return argumentValue.contains(targetValue)
|
||||
case .exactMatch:
|
||||
return argumentValue == targetValue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Extensions for recursively checking SwiftUI code for certain modifiers.
|
||||
extension SourceKittenDictionary {
|
||||
/// Call on a SwiftUI View to recursively check the substructure for a certain modifier with certain arguments.
|
||||
/// - Parameters:
|
||||
/// - modifiers: A list of `SwiftUIModifier` structs to check for in the view's substructure.
|
||||
/// In most cases, this can just be a single modifier, but since some modifiers have
|
||||
/// multiple versions, this enables checking for any modifier from the list.
|
||||
/// - file: The SwiftLintFile object for the current file, used to extract argument values.
|
||||
/// - Returns: A boolean value representing whether or not the given modifier with the specified
|
||||
/// arguments appears in the view's substructure.
|
||||
func hasModifier(anyOf modifiers: [SwiftUIModifier], in file: SwiftLintFile) -> Bool {
|
||||
// SwiftUI ViewModifiers are treated as `call` expressions, and we make sure we can get the expression's name.
|
||||
guard expressionKind == .call, let name else {
|
||||
return false
|
||||
}
|
||||
|
||||
// If any modifier from the list matches, return true.
|
||||
for modifier in modifiers {
|
||||
// Check for the given modifier name
|
||||
guard name.hasSuffix(modifier.name) else {
|
||||
continue
|
||||
}
|
||||
|
||||
// Check arguments.
|
||||
var matchesArgs = true
|
||||
for argument in modifier.arguments {
|
||||
var foundArg = false
|
||||
var argValue: String?
|
||||
|
||||
// Check for single unnamed argument.
|
||||
if argument.name.isEmpty {
|
||||
foundArg = true
|
||||
argValue = getSingleUnnamedArgumentValue(in: file)
|
||||
} else if let parsedArgument = enclosedArguments.first(where: { $0.name == argument.name }) {
|
||||
foundArg = true
|
||||
argValue = parsedArgument.getArgumentValue(in: file)
|
||||
}
|
||||
|
||||
// If argument is not required and we didn't find it, continue.
|
||||
if !foundArg && !argument.required {
|
||||
continue
|
||||
}
|
||||
|
||||
// Otherwise, we must have found an argument with a non-nil value to continue.
|
||||
guard foundArg, let argumentValue = argValue else {
|
||||
matchesArgs = false
|
||||
break
|
||||
}
|
||||
|
||||
// Argument value can match any of the options given in the argument struct.
|
||||
if argument.values.isEmpty || argument.values.contains(where: {
|
||||
argument.matchType.matches(argumentValue: argumentValue, targetValue: $0)
|
||||
}) {
|
||||
// Found a match, continue to next argument.
|
||||
continue
|
||||
} else {
|
||||
// Did not find a match, exit loop over arguments.
|
||||
matchesArgs = false
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Return true if all arguments matched
|
||||
if matchesArgs {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// Recursively check substructure.
|
||||
// SwiftUI literal Views with modifiers will have a SourceKittenDictionary structure like:
|
||||
// Image("myImage").resizable().accessibility(hidden: true).frame
|
||||
// --> Image("myImage").resizable().accessibility
|
||||
// --> Image("myImage").resizable
|
||||
// --> Image
|
||||
return substructure.contains(where: { $0.hasModifier(anyOf: modifiers, in: file) })
|
||||
}
|
||||
|
||||
// MARK: Sample use cases of `hasModifier` that are used in multiple rules
|
||||
|
||||
/// Whether or not the dictionary represents a SwiftUI View with an `accesibilityHidden(true)`
|
||||
/// or `accessibility(hidden: true)` modifier.
|
||||
func hasAccessibilityHiddenModifier(in file: SwiftLintFile) -> Bool {
|
||||
return hasModifier(
|
||||
anyOf: [
|
||||
SwiftUIModifier(
|
||||
name: "accessibilityHidden",
|
||||
arguments: [.init(name: "", values: ["true"])]
|
||||
),
|
||||
SwiftUIModifier(
|
||||
name: "accessibility",
|
||||
arguments: [.init(name: "hidden", values: ["true"])]
|
||||
)
|
||||
],
|
||||
in: file
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether or not the dictionary represents a SwiftUI View with an `accessibilityElement()` or
|
||||
/// `accessibilityElement(children: .ignore)` modifier (`.ignore` is the default parameter value).
|
||||
func hasAccessibilityElementChildrenIgnoreModifier(in file: SwiftLintFile) -> Bool {
|
||||
return hasModifier(
|
||||
anyOf: [
|
||||
SwiftUIModifier(
|
||||
name: "accessibilityElement",
|
||||
arguments: [.init(name: "children", required: false, values: [".ignore"], matchType: .suffix)]
|
||||
)
|
||||
],
|
||||
in: file
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: Helpers to extract argument values
|
||||
|
||||
/// Helper to get the value of an argument.
|
||||
func getArgumentValue(in file: SwiftLintFile) -> String? {
|
||||
guard expressionKind == .argument, let bodyByteRange else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return file.stringView.substringWithByteRange(bodyByteRange)
|
||||
}
|
||||
|
||||
/// Helper to get the value of a single unnamed argument to a function call.
|
||||
func getSingleUnnamedArgumentValue(in file: SwiftLintFile) -> String? {
|
||||
guard expressionKind == .call, let bodyByteRange else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return file.stringView.substringWithByteRange(bodyByteRange)
|
||||
}
|
||||
}
|
|
@ -1,109 +0,0 @@
|
|||
import SwiftSyntax
|
||||
import SwiftSyntaxBuilder
|
||||
|
||||
/// A helper to hold a visitor and rewriter that can lint and correct legacy NS/CG functions to a more modern syntax.
|
||||
enum LegacyFunctionRuleHelper {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
private let legacyFunctions: [String: RewriteStrategy]
|
||||
|
||||
init(legacyFunctions: [String: RewriteStrategy]) {
|
||||
self.legacyFunctions = legacyFunctions
|
||||
super.init(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: FunctionCallExprSyntax) {
|
||||
if node.isLegacyFunctionExpression(legacyFunctions: legacyFunctions) {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum RewriteStrategy {
|
||||
case equal
|
||||
case property(name: String)
|
||||
case function(name: String, argumentLabels: [String], reversed: Bool = false)
|
||||
|
||||
var expectedInitialArguments: Int {
|
||||
switch self {
|
||||
case .equal:
|
||||
return 2
|
||||
case .property:
|
||||
return 1
|
||||
case .function(name: _, argumentLabels: let argumentLabels, reversed: _):
|
||||
return argumentLabels.count + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class Rewriter: SyntaxRewriter, ViolationsSyntaxRewriter {
|
||||
private(set) var correctionPositions: [AbsolutePosition] = []
|
||||
private let locationConverter: SourceLocationConverter
|
||||
private let disabledRegions: [SourceRange]
|
||||
private let legacyFunctions: [String: RewriteStrategy]
|
||||
|
||||
init(
|
||||
legacyFunctions: [String: RewriteStrategy],
|
||||
locationConverter: SourceLocationConverter,
|
||||
disabledRegions: [SourceRange]
|
||||
) {
|
||||
self.legacyFunctions = legacyFunctions
|
||||
self.locationConverter = locationConverter
|
||||
self.disabledRegions = disabledRegions
|
||||
}
|
||||
|
||||
override func visit(_ node: FunctionCallExprSyntax) -> ExprSyntax {
|
||||
guard
|
||||
node.isLegacyFunctionExpression(legacyFunctions: legacyFunctions),
|
||||
let funcName = node.calledExpression.as(IdentifierExprSyntax.self)?.identifier.text,
|
||||
!node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter)
|
||||
else {
|
||||
return super.visit(node)
|
||||
}
|
||||
|
||||
correctionPositions.append(node.positionAfterSkippingLeadingTrivia)
|
||||
|
||||
let trimmedArguments = node.argumentList.map { $0.trimmingTrailingComma() }
|
||||
let rewriteStrategy = legacyFunctions[funcName]
|
||||
|
||||
let expr: ExprSyntax
|
||||
switch rewriteStrategy {
|
||||
case .equal:
|
||||
expr = "\(trimmedArguments[0]) == \(trimmedArguments[1])"
|
||||
case let .property(name: propertyName):
|
||||
expr = "\(trimmedArguments[0]).\(raw: propertyName)"
|
||||
case let .function(name: functionName, argumentLabels: argumentLabels, reversed: reversed):
|
||||
let arguments = reversed ? trimmedArguments.reversed() : trimmedArguments
|
||||
let params = zip(argumentLabels, arguments.dropFirst())
|
||||
.map { $0.isEmpty ? "\($1)" : "\($0): \($1)" }
|
||||
.joined(separator: ", ")
|
||||
expr = "\(arguments[0]).\(raw: functionName)(\(raw: params))"
|
||||
case .none:
|
||||
return super.visit(node)
|
||||
}
|
||||
|
||||
return expr
|
||||
.with(\.leadingTrivia, node.leadingTrivia)
|
||||
.with(\.trailingTrivia, node.trailingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension FunctionCallExprSyntax {
|
||||
func isLegacyFunctionExpression(legacyFunctions: [String: LegacyFunctionRuleHelper.RewriteStrategy]) -> Bool {
|
||||
guard
|
||||
let calledExpression = calledExpression.as(IdentifierExprSyntax.self),
|
||||
let rewriteStrategy = legacyFunctions[calledExpression.identifier.text],
|
||||
argumentList.count == rewriteStrategy.expectedInitialArguments
|
||||
else {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
private extension TupleExprElementSyntax {
|
||||
func trimmingTrailingComma() -> TupleExprElementSyntax {
|
||||
self.trimmed.with(\.trailingComma, nil).trimmed
|
||||
}
|
||||
}
|
|
@ -1,53 +0,0 @@
|
|||
import SourceKittenFramework
|
||||
|
||||
struct NamespaceCollector {
|
||||
struct Element {
|
||||
let name: String
|
||||
let kind: SwiftDeclarationKind
|
||||
let offset: ByteCount
|
||||
let dictionary: SourceKittenDictionary
|
||||
|
||||
init?(dictionary: SourceKittenDictionary, namespace: [String]) {
|
||||
guard let name = dictionary.name,
|
||||
let kind = dictionary.declarationKind,
|
||||
let offset = dictionary.offset else {
|
||||
return nil
|
||||
}
|
||||
|
||||
self.name = (namespace + [name]).joined(separator: ".")
|
||||
self.kind = kind
|
||||
self.offset = offset
|
||||
self.dictionary = dictionary
|
||||
}
|
||||
}
|
||||
|
||||
private let dictionary: SourceKittenDictionary
|
||||
|
||||
init(dictionary: SourceKittenDictionary) {
|
||||
self.dictionary = dictionary
|
||||
}
|
||||
|
||||
func findAllElements(of types: Set<SwiftDeclarationKind>,
|
||||
namespace: [String] = []) -> [Element] {
|
||||
return findAllElements(in: dictionary, of: types, namespace: namespace)
|
||||
}
|
||||
|
||||
private func findAllElements(in dictionary: SourceKittenDictionary,
|
||||
of types: Set<SwiftDeclarationKind>,
|
||||
namespace: [String] = []) -> [Element] {
|
||||
return dictionary.substructure.flatMap { subDict -> [Element] in
|
||||
var elements: [Element] = []
|
||||
guard let element = Element(dictionary: subDict, namespace: namespace) else {
|
||||
return elements
|
||||
}
|
||||
|
||||
if types.contains(element.kind) {
|
||||
elements.append(element)
|
||||
}
|
||||
|
||||
elements += findAllElements(in: subDict, of: types, namespace: [element.name])
|
||||
|
||||
return elements
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,233 +0,0 @@
|
|||
// Generated using Sourcery 2.0.2 — https://github.com/krzysztofzablocki/Sourcery
|
||||
// DO NOT EDIT
|
||||
|
||||
/// The rule list containing all available rules built into SwiftLint.
|
||||
public let builtInRules: [Rule.Type] = [
|
||||
AccessibilityLabelForImageRule.self,
|
||||
AccessibilityTraitForButtonRule.self,
|
||||
AnonymousArgumentInMultilineClosureRule.self,
|
||||
AnyObjectProtocolRule.self,
|
||||
ArrayInitRule.self,
|
||||
AttributesRule.self,
|
||||
BalancedXCTestLifecycleRule.self,
|
||||
BlanketDisableCommandRule.self,
|
||||
BlockBasedKVORule.self,
|
||||
CaptureVariableRule.self,
|
||||
ClassDelegateProtocolRule.self,
|
||||
ClosingBraceRule.self,
|
||||
ClosureBodyLengthRule.self,
|
||||
ClosureEndIndentationRule.self,
|
||||
ClosureParameterPositionRule.self,
|
||||
ClosureSpacingRule.self,
|
||||
CollectionAlignmentRule.self,
|
||||
ColonRule.self,
|
||||
CommaInheritanceRule.self,
|
||||
CommaRule.self,
|
||||
CommentSpacingRule.self,
|
||||
CompilerProtocolInitRule.self,
|
||||
ComputedAccessorsOrderRule.self,
|
||||
ConditionalReturnsOnNewlineRule.self,
|
||||
ContainsOverFilterCountRule.self,
|
||||
ContainsOverFilterIsEmptyRule.self,
|
||||
ContainsOverFirstNotNilRule.self,
|
||||
ContainsOverRangeNilComparisonRule.self,
|
||||
ControlStatementRule.self,
|
||||
ConvenienceTypeRule.self,
|
||||
CyclomaticComplexityRule.self,
|
||||
DeploymentTargetRule.self,
|
||||
DirectReturnRule.self,
|
||||
DiscardedNotificationCenterObserverRule.self,
|
||||
DiscouragedAssertRule.self,
|
||||
DiscouragedDirectInitRule.self,
|
||||
DiscouragedNoneNameRule.self,
|
||||
DiscouragedObjectLiteralRule.self,
|
||||
DiscouragedOptionalBooleanRule.self,
|
||||
DiscouragedOptionalCollectionRule.self,
|
||||
DuplicateConditionsRule.self,
|
||||
DuplicateEnumCasesRule.self,
|
||||
DuplicateImportsRule.self,
|
||||
DuplicatedKeyInDictionaryLiteralRule.self,
|
||||
DynamicInlineRule.self,
|
||||
EmptyCollectionLiteralRule.self,
|
||||
EmptyCountRule.self,
|
||||
EmptyEnumArgumentsRule.self,
|
||||
EmptyParametersRule.self,
|
||||
EmptyParenthesesWithTrailingClosureRule.self,
|
||||
EmptyStringRule.self,
|
||||
EmptyXCTestMethodRule.self,
|
||||
EnumCaseAssociatedValuesLengthRule.self,
|
||||
ExpiringTodoRule.self,
|
||||
ExplicitACLRule.self,
|
||||
ExplicitEnumRawValueRule.self,
|
||||
ExplicitInitRule.self,
|
||||
ExplicitSelfRule.self,
|
||||
ExplicitTopLevelACLRule.self,
|
||||
ExplicitTypeInterfaceRule.self,
|
||||
ExtensionAccessModifierRule.self,
|
||||
FallthroughRule.self,
|
||||
FatalErrorMessageRule.self,
|
||||
FileHeaderRule.self,
|
||||
FileLengthRule.self,
|
||||
FileNameNoSpaceRule.self,
|
||||
FileNameRule.self,
|
||||
FileTypesOrderRule.self,
|
||||
FirstWhereRule.self,
|
||||
FlatMapOverMapReduceRule.self,
|
||||
ForWhereRule.self,
|
||||
ForceCastRule.self,
|
||||
ForceTryRule.self,
|
||||
ForceUnwrappingRule.self,
|
||||
FunctionBodyLengthRule.self,
|
||||
FunctionDefaultParameterAtEndRule.self,
|
||||
FunctionParameterCountRule.self,
|
||||
GenericTypeNameRule.self,
|
||||
IBInspectableInExtensionRule.self,
|
||||
IdenticalOperandsRule.self,
|
||||
IdentifierNameRule.self,
|
||||
ImplicitGetterRule.self,
|
||||
ImplicitReturnRule.self,
|
||||
ImplicitlyUnwrappedOptionalRule.self,
|
||||
InclusiveLanguageRule.self,
|
||||
IndentationWidthRule.self,
|
||||
InertDeferRule.self,
|
||||
InvalidSwiftLintCommandRule.self,
|
||||
IsDisjointRule.self,
|
||||
JoinedDefaultParameterRule.self,
|
||||
LargeTupleRule.self,
|
||||
LastWhereRule.self,
|
||||
LeadingWhitespaceRule.self,
|
||||
LegacyCGGeometryFunctionsRule.self,
|
||||
LegacyConstantRule.self,
|
||||
LegacyConstructorRule.self,
|
||||
LegacyHashingRule.self,
|
||||
LegacyMultipleRule.self,
|
||||
LegacyNSGeometryFunctionsRule.self,
|
||||
LegacyObjcTypeRule.self,
|
||||
LegacyRandomRule.self,
|
||||
LetVarWhitespaceRule.self,
|
||||
LineLengthRule.self,
|
||||
LiteralExpressionEndIndentationRule.self,
|
||||
LocalDocCommentRule.self,
|
||||
LowerACLThanParentRule.self,
|
||||
MarkRule.self,
|
||||
MissingDocsRule.self,
|
||||
ModifierOrderRule.self,
|
||||
MultilineArgumentsBracketsRule.self,
|
||||
MultilineArgumentsRule.self,
|
||||
MultilineFunctionChainsRule.self,
|
||||
MultilineLiteralBracketsRule.self,
|
||||
MultilineParametersBracketsRule.self,
|
||||
MultilineParametersRule.self,
|
||||
MultipleClosuresWithTrailingClosureRule.self,
|
||||
NSLocalizedStringKeyRule.self,
|
||||
NSLocalizedStringRequireBundleRule.self,
|
||||
NSNumberInitAsFunctionReferenceRule.self,
|
||||
NSObjectPreferIsEqualRule.self,
|
||||
NestingRule.self,
|
||||
NimbleOperatorRule.self,
|
||||
NoExtensionAccessModifierRule.self,
|
||||
NoFallthroughOnlyRule.self,
|
||||
NoGroupingExtensionRule.self,
|
||||
NoMagicNumbersRule.self,
|
||||
NoSpaceInMethodCallRule.self,
|
||||
NotificationCenterDetachmentRule.self,
|
||||
NumberSeparatorRule.self,
|
||||
ObjectLiteralRule.self,
|
||||
OpeningBraceRule.self,
|
||||
OperatorFunctionWhitespaceRule.self,
|
||||
OperatorUsageWhitespaceRule.self,
|
||||
OptionalEnumCaseMatchingRule.self,
|
||||
OrphanedDocCommentRule.self,
|
||||
OverriddenSuperCallRule.self,
|
||||
OverrideInExtensionRule.self,
|
||||
PatternMatchingKeywordsRule.self,
|
||||
PeriodSpacingRule.self,
|
||||
PreferNimbleRule.self,
|
||||
PreferSelfInStaticReferencesRule.self,
|
||||
PreferSelfTypeOverTypeOfSelfRule.self,
|
||||
PreferZeroOverExplicitInitRule.self,
|
||||
PrefixedTopLevelConstantRule.self,
|
||||
PrivateActionRule.self,
|
||||
PrivateOutletRule.self,
|
||||
PrivateOverFilePrivateRule.self,
|
||||
PrivateSubjectRule.self,
|
||||
PrivateUnitTestRule.self,
|
||||
ProhibitedInterfaceBuilderRule.self,
|
||||
ProhibitedSuperRule.self,
|
||||
ProtocolPropertyAccessorsOrderRule.self,
|
||||
QuickDiscouragedCallRule.self,
|
||||
QuickDiscouragedFocusedTestRule.self,
|
||||
QuickDiscouragedPendingTestRule.self,
|
||||
RawValueForCamelCasedCodableEnumRule.self,
|
||||
ReduceBooleanRule.self,
|
||||
ReduceIntoRule.self,
|
||||
RedundantDiscardableLetRule.self,
|
||||
RedundantNilCoalescingRule.self,
|
||||
RedundantObjcAttributeRule.self,
|
||||
RedundantOptionalInitializationRule.self,
|
||||
RedundantSelfInClosureRule.self,
|
||||
RedundantSetAccessControlRule.self,
|
||||
RedundantStringEnumValueRule.self,
|
||||
RedundantTypeAnnotationRule.self,
|
||||
RedundantVoidReturnRule.self,
|
||||
RequiredDeinitRule.self,
|
||||
RequiredEnumCaseRule.self,
|
||||
ReturnArrowWhitespaceRule.self,
|
||||
ReturnValueFromVoidFunctionRule.self,
|
||||
SelfBindingRule.self,
|
||||
SelfInPropertyInitializationRule.self,
|
||||
ShorthandOperatorRule.self,
|
||||
ShorthandOptionalBindingRule.self,
|
||||
SingleTestClassRule.self,
|
||||
SortedEnumCasesRule.self,
|
||||
SortedFirstLastRule.self,
|
||||
SortedImportsRule.self,
|
||||
StatementPositionRule.self,
|
||||
StaticOperatorRule.self,
|
||||
StrictFilePrivateRule.self,
|
||||
StrongIBOutletRule.self,
|
||||
SuperfluousElseRule.self,
|
||||
SwitchCaseAlignmentRule.self,
|
||||
SwitchCaseOnNewlineRule.self,
|
||||
SyntacticSugarRule.self,
|
||||
TestCaseAccessibilityRule.self,
|
||||
TodoRule.self,
|
||||
ToggleBoolRule.self,
|
||||
TrailingClosureRule.self,
|
||||
TrailingCommaRule.self,
|
||||
TrailingNewlineRule.self,
|
||||
TrailingSemicolonRule.self,
|
||||
TrailingWhitespaceRule.self,
|
||||
TypeBodyLengthRule.self,
|
||||
TypeContentsOrderRule.self,
|
||||
TypeNameRule.self,
|
||||
TypesafeArrayInitRule.self,
|
||||
UnavailableConditionRule.self,
|
||||
UnavailableFunctionRule.self,
|
||||
UnhandledThrowingTaskRule.self,
|
||||
UnneededBreakInSwitchRule.self,
|
||||
UnneededParenthesesInClosureArgumentRule.self,
|
||||
UnownedVariableCaptureRule.self,
|
||||
UntypedErrorInCatchRule.self,
|
||||
UnusedCaptureListRule.self,
|
||||
UnusedClosureParameterRule.self,
|
||||
UnusedControlFlowLabelRule.self,
|
||||
UnusedDeclarationRule.self,
|
||||
UnusedEnumeratedRule.self,
|
||||
UnusedImportRule.self,
|
||||
UnusedOptionalBindingRule.self,
|
||||
UnusedSetterValueRule.self,
|
||||
ValidIBInspectableRule.self,
|
||||
VerticalParameterAlignmentOnCallRule.self,
|
||||
VerticalParameterAlignmentRule.self,
|
||||
VerticalWhitespaceBetweenCasesRule.self,
|
||||
VerticalWhitespaceClosingBracesRule.self,
|
||||
VerticalWhitespaceOpeningBracesRule.self,
|
||||
VerticalWhitespaceRule.self,
|
||||
VoidFunctionInTernaryConditionRule.self,
|
||||
VoidReturnRule.self,
|
||||
WeakDelegateRule.self,
|
||||
XCTFailMessageRule.self,
|
||||
XCTSpecificMatcherRule.self,
|
||||
YodaConditionRule.self
|
||||
]
|
|
@ -1,29 +0,0 @@
|
|||
import Foundation
|
||||
|
||||
/// Represents unused or missing import statements.
|
||||
enum ImportUsage {
|
||||
/// The import is unused. Range is for the entire import statement.
|
||||
case unused(module: String, range: NSRange)
|
||||
/// The file is missing an explicit import of the `module`.
|
||||
case missing(module: String)
|
||||
|
||||
/// The range where the violation for this import usage should be reported.
|
||||
var violationRange: NSRange? {
|
||||
switch self {
|
||||
case .unused(_, let range):
|
||||
return range
|
||||
case .missing:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// The reason why this import usage is a violation.
|
||||
var violationReason: String? {
|
||||
switch self {
|
||||
case .unused:
|
||||
return nil
|
||||
case .missing(let module):
|
||||
return "Missing import for referenced module '\(module)'"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,60 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct AnonymousArgumentInMultilineClosureRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "anonymous_argument_in_multiline_closure",
|
||||
name: "Anonymous Argument in Multiline Closure",
|
||||
description: "Use named arguments in multiline closures",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("closure { $0 }"),
|
||||
Example("closure { print($0) }"),
|
||||
Example("""
|
||||
closure { arg in
|
||||
print(arg)
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
closure { arg in
|
||||
nestedClosure { $0 + arg }
|
||||
}
|
||||
""")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("""
|
||||
closure {
|
||||
print(↓$0)
|
||||
}
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(locationConverter: file.locationConverter)
|
||||
}
|
||||
}
|
||||
|
||||
private extension AnonymousArgumentInMultilineClosureRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
private let locationConverter: SourceLocationConverter
|
||||
|
||||
init(locationConverter: SourceLocationConverter) {
|
||||
self.locationConverter = locationConverter
|
||||
super.init(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
override func visit(_ node: ClosureExprSyntax) -> SyntaxVisitorContinueKind {
|
||||
let startLocation = locationConverter.location(for: node.leftBrace.positionAfterSkippingLeadingTrivia)
|
||||
let endLocation = locationConverter.location(for: node.rightBrace.endPositionBeforeTrailingTrivia)
|
||||
return startLocation.line == endLocation.line ? .skipChildren : .visitChildren
|
||||
}
|
||||
|
||||
override func visitPost(_ node: IdentifierExprSyntax) {
|
||||
if case .dollarIdentifier = node.identifier.tokenKind {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,62 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct BlockBasedKVORule: SwiftSyntaxRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "block_based_kvo",
|
||||
name: "Block Based KVO",
|
||||
description: "Prefer the new block based KVO API with keypaths when using Swift 3.2 or later",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example(#"""
|
||||
let observer = foo.observe(\.value, options: [.new]) { (foo, change) in
|
||||
print(change.newValue)
|
||||
}
|
||||
"""#)
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("""
|
||||
class Foo: NSObject {
|
||||
override ↓func observeValue(forKeyPath keyPath: String?, of object: Any?,
|
||||
change: [NSKeyValueChangeKey : Any]?,
|
||||
context: UnsafeMutableRawPointer?) {}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo: NSObject {
|
||||
override ↓func observeValue(forKeyPath keyPath: String?, of object: Any?,
|
||||
change: Dictionary<NSKeyValueChangeKey, Any>?,
|
||||
context: UnsafeMutableRawPointer?) {}
|
||||
}
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension BlockBasedKVORule {
|
||||
private final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: FunctionDeclSyntax) {
|
||||
guard node.modifiers.containsOverride,
|
||||
case let parameterList = node.signature.input.parameterList,
|
||||
parameterList.count == 4,
|
||||
node.identifier.text == "observeValue",
|
||||
parameterList.map(\.firstName.text) == ["forKeyPath", "of", "change", "context"]
|
||||
else {
|
||||
return
|
||||
}
|
||||
|
||||
let types = parameterList
|
||||
.map { $0.type.trimmedDescription.replacingOccurrences(of: " ", with: "") }
|
||||
let firstTypes = ["String?", "Any?", "[NSKeyValueChangeKey:Any]?", "UnsafeMutableRawPointer?"]
|
||||
let secondTypes = ["String?", "Any?", "Dictionary<NSKeyValueChangeKey,Any>?", "UnsafeMutableRawPointer?"]
|
||||
if types == firstTypes || types == secondTypes {
|
||||
violations.append(node.funcKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,232 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct ConvenienceTypeRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "convenience_type",
|
||||
name: "Convenience Type",
|
||||
description: "Types used for hosting only static members should be implemented as a caseless enum " +
|
||||
"to avoid instantiation",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("""
|
||||
enum Math { // enum
|
||||
public static let pi = 3.14
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
// class with inheritance
|
||||
class MathViewController: UIViewController {
|
||||
public static let pi = 3.14
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
@objc class Math: NSObject { // class visible to Obj-C
|
||||
public static let pi = 3.14
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
struct Math { // type with non-static declarations
|
||||
public static let pi = 3.14
|
||||
public let randomNumber = 2
|
||||
}
|
||||
"""),
|
||||
Example("class DummyClass {}"),
|
||||
Example("""
|
||||
class Foo: NSObject { // class with Obj-C class property
|
||||
class @objc let foo = 1
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo: NSObject { // class with Obj-C static property
|
||||
static @objc let foo = 1
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo { // @objc class func can't exist on an enum
|
||||
@objc class func foo() {}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo { // @objc static func can't exist on an enum
|
||||
@objc static func foo() {}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
@objcMembers class Foo { // @objc static func can't exist on an enum
|
||||
static func foo() {}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
final class Foo { // final class, but @objc class func can't exist on an enum
|
||||
@objc class func foo() {}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
final class Foo { // final class, but @objc static func can't exist on an enum
|
||||
@objc static func foo() {}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
@globalActor actor MyActor {
|
||||
static let shared = MyActor()
|
||||
}
|
||||
""")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("""
|
||||
↓struct Math {
|
||||
public static let pi = 3.14
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
↓struct Math {
|
||||
public static let pi = 3.14
|
||||
@available(*, unavailable) init() {}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
final ↓class Foo { // final class can't be inherited
|
||||
class let foo = 1
|
||||
}
|
||||
"""),
|
||||
|
||||
// Intentional false positives. Non-final classes could be
|
||||
// subclassed, but we figure it is probably rare enough that it is
|
||||
// more important to catch these cases, and manually disable the
|
||||
// rule if needed.
|
||||
|
||||
Example("""
|
||||
↓class Foo {
|
||||
class let foo = 1
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
↓class Foo {
|
||||
final class let foo = 1
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
↓class SomeClass {
|
||||
static func foo() {}
|
||||
}
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension ConvenienceTypeRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override var skippableDeclarations: [DeclSyntaxProtocol.Type] { [ProtocolDeclSyntax.self] }
|
||||
|
||||
override func visitPost(_ node: StructDeclSyntax) {
|
||||
if hasViolation(
|
||||
inheritance: node.inheritanceClause,
|
||||
attributes: node.attributes,
|
||||
members: node.memberBlock
|
||||
) {
|
||||
violations.append(node.structKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: ClassDeclSyntax) {
|
||||
if hasViolation(
|
||||
inheritance: node.inheritanceClause,
|
||||
attributes: node.attributes,
|
||||
members: node.memberBlock
|
||||
) {
|
||||
violations.append(node.classKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
private func hasViolation(inheritance: TypeInheritanceClauseSyntax?,
|
||||
attributes: AttributeListSyntax?,
|
||||
members: MemberDeclBlockSyntax) -> Bool {
|
||||
guard inheritance.isNilOrEmpty,
|
||||
!attributes.containsObjcMembers,
|
||||
!attributes.containsObjc,
|
||||
!members.members.isEmpty else {
|
||||
return false
|
||||
}
|
||||
|
||||
return ConvenienceTypeCheckVisitor(viewMode: .sourceAccurate)
|
||||
.walk(tree: members, handler: \.canBeConvenienceType)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class ConvenienceTypeCheckVisitor: ViolationsSyntaxVisitor {
|
||||
override var skippableDeclarations: [DeclSyntaxProtocol.Type] { .all }
|
||||
|
||||
private(set) var canBeConvenienceType = true
|
||||
|
||||
override func visitPost(_ node: VariableDeclSyntax) {
|
||||
if node.isInstanceVariable {
|
||||
canBeConvenienceType = false
|
||||
} else if node.attributes.containsObjc {
|
||||
canBeConvenienceType = false
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: FunctionDeclSyntax) {
|
||||
if node.modifiers.containsStaticOrClass {
|
||||
if node.attributes.containsObjc {
|
||||
canBeConvenienceType = false
|
||||
}
|
||||
} else {
|
||||
canBeConvenienceType = false
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: InitializerDeclSyntax) {
|
||||
if !node.attributes.hasUnavailableAttribute {
|
||||
canBeConvenienceType = false
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: SubscriptDeclSyntax) {
|
||||
if !node.modifiers.containsStaticOrClass {
|
||||
canBeConvenienceType = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension TypeInheritanceClauseSyntax? {
|
||||
var isNilOrEmpty: Bool {
|
||||
self?.inheritedTypeCollection.isEmpty ?? true
|
||||
}
|
||||
}
|
||||
|
||||
private extension AttributeListSyntax? {
|
||||
var containsObjcMembers: Bool {
|
||||
contains(attributeNamed: "objcMembers")
|
||||
}
|
||||
|
||||
var containsObjc: Bool {
|
||||
contains(attributeNamed: "objc")
|
||||
}
|
||||
}
|
||||
|
||||
private extension AttributeListSyntax? {
|
||||
var hasUnavailableAttribute: Bool {
|
||||
guard let attrs = self else {
|
||||
return false
|
||||
}
|
||||
|
||||
return attrs.contains { elem in
|
||||
guard let attr = elem.as(AttributeSyntax.self),
|
||||
let arguments = attr.argument?.as(AvailabilitySpecListSyntax.self) else {
|
||||
return false
|
||||
}
|
||||
|
||||
return attr.attributeNameText == "available" && arguments.contains { arg in
|
||||
arg.entry.as(TokenSyntax.self)?.tokenKind.isUnavailableKeyword == true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,45 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct DiscouragedAssertRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "discouraged_assert",
|
||||
name: "Discouraged Assert",
|
||||
description: "Prefer `assertionFailure()` and/or `preconditionFailure()` over `assert(false)`",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example(#"assert(true)"#),
|
||||
Example(#"assert(true, "foobar")"#),
|
||||
Example(#"assert(true, "foobar", file: "toto", line: 42)"#),
|
||||
Example(#"assert(false || true)"#),
|
||||
Example(#"XCTAssert(false)"#)
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example(#"↓assert(false)"#),
|
||||
Example(#"↓assert(false, "foobar")"#),
|
||||
Example(#"↓assert(false, "foobar", file: "toto", line: 42)"#),
|
||||
Example(#"↓assert( false , "foobar")"#)
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension DiscouragedAssertRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: FunctionCallExprSyntax) {
|
||||
guard node.calledExpression.as(IdentifierExprSyntax.self)?.identifier.text == "assert",
|
||||
let firstArg = node.argumentList.first,
|
||||
firstArg.label == nil,
|
||||
let boolExpr = firstArg.expression.as(BooleanLiteralExprSyntax.self),
|
||||
boolExpr.booleanLiteral.tokenKind == .keyword(.false) else {
|
||||
return
|
||||
}
|
||||
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,237 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct DiscouragedNoneNameRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static var description = RuleDescription(
|
||||
identifier: "discouraged_none_name",
|
||||
name: "Discouraged None Name",
|
||||
description: "Enum cases and static members named `none` are discouraged as they can conflict with " +
|
||||
"`Optional<T>.none`.",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
// Should not trigger unless exactly matches "none"
|
||||
Example("""
|
||||
enum MyEnum {
|
||||
case nOne
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum MyEnum {
|
||||
case _none
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum MyEnum {
|
||||
case none_
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum MyEnum {
|
||||
case none(Any)
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum MyEnum {
|
||||
case nonenone
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class MyClass {
|
||||
class var nonenone: MyClass { MyClass() }
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class MyClass {
|
||||
static var nonenone = MyClass()
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class MyClass {
|
||||
static let nonenone = MyClass()
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
struct MyStruct {
|
||||
static var nonenone = MyStruct()
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
struct MyStruct {
|
||||
static let nonenone = MyStruct()
|
||||
}
|
||||
"""),
|
||||
|
||||
// Should not trigger if not an enum case or static/class member
|
||||
Example("""
|
||||
struct MyStruct {
|
||||
let none = MyStruct()
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
struct MyStruct {
|
||||
var none = MyStruct()
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class MyClass {
|
||||
let none = MyClass()
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class MyClass {
|
||||
var none = MyClass()
|
||||
}
|
||||
""")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("""
|
||||
enum MyEnum {
|
||||
case ↓none
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum MyEnum {
|
||||
case a, ↓none
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum MyEnum {
|
||||
case ↓none, b
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum MyEnum {
|
||||
case a, ↓none, b
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum MyEnum {
|
||||
case a
|
||||
case ↓none
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum MyEnum {
|
||||
case ↓none
|
||||
case b
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum MyEnum {
|
||||
case a
|
||||
case ↓none
|
||||
case b
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class MyClass {
|
||||
↓static let none = MyClass()
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class MyClass {
|
||||
↓static let none: MyClass = MyClass()
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class MyClass {
|
||||
↓static var none: MyClass = MyClass()
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class MyClass {
|
||||
↓class var none: MyClass { MyClass() }
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
struct MyStruct {
|
||||
↓static var none = MyStruct()
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
struct MyStruct {
|
||||
↓static var none: MyStruct = MyStruct()
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
struct MyStruct {
|
||||
↓static var none = MyStruct()
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
struct MyStruct {
|
||||
↓static var none: MyStruct = MyStruct()
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
struct MyStruct {
|
||||
↓static var a = MyStruct(), none = MyStruct()
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
struct MyStruct {
|
||||
↓static var none = MyStruct(), a = MyStruct()
|
||||
}
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension DiscouragedNoneNameRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: EnumCaseElementSyntax) {
|
||||
let emptyParams = node.associatedValue?.parameterList.isEmpty ?? true
|
||||
if emptyParams, node.identifier.isNone {
|
||||
violations.append(ReasonedRuleViolation(
|
||||
position: node.positionAfterSkippingLeadingTrivia,
|
||||
reason: reason(type: "`case`")
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: VariableDeclSyntax) {
|
||||
let type: String? = {
|
||||
if node.modifiers.isClass {
|
||||
return "`class` member"
|
||||
} else if node.modifiers.isStatic {
|
||||
return "`static` member"
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}()
|
||||
|
||||
guard let type else {
|
||||
return
|
||||
}
|
||||
|
||||
for binding in node.bindings {
|
||||
guard let pattern = binding.pattern.as(IdentifierPatternSyntax.self), pattern.identifier.isNone else {
|
||||
continue
|
||||
}
|
||||
|
||||
violations.append(ReasonedRuleViolation(
|
||||
position: node.positionAfterSkippingLeadingTrivia,
|
||||
reason: reason(type: type)
|
||||
))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
private func reason(type: String) -> String {
|
||||
let reason = "Avoid naming \(type) `none` as the compiler can think you mean `Optional<T>.none`"
|
||||
let recommendation = "consider using an Optional value instead"
|
||||
return "\(reason); \(recommendation)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension TokenSyntax {
|
||||
var isNone: Bool {
|
||||
tokenKind == .identifier("none") || tokenKind == .identifier("`none`")
|
||||
}
|
||||
}
|
|
@ -1,58 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct DiscouragedObjectLiteralRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRule {
|
||||
var configuration = DiscouragedObjectLiteralConfiguration()
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "discouraged_object_literal",
|
||||
name: "Discouraged Object Literal",
|
||||
description: "Prefer initializers over object literals",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("let image = UIImage(named: aVariable)"),
|
||||
Example("let image = UIImage(named: \"interpolated \\(variable)\")"),
|
||||
Example("let color = UIColor(red: value, green: value, blue: value, alpha: 1)"),
|
||||
Example("let image = NSImage(named: aVariable)"),
|
||||
Example("let image = NSImage(named: \"interpolated \\(variable)\")"),
|
||||
Example("let color = NSColor(red: value, green: value, blue: value, alpha: 1)")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("let image = ↓#imageLiteral(resourceName: \"image.jpg\")"),
|
||||
Example("let color = ↓#colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(configuration: configuration)
|
||||
}
|
||||
}
|
||||
|
||||
private extension DiscouragedObjectLiteralRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
private let configuration: ConfigurationType
|
||||
|
||||
init(configuration: ConfigurationType) {
|
||||
self.configuration = configuration
|
||||
super.init(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: MacroExpansionExprSyntax) {
|
||||
guard
|
||||
case let .identifier(identifierText) = node.macro.tokenKind,
|
||||
["colorLiteral", "imageLiteral"].contains(identifierText)
|
||||
else {
|
||||
return
|
||||
}
|
||||
|
||||
if !configuration.imageLiteral && identifierText == "imageLiteral" {
|
||||
return
|
||||
}
|
||||
|
||||
if !configuration.colorLiteral && identifierText == "colorLiteral" {
|
||||
return
|
||||
}
|
||||
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,49 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct DiscouragedOptionalBooleanRule: OptInRule, ConfigurationProviderRule, SwiftSyntaxRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "discouraged_optional_boolean",
|
||||
name: "Discouraged Optional Boolean",
|
||||
description: "Prefer non-optional booleans over optional booleans",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: DiscouragedOptionalBooleanRuleExamples.nonTriggeringExamples,
|
||||
triggeringExamples: DiscouragedOptionalBooleanRuleExamples.triggeringExamples
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension DiscouragedOptionalBooleanRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: OptionalTypeSyntax) {
|
||||
if node.wrappedType.as(SimpleTypeIdentifierSyntax.self)?.typeName == "Bool" {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: OptionalChainingExprSyntax) {
|
||||
if node.expression.as(IdentifierExprSyntax.self)?.identifier.text == "Bool" {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: FunctionCallExprSyntax) {
|
||||
guard
|
||||
let calledExpression = node.calledExpression.as(MemberAccessExprSyntax.self),
|
||||
let singleArgument = node.argumentList.onlyElement,
|
||||
singleArgument.expression.is(BooleanLiteralExprSyntax.self),
|
||||
let base = calledExpression.base?.as(IdentifierExprSyntax.self),
|
||||
base.identifier.text == "Optional",
|
||||
calledExpression.name.text == "some"
|
||||
else {
|
||||
return
|
||||
}
|
||||
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,168 +0,0 @@
|
|||
internal struct DiscouragedOptionalBooleanRuleExamples {
|
||||
static let nonTriggeringExamples = [
|
||||
// Global variable
|
||||
Example("var foo: Bool"),
|
||||
Example("var foo: [String: Bool]"),
|
||||
Example("var foo: [Bool]"),
|
||||
Example("let foo: Bool = true"),
|
||||
Example("let foo: Bool = false"),
|
||||
Example("let foo: [String: Bool] = [:]"),
|
||||
Example("let foo: [Bool] = []"),
|
||||
|
||||
// Computed get variable
|
||||
Example("var foo: Bool { return true }"),
|
||||
Example("let foo: Bool { return false }()"),
|
||||
|
||||
// Free function return
|
||||
Example("func foo() -> Bool {}"),
|
||||
Example("func foo() -> [String: Bool] {}"),
|
||||
Example("func foo() -> ([Bool]) -> String {}"),
|
||||
|
||||
// Free function parameter
|
||||
Example("func foo(input: Bool = true) {}"),
|
||||
Example("func foo(input: [String: Bool] = [:]) {}"),
|
||||
Example("func foo(input: [Bool] = []) {}"),
|
||||
|
||||
// Method return
|
||||
wrapExample("class", "func foo() -> Bool {}"),
|
||||
wrapExample("class", "func foo() -> [String: Bool] {}"),
|
||||
wrapExample("class", "func foo() -> ([Bool]) -> String {}"),
|
||||
|
||||
wrapExample("struct", "func foo() -> Bool {}"),
|
||||
wrapExample("struct", "func foo() -> [String: Bool] {}"),
|
||||
wrapExample("struct", "func foo() -> ([Bool]) -> String {}"),
|
||||
|
||||
wrapExample("enum", "func foo() -> Bool {}"),
|
||||
wrapExample("enum", "func foo() -> [String: Bool] {}"),
|
||||
wrapExample("enum", "func foo() -> ([Bool]) -> String {}"),
|
||||
|
||||
// Method parameter
|
||||
wrapExample("class", "func foo(input: Bool = true) {}"),
|
||||
wrapExample("class", "func foo(input: [String: Bool] = [:]) {}"),
|
||||
wrapExample("class", "func foo(input: [Bool] = []) {}"),
|
||||
|
||||
wrapExample("struct", "func foo(input: Bool = true) {}"),
|
||||
wrapExample("struct", "func foo(input: [String: Bool] = [:]) {}"),
|
||||
wrapExample("struct", "func foo(input: [Bool] = []) {}"),
|
||||
|
||||
wrapExample("enum", "func foo(input: Bool = true) {}"),
|
||||
wrapExample("enum", "func foo(input: [String: Bool] = [:]) {}"),
|
||||
wrapExample("enum", "func foo(input: [Bool] = []) {}")
|
||||
]
|
||||
|
||||
static let triggeringExamples = [
|
||||
// Global variable
|
||||
Example("var foo: ↓Bool?"),
|
||||
Example("var foo: [String: ↓Bool?]"),
|
||||
Example("var foo: [↓Bool?]"),
|
||||
Example("let foo: ↓Bool? = nil"),
|
||||
Example("let foo: [String: ↓Bool?] = [:]"),
|
||||
Example("let foo: [↓Bool?] = []"),
|
||||
Example("let foo = ↓Optional.some(false)"),
|
||||
Example("let foo = ↓Optional.some(true)"),
|
||||
|
||||
// Computed Get Variable
|
||||
Example("var foo: ↓Bool? { return nil }"),
|
||||
Example("let foo: ↓Bool? { return nil }()"),
|
||||
|
||||
// Free function return
|
||||
Example("func foo() -> ↓Bool? {}"),
|
||||
Example("func foo() -> [String: ↓Bool?] {}"),
|
||||
Example("func foo() -> [↓Bool?] {}"),
|
||||
Example("static func foo() -> ↓Bool? {}"),
|
||||
Example("static func foo() -> [String: ↓Bool?] {}"),
|
||||
Example("static func foo() -> [↓Bool?] {}"),
|
||||
Example("func foo() -> (↓Bool?) -> String {}"),
|
||||
Example("func foo() -> ([Int]) -> ↓Bool? {}"),
|
||||
|
||||
// Free function parameter
|
||||
Example("func foo(input: ↓Bool?) {}"),
|
||||
Example("func foo(input: [String: ↓Bool?]) {}"),
|
||||
Example("func foo(input: [↓Bool?]) {}"),
|
||||
Example("static func foo(input: ↓Bool?) {}"),
|
||||
Example("static func foo(input: [String: ↓Bool?]) {}"),
|
||||
Example("static func foo(input: [↓Bool?]) {}"),
|
||||
|
||||
// Instance variable
|
||||
wrapExample("class", "var foo: ↓Bool?"),
|
||||
wrapExample("class", "var foo: [String: ↓Bool?]"),
|
||||
wrapExample("class", "let foo: ↓Bool? = nil"),
|
||||
wrapExample("class", "let foo: [String: ↓Bool?] = [:]"),
|
||||
wrapExample("class", "let foo: [↓Bool?] = []"),
|
||||
|
||||
wrapExample("struct", "var foo: ↓Bool?"),
|
||||
wrapExample("struct", "var foo: [String: ↓Bool?]"),
|
||||
wrapExample("struct", "let foo: ↓Bool? = nil"),
|
||||
wrapExample("struct", "let foo: [String: ↓Bool?] = [:]"),
|
||||
wrapExample("struct", "let foo: [↓Bool?] = []"),
|
||||
|
||||
// Instance computed variable
|
||||
wrapExample("class", "var foo: ↓Bool? { return nil }"),
|
||||
wrapExample("class", "let foo: ↓Bool? { return nil }()"),
|
||||
|
||||
wrapExample("struct", "var foo: ↓Bool? { return nil }"),
|
||||
wrapExample("struct", "let foo: ↓Bool? { return nil }()"),
|
||||
|
||||
wrapExample("enum", "var foo: ↓Bool? { return nil }"),
|
||||
wrapExample("enum", "let foo: ↓Bool? { return nil }()"),
|
||||
|
||||
// Method return
|
||||
wrapExample("class", "func foo() -> ↓Bool? {}"),
|
||||
wrapExample("class", "func foo() -> [String: ↓Bool?] {}"),
|
||||
wrapExample("class", "func foo() -> [↓Bool?] {}"),
|
||||
wrapExample("class", "static func foo() -> ↓Bool? {}"),
|
||||
wrapExample("class", "static func foo() -> [String: ↓Bool?] {}"),
|
||||
wrapExample("class", "static func foo() -> [↓Bool?] {}"),
|
||||
wrapExample("class", "func foo() -> (↓Bool?) -> String {}"),
|
||||
wrapExample("class", "func foo() -> ([Int]) -> ↓Bool? {}"),
|
||||
|
||||
wrapExample("struct", "func foo() -> ↓Bool? {}"),
|
||||
wrapExample("struct", "func foo() -> [String: ↓Bool?] {}"),
|
||||
wrapExample("struct", "func foo() -> [↓Bool?] {}"),
|
||||
wrapExample("struct", "static func foo() -> ↓Bool? {}"),
|
||||
wrapExample("struct", "static func foo() -> [String: ↓Bool?] {}"),
|
||||
wrapExample("struct", "static func foo() -> [↓Bool?] {}"),
|
||||
wrapExample("struct", "func foo() -> (↓Bool?) -> String {}"),
|
||||
wrapExample("struct", "func foo() -> ([Int]) -> ↓Bool? {}"),
|
||||
|
||||
wrapExample("enum", "func foo() -> ↓Bool? {}"),
|
||||
wrapExample("enum", "func foo() -> [String: ↓Bool?] {}"),
|
||||
wrapExample("enum", "func foo() -> [↓Bool?] {}"),
|
||||
wrapExample("enum", "static func foo() -> ↓Bool? {}"),
|
||||
wrapExample("enum", "static func foo() -> [String: ↓Bool?] {}"),
|
||||
wrapExample("enum", "static func foo() -> [↓Bool?] {}"),
|
||||
wrapExample("enum", "func foo() -> (↓Bool?) -> String {}"),
|
||||
wrapExample("enum", "func foo() -> ([Int]) -> ↓Bool? {}"),
|
||||
|
||||
// Method parameter
|
||||
wrapExample("class", "func foo(input: ↓Bool?) {}"),
|
||||
wrapExample("class", "func foo(input: [String: ↓Bool?]) {}"),
|
||||
wrapExample("class", "func foo(input: [↓Bool?]) {}"),
|
||||
wrapExample("class", "static func foo(input: ↓Bool?) {}"),
|
||||
wrapExample("class", "static func foo(input: [String: ↓Bool?]) {}"),
|
||||
wrapExample("class", "static func foo(input: [↓Bool?]) {}"),
|
||||
|
||||
wrapExample("struct", "func foo(input: ↓Bool?) {}"),
|
||||
wrapExample("struct", "func foo(input: [String: ↓Bool?]) {}"),
|
||||
wrapExample("struct", "func foo(input: [↓Bool?]) {}"),
|
||||
wrapExample("struct", "static func foo(input: ↓Bool?) {}"),
|
||||
wrapExample("struct", "static func foo(input: [String: ↓Bool?]) {}"),
|
||||
wrapExample("struct", "static func foo(input: [↓Bool?]) {}"),
|
||||
|
||||
wrapExample("enum", "func foo(input: ↓Bool?) {}"),
|
||||
wrapExample("enum", "func foo(input: [String: ↓Bool?]) {}"),
|
||||
wrapExample("enum", "func foo(input: [↓Bool?]) {}"),
|
||||
wrapExample("enum", "static func foo(input: ↓Bool?) {}"),
|
||||
wrapExample("enum", "static func foo(input: [String: ↓Bool?]) {}"),
|
||||
wrapExample("enum", "static func foo(input: [↓Bool?]) {}"),
|
||||
|
||||
// Optional chaining
|
||||
Example("_ = ↓Bool?.values()")
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
private func wrapExample(_ type: String, _ test: String, file: StaticString = #file, line: UInt = #line) -> Example {
|
||||
return Example("\(type) Foo {\n\t\(test)\n}", file: file, line: line)
|
||||
}
|
|
@ -1,219 +0,0 @@
|
|||
internal struct DiscouragedOptionalCollectionExamples {
|
||||
static let nonTriggeringExamples = [
|
||||
// Global variable
|
||||
Example("var foo: [Int]"),
|
||||
Example("var foo: [String: Int]"),
|
||||
Example("var foo: Set<String>"),
|
||||
Example("var foo: [String: [String: Int]]"),
|
||||
Example("let foo: [Int] = []"),
|
||||
Example("let foo: [String: Int] = [:]"),
|
||||
Example("let foo: Set<String> = []"),
|
||||
Example("let foo: [String: [String: Int]] = [:]"),
|
||||
|
||||
// Computed get variable
|
||||
Example("var foo: [Int] { return [] }"),
|
||||
|
||||
// Free function return
|
||||
Example("func foo() -> [Int] {}"),
|
||||
Example("func foo() -> [String: String] {}"),
|
||||
Example("func foo() -> Set<Int> {}"),
|
||||
Example("func foo() -> ([Int]) -> String {}"),
|
||||
|
||||
// Free function parameter
|
||||
Example("func foo(input: [String] = []) {}"),
|
||||
Example("func foo(input: [String: String] = [:]) {}"),
|
||||
Example("func foo(input: Set<String> = []) {}"),
|
||||
|
||||
// Method return
|
||||
wrapExample("class", "func foo() -> [Int] {}"),
|
||||
wrapExample("class", "func foo() -> [String: String] {}"),
|
||||
wrapExample("class", "func foo() -> Set<Int> {}"),
|
||||
wrapExample("class", "func foo() -> ([Int]) -> String {}"),
|
||||
|
||||
wrapExample("struct", "func foo() -> [Int] {}"),
|
||||
wrapExample("struct", "func foo() -> [String: String] {}"),
|
||||
wrapExample("struct", "func foo() -> Set<Int> {}"),
|
||||
wrapExample("struct", "func foo() -> ([Int]) -> String {}"),
|
||||
|
||||
wrapExample("enum", "func foo() -> [Int] {}"),
|
||||
wrapExample("enum", "func foo() -> [String: String] {}"),
|
||||
wrapExample("enum", "func foo() -> Set<Int> {}"),
|
||||
wrapExample("enum", "func foo() -> ([Int]) -> String {}"),
|
||||
|
||||
// Method parameter
|
||||
wrapExample("class", "func foo(input: [String] = []) {}"),
|
||||
wrapExample("class", "func foo(input: [String: String] = [:]) {}"),
|
||||
wrapExample("class", "func foo(input: Set<String> = []) {}"),
|
||||
|
||||
wrapExample("struct", "func foo(input: [String] = []) {}"),
|
||||
wrapExample("struct", "func foo(input: [String: String] = [:]) {}"),
|
||||
wrapExample("struct", "func foo(input: Set<String> = []) {}"),
|
||||
|
||||
wrapExample("enum", "func foo(input: [String] = []) {}"),
|
||||
wrapExample("enum", "func foo(input: [String: String] = [:]) {}"),
|
||||
wrapExample("enum", "func foo(input: Set<String> = []) {}")
|
||||
]
|
||||
|
||||
static let triggeringExamples = [
|
||||
// Global variable
|
||||
Example("↓var foo: [Int]?"),
|
||||
Example("↓var foo: [String: Int]?"),
|
||||
Example("↓var foo: Set<String>?"),
|
||||
Example("↓let foo: [Int]? = nil"),
|
||||
Example("↓let foo: [String: Int]? = nil"),
|
||||
Example("↓let foo: Set<String>? = nil"),
|
||||
|
||||
// Computed Get Variable
|
||||
Example("↓var foo: [Int]? { return nil }"),
|
||||
Example("↓let foo: [Int]? { return nil }()"),
|
||||
|
||||
// Free function return
|
||||
Example("func ↓foo() -> [T]? {}"),
|
||||
Example("func ↓foo() -> [String: String]? {}"),
|
||||
Example("func ↓foo() -> [String: [String: String]]? {}"),
|
||||
Example("func ↓foo() -> [String: [String: String]?] {}"),
|
||||
Example("func ↓foo() -> Set<Int>? {}"),
|
||||
Example("static func ↓foo() -> [T]? {}"),
|
||||
Example("static func ↓foo() -> [String: String]? {}"),
|
||||
Example("static func ↓foo() -> [String: [String: String]]? {}"),
|
||||
Example("static func ↓foo() -> [String: [String: String]?] {}"),
|
||||
Example("static func ↓foo() -> Set<Int>? {}"),
|
||||
Example("func ↓foo() -> ([Int]?) -> String {}"),
|
||||
Example("func ↓foo() -> ([Int]) -> [String]? {}"),
|
||||
|
||||
// Free function parameter
|
||||
Example("func foo(↓input: [String: String]?) {}"),
|
||||
Example("func foo(↓input: [String: [String: String]]?) {}"),
|
||||
Example("func foo(↓input: [String: [String: String]?]) {}"),
|
||||
Example("func foo(↓↓input: [String: [String: String]?]?) {}"),
|
||||
Example("func foo<K, V>(_ dict1: [K: V], ↓_ dict2: [K: V]?) -> [K: V]"),
|
||||
Example("func foo<K, V>(dict1: [K: V], ↓dict2: [K: V]?) -> [K: V]"),
|
||||
Example("static func foo(↓input: [String: String]?) {}"),
|
||||
Example("static func foo(↓input: [String: [String: String]]?) {}"),
|
||||
Example("static func foo(↓input: [String: [String: String]?]) {}"),
|
||||
Example("static func foo(↓↓input: [String: [String: String]?]?) {}"),
|
||||
Example("static func foo<K, V>(_ dict1: [K: V], ↓_ dict2: [K: V]?) -> [K: V]"),
|
||||
Example("static func foo<K, V>(dict1: [K: V], ↓dict2: [K: V]?) -> [K: V]"),
|
||||
|
||||
// Instance variable
|
||||
wrapExample("class", "↓var foo: [Int]?"),
|
||||
wrapExample("class", "↓var foo: [String: Int]?"),
|
||||
wrapExample("class", "↓var foo: Set<String>?"),
|
||||
wrapExample("class", "↓let foo: [Int]? = nil"),
|
||||
wrapExample("class", "↓let foo: [String: Int]? = nil"),
|
||||
wrapExample("class", "↓let foo: Set<String>? = nil"),
|
||||
|
||||
wrapExample("struct", "↓var foo: [Int]?"),
|
||||
wrapExample("struct", "↓var foo: [String: Int]?"),
|
||||
wrapExample("struct", "↓var foo: Set<String>?"),
|
||||
wrapExample("struct", "↓let foo: [Int]? = nil"),
|
||||
wrapExample("struct", "↓let foo: [String: Int]? = nil"),
|
||||
wrapExample("struct", "↓let foo: Set<String>? = nil"),
|
||||
|
||||
// Instance computed variable
|
||||
wrapExample("class", "↓var foo: [Int]? { return nil }"),
|
||||
wrapExample("class", "↓let foo: [Int]? { return nil }()"),
|
||||
wrapExample("class", "↓var foo: Set<String>? { return nil }"),
|
||||
wrapExample("class", "↓let foo: Set<String>? { return nil }()"),
|
||||
|
||||
wrapExample("struct", "↓var foo: [Int]? { return nil }"),
|
||||
wrapExample("struct", "↓let foo: [Int]? { return nil }()"),
|
||||
wrapExample("struct", "↓var foo: Set<String>? { return nil }"),
|
||||
wrapExample("struct", "↓let foo: Set<String>? { return nil }()"),
|
||||
|
||||
wrapExample("enum", "↓var foo: [Int]? { return nil }"),
|
||||
wrapExample("enum", "↓let foo: [Int]? { return nil }()"),
|
||||
wrapExample("enum", "↓var foo: Set<String>? { return nil }"),
|
||||
wrapExample("enum", "↓let foo: Set<String>? { return nil }()"),
|
||||
|
||||
// Method return
|
||||
wrapExample("class", "func ↓foo() -> [T]? {}"),
|
||||
wrapExample("class", "func ↓foo() -> [String: String]? {}"),
|
||||
wrapExample("class", "func ↓foo() -> [String: [String: String]]? {}"),
|
||||
wrapExample("class", "func ↓foo() -> [String: [String: String]?] {}"),
|
||||
wrapExample("class", "func ↓foo() -> Set<Int>? {}"),
|
||||
wrapExample("class", "static func ↓foo() -> [T]? {}"),
|
||||
wrapExample("class", "static func ↓foo() -> [String: String]? {}"),
|
||||
wrapExample("class", "static func ↓foo() -> [String: [String: String]]? {}"),
|
||||
wrapExample("class", "static func ↓foo() -> [String: [String: String]?] {}"),
|
||||
wrapExample("class", "static func ↓foo() -> Set<Int>? {}"),
|
||||
wrapExample("class", "func ↓foo() -> ([Int]?) -> String {}"),
|
||||
wrapExample("class", "func ↓foo() -> ([Int]) -> [String]? {}"),
|
||||
|
||||
wrapExample("struct", "func ↓foo() -> [T]? {}"),
|
||||
wrapExample("struct", "func ↓foo() -> [String: String]? {}"),
|
||||
wrapExample("struct", "func ↓foo() -> [String: [String: String]]? {}"),
|
||||
wrapExample("struct", "func ↓foo() -> [String: [String: String]?] {}"),
|
||||
wrapExample("struct", "func ↓foo() -> Set<Int>? {}"),
|
||||
wrapExample("struct", "static func ↓foo() -> [T]? {}"),
|
||||
wrapExample("struct", "static func ↓foo() -> [String: String]? {}"),
|
||||
wrapExample("struct", "static func ↓foo() -> [String: [String: String]]? {}"),
|
||||
wrapExample("struct", "static func ↓foo() -> [String: [String: String]?] {}"),
|
||||
wrapExample("struct", "static func ↓foo() -> Set<Int>? {}"),
|
||||
wrapExample("struct", "func ↓foo() -> ([Int]?) -> String {}"),
|
||||
wrapExample("struct", "func ↓foo() -> ([Int]) -> [String]? {}"),
|
||||
|
||||
wrapExample("enum", "func ↓foo() -> [T]? {}"),
|
||||
wrapExample("enum", "func ↓foo() -> [String: String]? {}"),
|
||||
wrapExample("enum", "func ↓foo() -> [String: [String: String]]? {}"),
|
||||
wrapExample("enum", "func ↓foo() -> [String: [String: String]?] {}"),
|
||||
wrapExample("enum", "func ↓foo() -> Set<Int>? {}"),
|
||||
wrapExample("enum", "static func ↓foo() -> [T]? {}"),
|
||||
wrapExample("enum", "static func ↓foo() -> [String: String]? {}"),
|
||||
wrapExample("enum", "static func ↓foo() -> [String: [String: String]]? {}"),
|
||||
wrapExample("enum", "static func ↓foo() -> [String: [String: String]?] {}"),
|
||||
wrapExample("enum", "static func ↓foo() -> Set<Int>? {}"),
|
||||
wrapExample("enum", "func ↓foo() -> ([Int]?) -> String {}"),
|
||||
wrapExample("enum", "func ↓foo() -> ([Int]) -> [String]? {}"),
|
||||
|
||||
// Method parameter
|
||||
wrapExample("class", "func foo(↓input: [String: String]?) {}"),
|
||||
wrapExample("class", "func foo(↓input: [String: [String: String]]?) {}"),
|
||||
wrapExample("class", "func foo(↓input: [String: [String: String]?]) {}"),
|
||||
wrapExample("class", "func foo(↓↓input: [String: [String: String]?]?) {}"),
|
||||
wrapExample("class", "func foo<K, V>(_ dict1: [K: V], ↓_ dict2: [K: V]?) -> [K: V]"),
|
||||
wrapExample("class", "func foo<K, V>(dict1: [K: V], ↓dict2: [K: V]?) -> [K: V]"),
|
||||
wrapExample("class", "static func foo(↓input: [String: String]?) {}"),
|
||||
wrapExample("class", "static func foo(↓input: [String: [String: String]]?) {}"),
|
||||
wrapExample("class", "static func foo(↓input: [String: [String: String]?]) {}"),
|
||||
wrapExample("class", "static func foo(↓↓input: [String: [String: String]?]?) {}"),
|
||||
wrapExample("class", "static func foo<K, V>(_ dict1: [K: V], ↓_ dict2: [K: V]?) -> [K: V]"),
|
||||
wrapExample("class", "static func foo<K, V>(dict1: [K: V], ↓dict2: [K: V]?) -> [K: V]"),
|
||||
|
||||
wrapExample("struct", "func foo(↓input: [String: String]?) {}"),
|
||||
wrapExample("struct", "func foo(↓input: [String: [String: String]]?) {}"),
|
||||
wrapExample("struct", "func foo(↓input: [String: [String: String]?]) {}"),
|
||||
wrapExample("struct", "func foo(↓↓input: [String: [String: String]?]?) {}"),
|
||||
wrapExample("struct", "func foo<K, V>(_ dict1: [K: V], ↓_ dict2: [K: V]?) -> [K: V]"),
|
||||
wrapExample("struct", "func foo<K, V>(dict1: [K: V], ↓dict2: [K: V]?) -> [K: V]"),
|
||||
wrapExample("struct", "static func foo(↓input: [String: String]?) {}"),
|
||||
wrapExample("struct", "static func foo(↓input: [String: [String: String]]?) {}"),
|
||||
wrapExample("struct", "static func foo(↓input: [String: [String: String]?]) {}"),
|
||||
wrapExample("struct", "static func foo(↓↓input: [String: [String: String]?]?) {}"),
|
||||
wrapExample("struct", "static func foo<K, V>(_ dict1: [K: V], ↓_ dict2: [K: V]?) -> [K: V]"),
|
||||
wrapExample("struct", "static func foo<K, V>(dict1: [K: V], ↓dict2: [K: V]?) -> [K: V]"),
|
||||
|
||||
wrapExample("enum", "func foo(↓input: [String: String]?) {}"),
|
||||
wrapExample("enum", "func foo(↓input: [String: [String: String]]?) {}"),
|
||||
wrapExample("enum", "func foo(↓input: [String: [String: String]?]) {}"),
|
||||
wrapExample("enum", "func foo(↓↓input: [String: [String: String]?]?) {}"),
|
||||
wrapExample("enum", "func foo<K, V>(_ dict1: [K: V], ↓_ dict2: [K: V]?) -> [K: V]"),
|
||||
wrapExample("enum", "func foo<K, V>(dict1: [K: V], ↓dict2: [K: V]?) -> [K: V]"),
|
||||
wrapExample("enum", "static func foo(↓input: [String: String]?) {}"),
|
||||
wrapExample("enum", "static func foo(↓input: [String: [String: String]]?) {}"),
|
||||
wrapExample("enum", "static func foo(↓input: [String: [String: String]?]) {}"),
|
||||
wrapExample("enum", "static func foo(↓↓input: [String: [String: String]?]?) {}"),
|
||||
wrapExample("enum", "static func foo<K, V>(_ dict1: [K: V], ↓_ dict2: [K: V]?) -> [K: V]"),
|
||||
wrapExample("enum", "static func foo<K, V>(dict1: [K: V], ↓dict2: [K: V]?) -> [K: V]")
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
private func wrapExample(_ type: String, _ test: String, file: StaticString = #file, line: UInt = #line) -> Example {
|
||||
return Example("""
|
||||
\(type) Foo {
|
||||
\(test)
|
||||
}
|
||||
""", file: file, line: line)
|
||||
}
|
|
@ -1,164 +0,0 @@
|
|||
import SourceKittenFramework
|
||||
|
||||
struct DiscouragedOptionalCollectionRule: ASTRule, OptInRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "discouraged_optional_collection",
|
||||
name: "Discouraged Optional Collection",
|
||||
description: "Prefer empty collection over optional collection",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: DiscouragedOptionalCollectionExamples.nonTriggeringExamples,
|
||||
triggeringExamples: DiscouragedOptionalCollectionExamples.triggeringExamples
|
||||
)
|
||||
|
||||
func validate(file: SwiftLintFile,
|
||||
kind: SwiftDeclarationKind,
|
||||
dictionary: SourceKittenDictionary) -> [StyleViolation] {
|
||||
let offsets = variableViolations(kind: kind, dictionary: dictionary) +
|
||||
functionViolations(file: file, kind: kind, dictionary: dictionary)
|
||||
|
||||
return offsets.map {
|
||||
StyleViolation(ruleDescription: Self.description,
|
||||
severity: configuration.severity,
|
||||
location: Location(file: file, byteOffset: $0))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
private func variableViolations(kind: SwiftDeclarationKind, dictionary: SourceKittenDictionary) -> [ByteCount] {
|
||||
guard
|
||||
SwiftDeclarationKind.variableKinds.contains(kind),
|
||||
let offset = dictionary.offset,
|
||||
let typeName = dictionary.typeName else { return [] }
|
||||
|
||||
return typeName.optionalCollectionRanges().map { _ in offset }
|
||||
}
|
||||
|
||||
private func functionViolations(file: SwiftLintFile,
|
||||
kind: SwiftDeclarationKind,
|
||||
dictionary: SourceKittenDictionary) -> [ByteCount] {
|
||||
guard
|
||||
SwiftDeclarationKind.functionKinds.contains(kind),
|
||||
let nameOffset = dictionary.nameOffset,
|
||||
let nameLength = dictionary.nameLength,
|
||||
let length = dictionary.length,
|
||||
let offset = dictionary.offset,
|
||||
case let start = nameOffset + nameLength,
|
||||
case let end = dictionary.bodyOffset ?? offset + length,
|
||||
case let byteRange = ByteRange(location: start, length: end - start),
|
||||
case let contents = file.stringView,
|
||||
let range = file.stringView.byteRangeToNSRange(byteRange),
|
||||
let match = file.match(pattern: "->\\s*(.*?)\\{", excludingSyntaxKinds: excludingKinds, range: range).first
|
||||
else { return [] }
|
||||
|
||||
return contents.substring(with: match).optionalCollectionRanges().map { _ in nameOffset }
|
||||
}
|
||||
|
||||
private let excludingKinds = SyntaxKind.allKinds.subtracting([.typeidentifier])
|
||||
}
|
||||
|
||||
private extension String {
|
||||
/// Ranges of optional collections within the bounds of the string.
|
||||
///
|
||||
/// Example: [String: [Int]?]
|
||||
///
|
||||
/// [ S t r i n g : [ I n t ] ? ]
|
||||
/// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
||||
/// ^ ^
|
||||
/// = [9, 14]
|
||||
/// = [9, 15), mathematical interval, w/ lower and upper bounds.
|
||||
///
|
||||
/// Example: [String: [Int]?]?
|
||||
///
|
||||
/// [ S t r i n g : [ I n t ] ? ] ?
|
||||
/// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
||||
/// ^ ^ ^ ^
|
||||
/// = [0, 16], [9, 14]
|
||||
/// = [0, 17), [9, 15), mathematical interval, w/ lower and upper bounds.
|
||||
///
|
||||
/// Example: var x = Set<Int>?
|
||||
///
|
||||
/// v a r x = S e t < I n t > ?
|
||||
/// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
||||
/// ^ ^
|
||||
/// = [8, 16]
|
||||
/// = [8, 17), mathematical interval, w/ lower and upper bounds.
|
||||
///
|
||||
/// - returns: An array of ranges.
|
||||
func optionalCollectionRanges() -> [Range<String.Index>] {
|
||||
let squareBrackets = balancedRanges(from: "[", to: "]").compactMap { range -> Range<String.Index>? in
|
||||
guard
|
||||
range.upperBound < endIndex,
|
||||
let finalIndex = index(range.upperBound, offsetBy: 1, limitedBy: endIndex),
|
||||
self[range.upperBound] == "?" else { return nil }
|
||||
|
||||
return range.lowerBound..<finalIndex
|
||||
}
|
||||
|
||||
let angleBrackets = balancedRanges(from: "<", to: ">").compactMap { range -> Range<String.Index>? in
|
||||
guard
|
||||
range.upperBound < endIndex,
|
||||
let initialIndex = index(range.lowerBound, offsetBy: -3, limitedBy: startIndex),
|
||||
let finalIndex = index(range.upperBound, offsetBy: 1, limitedBy: endIndex),
|
||||
self[initialIndex..<range.lowerBound] == "Set",
|
||||
self[range.upperBound] == "?" else { return nil }
|
||||
|
||||
return initialIndex..<finalIndex
|
||||
}
|
||||
|
||||
return squareBrackets + angleBrackets
|
||||
}
|
||||
|
||||
/// Indices of character within the bounds of the string.
|
||||
///
|
||||
/// Example:
|
||||
/// a m a n h a
|
||||
/// 0 1 2 3 4 5
|
||||
/// ^ ^ ^
|
||||
/// = [0, 2, 5]
|
||||
///
|
||||
/// - parameter character: The character to look for.
|
||||
/// - returns: Array of indices.
|
||||
private func indices(of character: Character) -> [String.Index] {
|
||||
return indices.compactMap { self[$0] == character ? $0 : nil }
|
||||
}
|
||||
|
||||
/// Ranges of balanced substrings.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// ```
|
||||
/// ((1+2)*(3+4))
|
||||
/// ( ( 1 + 2 ) * ( 3 + 4 ) )
|
||||
/// 0 1 2 3 4 5 6 7 8 9 10 11 12
|
||||
/// ^ ^ ^ ^ ^ ^
|
||||
/// = [0, 12], [1, 5], [7, 11]
|
||||
/// = [0, 13), [1, 6), [7, 12), mathematical interval, w/ lower and upper bounds.
|
||||
/// ```
|
||||
///
|
||||
/// - parameter prefix: The prefix to look for.
|
||||
/// - parameter suffix: The suffix to look for.
|
||||
///
|
||||
/// - returns: Array of ranges of balanced substrings.
|
||||
private func balancedRanges(from prefix: Character, to suffix: Character) -> [Range<String.Index>] {
|
||||
return indices(of: prefix).compactMap { prefixIndex in
|
||||
var pairCount = 0
|
||||
var currentIndex = prefixIndex
|
||||
var foundCharacter = false
|
||||
|
||||
while currentIndex < endIndex {
|
||||
let character = self[currentIndex]
|
||||
currentIndex = index(after: currentIndex)
|
||||
|
||||
if character == prefix { pairCount += 1 }
|
||||
if character == suffix { pairCount -= 1 }
|
||||
if pairCount != 0 { foundCharacter = true }
|
||||
if pairCount == 0 && foundCharacter { break }
|
||||
}
|
||||
|
||||
return pairCount == 0 && foundCharacter ? prefixIndex..<currentIndex : nil
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,212 +0,0 @@
|
|||
import Foundation
|
||||
import SourceKittenFramework
|
||||
|
||||
struct DuplicateImportsRule: ConfigurationProviderRule, CorrectableRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
// List of all possible import kinds
|
||||
static let importKinds = [
|
||||
"typealias", "struct", "class",
|
||||
"enum", "protocol", "let",
|
||||
"var", "func"
|
||||
]
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "duplicate_imports",
|
||||
name: "Duplicate Imports",
|
||||
description: "Imports should be unique",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: DuplicateImportsRuleExamples.nonTriggeringExamples,
|
||||
triggeringExamples: DuplicateImportsRuleExamples.triggeringExamples,
|
||||
corrections: DuplicateImportsRuleExamples.corrections
|
||||
)
|
||||
|
||||
private func rangesInConditionalCompilation(file: SwiftLintFile) -> [ByteRange] {
|
||||
let contents = file.stringView
|
||||
|
||||
let ranges = file.syntaxMap.tokens
|
||||
.filter { $0.kind == .buildconfigKeyword }
|
||||
.map { $0.range }
|
||||
.filter { range in
|
||||
return ["#if", "#endif"].contains(contents.substringWithByteRange(range))
|
||||
}
|
||||
|
||||
// Make sure that each #if has corresponding #endif
|
||||
guard ranges.count.isMultiple(of: 2) else { return [] }
|
||||
|
||||
return stride(from: 0, to: ranges.count, by: 2).reduce(into: []) { result, rangeIndex in
|
||||
result.append(ranges[rangeIndex].union(with: ranges[rangeIndex + 1]))
|
||||
}
|
||||
}
|
||||
|
||||
private func buildImportLineSlicesByImportSubpath(
|
||||
importLines: [Line]
|
||||
) -> [ImportSubpath: [ImportLineSlice]] {
|
||||
var importLineSlices = [ImportSubpath: [ImportLineSlice]]()
|
||||
|
||||
importLines.forEach { importLine in
|
||||
importLine.importSlices.forEach { slice in
|
||||
importLineSlices[slice.subpath, default: []].append(
|
||||
ImportLineSlice(
|
||||
slice: slice,
|
||||
line: importLine
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return importLineSlices
|
||||
}
|
||||
|
||||
private func findDuplicateImports(
|
||||
file: SwiftLintFile,
|
||||
importLineSlicesGroupedBySubpath: [[ImportLineSlice]]
|
||||
) -> [DuplicateImport] {
|
||||
typealias ImportLocation = Int
|
||||
|
||||
var duplicateImportsByLocation = [ImportLocation: DuplicateImport]()
|
||||
|
||||
importLineSlicesGroupedBySubpath.forEach { linesImportingSubpath in
|
||||
guard linesImportingSubpath.count > 1 else { return }
|
||||
guard let primaryImportIndex = linesImportingSubpath.firstIndex(where: {
|
||||
$0.slice.type == .complete
|
||||
}) else { return }
|
||||
|
||||
linesImportingSubpath.enumerated().forEach { index, importedLine in
|
||||
guard index != primaryImportIndex else { return }
|
||||
let location = Location(
|
||||
file: file,
|
||||
characterOffset: importedLine.line.range.location
|
||||
)
|
||||
duplicateImportsByLocation[importedLine.line.range.location] = DuplicateImport(
|
||||
location: location,
|
||||
range: importedLine.line.range
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return Array(duplicateImportsByLocation.values)
|
||||
}
|
||||
|
||||
private struct DuplicateImport {
|
||||
let location: Location
|
||||
var range: NSRange
|
||||
}
|
||||
|
||||
private func duplicateImports(file: SwiftLintFile) -> [DuplicateImport] {
|
||||
let contents = file.stringView
|
||||
|
||||
let ignoredRanges = self.rangesInConditionalCompilation(file: file)
|
||||
|
||||
let importKinds = Self.importKinds.joined(separator: "|")
|
||||
|
||||
// Grammar of import declaration
|
||||
// attributes(optional) import import-kind(optional) import-path
|
||||
let regex = "^([a-zA-Z@_]+\\s)?import(\\s(\(importKinds)))?\\s+[a-zA-Z0-9._]+$"
|
||||
let importRanges = file.match(pattern: regex)
|
||||
.filter { $0.1.allSatisfy { [.keyword, .identifier, .attributeBuiltin].contains($0) } }
|
||||
.compactMap { contents.NSRangeToByteRange(start: $0.0.location, length: $0.0.length) }
|
||||
.filter { importRange -> Bool in
|
||||
return !importRange.intersects(ignoredRanges)
|
||||
}
|
||||
|
||||
let lines = file.lines
|
||||
|
||||
let importLines: [Line] = importRanges.compactMap { range in
|
||||
guard let line = contents.lineAndCharacter(forByteOffset: range.location)?.line
|
||||
else { return nil }
|
||||
return lines[line - 1]
|
||||
}
|
||||
|
||||
let importLineSlices = buildImportLineSlicesByImportSubpath(importLines: importLines)
|
||||
|
||||
let duplicateImports = findDuplicateImports(
|
||||
file: file,
|
||||
importLineSlicesGroupedBySubpath: Array(importLineSlices.values)
|
||||
)
|
||||
|
||||
return duplicateImports.sorted(by: {
|
||||
$0.range.lowerBound < $1.range.lowerBound
|
||||
})
|
||||
}
|
||||
|
||||
func validate(file: SwiftLintFile) -> [StyleViolation] {
|
||||
return duplicateImports(file: file).map { duplicateImport in
|
||||
StyleViolation(
|
||||
ruleDescription: Self.description,
|
||||
severity: configuration.severity,
|
||||
location: duplicateImport.location
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func correct(file: SwiftLintFile) -> [Correction] {
|
||||
let duplicateImports = duplicateImports(file: file).reversed().filter {
|
||||
file.ruleEnabled(violatingRange: $0.range, for: self) != nil
|
||||
}
|
||||
|
||||
let violatingRanges = duplicateImports.map(\.range)
|
||||
let correctedFileContents = violatingRanges.reduce(file.stringView.nsString) { contents, range in
|
||||
contents.replacingCharacters(
|
||||
in: range,
|
||||
with: ""
|
||||
).bridge()
|
||||
}
|
||||
|
||||
file.write(correctedFileContents.bridge())
|
||||
|
||||
return duplicateImports.map { duplicateImport in
|
||||
Correction(
|
||||
ruleDescription: Self.description,
|
||||
location: duplicateImport.location
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private typealias ImportSubpath = ArraySlice<String>
|
||||
|
||||
private struct ImportSlice {
|
||||
enum ImportSliceType {
|
||||
/// For "import A.B.C" parent subpaths are ["A", "B"] and ["A"]
|
||||
case parent
|
||||
|
||||
/// For "import A.B.C" complete subpath is ["A", "B", "C"]
|
||||
case complete
|
||||
}
|
||||
|
||||
let subpath: ImportSubpath
|
||||
let type: ImportSliceType
|
||||
}
|
||||
|
||||
private struct ImportLineSlice {
|
||||
let slice: ImportSlice
|
||||
let line: Line
|
||||
}
|
||||
|
||||
private extension Line {
|
||||
/// Returns name of the module being imported.
|
||||
var importIdentifier: Substring? {
|
||||
return self.content.split(separator: " ").last
|
||||
}
|
||||
|
||||
/// For "import A.B.C" returns slices [["A", "B", "C"], ["A", "B"], ["A"]]
|
||||
var importSlices: [ImportSlice] {
|
||||
guard let importIdentifier else { return [] }
|
||||
|
||||
let importedSubpathParts = importIdentifier.split(separator: ".").map { String($0) }
|
||||
guard !importedSubpathParts.isEmpty else { return [] }
|
||||
|
||||
return [
|
||||
ImportSlice(
|
||||
subpath: importedSubpathParts[0..<importedSubpathParts.count],
|
||||
type: .complete
|
||||
)
|
||||
] + (1..<importedSubpathParts.count).map {
|
||||
ImportSlice(
|
||||
subpath: importedSubpathParts[0..<importedSubpathParts.count - $0],
|
||||
type: .parent
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,219 +0,0 @@
|
|||
internal struct DuplicateImportsRuleExamples {
|
||||
static let nonTriggeringExamples = [
|
||||
Example("""
|
||||
import A
|
||||
import B
|
||||
import C
|
||||
"""),
|
||||
Example("""
|
||||
import A.B
|
||||
import A.C
|
||||
"""),
|
||||
Example("""
|
||||
@_implementationOnly import A
|
||||
@_implementationOnly import B
|
||||
"""),
|
||||
Example("""
|
||||
@testable import A
|
||||
@testable import B
|
||||
"""),
|
||||
Example("""
|
||||
#if DEBUG
|
||||
@testable import KsApi
|
||||
#else
|
||||
import KsApi
|
||||
#endif
|
||||
"""),
|
||||
Example("""
|
||||
import A // module
|
||||
import B // module
|
||||
"""),
|
||||
Example("""
|
||||
#if TEST
|
||||
func test() {
|
||||
}
|
||||
""")
|
||||
]
|
||||
|
||||
static let triggeringExamples = Array(corrections.keys.sorted())
|
||||
|
||||
static let corrections: [Example: Example] = {
|
||||
var corrections = [
|
||||
Example("""
|
||||
import Foundation
|
||||
import Dispatch
|
||||
↓import Foundation
|
||||
|
||||
"""): Example(
|
||||
"""
|
||||
import Foundation
|
||||
import Dispatch
|
||||
|
||||
"""),
|
||||
Example("""
|
||||
import Foundation
|
||||
↓import Foundation.NSString
|
||||
|
||||
"""): Example("""
|
||||
import Foundation
|
||||
|
||||
"""),
|
||||
Example("""
|
||||
↓import Foundation.NSString
|
||||
import Foundation
|
||||
|
||||
"""): Example("""
|
||||
import Foundation
|
||||
|
||||
"""),
|
||||
Example("""
|
||||
@_implementationOnly import A
|
||||
↓@_implementationOnly import A
|
||||
|
||||
"""): Example("""
|
||||
@_implementationOnly import A
|
||||
|
||||
"""),
|
||||
Example("""
|
||||
@testable import A
|
||||
↓@testable import A
|
||||
|
||||
"""): Example("""
|
||||
@testable import A
|
||||
|
||||
"""),
|
||||
Example("""
|
||||
↓import A.B.C
|
||||
import A.B
|
||||
|
||||
"""): Example("""
|
||||
import A.B
|
||||
|
||||
"""),
|
||||
Example("""
|
||||
import A.B
|
||||
↓import A.B.C
|
||||
|
||||
"""): Example("""
|
||||
import A.B
|
||||
|
||||
"""),
|
||||
Example("""
|
||||
import A
|
||||
#if DEBUG
|
||||
@testable import KsApi
|
||||
#else
|
||||
import KsApi
|
||||
#endif
|
||||
↓import A
|
||||
|
||||
"""): Example("""
|
||||
import A
|
||||
#if DEBUG
|
||||
@testable import KsApi
|
||||
#else
|
||||
import KsApi
|
||||
#endif
|
||||
|
||||
"""),
|
||||
Example("""
|
||||
import Foundation
|
||||
↓import Foundation
|
||||
↓import Foundation
|
||||
|
||||
"""): Example("""
|
||||
import Foundation
|
||||
|
||||
"""),
|
||||
Example("""
|
||||
↓import A.B.C
|
||||
↓import A.B
|
||||
import A
|
||||
|
||||
""", excludeFromDocumentation: true): Example("""
|
||||
import A
|
||||
|
||||
"""),
|
||||
Example("""
|
||||
import A.B.C
|
||||
↓import A.B.C.D
|
||||
↓import A.B.C.E
|
||||
|
||||
""", excludeFromDocumentation: true): Example("""
|
||||
import A.B.C
|
||||
|
||||
"""),
|
||||
Example("""
|
||||
↓import A.B.C
|
||||
import A
|
||||
↓import A.B
|
||||
|
||||
""", excludeFromDocumentation: true): Example("""
|
||||
import A
|
||||
|
||||
"""),
|
||||
Example("""
|
||||
↓import A.B
|
||||
import A
|
||||
↓import A.B.C
|
||||
|
||||
""", excludeFromDocumentation: true): Example("""
|
||||
import A
|
||||
|
||||
"""),
|
||||
Example("""
|
||||
import A
|
||||
↓import A.B.C
|
||||
↓import A.B
|
||||
|
||||
""", excludeFromDocumentation: true): Example("""
|
||||
import A
|
||||
|
||||
""")
|
||||
]
|
||||
|
||||
DuplicateImportsRule.importKinds.map { importKind in
|
||||
Example("""
|
||||
import A
|
||||
↓import \(importKind) A.Foo
|
||||
|
||||
""")
|
||||
}.forEach {
|
||||
corrections[$0] = Example(
|
||||
"""
|
||||
import A
|
||||
|
||||
""")
|
||||
}
|
||||
|
||||
DuplicateImportsRule.importKinds.map { importKind in
|
||||
Example("""
|
||||
import A
|
||||
↓import \(importKind) A.B.Foo
|
||||
|
||||
""", excludeFromDocumentation: true)
|
||||
}.forEach {
|
||||
corrections[$0] = Example(
|
||||
"""
|
||||
import A
|
||||
|
||||
""")
|
||||
}
|
||||
|
||||
DuplicateImportsRule.importKinds.map { importKind in
|
||||
Example("""
|
||||
import A.B
|
||||
↓import \(importKind) A.B.Foo
|
||||
|
||||
""", excludeFromDocumentation: true)
|
||||
}.forEach {
|
||||
corrections[$0] = Example(
|
||||
"""
|
||||
import A.B
|
||||
|
||||
""")
|
||||
}
|
||||
|
||||
return corrections
|
||||
}()
|
||||
}
|
|
@ -1,194 +0,0 @@
|
|||
import Foundation
|
||||
import SourceKittenFramework
|
||||
|
||||
private typealias SourceKittenElement = SourceKittenDictionary
|
||||
|
||||
struct ExplicitACLRule: OptInRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "explicit_acl",
|
||||
name: "Explicit ACL",
|
||||
description: "All declarations should specify Access Control Level keywords explicitly",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("internal enum A {}\n"),
|
||||
Example("public final class B {}\n"),
|
||||
Example("private struct C {}\n"),
|
||||
Example("internal enum A {\n internal enum B {}\n}"),
|
||||
Example("internal final class Foo {}"),
|
||||
Example("""
|
||||
internal
|
||||
class Foo {
|
||||
private let bar = 5
|
||||
}
|
||||
"""),
|
||||
Example("internal func a() { let a = }\n"),
|
||||
Example("private func a() { func innerFunction() { } }"),
|
||||
Example("private enum Foo { enum Bar { } }"),
|
||||
Example("private struct C { let d = 5 }"),
|
||||
Example("""
|
||||
internal protocol A {
|
||||
func b()
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
internal protocol A {
|
||||
var b: Int
|
||||
}
|
||||
"""),
|
||||
Example("internal class A { deinit {} }"),
|
||||
Example("extension A: Equatable {}"),
|
||||
Example("extension A {}"),
|
||||
Example("""
|
||||
extension Foo {
|
||||
internal func bar() {}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
internal enum Foo {
|
||||
case bar
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
extension Foo {
|
||||
public var isValid: Bool {
|
||||
let result = true
|
||||
return result
|
||||
}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
extension Foo {
|
||||
private var isValid: Bool {
|
||||
get {
|
||||
return true
|
||||
}
|
||||
set(newValue) {
|
||||
print(newValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
""")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("↓enum A {}\n"),
|
||||
Example("final ↓class B {}\n"),
|
||||
Example("internal struct C { ↓let d = 5 }\n"),
|
||||
Example("public struct C { ↓let d = 5 }\n"),
|
||||
Example("func a() {}\n"),
|
||||
Example("internal let a = 0\n↓func b() {}\n"),
|
||||
Example("""
|
||||
extension Foo {
|
||||
↓func bar() {}
|
||||
}
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
private func findAllExplicitInternalTokens(in file: SwiftLintFile) -> [ByteRange] {
|
||||
let contents = file.stringView
|
||||
return file.match(pattern: "internal", with: [.attributeBuiltin]).compactMap {
|
||||
contents.NSRangeToByteRange(start: $0.location, length: $0.length)
|
||||
}
|
||||
}
|
||||
|
||||
private func offsetOfElements(from elements: [SourceKittenElement], in file: SwiftLintFile,
|
||||
thatAreNotInRanges ranges: [ByteRange]) -> [ByteCount] {
|
||||
return elements.compactMap { element in
|
||||
guard let typeOffset = element.offset else {
|
||||
return nil
|
||||
}
|
||||
|
||||
guard let kind = element.declarationKind,
|
||||
!SwiftDeclarationKind.extensionKinds.contains(kind) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
// find the last "internal" token before the type
|
||||
guard let previousInternalByteRange = lastInternalByteRange(before: typeOffset, in: ranges) else {
|
||||
return typeOffset
|
||||
}
|
||||
|
||||
// the "internal" token correspond to the type if there're only
|
||||
// attributeBuiltin (`final` for example) tokens between them
|
||||
let length = typeOffset - previousInternalByteRange.location
|
||||
let range = ByteRange(location: previousInternalByteRange.location, length: length)
|
||||
let internalDoesntBelongToType = Set(file.syntaxMap.kinds(inByteRange: range)) != [.attributeBuiltin]
|
||||
|
||||
return internalDoesntBelongToType ? typeOffset : nil
|
||||
}
|
||||
}
|
||||
|
||||
func validate(file: SwiftLintFile) -> [StyleViolation] {
|
||||
let implicitAndExplicitInternalElements = internalTypeElements(in: file.structureDictionary)
|
||||
|
||||
guard implicitAndExplicitInternalElements.isNotEmpty else {
|
||||
return []
|
||||
}
|
||||
|
||||
let explicitInternalRanges = findAllExplicitInternalTokens(in: file)
|
||||
|
||||
let violations = offsetOfElements(from: implicitAndExplicitInternalElements, in: file,
|
||||
thatAreNotInRanges: explicitInternalRanges)
|
||||
|
||||
return violations.map {
|
||||
StyleViolation(ruleDescription: Self.description,
|
||||
severity: configuration.severity,
|
||||
location: Location(file: file, byteOffset: $0))
|
||||
}
|
||||
}
|
||||
|
||||
private func lastInternalByteRange(before typeOffset: ByteCount, in ranges: [ByteRange]) -> ByteRange? {
|
||||
let firstPartition = ranges.prefix(while: { typeOffset > $0.location })
|
||||
return firstPartition.last
|
||||
}
|
||||
|
||||
private func internalTypeElements(in parent: SourceKittenElement) -> [SourceKittenElement] {
|
||||
return parent.substructure.flatMap { element -> [SourceKittenElement] in
|
||||
guard let elementKind = element.declarationKind,
|
||||
elementKind != .varLocal, elementKind != .varParameter else {
|
||||
return []
|
||||
}
|
||||
|
||||
let isDeinit = elementKind == .functionMethodInstance && element.name == "deinit"
|
||||
guard !isDeinit else {
|
||||
return []
|
||||
}
|
||||
|
||||
let isPrivate = element.accessibility?.isPrivate ?? false
|
||||
let internalTypeElementsInSubstructure = elementKind.childsAreExemptFromACL || isPrivate ? [] :
|
||||
internalTypeElements(in: element)
|
||||
|
||||
var isInExtension = false
|
||||
if let kind = parent.declarationKind {
|
||||
isInExtension = SwiftDeclarationKind.extensionKinds.contains(kind)
|
||||
}
|
||||
|
||||
if element.accessibility == .internal || (element.accessibility == nil && isInExtension) {
|
||||
return internalTypeElementsInSubstructure + [element]
|
||||
}
|
||||
|
||||
return internalTypeElementsInSubstructure
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension SwiftDeclarationKind {
|
||||
var childsAreExemptFromACL: Bool {
|
||||
switch self {
|
||||
case .associatedtype, .enumcase, .enumelement, .functionAccessorAddress,
|
||||
.functionAccessorDidset, .functionAccessorGetter, .functionAccessorMutableaddress,
|
||||
.functionAccessorSetter, .functionAccessorWillset, .genericTypeParam, .module,
|
||||
.precedenceGroup, .varLocal, .varParameter, .varClass,
|
||||
.varGlobal, .varInstance, .varStatic, .typealias, .functionAccessorModify, .functionAccessorRead,
|
||||
.functionConstructor, .functionDestructor, .functionFree, .functionMethodClass,
|
||||
.functionMethodInstance, .functionMethodStatic, .functionOperator, .functionOperatorInfix,
|
||||
.functionOperatorPostfix, .functionOperatorPrefix, .functionSubscript, .protocol, .opaqueType:
|
||||
return true
|
||||
case .actor, .class, .enum, .extension, .extensionClass, .extensionEnum,
|
||||
.extensionProtocol, .extensionStruct, .struct:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,105 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct ExplicitEnumRawValueRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "explicit_enum_raw_value",
|
||||
name: "Explicit Enum Raw Value",
|
||||
description: "Enums should be explicitly assigned their raw values",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("""
|
||||
enum Numbers {
|
||||
case int(Int)
|
||||
case short(Int16)
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum Numbers: Int {
|
||||
case one = 1
|
||||
case two = 2
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum Numbers: Double {
|
||||
case one = 1.1
|
||||
case two = 2.2
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum Numbers: String {
|
||||
case one = "one"
|
||||
case two = "two"
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
protocol Algebra {}
|
||||
enum Numbers: Algebra {
|
||||
case one
|
||||
}
|
||||
""")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("""
|
||||
enum Numbers: Int {
|
||||
case one = 10, ↓two, three = 30
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum Numbers: NSInteger {
|
||||
case ↓one
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum Numbers: String {
|
||||
case ↓one
|
||||
case ↓two
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum Numbers: String {
|
||||
case ↓one, two = "two"
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum Numbers: Decimal {
|
||||
case ↓one, ↓two
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum Outer {
|
||||
enum Numbers: Decimal {
|
||||
case ↓one, ↓two
|
||||
}
|
||||
}
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension ExplicitEnumRawValueRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override var skippableDeclarations: [DeclSyntaxProtocol.Type] { [ProtocolDeclSyntax.self] }
|
||||
|
||||
override func visitPost(_ node: EnumCaseElementSyntax) {
|
||||
if node.rawValue == nil, node.enclosingEnum()?.supportsRawValues == true {
|
||||
violations.append(node.identifier.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension SyntaxProtocol {
|
||||
func enclosingEnum() -> EnumDeclSyntax? {
|
||||
if let node = self.as(EnumDeclSyntax.self) {
|
||||
return node
|
||||
}
|
||||
|
||||
return parent?.enclosingEnum()
|
||||
}
|
||||
}
|
|
@ -1,254 +0,0 @@
|
|||
import SwiftSyntax
|
||||
import SwiftSyntaxBuilder
|
||||
|
||||
struct ExplicitInitRule: SwiftSyntaxCorrectableRule, ConfigurationProviderRule, OptInRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "explicit_init",
|
||||
name: "Explicit Init",
|
||||
description: "Explicitly calling .init() should be avoided",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("""
|
||||
import Foundation
|
||||
class C: NSObject {
|
||||
override init() {
|
||||
super.init()
|
||||
}
|
||||
}
|
||||
"""), // super
|
||||
Example("""
|
||||
struct S {
|
||||
let n: Int
|
||||
}
|
||||
extension S {
|
||||
init() {
|
||||
self.init(n: 1)
|
||||
}
|
||||
}
|
||||
"""), // self
|
||||
Example("""
|
||||
[1].flatMap(String.init)
|
||||
"""), // pass init as closure
|
||||
Example("""
|
||||
[String.self].map { $0.init(1) }
|
||||
"""), // initialize from a metatype value
|
||||
Example("""
|
||||
[String.self].map { type in type.init(1) }
|
||||
"""), // initialize from a metatype value
|
||||
Example("""
|
||||
Observable.zip(obs1, obs2, resultSelector: MyType.init).asMaybe()
|
||||
"""),
|
||||
Example("_ = GleanMetrics.Tabs.someType.init()"),
|
||||
Example("""
|
||||
Observable.zip(
|
||||
obs1,
|
||||
obs2,
|
||||
resultSelector: MyType.init
|
||||
).asMaybe()
|
||||
""")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("""
|
||||
[1].flatMap{String↓.init($0)}
|
||||
"""),
|
||||
Example("""
|
||||
[String.self].map { Type in Type↓.init(1) }
|
||||
"""), // Starting with capital letter assumes a type
|
||||
Example("""
|
||||
func foo() -> [String] {
|
||||
return [1].flatMap { String↓.init($0) }
|
||||
}
|
||||
"""),
|
||||
Example("_ = GleanMetrics.Tabs.GroupedTabExtra↓.init()"),
|
||||
Example("_ = Set<KsApi.Category>↓.init()"),
|
||||
Example("""
|
||||
Observable.zip(
|
||||
obs1,
|
||||
obs2,
|
||||
resultSelector: { MyType↓.init($0, $1) }
|
||||
).asMaybe()
|
||||
"""),
|
||||
Example("""
|
||||
let int = In🤓t↓
|
||||
.init(1.0)
|
||||
""", excludeFromDocumentation: true),
|
||||
Example("""
|
||||
let int = Int↓
|
||||
|
||||
|
||||
.init(1.0)
|
||||
""", excludeFromDocumentation: true),
|
||||
Example("""
|
||||
let int = Int↓
|
||||
|
||||
|
||||
.init(1.0)
|
||||
""", excludeFromDocumentation: true)
|
||||
],
|
||||
corrections: [
|
||||
Example("""
|
||||
[1].flatMap{String↓.init($0)}
|
||||
"""):
|
||||
Example("""
|
||||
[1].flatMap{String($0)}
|
||||
"""),
|
||||
Example("""
|
||||
func foo() -> [String] {
|
||||
return [1].flatMap { String↓.init($0) }
|
||||
}
|
||||
"""):
|
||||
Example("""
|
||||
func foo() -> [String] {
|
||||
return [1].flatMap { String($0) }
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class C {
|
||||
#if true
|
||||
func f() {
|
||||
[1].flatMap{String↓.init($0)}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
"""):
|
||||
Example("""
|
||||
class C {
|
||||
#if true
|
||||
func f() {
|
||||
[1].flatMap{String($0)}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
let int = Int↓
|
||||
.init(1.0)
|
||||
"""):
|
||||
Example("""
|
||||
let int = Int(1.0)
|
||||
"""),
|
||||
Example("""
|
||||
let int = Int↓
|
||||
|
||||
|
||||
.init(1.0)
|
||||
"""):
|
||||
Example("""
|
||||
let int = Int(1.0)
|
||||
"""),
|
||||
Example("""
|
||||
let int = Int↓
|
||||
|
||||
|
||||
.init(1.0)
|
||||
"""):
|
||||
Example("""
|
||||
let int = Int(1.0)
|
||||
"""),
|
||||
Example("""
|
||||
let int = Int↓
|
||||
|
||||
|
||||
.init(1.0)
|
||||
|
||||
|
||||
|
||||
"""):
|
||||
Example("""
|
||||
let int = Int(1.0)
|
||||
|
||||
|
||||
|
||||
"""),
|
||||
Example("_ = GleanMetrics.Tabs.GroupedTabExtra↓.init()"):
|
||||
Example("_ = GleanMetrics.Tabs.GroupedTabExtra()"),
|
||||
Example("_ = Set<KsApi.Category>↓.init()"):
|
||||
Example("_ = Set<KsApi.Category>()")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter? {
|
||||
Rewriter(
|
||||
locationConverter: file.locationConverter,
|
||||
disabledRegions: disabledRegions(file: file)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private extension ExplicitInitRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: FunctionCallExprSyntax) {
|
||||
guard
|
||||
let calledExpression = node.calledExpression.as(MemberAccessExprSyntax.self),
|
||||
let violationPosition = calledExpression.explicitInitPosition
|
||||
else {
|
||||
return
|
||||
}
|
||||
|
||||
violations.append(violationPosition)
|
||||
}
|
||||
}
|
||||
|
||||
final class Rewriter: SyntaxRewriter, ViolationsSyntaxRewriter {
|
||||
private(set) var correctionPositions: [AbsolutePosition] = []
|
||||
let locationConverter: SourceLocationConverter
|
||||
let disabledRegions: [SourceRange]
|
||||
|
||||
init(locationConverter: SourceLocationConverter, disabledRegions: [SourceRange]) {
|
||||
self.locationConverter = locationConverter
|
||||
self.disabledRegions = disabledRegions
|
||||
}
|
||||
|
||||
override func visit(_ node: FunctionCallExprSyntax) -> ExprSyntax {
|
||||
guard
|
||||
let calledExpression = node.calledExpression.as(MemberAccessExprSyntax.self),
|
||||
let violationPosition = calledExpression.explicitInitPosition,
|
||||
let calledBase = calledExpression.base,
|
||||
!node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter)
|
||||
else {
|
||||
return super.visit(node)
|
||||
}
|
||||
|
||||
correctionPositions.append(violationPosition)
|
||||
let newNode = node.with(\.calledExpression, calledBase.trimmed)
|
||||
return super.visit(newNode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension MemberAccessExprSyntax {
|
||||
var explicitInitPosition: AbsolutePosition? {
|
||||
if let base, base.isTypeReferenceLike, name.text == "init" {
|
||||
return base.endPositionBeforeTrailingTrivia
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension ExprSyntax {
|
||||
/// `String` or `Nested.Type`.
|
||||
var isTypeReferenceLike: Bool {
|
||||
if let expr = self.as(IdentifierExprSyntax.self), expr.identifier.text.startsWithUppercase {
|
||||
return true
|
||||
} else if let expr = self.as(MemberAccessExprSyntax.self),
|
||||
expr.description.split(separator: ".").allSatisfy(\.startsWithUppercase) {
|
||||
return true
|
||||
} else if let expr = self.as(SpecializeExprSyntax.self)?.expression.as(IdentifierExprSyntax.self),
|
||||
expr.identifier.text.startsWithUppercase {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension StringProtocol {
|
||||
var startsWithUppercase: Bool { first?.isUppercase == true }
|
||||
}
|
|
@ -1,118 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct ExplicitTopLevelACLRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "explicit_top_level_acl",
|
||||
name: "Explicit Top Level ACL",
|
||||
description: "Top-level declarations should specify Access Control Level keywords explicitly",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("internal enum A {}\n"),
|
||||
Example("public final class B {}\n"),
|
||||
Example("private struct C {}\n"),
|
||||
Example("internal enum A {\n enum B {}\n}"),
|
||||
Example("internal final class Foo {}"),
|
||||
Example("internal\nclass Foo {}"),
|
||||
Example("internal func a() {}\n"),
|
||||
Example("extension A: Equatable {}"),
|
||||
Example("extension A {}")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("↓enum A {}\n"),
|
||||
Example("final ↓class B {}\n"),
|
||||
Example("↓struct C {}\n"),
|
||||
Example("↓func a() {}\n"),
|
||||
Example("internal let a = 0\n↓func b() {}\n")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension ExplicitTopLevelACLRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override var skippableDeclarations: [DeclSyntaxProtocol.Type] { .all }
|
||||
|
||||
override func visitPost(_ node: ClassDeclSyntax) {
|
||||
if hasViolation(modifiers: node.modifiers) {
|
||||
violations.append(node.classKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: StructDeclSyntax) {
|
||||
if hasViolation(modifiers: node.modifiers) {
|
||||
violations.append(node.structKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: EnumDeclSyntax) {
|
||||
if hasViolation(modifiers: node.modifiers) {
|
||||
violations.append(node.enumKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: ProtocolDeclSyntax) {
|
||||
if hasViolation(modifiers: node.modifiers) {
|
||||
violations.append(node.protocolKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: ActorDeclSyntax) {
|
||||
if hasViolation(modifiers: node.modifiers) {
|
||||
violations.append(node.actorKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: TypealiasDeclSyntax) {
|
||||
if hasViolation(modifiers: node.modifiers) {
|
||||
violations.append(node.typealiasKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: FunctionDeclSyntax) {
|
||||
if hasViolation(modifiers: node.modifiers) {
|
||||
violations.append(node.funcKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: VariableDeclSyntax) {
|
||||
if hasViolation(modifiers: node.modifiers) {
|
||||
violations.append(node.bindingKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visit(_ node: CodeBlockSyntax) -> SyntaxVisitorContinueKind {
|
||||
.skipChildren
|
||||
}
|
||||
|
||||
override func visit(_ node: ClosureExprSyntax) -> SyntaxVisitorContinueKind {
|
||||
.skipChildren
|
||||
}
|
||||
|
||||
private func hasViolation(modifiers: ModifierListSyntax?) -> Bool {
|
||||
guard let modifiers else {
|
||||
return true
|
||||
}
|
||||
|
||||
return !modifiers.contains(where: \.isACLModifier)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension DeclModifierSyntax {
|
||||
var isACLModifier: Bool {
|
||||
let aclModifiers: Set<TokenKind> = [
|
||||
.keyword(.private),
|
||||
.keyword(.fileprivate),
|
||||
.keyword(.internal),
|
||||
.keyword(.public),
|
||||
.keyword(.open)
|
||||
]
|
||||
|
||||
return detail == nil && aclModifiers.contains(name.tokenKind)
|
||||
}
|
||||
}
|
|
@ -1,142 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct ExplicitTypeInterfaceRule: OptInRule, ConfigurationProviderRule, SwiftSyntaxRule {
|
||||
var configuration = ExplicitTypeInterfaceConfiguration()
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "explicit_type_interface",
|
||||
name: "Explicit Type Interface",
|
||||
description: "Properties should have a type interface",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("""
|
||||
class Foo {
|
||||
var myVar: Int? = 0
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo {
|
||||
let myVar: Int? = 0, s: String = ""
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo {
|
||||
static var myVar: Int? = 0
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo {
|
||||
class var myVar: Int? = 0
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
func f() {
|
||||
if case .failure(let error) = errorCompletion {}
|
||||
}
|
||||
""", excludeFromDocumentation: true)
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("""
|
||||
class Foo {
|
||||
var ↓myVar = 0
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo {
|
||||
let ↓mylet = 0
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo {
|
||||
static var ↓myStaticVar = 0
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo {
|
||||
class var ↓myClassVar = 0
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo {
|
||||
let ↓myVar = Int(0), ↓s = ""
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo {
|
||||
let ↓myVar = Set<Int>(0)
|
||||
}
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(configuration: configuration)
|
||||
}
|
||||
}
|
||||
|
||||
private class Visitor: ViolationsSyntaxVisitor {
|
||||
let configuration: ExplicitTypeInterfaceConfiguration
|
||||
|
||||
override var skippableDeclarations: [DeclSyntaxProtocol.Type] { [ProtocolDeclSyntax.self] }
|
||||
|
||||
init(configuration: ExplicitTypeInterfaceConfiguration) {
|
||||
self.configuration = configuration
|
||||
super.init(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: VariableDeclSyntax) {
|
||||
if node.modifiers.isClass {
|
||||
if configuration.allowedKinds.contains(.class) {
|
||||
checkViolation(node)
|
||||
}
|
||||
} else if node.modifiers.isStatic {
|
||||
if configuration.allowedKinds.contains(.static) {
|
||||
checkViolation(node)
|
||||
}
|
||||
} else if node.parent?.is(MemberDeclListItemSyntax.self) == true {
|
||||
if configuration.allowedKinds.contains(.instance) {
|
||||
checkViolation(node)
|
||||
}
|
||||
} else if node.parent?.is(CodeBlockItemSyntax.self) == true {
|
||||
if configuration.allowedKinds.contains(.local) {
|
||||
checkViolation(node)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func checkViolation(_ node: VariableDeclSyntax) {
|
||||
for binding in node.bindings {
|
||||
if configuration.allowRedundancy, let initializer = binding.initializer,
|
||||
initializer.isTypeConstructor || initializer.isTypeReference {
|
||||
continue
|
||||
}
|
||||
if binding.typeAnnotation == nil {
|
||||
violations.append(binding.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension InitializerClauseSyntax {
|
||||
var isTypeConstructor: Bool {
|
||||
if value.as(FunctionCallExprSyntax.self)?.callsPotentialType == true {
|
||||
return true
|
||||
}
|
||||
if let tryExpr = value.as(TryExprSyntax.self),
|
||||
tryExpr.expression.as(FunctionCallExprSyntax.self)?.callsPotentialType == true {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var isTypeReference: Bool {
|
||||
value.as(MemberAccessExprSyntax.self)?.name.tokenKind == .keyword(.self)
|
||||
}
|
||||
}
|
||||
|
||||
private extension FunctionCallExprSyntax {
|
||||
var callsPotentialType: Bool {
|
||||
let name = calledExpression.debugDescription
|
||||
return name.first?.isUppercase == true || (name.first == "[" && name.last == "]")
|
||||
}
|
||||
}
|
|
@ -1,172 +0,0 @@
|
|||
import Foundation
|
||||
import SourceKittenFramework
|
||||
|
||||
struct ExtensionAccessModifierRule: ASTRule, ConfigurationProviderRule, OptInRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "extension_access_modifier",
|
||||
name: "Extension Access Modifier",
|
||||
description: "Prefer to use extension access modifiers",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("""
|
||||
extension Foo: SomeProtocol {
|
||||
public var bar: Int { return 1 }
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
extension Foo {
|
||||
private var bar: Int { return 1 }
|
||||
public var baz: Int { return 1 }
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
extension Foo {
|
||||
private var bar: Int { return 1 }
|
||||
public func baz() {}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
extension Foo {
|
||||
var bar: Int { return 1 }
|
||||
var baz: Int { return 1 }
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
public extension Foo {
|
||||
var bar: Int { return 1 }
|
||||
var baz: Int { return 1 }
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
extension Foo {
|
||||
private bar: Int { return 1 }
|
||||
private baz: Int { return 1 }
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
extension Foo {
|
||||
open bar: Int { return 1 }
|
||||
open baz: Int { return 1 }
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
extension Foo {
|
||||
func setup() {}
|
||||
public func update() {}
|
||||
}
|
||||
""")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("""
|
||||
↓extension Foo {
|
||||
public var bar: Int { return 1 }
|
||||
public var baz: Int { return 1 }
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
↓extension Foo {
|
||||
public var bar: Int { return 1 }
|
||||
public func baz() {}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
public extension Foo {
|
||||
public ↓func bar() {}
|
||||
public ↓func baz() {}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
↓extension Foo {
|
||||
public var bar: Int {
|
||||
let value = 1
|
||||
return value
|
||||
}
|
||||
|
||||
public var baz: Int { return 1 }
|
||||
}
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func validate(file: SwiftLintFile, kind: SwiftDeclarationKind,
|
||||
dictionary: SourceKittenDictionary) -> [StyleViolation] {
|
||||
guard kind == .extension, let offset = dictionary.offset,
|
||||
dictionary.inheritedTypes.isEmpty
|
||||
else {
|
||||
return []
|
||||
}
|
||||
|
||||
let declarations = dictionary.substructure
|
||||
.compactMap { entry -> (acl: AccessControlLevel, offset: ByteCount)? in
|
||||
guard let kind = entry.declarationKind,
|
||||
kind != .varLocal, kind != .varParameter,
|
||||
let offset = entry.offset else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return (acl: entry.accessibility ?? .internal, offset: offset)
|
||||
}
|
||||
|
||||
let declarationsACLs = declarations.map { $0.acl }.unique
|
||||
let allowedACLs: Set<AccessControlLevel> = [.internal, .private, .open]
|
||||
guard declarationsACLs.count == 1, !allowedACLs.contains(declarationsACLs[0]) else {
|
||||
return []
|
||||
}
|
||||
|
||||
let syntaxTokens = file.syntaxMap.tokens
|
||||
let parts = syntaxTokens.partitioned { offset <= $0.offset }
|
||||
if let aclToken = parts.first.last, file.isACL(token: aclToken) {
|
||||
return declarationsViolations(file: file, acl: declarationsACLs[0],
|
||||
declarationOffsets: declarations.map { $0.offset },
|
||||
dictionary: dictionary)
|
||||
}
|
||||
|
||||
return [
|
||||
StyleViolation(ruleDescription: Self.description,
|
||||
severity: configuration.severity,
|
||||
location: Location(file: file, byteOffset: offset))
|
||||
]
|
||||
}
|
||||
|
||||
private func declarationsViolations(file: SwiftLintFile, acl: AccessControlLevel,
|
||||
declarationOffsets: [ByteCount],
|
||||
dictionary: SourceKittenDictionary) -> [StyleViolation] {
|
||||
guard let byteRange = dictionary.byteRange,
|
||||
case let contents = file.stringView,
|
||||
let range = contents.byteRangeToNSRange(byteRange) else {
|
||||
return []
|
||||
}
|
||||
|
||||
// find all ACL tokens
|
||||
let allACLRanges = file.match(pattern: acl.description, with: [.attributeBuiltin], range: range).compactMap {
|
||||
contents.NSRangeToByteRange(start: $0.location, length: $0.length)
|
||||
}
|
||||
|
||||
let violationOffsets = declarationOffsets.filter { typeOffset in
|
||||
// find the last ACL token before the type
|
||||
guard let previousInternalByteRange = lastACLByteRange(before: typeOffset, in: allACLRanges) else {
|
||||
// didn't find a candidate token, so the ACL is implicit (not a violation)
|
||||
return false
|
||||
}
|
||||
|
||||
// the ACL token correspond to the type if there're only
|
||||
// attributeBuiltin (`final` for example) tokens between them
|
||||
let length = typeOffset - previousInternalByteRange.location
|
||||
let range = ByteRange(location: previousInternalByteRange.location, length: length)
|
||||
return Set(file.syntaxMap.kinds(inByteRange: range)) == [.attributeBuiltin]
|
||||
}
|
||||
|
||||
return violationOffsets.map {
|
||||
StyleViolation(ruleDescription: Self.description,
|
||||
severity: configuration.severity,
|
||||
location: Location(file: file, byteOffset: $0))
|
||||
}
|
||||
}
|
||||
|
||||
private func lastACLByteRange(before typeOffset: ByteCount, in ranges: [ByteRange]) -> ByteRange? {
|
||||
let firstPartition = ranges.partitioned(by: { $0.location > typeOffset }).first
|
||||
return firstPartition.last
|
||||
}
|
||||
}
|
|
@ -1,42 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct FallthroughRule: SwiftSyntaxRule, ConfigurationProviderRule, OptInRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "fallthrough",
|
||||
name: "Fallthrough",
|
||||
description: "Fallthrough should be avoided",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("""
|
||||
switch foo {
|
||||
case .bar, .bar2, .bar3:
|
||||
something()
|
||||
}
|
||||
""")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("""
|
||||
switch foo {
|
||||
case .bar:
|
||||
↓fallthrough
|
||||
case .bar2:
|
||||
something()
|
||||
}
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension FallthroughRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: FallthroughStmtSyntax) {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,63 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct FatalErrorMessageRule: SwiftSyntaxRule, ConfigurationProviderRule, OptInRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "fatal_error_message",
|
||||
name: "Fatal Error Message",
|
||||
description: "A fatalError call should have a message",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("""
|
||||
func foo() {
|
||||
fatalError("Foo")
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
func foo() {
|
||||
fatalError(x)
|
||||
}
|
||||
""")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("""
|
||||
func foo() {
|
||||
↓fatalError("")
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
func foo() {
|
||||
↓fatalError()
|
||||
}
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension FatalErrorMessageRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: FunctionCallExprSyntax) {
|
||||
guard let expression = node.calledExpression.as(IdentifierExprSyntax.self),
|
||||
expression.identifier.text == "fatalError",
|
||||
node.argumentList.isEmptyOrEmptyString else {
|
||||
return
|
||||
}
|
||||
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension TupleExprElementListSyntax {
|
||||
var isEmptyOrEmptyString: Bool {
|
||||
if isEmpty {
|
||||
return true
|
||||
}
|
||||
return count == 1 && first?.expression.as(StringLiteralExprSyntax.self)?.isEmptyString == true
|
||||
}
|
||||
}
|
|
@ -1,26 +0,0 @@
|
|||
import Foundation
|
||||
import SourceKittenFramework
|
||||
|
||||
struct FileNameNoSpaceRule: ConfigurationProviderRule, OptInRule, SourceKitFreeRule {
|
||||
var configuration = FileNameNoSpaceConfiguration()
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "file_name_no_space",
|
||||
name: "File Name no Space",
|
||||
description: "File name should not contain any whitespace",
|
||||
kind: .idiomatic
|
||||
)
|
||||
|
||||
func validate(file: SwiftLintFile) -> [StyleViolation] {
|
||||
guard let filePath = file.path,
|
||||
case let fileName = filePath.bridge().lastPathComponent,
|
||||
!configuration.excluded.contains(fileName),
|
||||
fileName.rangeOfCharacter(from: .whitespaces) != nil else {
|
||||
return []
|
||||
}
|
||||
|
||||
return [StyleViolation(ruleDescription: Self.description,
|
||||
severity: configuration.severity,
|
||||
location: Location(file: filePath, line: 1))]
|
||||
}
|
||||
}
|
|
@ -1,84 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct FileNameRule: ConfigurationProviderRule, OptInRule, SourceKitFreeRule {
|
||||
var configuration = FileNameConfiguration()
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "file_name",
|
||||
name: "File Name",
|
||||
description: "File name should match a type or extension declared in the file (if any)",
|
||||
kind: .idiomatic
|
||||
)
|
||||
|
||||
func validate(file: SwiftLintFile) -> [StyleViolation] {
|
||||
guard let filePath = file.path,
|
||||
case let fileName = filePath.bridge().lastPathComponent,
|
||||
!configuration.excluded.contains(fileName) else {
|
||||
return []
|
||||
}
|
||||
|
||||
let prefixRegex = regex("\\A(?:\(configuration.prefixPattern))")
|
||||
let suffixRegex = regex("(?:\(configuration.suffixPattern))\\z")
|
||||
|
||||
var typeInFileName = fileName.bridge().deletingPathExtension
|
||||
|
||||
// Process prefix
|
||||
if let match = prefixRegex.firstMatch(in: typeInFileName, options: [], range: typeInFileName.fullNSRange),
|
||||
let range = typeInFileName.nsrangeToIndexRange(match.range) {
|
||||
typeInFileName.removeSubrange(range)
|
||||
}
|
||||
|
||||
// Process suffix
|
||||
if let match = suffixRegex.firstMatch(in: typeInFileName, options: [], range: typeInFileName.fullNSRange),
|
||||
let range = typeInFileName.nsrangeToIndexRange(match.range) {
|
||||
typeInFileName.removeSubrange(range)
|
||||
}
|
||||
|
||||
// Process nested type separator
|
||||
let allDeclaredTypeNames = TypeNameCollectingVisitor(viewMode: .sourceAccurate)
|
||||
.walk(tree: file.syntaxTree, handler: \.names)
|
||||
.map {
|
||||
$0.replacingOccurrences(of: ".", with: configuration.nestedTypeSeparator)
|
||||
}
|
||||
|
||||
guard allDeclaredTypeNames.isNotEmpty, !allDeclaredTypeNames.contains(typeInFileName) else {
|
||||
return []
|
||||
}
|
||||
|
||||
return [StyleViolation(ruleDescription: Self.description,
|
||||
severity: configuration.severity,
|
||||
location: Location(file: filePath, line: 1))]
|
||||
}
|
||||
}
|
||||
|
||||
private class TypeNameCollectingVisitor: SyntaxVisitor {
|
||||
private(set) var names: Set<String> = []
|
||||
|
||||
override func visitPost(_ node: ClassDeclSyntax) {
|
||||
names.insert(node.identifier.text)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: ActorDeclSyntax) {
|
||||
names.insert(node.identifier.text)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: StructDeclSyntax) {
|
||||
names.insert(node.identifier.text)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: TypealiasDeclSyntax) {
|
||||
names.insert(node.identifier.text)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: EnumDeclSyntax) {
|
||||
names.insert(node.identifier.text)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: ProtocolDeclSyntax) {
|
||||
names.insert(node.identifier.text)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: ExtensionDeclSyntax) {
|
||||
names.insert(node.extendedType.trimmedDescription)
|
||||
}
|
||||
}
|
|
@ -1,189 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct ForWhereRule: SwiftSyntaxRule, ConfigurationProviderRule {
|
||||
var configuration = ForWhereConfiguration()
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "for_where",
|
||||
name: "Prefer For-Where",
|
||||
description: "`where` clauses are preferred over a single `if` inside a `for`",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("""
|
||||
for user in users where user.id == 1 { }
|
||||
"""),
|
||||
// if let
|
||||
Example("""
|
||||
for user in users {
|
||||
if let id = user.id { }
|
||||
}
|
||||
"""),
|
||||
// if var
|
||||
Example("""
|
||||
for user in users {
|
||||
if var id = user.id { }
|
||||
}
|
||||
"""),
|
||||
// if with else
|
||||
Example("""
|
||||
for user in users {
|
||||
if user.id == 1 { } else { }
|
||||
}
|
||||
"""),
|
||||
// if with else if
|
||||
Example("""
|
||||
for user in users {
|
||||
if user.id == 1 {
|
||||
} else if user.id == 2 { }
|
||||
}
|
||||
"""),
|
||||
// if is not the only expression inside for
|
||||
Example("""
|
||||
for user in users {
|
||||
if user.id == 1 { }
|
||||
print(user)
|
||||
}
|
||||
"""),
|
||||
// if a variable is used
|
||||
Example("""
|
||||
for user in users {
|
||||
let id = user.id
|
||||
if id == 1 { }
|
||||
}
|
||||
"""),
|
||||
// if something is after if
|
||||
Example("""
|
||||
for user in users {
|
||||
if user.id == 1 { }
|
||||
return true
|
||||
}
|
||||
"""),
|
||||
// condition with multiple clauses
|
||||
Example("""
|
||||
for user in users {
|
||||
if user.id == 1 && user.age > 18 { }
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
for user in users {
|
||||
if user.id == 1, user.age > 18 { }
|
||||
}
|
||||
"""),
|
||||
// if case
|
||||
Example("""
|
||||
for (index, value) in array.enumerated() {
|
||||
if case .valueB(_) = value {
|
||||
return index
|
||||
}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
for user in users {
|
||||
if user.id == 1 { return true }
|
||||
}
|
||||
""", configuration: ["allow_for_as_filter": true]),
|
||||
Example("""
|
||||
for user in users {
|
||||
if user.id == 1 {
|
||||
let derivedValue = calculateValue(from: user)
|
||||
return derivedValue != 0
|
||||
}
|
||||
}
|
||||
""", configuration: ["allow_for_as_filter": true])
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("""
|
||||
for user in users {
|
||||
↓if user.id == 1 { return true }
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
for subview in subviews {
|
||||
↓if !(subview is UIStackView) {
|
||||
subview.removeConstraints(subview.constraints)
|
||||
subview.removeFromSuperview()
|
||||
}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
for subview in subviews {
|
||||
↓if !(subview is UIStackView) {
|
||||
subview.removeConstraints(subview.constraints)
|
||||
subview.removeFromSuperview()
|
||||
}
|
||||
}
|
||||
""", configuration: ["allow_for_as_filter": true])
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(allowForAsFilter: configuration.allowForAsFilter)
|
||||
}
|
||||
}
|
||||
|
||||
private extension ForWhereRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
private let allowForAsFilter: Bool
|
||||
|
||||
init(allowForAsFilter: Bool) {
|
||||
self.allowForAsFilter = allowForAsFilter
|
||||
super.init(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: ForInStmtSyntax) {
|
||||
guard node.whereClause == nil,
|
||||
let onlyExprStmt = node.body.statements.onlyElement?.item.as(ExpressionStmtSyntax.self),
|
||||
let ifExpr = onlyExprStmt.expression.as(IfExprSyntax.self),
|
||||
ifExpr.elseBody == nil,
|
||||
!ifExpr.containsOptionalBinding,
|
||||
!ifExpr.containsPatternCondition,
|
||||
let condition = ifExpr.conditions.onlyElement,
|
||||
!condition.containsMultipleConditions else {
|
||||
return
|
||||
}
|
||||
|
||||
if allowForAsFilter, ifExpr.containsReturnStatement {
|
||||
return
|
||||
}
|
||||
|
||||
violations.append(ifExpr.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension IfExprSyntax {
|
||||
var containsOptionalBinding: Bool {
|
||||
conditions.contains { element in
|
||||
element.condition.is(OptionalBindingConditionSyntax.self)
|
||||
}
|
||||
}
|
||||
|
||||
var containsPatternCondition: Bool {
|
||||
conditions.contains { element in
|
||||
element.condition.is(MatchingPatternConditionSyntax.self)
|
||||
}
|
||||
}
|
||||
|
||||
var containsReturnStatement: Bool {
|
||||
body.statements.contains { element in
|
||||
element.item.is(ReturnStmtSyntax.self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension ConditionElementSyntax {
|
||||
var containsMultipleConditions: Bool {
|
||||
guard let condition = condition.as(SequenceExprSyntax.self) else {
|
||||
return false
|
||||
}
|
||||
|
||||
return condition.elements.contains { expr in
|
||||
guard let binaryExpr = expr.as(BinaryOperatorExprSyntax.self) else {
|
||||
return false
|
||||
}
|
||||
|
||||
let operators: Set = ["&&", "||"]
|
||||
return operators.contains(binaryExpr.operatorToken.text)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,34 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct ForceCastRule: ConfigurationProviderRule, SwiftSyntaxRule {
|
||||
var configuration = SeverityConfiguration<Self>(.error)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "force_cast",
|
||||
name: "Force Cast",
|
||||
description: "Force casts should be avoided",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("NSNumber() as? Int\n")
|
||||
],
|
||||
triggeringExamples: [ Example("NSNumber() ↓as! Int\n") ]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
ForceCastRuleVisitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private final class ForceCastRuleVisitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: AsExprSyntax) {
|
||||
if node.questionOrExclamationMark?.tokenKind == .exclamationMark {
|
||||
violations.append(node.asTok.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: UnresolvedAsExprSyntax) {
|
||||
if node.questionOrExclamationMark?.tokenKind == .exclamationMark {
|
||||
violations.append(node.asTok.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,40 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct ForceTryRule: ConfigurationProviderRule, SwiftSyntaxRule {
|
||||
var configuration = SeverityConfiguration<Self>(.error)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "force_try",
|
||||
name: "Force Try",
|
||||
description: "Force tries should be avoided",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("""
|
||||
func a() throws {}
|
||||
do {
|
||||
try a()
|
||||
} catch {}
|
||||
""")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("""
|
||||
func a() throws {}
|
||||
↓try! a()
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension ForceTryRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: TryExprSyntax) {
|
||||
if node.questionOrExclamationMark?.tokenKind == .exclamationMark {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,77 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct ForceUnwrappingRule: OptInRule, SwiftSyntaxRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "force_unwrapping",
|
||||
name: "Force Unwrapping",
|
||||
description: "Force unwrapping should be avoided",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("if let url = NSURL(string: query)"),
|
||||
Example("navigationController?.pushViewController(viewController, animated: true)"),
|
||||
Example("let s as! Test"),
|
||||
Example("try! canThrowErrors()"),
|
||||
Example("let object: Any!"),
|
||||
Example("@IBOutlet var constraints: [NSLayoutConstraint]!"),
|
||||
Example("setEditing(!editing, animated: true)"),
|
||||
Example("navigationController.setNavigationBarHidden(!navigationController." +
|
||||
"navigationBarHidden, animated: true)"),
|
||||
Example("if addedToPlaylist && (!self.selectedFilters.isEmpty || " +
|
||||
"self.searchBar?.text?.isEmpty == false) {}"),
|
||||
Example("print(\"\\(xVar)!\")"),
|
||||
Example("var test = (!bar)"),
|
||||
Example("var a: [Int]!"),
|
||||
Example("private var myProperty: (Void -> Void)!"),
|
||||
Example("func foo(_ options: [AnyHashable: Any]!) {"),
|
||||
Example("func foo() -> [Int]!"),
|
||||
Example("func foo() -> [AnyHashable: Any]!"),
|
||||
Example("func foo() -> [Int]! { return [] }"),
|
||||
Example("return self")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("let url = NSURL(string: query)↓!"),
|
||||
Example("navigationController↓!.pushViewController(viewController, animated: true)"),
|
||||
Example("let unwrapped = optional↓!"),
|
||||
Example("return cell↓!"),
|
||||
Example("let url = NSURL(string: \"http://www.google.com\")↓!"),
|
||||
Example("""
|
||||
let dict = ["Boooo": "👻"]
|
||||
func bla() -> String {
|
||||
return dict["Boooo"]↓!
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
let dict = ["Boooo": "👻"]
|
||||
func bla() -> String {
|
||||
return dict["Boooo"]↓!.contains("B")
|
||||
}
|
||||
"""),
|
||||
Example("let a = dict[\"abc\"]↓!.contains(\"B\")"),
|
||||
Example("dict[\"abc\"]↓!.bar(\"B\")"),
|
||||
Example("if dict[\"a\"]↓!↓!↓!↓! {}"),
|
||||
Example("var foo: [Bool]! = dict[\"abc\"]↓!"),
|
||||
Example("realm.objects(SwiftUTF8Object.self).filter(\"%K == %@\", \"柱нǢкƱаم👍\", utf8TestString).first↓!"),
|
||||
Example("""
|
||||
context("abc") {
|
||||
var foo: [Bool]! = dict["abc"]↓!
|
||||
}
|
||||
"""),
|
||||
Example("open var computed: String { return foo.bar↓! }"),
|
||||
Example("return self↓!"),
|
||||
Example("[1, 3, 5, 6].first { $0.isMultiple(of: 2) }↓!"),
|
||||
Example("map[\"a\"]↓!↓!")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
ForceUnwrappingVisitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private final class ForceUnwrappingVisitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: ForcedValueExprSyntax) {
|
||||
violations.append(node.exclamationMark.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
|
@ -1,132 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct FunctionDefaultParameterAtEndRule: SwiftSyntaxRule, ConfigurationProviderRule, OptInRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "function_default_parameter_at_end",
|
||||
name: "Function Default Parameter at End",
|
||||
description: "Prefer to locate parameters with defaults toward the end of the parameter list",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("func foo(baz: String, bar: Int = 0) {}"),
|
||||
Example("func foo(x: String, y: Int = 0, z: CGFloat = 0) {}"),
|
||||
Example("func foo(bar: String, baz: Int = 0, z: () -> Void) {}"),
|
||||
Example("func foo(bar: String, z: () -> Void, baz: Int = 0) {}"),
|
||||
Example("func foo(bar: Int = 0) {}"),
|
||||
Example("func foo() {}"),
|
||||
Example("""
|
||||
class A: B {
|
||||
override func foo(bar: Int = 0, baz: String) {}
|
||||
"""),
|
||||
Example("func foo(bar: Int = 0, completion: @escaping CompletionHandler) {}"),
|
||||
Example("""
|
||||
func foo(a: Int, b: CGFloat = 0) {
|
||||
let block = { (error: Error?) in }
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
func foo(a: String, b: String? = nil,
|
||||
c: String? = nil, d: @escaping AlertActionHandler = { _ in }) {}
|
||||
"""),
|
||||
Example("override init?(for date: Date = Date(), coordinate: CLLocationCoordinate2D) {}"),
|
||||
Example("""
|
||||
func handleNotification(_ userInfo: NSDictionary,
|
||||
userInteraction: Bool = false,
|
||||
completionHandler: ((UIBackgroundFetchResult) -> Void)?) {}
|
||||
"""),
|
||||
Example("""
|
||||
func write(withoutNotifying tokens: [NotificationToken] = {}, _ block: (() throws -> Int)) {}
|
||||
"""),
|
||||
Example("""
|
||||
func expect<T>(file: String = #file, _ expression: @autoclosure () -> (() throws -> T)) -> Expectation<T> {}
|
||||
""", excludeFromDocumentation: true)
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("↓func foo(bar: Int = 0, baz: String) {}"),
|
||||
Example("private ↓func foo(bar: Int = 0, baz: String) {}"),
|
||||
Example("public ↓init?(for date: Date = Date(), coordinate: CLLocationCoordinate2D) {}")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension FunctionDefaultParameterAtEndRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: FunctionDeclSyntax) {
|
||||
guard !node.modifiers.containsOverride, node.signature.containsViolation else {
|
||||
return
|
||||
}
|
||||
|
||||
violations.append(node.funcKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: InitializerDeclSyntax) {
|
||||
guard !node.modifiers.containsOverride, node.signature.containsViolation else {
|
||||
return
|
||||
}
|
||||
|
||||
violations.append(node.initKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension FunctionSignatureSyntax {
|
||||
var containsViolation: Bool {
|
||||
let params = input.parameterList.filter { param in
|
||||
!param.isClosure
|
||||
}
|
||||
|
||||
guard params.isNotEmpty else {
|
||||
return false
|
||||
}
|
||||
|
||||
let defaultParams = params.filter { param in
|
||||
param.defaultArgument != nil
|
||||
}
|
||||
guard defaultParams.isNotEmpty else {
|
||||
return false
|
||||
}
|
||||
|
||||
let lastParameters = params.suffix(defaultParams.count)
|
||||
let lastParametersWithDefaultValue = lastParameters.filter { param in
|
||||
param.defaultArgument != nil
|
||||
}
|
||||
|
||||
return lastParameters.count != lastParametersWithDefaultValue.count
|
||||
}
|
||||
}
|
||||
|
||||
private extension FunctionParameterSyntax {
|
||||
var isClosure: Bool {
|
||||
if isEscaping || type.is(FunctionTypeSyntax.self) {
|
||||
return true
|
||||
}
|
||||
|
||||
if let optionalType = type.as(OptionalTypeSyntax.self),
|
||||
let tuple = optionalType.wrappedType.as(TupleTypeSyntax.self) {
|
||||
return tuple.elements.onlyElement?.type.as(FunctionTypeSyntax.self) != nil
|
||||
}
|
||||
|
||||
if let tuple = type.as(TupleTypeSyntax.self) {
|
||||
return tuple.elements.onlyElement?.type.as(FunctionTypeSyntax.self) != nil
|
||||
}
|
||||
|
||||
if let attrType = type.as(AttributedTypeSyntax.self) {
|
||||
return attrType.baseType.is(FunctionTypeSyntax.self)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
var isEscaping: Bool {
|
||||
guard let attrType = type.as(AttributedTypeSyntax.self) else {
|
||||
return false
|
||||
}
|
||||
|
||||
return attrType.attributes.contains(attributeNamed: "escaping")
|
||||
}
|
||||
}
|
|
@ -1,101 +0,0 @@
|
|||
import Foundation
|
||||
import SwiftSyntax
|
||||
|
||||
struct GenericTypeNameRule: SwiftSyntaxRule, ConfigurationProviderRule {
|
||||
var configuration = NameConfiguration<Self>(minLengthWarning: 1,
|
||||
minLengthError: 0,
|
||||
maxLengthWarning: 20,
|
||||
maxLengthError: 1000)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "generic_type_name",
|
||||
name: "Generic Type Name",
|
||||
description: "Generic type name should only contain alphanumeric characters, start with an " +
|
||||
"uppercase character and span between 1 and 20 characters in length.",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("func foo<T>() {}\n"),
|
||||
Example("func foo<T>() -> T {}\n"),
|
||||
Example("func foo<T, U>(param: U) -> T {}\n"),
|
||||
Example("func foo<T: Hashable, U: Rule>(param: U) -> T {}\n"),
|
||||
Example("struct Foo<T> {}\n"),
|
||||
Example("class Foo<T> {}\n"),
|
||||
Example("enum Foo<T> {}\n"),
|
||||
Example("func run(_ options: NoOptions<CommandantError<()>>) {}\n"),
|
||||
Example("func foo(_ options: Set<type>) {}\n"),
|
||||
Example("func < <T: Comparable>(lhs: T?, rhs: T?) -> Bool\n"),
|
||||
Example("func configureWith(data: Either<MessageThread, (project: Project, backing: Backing)>)\n"),
|
||||
Example("typealias StringDictionary<T> = Dictionary<String, T>\n"),
|
||||
Example("typealias BackwardTriple<T1, T2, T3> = (T3, T2, T1)\n"),
|
||||
Example("typealias DictionaryOfStrings<T : Hashable> = Dictionary<T, String>\n")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("func foo<↓T_Foo>() {}\n"),
|
||||
Example("func foo<T, ↓U_Foo>(param: U_Foo) -> T {}\n"),
|
||||
Example("func foo<↓\(String(repeating: "T", count: 21))>() {}\n"),
|
||||
Example("func foo<↓type>() {}\n"),
|
||||
Example("typealias StringDictionary<↓T_Foo> = Dictionary<String, T_Foo>\n"),
|
||||
Example("typealias BackwardTriple<T1, ↓T2_Bar, T3> = (T3, T2_Bar, T1)\n"),
|
||||
Example("typealias DictionaryOfStrings<↓T_Foo: Hashable> = Dictionary<T_Foo, String>\n")
|
||||
] + ["class", "struct", "enum"].flatMap { type -> [Example] in
|
||||
return [
|
||||
Example("\(type) Foo<↓T_Foo> {}\n"),
|
||||
Example("\(type) Foo<T, ↓U_Foo> {}\n"),
|
||||
Example("\(type) Foo<↓T_Foo, ↓U_Foo> {}\n"),
|
||||
Example("\(type) Foo<↓\(String(repeating: "T", count: 21))> {}\n"),
|
||||
Example("\(type) Foo<↓type> {}\n")
|
||||
]
|
||||
}
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(configuration: configuration)
|
||||
}
|
||||
}
|
||||
|
||||
private extension GenericTypeNameRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
private let configuration: ConfigurationType
|
||||
|
||||
init(configuration: ConfigurationType) {
|
||||
self.configuration = configuration
|
||||
super.init(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: GenericParameterSyntax) {
|
||||
let name = node.name.text
|
||||
guard !name.isEmpty, !configuration.shouldExclude(name: name) else { return }
|
||||
|
||||
if !configuration.allowedSymbolsAndAlphanumerics.isSuperset(of: CharacterSet(charactersIn: name)) {
|
||||
violations.append(
|
||||
ReasonedRuleViolation(
|
||||
position: node.positionAfterSkippingLeadingTrivia,
|
||||
reason: """
|
||||
Generic type name '\(name)' should only contain alphanumeric and other allowed characters
|
||||
""",
|
||||
severity: .error
|
||||
)
|
||||
)
|
||||
} else if let caseCheckSeverity = configuration.validatesStartWithLowercase.severity,
|
||||
!String(name[name.startIndex]).isUppercase() {
|
||||
violations.append(
|
||||
ReasonedRuleViolation(
|
||||
position: node.positionAfterSkippingLeadingTrivia,
|
||||
reason: "Generic type name '\(name)' should start with an uppercase character",
|
||||
severity: caseCheckSeverity
|
||||
)
|
||||
)
|
||||
} else if let severity = configuration.severity(forLength: name.count) {
|
||||
let reason = "Generic type name '\(name)' should be between \(configuration.minLengthThreshold) and " +
|
||||
"\(configuration.maxLengthThreshold) characters long"
|
||||
violations.append(
|
||||
ReasonedRuleViolation(
|
||||
position: node.positionAfterSkippingLeadingTrivia,
|
||||
reason: reason,
|
||||
severity: severity
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,71 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct ImplicitlyUnwrappedOptionalRule: SwiftSyntaxRule, ConfigurationProviderRule, OptInRule {
|
||||
var configuration = ImplicitlyUnwrappedOptionalConfiguration()
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "implicitly_unwrapped_optional",
|
||||
name: "Implicitly Unwrapped Optional",
|
||||
description: "Implicitly unwrapped optionals should be avoided when possible",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("@IBOutlet private var label: UILabel!"),
|
||||
Example("@IBOutlet var label: UILabel!"),
|
||||
Example("@IBOutlet var label: [UILabel!]"),
|
||||
Example("if !boolean {}"),
|
||||
Example("let int: Int? = 42"),
|
||||
Example("let int: Int? = nil"),
|
||||
Example("""
|
||||
class MyClass {
|
||||
@IBOutlet
|
||||
weak var bar: SomeObject!
|
||||
}
|
||||
""", configuration: ["mode": "all_except_iboutlets"], excludeFromDocumentation: true)
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("let label: ↓UILabel!"),
|
||||
Example("let IBOutlet: ↓UILabel!"),
|
||||
Example("let labels: [↓UILabel!]"),
|
||||
Example("var ints: [↓Int!] = [42, nil, 42]"),
|
||||
Example("let label: ↓IBOutlet!"),
|
||||
Example("let int: ↓Int! = 42"),
|
||||
Example("let int: ↓Int! = nil"),
|
||||
Example("var int: ↓Int! = 42"),
|
||||
Example("let collection: AnyCollection<↓Int!>"),
|
||||
Example("func foo(int: ↓Int!) {}"),
|
||||
Example("""
|
||||
class MyClass {
|
||||
weak var bar: ↓SomeObject!
|
||||
}
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(mode: configuration.mode)
|
||||
}
|
||||
}
|
||||
|
||||
private extension ImplicitlyUnwrappedOptionalRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
private let mode: ConfigurationType.ImplicitlyUnwrappedOptionalModeConfiguration
|
||||
|
||||
init(mode: ConfigurationType.ImplicitlyUnwrappedOptionalModeConfiguration) {
|
||||
self.mode = mode
|
||||
super.init(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: ImplicitlyUnwrappedOptionalTypeSyntax) {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
|
||||
override func visit(_ node: VariableDeclSyntax) -> SyntaxVisitorContinueKind {
|
||||
switch mode {
|
||||
case .all:
|
||||
return .visitChildren
|
||||
case .allExceptIBOutlets:
|
||||
return node.isIBOutlet ? .skipChildren : .visitChildren
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,43 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct IsDisjointRule: SwiftSyntaxRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "is_disjoint",
|
||||
name: "Is Disjoint",
|
||||
description: "Prefer using `Set.isDisjoint(with:)` over `Set.intersection(_:).isEmpty`",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("_ = Set(syntaxKinds).isDisjoint(with: commentAndStringKindsSet)"),
|
||||
Example("let isObjc = !objcAttributes.isDisjoint(with: dictionary.enclosedSwiftAttributes)"),
|
||||
Example("_ = Set(syntaxKinds).intersection(commentAndStringKindsSet)"),
|
||||
Example("_ = !objcAttributes.intersection(dictionary.enclosedSwiftAttributes)")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("_ = Set(syntaxKinds).↓intersection(commentAndStringKindsSet).isEmpty"),
|
||||
Example("let isObjc = !objcAttributes.↓intersection(dictionary.enclosedSwiftAttributes).isEmpty")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension IsDisjointRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: MemberAccessExprSyntax) {
|
||||
guard
|
||||
node.name.text == "isEmpty",
|
||||
let firstBase = node.base?.asFunctionCall,
|
||||
let firstBaseCalledExpression = firstBase.calledExpression.as(MemberAccessExprSyntax.self),
|
||||
firstBaseCalledExpression.name.text == "intersection"
|
||||
else {
|
||||
return
|
||||
}
|
||||
|
||||
violations.append(firstBaseCalledExpression.name.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,96 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct JoinedDefaultParameterRule: SwiftSyntaxCorrectableRule, ConfigurationProviderRule, OptInRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "joined_default_parameter",
|
||||
name: "Joined Default Parameter",
|
||||
description: "Discouraged explicit usage of the default separator",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("let foo = bar.joined()"),
|
||||
Example("let foo = bar.joined(separator: \",\")"),
|
||||
Example("let foo = bar.joined(separator: toto)")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("let foo = bar.joined(↓separator: \"\")"),
|
||||
Example("""
|
||||
let foo = bar.filter(toto)
|
||||
.joined(↓separator: ""),
|
||||
"""),
|
||||
Example("""
|
||||
func foo() -> String {
|
||||
return ["1", "2"].joined(↓separator: "")
|
||||
}
|
||||
""")
|
||||
],
|
||||
corrections: [
|
||||
Example("let foo = bar.joined(↓separator: \"\")"): Example("let foo = bar.joined()"),
|
||||
Example("let foo = bar.filter(toto)\n.joined(↓separator: \"\")"):
|
||||
Example("let foo = bar.filter(toto)\n.joined()"),
|
||||
Example("func foo() -> String {\n return [\"1\", \"2\"].joined(↓separator: \"\")\n}"):
|
||||
Example("func foo() -> String {\n return [\"1\", \"2\"].joined()\n}"),
|
||||
Example("class C {\n#if true\nlet foo = bar.joined(↓separator: \"\")\n#endif\n}"):
|
||||
Example("class C {\n#if true\nlet foo = bar.joined()\n#endif\n}")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter? {
|
||||
Rewriter(
|
||||
locationConverter: file.locationConverter,
|
||||
disabledRegions: disabledRegions(file: file)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private extension JoinedDefaultParameterRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: FunctionCallExprSyntax) {
|
||||
if let violationPosition = node.violationPosition {
|
||||
violations.append(violationPosition)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class Rewriter: SyntaxRewriter, ViolationsSyntaxRewriter {
|
||||
private(set) var correctionPositions: [AbsolutePosition] = []
|
||||
private let locationConverter: SourceLocationConverter
|
||||
private let disabledRegions: [SourceRange]
|
||||
|
||||
init(locationConverter: SourceLocationConverter, disabledRegions: [SourceRange]) {
|
||||
self.locationConverter = locationConverter
|
||||
self.disabledRegions = disabledRegions
|
||||
}
|
||||
|
||||
override func visit(_ node: FunctionCallExprSyntax) -> ExprSyntax {
|
||||
guard let violationPosition = node.violationPosition,
|
||||
!node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter) else {
|
||||
return super.visit(node)
|
||||
}
|
||||
|
||||
correctionPositions.append(violationPosition)
|
||||
let newNode = node.with(\.argumentList, [])
|
||||
return super.visit(newNode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension FunctionCallExprSyntax {
|
||||
var violationPosition: AbsolutePosition? {
|
||||
guard let argument = argumentList.first,
|
||||
let memberExp = calledExpression.as(MemberAccessExprSyntax.self),
|
||||
memberExp.name.text == "joined",
|
||||
argument.label?.text == "separator",
|
||||
let strLiteral = argument.expression.as(StringLiteralExprSyntax.self),
|
||||
strLiteral.isEmptyString else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return argument.positionAfterSkippingLeadingTrivia
|
||||
}
|
||||
}
|
|
@ -1,114 +0,0 @@
|
|||
struct LegacyCGGeometryFunctionsRule: SwiftSyntaxCorrectableRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "legacy_cggeometry_functions",
|
||||
name: "Legacy CGGeometry Functions",
|
||||
description: "Struct extension properties and methods are preferred over legacy functions",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("rect.width"),
|
||||
Example("rect.height"),
|
||||
Example("rect.minX"),
|
||||
Example("rect.midX"),
|
||||
Example("rect.maxX"),
|
||||
Example("rect.minY"),
|
||||
Example("rect.midY"),
|
||||
Example("rect.maxY"),
|
||||
Example("rect.isNull"),
|
||||
Example("rect.isEmpty"),
|
||||
Example("rect.isInfinite"),
|
||||
Example("rect.standardized"),
|
||||
Example("rect.integral"),
|
||||
Example("rect.insetBy(dx: 5.0, dy: -7.0)"),
|
||||
Example("rect.offsetBy(dx: 5.0, dy: -7.0)"),
|
||||
Example("rect1.union(rect2)"),
|
||||
Example("rect1.intersect(rect2)"),
|
||||
// "rect.divide(atDistance: 10.2, fromEdge: edge)", No correction available for divide
|
||||
Example("rect1.contains(rect2)"),
|
||||
Example("rect.contains(point)"),
|
||||
Example("rect1.intersects(rect2)")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("↓CGRectGetWidth(rect)"),
|
||||
Example("↓CGRectGetHeight(rect)"),
|
||||
Example("↓CGRectGetMinX(rect)"),
|
||||
Example("↓CGRectGetMidX(rect)"),
|
||||
Example("↓CGRectGetMaxX(rect)"),
|
||||
Example("↓CGRectGetMinY(rect)"),
|
||||
Example("↓CGRectGetMidY(rect)"),
|
||||
Example("↓CGRectGetMaxY(rect)"),
|
||||
Example("↓CGRectIsNull(rect)"),
|
||||
Example("↓CGRectIsEmpty(rect)"),
|
||||
Example("↓CGRectIsInfinite(rect)"),
|
||||
Example("↓CGRectStandardize(rect)"),
|
||||
Example("↓CGRectIntegral(rect)"),
|
||||
Example("↓CGRectInset(rect, 10, 5)"),
|
||||
Example("↓CGRectOffset(rect, -2, 8.3)"),
|
||||
Example("↓CGRectUnion(rect1, rect2)"),
|
||||
Example("↓CGRectIntersection(rect1, rect2)"),
|
||||
Example("↓CGRectContainsRect(rect1, rect2)"),
|
||||
Example("↓CGRectContainsPoint(rect, point)"),
|
||||
Example("↓CGRectIntersectsRect(rect1, rect2)")
|
||||
],
|
||||
corrections: [
|
||||
Example("↓CGRectGetWidth( rect )\n"): Example("rect.width\n"),
|
||||
Example("↓CGRectGetHeight(rect )\n"): Example("rect.height\n"),
|
||||
Example("↓CGRectGetMinX( rect)\n"): Example("rect.minX\n"),
|
||||
Example("↓CGRectGetMidX( rect)\n"): Example("rect.midX\n"),
|
||||
Example("↓CGRectGetMaxX( rect)\n"): Example("rect.maxX\n"),
|
||||
Example("↓CGRectGetMinY(rect )\n"): Example("rect.minY\n"),
|
||||
Example("↓CGRectGetMidY(rect )\n"): Example("rect.midY\n"),
|
||||
Example("↓CGRectGetMaxY( rect )\n"): Example("rect.maxY\n"),
|
||||
Example("↓CGRectIsNull( rect )\n"): Example("rect.isNull\n"),
|
||||
Example("↓CGRectIsEmpty( rect )\n"): Example("rect.isEmpty\n"),
|
||||
Example("↓CGRectIsInfinite( rect )\n"): Example("rect.isInfinite\n"),
|
||||
Example("↓CGRectStandardize( rect)\n"): Example("rect.standardized\n"),
|
||||
Example("↓CGRectIntegral(rect )\n"): Example("rect.integral\n"),
|
||||
Example("↓CGRectInset(rect, 5.0, -7.0)\n"): Example("rect.insetBy(dx: 5.0, dy: -7.0)\n"),
|
||||
Example("↓CGRectOffset(rect, -2, 8.3)\n"): Example("rect.offsetBy(dx: -2, dy: 8.3)\n"),
|
||||
Example("↓CGRectUnion(rect1, rect2)\n"): Example("rect1.union(rect2)\n"),
|
||||
Example("↓CGRectIntersection( rect1 ,rect2)\n"): Example("rect1.intersection(rect2)\n"),
|
||||
Example("↓CGRectContainsRect( rect1,rect2 )\n"): Example("rect1.contains(rect2)\n"),
|
||||
Example("↓CGRectContainsPoint(rect ,point)\n"): Example("rect.contains(point)\n"),
|
||||
Example("↓CGRectIntersectsRect( rect1,rect2 )\n"): Example("rect1.intersects(rect2)\n"),
|
||||
Example("↓CGRectIntersectsRect(rect1, rect2 )\n↓CGRectGetWidth(rect )\n"):
|
||||
Example("rect1.intersects(rect2)\nrect.width\n")
|
||||
]
|
||||
)
|
||||
|
||||
private static let legacyFunctions: [String: LegacyFunctionRuleHelper.RewriteStrategy] = [
|
||||
"CGRectGetWidth": .property(name: "width"),
|
||||
"CGRectGetHeight": .property(name: "height"),
|
||||
"CGRectGetMinX": .property(name: "minX"),
|
||||
"CGRectGetMidX": .property(name: "midX"),
|
||||
"CGRectGetMaxX": .property(name: "maxX"),
|
||||
"CGRectGetMinY": .property(name: "minY"),
|
||||
"CGRectGetMidY": .property(name: "midY"),
|
||||
"CGRectGetMaxY": .property(name: "maxY"),
|
||||
"CGRectIsNull": .property(name: "isNull"),
|
||||
"CGRectIsEmpty": .property(name: "isEmpty"),
|
||||
"CGRectIsInfinite": .property(name: "isInfinite"),
|
||||
"CGRectStandardize": .property(name: "standardized"),
|
||||
"CGRectIntegral": .property(name: "integral"),
|
||||
"CGRectInset": .function(name: "insetBy", argumentLabels: ["dx", "dy"]),
|
||||
"CGRectOffset": .function(name: "offsetBy", argumentLabels: ["dx", "dy"]),
|
||||
"CGRectUnion": .function(name: "union", argumentLabels: [""]),
|
||||
"CGRectContainsRect": .function(name: "contains", argumentLabels: [""]),
|
||||
"CGRectContainsPoint": .function(name: "contains", argumentLabels: [""]),
|
||||
"CGRectIntersectsRect": .function(name: "intersects", argumentLabels: [""]),
|
||||
"CGRectIntersection": .function(name: "intersection", argumentLabels: [""])
|
||||
]
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
LegacyFunctionRuleHelper.Visitor(legacyFunctions: Self.legacyFunctions)
|
||||
}
|
||||
|
||||
func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter? {
|
||||
LegacyFunctionRuleHelper.Rewriter(
|
||||
legacyFunctions: Self.legacyFunctions,
|
||||
locationConverter: file.locationConverter,
|
||||
disabledRegions: disabledRegions(file: file)
|
||||
)
|
||||
}
|
||||
}
|
|
@ -1,98 +0,0 @@
|
|||
import SwiftSyntax
|
||||
import SwiftSyntaxBuilder
|
||||
|
||||
struct LegacyConstantRule: SwiftSyntaxCorrectableRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "legacy_constant",
|
||||
name: "Legacy Constant",
|
||||
description: "Struct-scoped constants are preferred over legacy global constants",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: LegacyConstantRuleExamples.nonTriggeringExamples,
|
||||
triggeringExamples: LegacyConstantRuleExamples.triggeringExamples,
|
||||
corrections: LegacyConstantRuleExamples.corrections
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter? {
|
||||
Rewriter(
|
||||
locationConverter: file.locationConverter,
|
||||
disabledRegions: disabledRegions(file: file)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private extension LegacyConstantRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: IdentifierExprSyntax) {
|
||||
if LegacyConstantRuleExamples.patterns.keys.contains(node.identifier.text) {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: FunctionCallExprSyntax) {
|
||||
if node.isLegacyPiExpression {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class Rewriter: SyntaxRewriter, ViolationsSyntaxRewriter {
|
||||
private(set) var correctionPositions: [AbsolutePosition] = []
|
||||
let locationConverter: SourceLocationConverter
|
||||
let disabledRegions: [SourceRange]
|
||||
|
||||
init(locationConverter: SourceLocationConverter, disabledRegions: [SourceRange]) {
|
||||
self.locationConverter = locationConverter
|
||||
self.disabledRegions = disabledRegions
|
||||
}
|
||||
|
||||
override func visit(_ node: IdentifierExprSyntax) -> ExprSyntax {
|
||||
guard
|
||||
let correction = LegacyConstantRuleExamples.patterns[node.identifier.text],
|
||||
!node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter)
|
||||
else {
|
||||
return super.visit(node)
|
||||
}
|
||||
|
||||
correctionPositions.append(node.positionAfterSkippingLeadingTrivia)
|
||||
return ("\(raw: correction)" as ExprSyntax)
|
||||
.with(\.leadingTrivia, node.leadingTrivia)
|
||||
.with(\.trailingTrivia, node.trailingTrivia)
|
||||
}
|
||||
|
||||
override func visit(_ node: FunctionCallExprSyntax) -> ExprSyntax {
|
||||
guard
|
||||
node.isLegacyPiExpression,
|
||||
let calledExpression = node.calledExpression.as(IdentifierExprSyntax.self),
|
||||
!node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter)
|
||||
else {
|
||||
return super.visit(node)
|
||||
}
|
||||
|
||||
correctionPositions.append(node.positionAfterSkippingLeadingTrivia)
|
||||
return ("\(raw: calledExpression.identifier.text).pi" as ExprSyntax)
|
||||
.with(\.leadingTrivia, node.leadingTrivia)
|
||||
.with(\.trailingTrivia, node.trailingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension FunctionCallExprSyntax {
|
||||
var isLegacyPiExpression: Bool {
|
||||
guard
|
||||
let calledExpression = calledExpression.as(IdentifierExprSyntax.self),
|
||||
calledExpression.identifier.text == "CGFloat" || calledExpression.identifier.text == "Float",
|
||||
let argument = argumentList.onlyElement?.expression.as(IdentifierExprSyntax.self),
|
||||
argument.identifier.text == "M_PI"
|
||||
else {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
}
|
|
@ -1,53 +0,0 @@
|
|||
internal struct LegacyConstantRuleExamples {
|
||||
static let nonTriggeringExamples: [Example] = [
|
||||
Example("CGRect.infinite"),
|
||||
Example("CGPoint.zero"),
|
||||
Example("CGRect.zero"),
|
||||
Example("CGSize.zero"),
|
||||
Example("NSPoint.zero"),
|
||||
Example("NSRect.zero"),
|
||||
Example("NSSize.zero"),
|
||||
Example("CGRect.null"),
|
||||
Example("CGFloat.pi"),
|
||||
Example("Float.pi")
|
||||
]
|
||||
|
||||
static let triggeringExamples: [Example] = [
|
||||
Example("↓CGRectInfinite"),
|
||||
Example("↓CGPointZero"),
|
||||
Example("↓CGRectZero"),
|
||||
Example("↓CGSizeZero"),
|
||||
Example("↓NSZeroPoint"),
|
||||
Example("↓NSZeroRect"),
|
||||
Example("↓NSZeroSize"),
|
||||
Example("↓CGRectNull"),
|
||||
Example("↓CGFloat(M_PI)"),
|
||||
Example("↓Float(M_PI)")
|
||||
]
|
||||
|
||||
static let corrections: [Example: Example] = [
|
||||
Example("↓CGRectInfinite"): Example("CGRect.infinite"),
|
||||
Example("↓CGPointZero"): Example("CGPoint.zero"),
|
||||
Example("↓CGRectZero"): Example("CGRect.zero"),
|
||||
Example("↓CGSizeZero"): Example("CGSize.zero"),
|
||||
Example("↓NSZeroPoint"): Example("NSPoint.zero"),
|
||||
Example("↓NSZeroRect"): Example("NSRect.zero"),
|
||||
Example("↓NSZeroSize"): Example("NSSize.zero"),
|
||||
Example("↓CGRectNull"): Example("CGRect.null"),
|
||||
Example("↓CGRectInfinite\n↓CGRectNull\n"): Example("CGRect.infinite\nCGRect.null\n"),
|
||||
Example("↓CGFloat(M_PI)"): Example("CGFloat.pi"),
|
||||
Example("↓Float(M_PI)"): Example("Float.pi"),
|
||||
Example("↓CGFloat(M_PI)\n↓Float(M_PI)\n"): Example("CGFloat.pi\nFloat.pi\n")
|
||||
]
|
||||
|
||||
static let patterns = [
|
||||
"CGRectInfinite": "CGRect.infinite",
|
||||
"CGPointZero": "CGPoint.zero",
|
||||
"CGRectZero": "CGRect.zero",
|
||||
"CGSizeZero": "CGSize.zero",
|
||||
"NSZeroPoint": "NSPoint.zero",
|
||||
"NSZeroRect": "NSRect.zero",
|
||||
"NSZeroSize": "NSSize.zero",
|
||||
"CGRectNull": "CGRect.null"
|
||||
]
|
||||
}
|
|
@ -1,187 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct LegacyConstructorRule: SwiftSyntaxCorrectableRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "legacy_constructor",
|
||||
name: "Legacy Constructor",
|
||||
description: "Swift constructors are preferred over legacy convenience functions",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("CGPoint(x: 10, y: 10)"),
|
||||
Example("CGPoint(x: xValue, y: yValue)"),
|
||||
Example("CGSize(width: 10, height: 10)"),
|
||||
Example("CGSize(width: aWidth, height: aHeight)"),
|
||||
Example("CGRect(x: 0, y: 0, width: 10, height: 10)"),
|
||||
Example("CGRect(x: xVal, y: yVal, width: aWidth, height: aHeight)"),
|
||||
Example("CGVector(dx: 10, dy: 10)"),
|
||||
Example("CGVector(dx: deltaX, dy: deltaY)"),
|
||||
Example("NSPoint(x: 10, y: 10)"),
|
||||
Example("NSPoint(x: xValue, y: yValue)"),
|
||||
Example("NSSize(width: 10, height: 10)"),
|
||||
Example("NSSize(width: aWidth, height: aHeight)"),
|
||||
Example("NSRect(x: 0, y: 0, width: 10, height: 10)"),
|
||||
Example("NSRect(x: xVal, y: yVal, width: aWidth, height: aHeight)"),
|
||||
Example("NSRange(location: 10, length: 1)"),
|
||||
Example("NSRange(location: loc, length: len)"),
|
||||
Example("UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 10)"),
|
||||
Example("UIEdgeInsets(top: aTop, left: aLeft, bottom: aBottom, right: aRight)"),
|
||||
Example("NSEdgeInsets(top: 0, left: 0, bottom: 10, right: 10)"),
|
||||
Example("NSEdgeInsets(top: aTop, left: aLeft, bottom: aBottom, right: aRight)"),
|
||||
Example("UIOffset(horizontal: 0, vertical: 10)"),
|
||||
Example("UIOffset(horizontal: horizontal, vertical: vertical)")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("↓CGPointMake(10, 10)"),
|
||||
Example("↓CGPointMake(xVal, yVal)"),
|
||||
Example("↓CGPointMake(calculateX(), 10)\n"),
|
||||
Example("↓CGSizeMake(10, 10)"),
|
||||
Example("↓CGSizeMake(aWidth, aHeight)"),
|
||||
Example("↓CGRectMake(0, 0, 10, 10)"),
|
||||
Example("↓CGRectMake(xVal, yVal, width, height)"),
|
||||
Example("↓CGVectorMake(10, 10)"),
|
||||
Example("↓CGVectorMake(deltaX, deltaY)"),
|
||||
Example("↓NSMakePoint(10, 10)"),
|
||||
Example("↓NSMakePoint(xVal, yVal)"),
|
||||
Example("↓NSMakeSize(10, 10)"),
|
||||
Example("↓NSMakeSize(aWidth, aHeight)"),
|
||||
Example("↓NSMakeRect(0, 0, 10, 10)"),
|
||||
Example("↓NSMakeRect(xVal, yVal, width, height)"),
|
||||
Example("↓NSMakeRange(10, 1)"),
|
||||
Example("↓NSMakeRange(loc, len)"),
|
||||
Example("↓UIEdgeInsetsMake(0, 0, 10, 10)"),
|
||||
Example("↓UIEdgeInsetsMake(top, left, bottom, right)"),
|
||||
Example("↓NSEdgeInsetsMake(0, 0, 10, 10)"),
|
||||
Example("↓NSEdgeInsetsMake(top, left, bottom, right)"),
|
||||
Example("↓CGVectorMake(10, 10)\n↓NSMakeRange(10, 1)"),
|
||||
Example("↓UIOffsetMake(0, 10)"),
|
||||
Example("↓UIOffsetMake(horizontal, vertical)")
|
||||
],
|
||||
corrections: [
|
||||
Example("↓CGPointMake(10, 10)\n"): Example("CGPoint(x: 10, y: 10)\n"),
|
||||
Example("↓CGPointMake(xPos, yPos)\n"): Example("CGPoint(x: xPos, y: yPos)\n"),
|
||||
Example("↓CGSizeMake(10, 10)\n"): Example("CGSize(width: 10, height: 10)\n"),
|
||||
Example("↓CGSizeMake( aWidth, aHeight )\n"): Example("CGSize( width: aWidth, height: aHeight )\n"),
|
||||
Example("↓CGRectMake(0, 0, 10, 10)\n"): Example("CGRect(x: 0, y: 0, width: 10, height: 10)\n"),
|
||||
Example("↓CGRectMake(xPos, yPos , width, height)\n"):
|
||||
Example("CGRect(x: xPos, y: yPos , width: width, height: height)\n"),
|
||||
Example("↓CGVectorMake(10, 10)\n"): Example("CGVector(dx: 10, dy: 10)\n"),
|
||||
Example("↓CGVectorMake(deltaX, deltaY)\n"): Example("CGVector(dx: deltaX, dy: deltaY)\n"),
|
||||
Example("↓NSMakePoint(10, 10 )\n"): Example("NSPoint(x: 10, y: 10 )\n"),
|
||||
Example("↓NSMakePoint(xPos, yPos )\n"): Example("NSPoint(x: xPos, y: yPos )\n"),
|
||||
Example("↓NSMakeSize(10, 10)\n"): Example("NSSize(width: 10, height: 10)\n"),
|
||||
Example("↓NSMakeSize( aWidth, aHeight )\n"): Example("NSSize( width: aWidth, height: aHeight )\n"),
|
||||
Example("↓NSMakeRect(0, 0, 10, 10)\n"): Example("NSRect(x: 0, y: 0, width: 10, height: 10)\n"),
|
||||
Example("↓NSMakeRect(xPos, yPos , width, height)\n"):
|
||||
Example("NSRect(x: xPos, y: yPos , width: width, height: height)\n"),
|
||||
Example("↓NSMakeRange(10, 1)\n"): Example("NSRange(location: 10, length: 1)\n"),
|
||||
Example("↓NSMakeRange(loc, len)\n"): Example("NSRange(location: loc, length: len)\n"),
|
||||
Example("↓CGVectorMake(10, 10)\n↓NSMakeRange(10, 1)\n"):
|
||||
Example("CGVector(dx: 10, dy: 10)\nNSRange(location: 10, length: 1)\n"),
|
||||
Example("↓CGVectorMake(dx, dy)\n↓NSMakeRange(loc, len)\n"):
|
||||
Example("CGVector(dx: dx, dy: dy)\nNSRange(location: loc, length: len)\n"),
|
||||
Example("↓UIEdgeInsetsMake(0, 0, 10, 10)\n"):
|
||||
Example("UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 10)\n"),
|
||||
Example("↓UIEdgeInsetsMake(top, left, bottom, right)\n"):
|
||||
Example("UIEdgeInsets(top: top, left: left, bottom: bottom, right: right)\n"),
|
||||
Example("↓NSEdgeInsetsMake(0, 0, 10, 10)\n"):
|
||||
Example("NSEdgeInsets(top: 0, left: 0, bottom: 10, right: 10)\n"),
|
||||
Example("↓NSEdgeInsetsMake(top, left, bottom, right)\n"):
|
||||
Example("NSEdgeInsets(top: top, left: left, bottom: bottom, right: right)\n"),
|
||||
Example("↓NSMakeRange(0, attributedString.length)\n"):
|
||||
Example("NSRange(location: 0, length: attributedString.length)\n"),
|
||||
Example("↓CGPointMake(calculateX(), 10)\n"): Example("CGPoint(x: calculateX(), y: 10)\n"),
|
||||
Example("↓UIOffsetMake(0, 10)\n"): Example("UIOffset(horizontal: 0, vertical: 10)\n"),
|
||||
Example("↓UIOffsetMake(horizontal, vertical)\n"):
|
||||
Example("UIOffset(horizontal: horizontal, vertical: vertical)\n")
|
||||
]
|
||||
)
|
||||
|
||||
private static let constructorsToArguments = ["CGRectMake": ["x", "y", "width", "height"],
|
||||
"CGPointMake": ["x", "y"],
|
||||
"CGSizeMake": ["width", "height"],
|
||||
"CGVectorMake": ["dx", "dy"],
|
||||
"NSMakePoint": ["x", "y"],
|
||||
"NSMakeSize": ["width", "height"],
|
||||
"NSMakeRect": ["x", "y", "width", "height"],
|
||||
"NSMakeRange": ["location", "length"],
|
||||
"UIEdgeInsetsMake": ["top", "left", "bottom", "right"],
|
||||
"NSEdgeInsetsMake": ["top", "left", "bottom", "right"],
|
||||
"UIOffsetMake": ["horizontal", "vertical"]]
|
||||
|
||||
private static let constructorsToCorrectedNames = ["CGRectMake": "CGRect",
|
||||
"CGPointMake": "CGPoint",
|
||||
"CGSizeMake": "CGSize",
|
||||
"CGVectorMake": "CGVector",
|
||||
"NSMakePoint": "NSPoint",
|
||||
"NSMakeSize": "NSSize",
|
||||
"NSMakeRect": "NSRect",
|
||||
"NSMakeRange": "NSRange",
|
||||
"UIEdgeInsetsMake": "UIEdgeInsets",
|
||||
"NSEdgeInsetsMake": "NSEdgeInsets",
|
||||
"UIOffsetMake": "UIOffset"]
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter? {
|
||||
Rewriter(
|
||||
locationConverter: file.locationConverter,
|
||||
disabledRegions: disabledRegions(file: file)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private extension LegacyConstructorRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: FunctionCallExprSyntax) {
|
||||
if let identifierExpr = node.calledExpression.as(IdentifierExprSyntax.self),
|
||||
constructorsToCorrectedNames[identifierExpr.identifier.text] != nil {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class Rewriter: SyntaxRewriter, ViolationsSyntaxRewriter {
|
||||
private(set) var correctionPositions: [AbsolutePosition] = []
|
||||
let locationConverter: SourceLocationConverter
|
||||
let disabledRegions: [SourceRange]
|
||||
|
||||
init(locationConverter: SourceLocationConverter, disabledRegions: [SourceRange]) {
|
||||
self.locationConverter = locationConverter
|
||||
self.disabledRegions = disabledRegions
|
||||
}
|
||||
|
||||
override func visit(_ node: FunctionCallExprSyntax) -> ExprSyntax {
|
||||
guard let identifierExpr = node.calledExpression.as(IdentifierExprSyntax.self),
|
||||
case let identifier = identifierExpr.identifier.text,
|
||||
let correctedName = constructorsToCorrectedNames[identifier],
|
||||
let args = constructorsToArguments[identifier],
|
||||
!node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter) else {
|
||||
return super.visit(node)
|
||||
}
|
||||
|
||||
correctionPositions.append(node.positionAfterSkippingLeadingTrivia)
|
||||
|
||||
let arguments = TupleExprElementListSyntax(node.argumentList.enumerated().map { index, elem in
|
||||
elem
|
||||
.with(\.label, .identifier(args[index]))
|
||||
.with(\.colon, .colonToken(trailingTrivia: .space))
|
||||
})
|
||||
let newExpression = identifierExpr.with(
|
||||
\.identifier,
|
||||
.identifier(
|
||||
correctedName,
|
||||
leadingTrivia: identifierExpr.identifier.leadingTrivia,
|
||||
trailingTrivia: identifierExpr.identifier.trailingTrivia
|
||||
)
|
||||
)
|
||||
let newNode = node
|
||||
.with(\.calledExpression, ExprSyntax(newExpression))
|
||||
.with(\.argumentList, arguments)
|
||||
return super.visit(newNode)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,99 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct LegacyHashingRule: SwiftSyntaxRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "legacy_hashing",
|
||||
name: "Legacy Hashing",
|
||||
description: "Prefer using the `hash(into:)` function instead of overriding `hashValue`",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("""
|
||||
struct Foo: Hashable {
|
||||
let bar: Int = 10
|
||||
|
||||
func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(bar)
|
||||
}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo: Hashable {
|
||||
let bar: Int = 10
|
||||
|
||||
func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(bar)
|
||||
}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
var hashValue: Int { return 1 }
|
||||
class Foo: Hashable { \n }
|
||||
"""),
|
||||
Example("""
|
||||
class Foo: Hashable {
|
||||
let bar: String = "Foo"
|
||||
|
||||
public var hashValue: String {
|
||||
return bar
|
||||
}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo: Hashable {
|
||||
let bar: String = "Foo"
|
||||
|
||||
public var hashValue: String {
|
||||
get { return bar }
|
||||
set { bar = newValue }
|
||||
}
|
||||
}
|
||||
""")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("""
|
||||
struct Foo: Hashable {
|
||||
let bar: Int = 10
|
||||
|
||||
public ↓var hashValue: Int {
|
||||
return bar
|
||||
}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo: Hashable {
|
||||
let bar: Int = 10
|
||||
|
||||
public ↓var hashValue: Int {
|
||||
return bar
|
||||
}
|
||||
}
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
extension LegacyHashingRule {
|
||||
private final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: VariableDeclSyntax) {
|
||||
guard
|
||||
node.parent?.is(MemberDeclListItemSyntax.self) == true,
|
||||
node.bindingKeyword.tokenKind == .keyword(.var),
|
||||
let binding = node.bindings.onlyElement,
|
||||
let identifier = binding.pattern.as(IdentifierPatternSyntax.self),
|
||||
identifier.identifier.text == "hashValue",
|
||||
let returnType = binding.typeAnnotation?.type.as(SimpleTypeIdentifierSyntax.self),
|
||||
returnType.name.text == "Int"
|
||||
else {
|
||||
return
|
||||
}
|
||||
|
||||
violations.append(node.bindingKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,84 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct LegacyMultipleRule: OptInRule, ConfigurationProviderRule, SwiftSyntaxRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "legacy_multiple",
|
||||
name: "Legacy Multiple",
|
||||
description: "Prefer using the `isMultiple(of:)` function instead of using the remainder operator (`%`)",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("cell.contentView.backgroundColor = indexPath.row.isMultiple(of: 2) ? .gray : .white"),
|
||||
Example("guard count.isMultiple(of: 2) else { throw DecodingError.dataCorrupted(...) }"),
|
||||
Example("sanityCheck(bytes > 0 && bytes.isMultiple(of: 4), \"capacity must be multiple of 4 bytes\")"),
|
||||
Example("guard let i = reversedNumbers.firstIndex(where: { $0.isMultiple(of: 2) }) else { return }"),
|
||||
Example("""
|
||||
let constant = 56
|
||||
let isMultiple = value.isMultiple(of: constant)
|
||||
"""),
|
||||
Example("""
|
||||
let constant = 56
|
||||
let secret = value % constant == 5
|
||||
"""),
|
||||
Example("let secretValue = (value % 3) + 2")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("cell.contentView.backgroundColor = indexPath.row ↓% 2 == 0 ? .gray : .white"),
|
||||
Example("cell.contentView.backgroundColor = 0 == indexPath.row ↓% 2 ? .gray : .white"),
|
||||
Example("cell.contentView.backgroundColor = indexPath.row ↓% 2 != 0 ? .gray : .white"),
|
||||
Example("guard count ↓% 2 == 0 else { throw DecodingError.dataCorrupted(...) }"),
|
||||
Example("sanityCheck(bytes > 0 && bytes ↓% 4 == 0, \"capacity must be multiple of 4 bytes\")"),
|
||||
Example("guard let i = reversedNumbers.firstIndex(where: { $0 ↓% 2 == 0 }) else { return }"),
|
||||
Example("""
|
||||
let constant = 56
|
||||
let isMultiple = value ↓% constant == 0
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func preprocess(file: SwiftLintFile) -> SourceFileSyntax? {
|
||||
file.foldedSyntaxTree
|
||||
}
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension LegacyMultipleRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: InfixOperatorExprSyntax) {
|
||||
guard let operatorNode = node.operatorOperand.as(BinaryOperatorExprSyntax.self),
|
||||
operatorNode.operatorToken.tokenKind == .binaryOperator("%"),
|
||||
let parent = node.parent?.as(InfixOperatorExprSyntax.self),
|
||||
let parentOperatorNode = parent.operatorOperand.as(BinaryOperatorExprSyntax.self),
|
||||
parentOperatorNode.isEqualityOrInequalityOperator else {
|
||||
return
|
||||
}
|
||||
|
||||
let isExprEqualTo0 = {
|
||||
parent.leftOperand.as(InfixOperatorExprSyntax.self) == node &&
|
||||
parent.rightOperand.as(IntegerLiteralExprSyntax.self)?.isZero == true
|
||||
}
|
||||
|
||||
let is0EqualToExpr = {
|
||||
parent.leftOperand.as(IntegerLiteralExprSyntax.self)?.isZero == true &&
|
||||
parent.rightOperand.as(InfixOperatorExprSyntax.self) == node
|
||||
}
|
||||
|
||||
guard isExprEqualTo0() || is0EqualToExpr() else {
|
||||
return
|
||||
}
|
||||
|
||||
violations.append(node.operatorOperand.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension BinaryOperatorExprSyntax {
|
||||
var isEqualityOrInequalityOperator: Bool {
|
||||
operatorToken.tokenKind == .binaryOperator("==") ||
|
||||
operatorToken.tokenKind == .binaryOperator("!=")
|
||||
}
|
||||
}
|
|
@ -1,114 +0,0 @@
|
|||
struct LegacyNSGeometryFunctionsRule: SwiftSyntaxCorrectableRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "legacy_nsgeometry_functions",
|
||||
name: "Legacy NSGeometry Functions",
|
||||
description: "Struct extension properties and methods are preferred over legacy functions",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("rect.width"),
|
||||
Example("rect.height"),
|
||||
Example("rect.minX"),
|
||||
Example("rect.midX"),
|
||||
Example("rect.maxX"),
|
||||
Example("rect.minY"),
|
||||
Example("rect.midY"),
|
||||
Example("rect.maxY"),
|
||||
Example("rect.isEmpty"),
|
||||
Example("rect.integral"),
|
||||
Example("rect.insetBy(dx: 5.0, dy: -7.0)"),
|
||||
Example("rect.offsetBy(dx: 5.0, dy: -7.0)"),
|
||||
Example("rect1.union(rect2)"),
|
||||
Example("rect1.intersection(rect2)"),
|
||||
// "rect.divide(atDistance: 10.2, fromEdge: edge)", No correction available for divide
|
||||
Example("rect1.contains(rect2)"),
|
||||
Example("rect.contains(point)"),
|
||||
Example("rect1.intersects(rect2)")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("↓NSWidth(rect)"),
|
||||
Example("↓NSHeight(rect)"),
|
||||
Example("↓NSMinX(rect)"),
|
||||
Example("↓NSMidX(rect)"),
|
||||
Example("↓NSMaxX(rect)"),
|
||||
Example("↓NSMinY(rect)"),
|
||||
Example("↓NSMidY(rect)"),
|
||||
Example("↓NSMaxY(rect)"),
|
||||
Example("↓NSEqualRects(rect1, rect2)"),
|
||||
Example("↓NSEqualSizes(size1, size2)"),
|
||||
Example("↓NSEqualPoints(point1, point2)"),
|
||||
Example("↓NSEdgeInsetsEqual(insets2, insets2)"),
|
||||
Example("↓NSIsEmptyRect(rect)"),
|
||||
Example("↓NSIntegralRect(rect)"),
|
||||
Example("↓NSInsetRect(rect, 10, 5)"),
|
||||
Example("↓NSOffsetRect(rect, -2, 8.3)"),
|
||||
Example("↓NSUnionRect(rect1, rect2)"),
|
||||
Example("↓NSIntersectionRect(rect1, rect2)"),
|
||||
Example("↓NSContainsRect(rect1, rect2)"),
|
||||
Example("↓NSPointInRect(rect, point)"),
|
||||
Example("↓NSIntersectsRect(rect1, rect2)")
|
||||
],
|
||||
corrections: [
|
||||
Example("↓NSWidth( rect )\n"): Example("rect.width\n"),
|
||||
Example("↓NSHeight(rect )\n"): Example("rect.height\n"),
|
||||
Example("↓NSMinX( rect)\n"): Example("rect.minX\n"),
|
||||
Example("↓NSMidX( rect)\n"): Example("rect.midX\n"),
|
||||
Example("↓NSMaxX( rect)\n"): Example("rect.maxX\n"),
|
||||
Example("↓NSMinY(rect )\n"): Example("rect.minY\n"),
|
||||
Example("↓NSMidY(rect )\n"): Example("rect.midY\n"),
|
||||
Example("↓NSMaxY( rect )\n"): Example("rect.maxY\n"),
|
||||
Example("↓NSEqualPoints( point1 , point2)\n"): Example("point1 == point2\n"),
|
||||
Example("↓NSEqualSizes(size1,size2 )\n"): Example("size1 == size2\n"),
|
||||
Example("↓NSEqualRects( rect1, rect2)\n"): Example("rect1 == rect2\n"),
|
||||
Example("↓NSEdgeInsetsEqual(insets1, insets2)\n"): Example("insets1 == insets2\n"),
|
||||
Example("↓NSIsEmptyRect( rect )\n"): Example("rect.isEmpty\n"),
|
||||
Example("↓NSIntegralRect(rect )\n"): Example("rect.integral\n"),
|
||||
Example("↓NSInsetRect(rect, 5.0, -7.0)\n"): Example("rect.insetBy(dx: 5.0, dy: -7.0)\n"),
|
||||
Example("↓NSOffsetRect(rect, -2, 8.3)\n"): Example("rect.offsetBy(dx: -2, dy: 8.3)\n"),
|
||||
Example("↓NSUnionRect(rect1, rect2)\n"): Example("rect1.union(rect2)\n"),
|
||||
Example("↓NSContainsRect( rect1,rect2 )\n"): Example("rect1.contains(rect2)\n"),
|
||||
Example("↓NSPointInRect(point ,rect)\n"): Example("rect.contains(point)\n"), // note order of arguments
|
||||
Example("↓NSIntersectsRect( rect1,rect2 )\n"): Example("rect1.intersects(rect2)\n"),
|
||||
Example("↓NSIntersectsRect(rect1, rect2 )\n↓NSWidth(rect )\n"):
|
||||
Example("rect1.intersects(rect2)\nrect.width\n"),
|
||||
Example("↓NSIntersectionRect(rect1, rect2)"): Example("rect1.intersection(rect2)")
|
||||
]
|
||||
)
|
||||
|
||||
private static let legacyFunctions: [String: LegacyFunctionRuleHelper.RewriteStrategy] = [
|
||||
"NSHeight": .property(name: "height"),
|
||||
"NSIntegralRect": .property(name: "integral"),
|
||||
"NSIsEmptyRect": .property(name: "isEmpty"),
|
||||
"NSMaxX": .property(name: "maxX"),
|
||||
"NSMaxY": .property(name: "maxY"),
|
||||
"NSMidX": .property(name: "midX"),
|
||||
"NSMidY": .property(name: "midY"),
|
||||
"NSMinX": .property(name: "minX"),
|
||||
"NSMinY": .property(name: "minY"),
|
||||
"NSWidth": .property(name: "width"),
|
||||
"NSEqualPoints": .equal,
|
||||
"NSEqualSizes": .equal,
|
||||
"NSEqualRects": .equal,
|
||||
"NSEdgeInsetsEqual": .equal,
|
||||
"NSInsetRect": .function(name: "insetBy", argumentLabels: ["dx", "dy"]),
|
||||
"NSOffsetRect": .function(name: "offsetBy", argumentLabels: ["dx", "dy"]),
|
||||
"NSUnionRect": .function(name: "union", argumentLabels: [""]),
|
||||
"NSContainsRect": .function(name: "contains", argumentLabels: [""]),
|
||||
"NSIntersectsRect": .function(name: "intersects", argumentLabels: [""]),
|
||||
"NSIntersectionRect": .function(name: "intersection", argumentLabels: [""]),
|
||||
"NSPointInRect": .function(name: "contains", argumentLabels: [""], reversed: true)
|
||||
]
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
LegacyFunctionRuleHelper.Visitor(legacyFunctions: Self.legacyFunctions)
|
||||
}
|
||||
|
||||
func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter? {
|
||||
LegacyFunctionRuleHelper.Rewriter(
|
||||
legacyFunctions: Self.legacyFunctions,
|
||||
locationConverter: file.locationConverter,
|
||||
disabledRegions: disabledRegions(file: file)
|
||||
)
|
||||
}
|
||||
}
|
|
@ -1,98 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
private let legacyObjcTypes = [
|
||||
"NSAffineTransform",
|
||||
"NSArray",
|
||||
"NSCalendar",
|
||||
"NSCharacterSet",
|
||||
"NSData",
|
||||
"NSDateComponents",
|
||||
"NSDateInterval",
|
||||
"NSDate",
|
||||
"NSDecimalNumber",
|
||||
"NSDictionary",
|
||||
"NSIndexPath",
|
||||
"NSIndexSet",
|
||||
"NSLocale",
|
||||
"NSMeasurement",
|
||||
"NSNotification",
|
||||
"NSNumber",
|
||||
"NSPersonNameComponents",
|
||||
"NSSet",
|
||||
"NSString",
|
||||
"NSTimeZone",
|
||||
"NSURL",
|
||||
"NSURLComponents",
|
||||
"NSURLQueryItem",
|
||||
"NSURLRequest",
|
||||
"NSUUID"
|
||||
]
|
||||
|
||||
struct LegacyObjcTypeRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "legacy_objc_type",
|
||||
name: "Legacy Objective-C Reference Type",
|
||||
description: "Prefer Swift value types to bridged Objective-C reference types",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("var array = Array<Int>()\n"),
|
||||
Example("var calendar: Calendar? = nil"),
|
||||
Example("var formatter: NSDataDetector"),
|
||||
Example("var className: String = NSStringFromClass(MyClass.self)"),
|
||||
Example("_ = URLRequest.CachePolicy.reloadIgnoringLocalCacheData"),
|
||||
Example(#"_ = Notification.Name("com.apple.Music.playerInfo")"#)
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("var array = ↓NSArray()"),
|
||||
Example("var calendar: ↓NSCalendar? = nil"),
|
||||
Example("_ = ↓NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData"),
|
||||
Example(#"_ = ↓NSNotification.Name("com.apple.Music.playerInfo")"#),
|
||||
Example(#"""
|
||||
let keyValuePair: (Int) -> (↓NSString, ↓NSString) = {
|
||||
let n = "\($0)" as ↓NSString; return (n, n)
|
||||
}
|
||||
dictionary = [↓NSString: ↓NSString](uniqueKeysWithValues:
|
||||
(1...10_000).lazy.map(keyValuePair))
|
||||
"""#),
|
||||
Example("""
|
||||
extension Foundation.Notification.Name {
|
||||
static var reachabilityChanged: Foundation.↓NSNotification.Name {
|
||||
return Foundation.Notification.Name("org.wordpress.reachability.changed")
|
||||
}
|
||||
}
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension LegacyObjcTypeRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: SimpleTypeIdentifierSyntax) {
|
||||
if let typeName = node.typeName, legacyObjcTypes.contains(typeName) {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: IdentifierExprSyntax) {
|
||||
if legacyObjcTypes.contains(node.identifier.text) {
|
||||
violations.append(node.identifier.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: MemberTypeIdentifierSyntax) {
|
||||
guard node.baseType.as(SimpleTypeIdentifierSyntax.self)?.typeName == "Foundation",
|
||||
legacyObjcTypes.contains(node.name.text)
|
||||
else {
|
||||
return
|
||||
}
|
||||
|
||||
violations.append(node.name.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,43 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct LegacyRandomRule: SwiftSyntaxRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static var description = RuleDescription(
|
||||
identifier: "legacy_random",
|
||||
name: "Legacy Random",
|
||||
description: "Prefer using `type.random(in:)` over legacy functions",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("Int.random(in: 0..<10)\n"),
|
||||
Example("Double.random(in: 8.6...111.34)\n"),
|
||||
Example("Float.random(in: 0 ..< 1)\n")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("↓arc4random()\n"),
|
||||
Example("↓arc4random_uniform(83)\n"),
|
||||
Example("↓drand48()\n")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension LegacyRandomRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
private static let legacyRandomFunctions: Set<String> = [
|
||||
"arc4random",
|
||||
"arc4random_uniform",
|
||||
"drand48"
|
||||
]
|
||||
|
||||
override func visitPost(_ node: FunctionCallExprSyntax) {
|
||||
if let function = node.calledExpression.as(IdentifierExprSyntax.self)?.identifier.text,
|
||||
Self.legacyRandomFunctions.contains(function) {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,214 +0,0 @@
|
|||
import Foundation
|
||||
import SourceKittenFramework
|
||||
|
||||
struct NimbleOperatorRule: ConfigurationProviderRule, OptInRule, CorrectableRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "nimble_operator",
|
||||
name: "Nimble Operator",
|
||||
description: "Prefer Nimble operator overloads over free matcher functions",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("expect(seagull.squawk) != \"Hi!\"\n"),
|
||||
Example("expect(\"Hi!\") == \"Hi!\"\n"),
|
||||
Example("expect(10) > 2\n"),
|
||||
Example("expect(10) >= 10\n"),
|
||||
Example("expect(10) < 11\n"),
|
||||
Example("expect(10) <= 10\n"),
|
||||
Example("expect(x) === x"),
|
||||
Example("expect(10) == 10"),
|
||||
Example("expect(success) == true"),
|
||||
Example("expect(value) == nil"),
|
||||
Example("expect(value) != nil"),
|
||||
Example("expect(object.asyncFunction()).toEventually(equal(1))\n"),
|
||||
Example("expect(actual).to(haveCount(expected))\n"),
|
||||
Example("""
|
||||
foo.method {
|
||||
expect(value).to(equal(expectedValue), description: "Failed")
|
||||
return Bar(value: ())
|
||||
}
|
||||
""")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("↓expect(seagull.squawk).toNot(equal(\"Hi\"))\n"),
|
||||
Example("↓expect(12).toNot(equal(10))\n"),
|
||||
Example("↓expect(10).to(equal(10))\n"),
|
||||
Example("↓expect(10, line: 1).to(equal(10))\n"),
|
||||
Example("↓expect(10).to(beGreaterThan(8))\n"),
|
||||
Example("↓expect(10).to(beGreaterThanOrEqualTo(10))\n"),
|
||||
Example("↓expect(10).to(beLessThan(11))\n"),
|
||||
Example("↓expect(10).to(beLessThanOrEqualTo(10))\n"),
|
||||
Example("↓expect(x).to(beIdenticalTo(x))\n"),
|
||||
Example("↓expect(success).to(beTrue())\n"),
|
||||
Example("↓expect(success).to(beFalse())\n"),
|
||||
Example("↓expect(value).to(beNil())\n"),
|
||||
Example("↓expect(value).toNot(beNil())\n"),
|
||||
Example("expect(10) > 2\n ↓expect(10).to(beGreaterThan(2))\n")
|
||||
],
|
||||
corrections: [
|
||||
Example("↓expect(seagull.squawk).toNot(equal(\"Hi\"))\n"): Example("expect(seagull.squawk) != \"Hi\"\n"),
|
||||
Example("↓expect(\"Hi!\").to(equal(\"Hi!\"))\n"): Example("expect(\"Hi!\") == \"Hi!\"\n"),
|
||||
Example("↓expect(12).toNot(equal(10))\n"): Example("expect(12) != 10\n"),
|
||||
Example("↓expect(value1).to(equal(value2))\n"): Example("expect(value1) == value2\n"),
|
||||
Example("↓expect( value1 ).to(equal( value2.foo))\n"): Example("expect(value1) == value2.foo\n"),
|
||||
Example("↓expect(value1).to(equal(10))\n"): Example("expect(value1) == 10\n"),
|
||||
Example("↓expect(10).to(beGreaterThan(8))\n"): Example("expect(10) > 8\n"),
|
||||
Example("↓expect(10).to(beGreaterThanOrEqualTo(10))\n"): Example("expect(10) >= 10\n"),
|
||||
Example("↓expect(10).to(beLessThan(11))\n"): Example("expect(10) < 11\n"),
|
||||
Example("↓expect(10).to(beLessThanOrEqualTo(10))\n"): Example("expect(10) <= 10\n"),
|
||||
Example("↓expect(x).to(beIdenticalTo(x))\n"): Example("expect(x) === x\n"),
|
||||
Example("↓expect(success).to(beTrue())\n"): Example("expect(success) == true\n"),
|
||||
Example("↓expect(success).to(beFalse())\n"): Example("expect(success) == false\n"),
|
||||
Example("↓expect(success).toNot(beFalse())\n"): Example("expect(success) != false\n"),
|
||||
Example("↓expect(success).toNot(beTrue())\n"): Example("expect(success) != true\n"),
|
||||
Example("↓expect(value).to(beNil())\n"): Example("expect(value) == nil\n"),
|
||||
Example("↓expect(value).toNot(beNil())\n"): Example("expect(value) != nil\n"),
|
||||
Example("expect(10) > 2\n ↓expect(10).to(beGreaterThan(2))\n"): Example("expect(10) > 2\n expect(10) > 2\n")
|
||||
]
|
||||
)
|
||||
|
||||
fileprivate typealias MatcherFunction = String
|
||||
|
||||
fileprivate enum Arity {
|
||||
case nullary(analogueValue: String)
|
||||
case withArguments
|
||||
|
||||
var hasArguments: Bool {
|
||||
guard case .withArguments = self else {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate typealias PredicateDescription = (to: String?, toNot: String?, arity: Arity)
|
||||
|
||||
private let predicatesMapping: [MatcherFunction: PredicateDescription] = [
|
||||
"equal": (to: "==", toNot: "!=", .withArguments),
|
||||
"beIdenticalTo": (to: "===", toNot: "!==", .withArguments),
|
||||
"beGreaterThan": (to: ">", toNot: nil, .withArguments),
|
||||
"beGreaterThanOrEqualTo": (to: ">=", toNot: nil, .withArguments),
|
||||
"beLessThan": (to: "<", toNot: nil, .withArguments),
|
||||
"beLessThanOrEqualTo": (to: "<=", toNot: nil, .withArguments),
|
||||
"beTrue": (to: "==", toNot: "!=", .nullary(analogueValue: "true")),
|
||||
"beFalse": (to: "==", toNot: "!=", .nullary(analogueValue: "false")),
|
||||
"beNil": (to: "==", toNot: "!=", .nullary(analogueValue: "nil"))
|
||||
]
|
||||
|
||||
func validate(file: SwiftLintFile) -> [StyleViolation] {
|
||||
let matches = violationMatchesRanges(in: file)
|
||||
return matches.map {
|
||||
StyleViolation(ruleDescription: Self.description,
|
||||
severity: configuration.severity,
|
||||
location: Location(file: file, characterOffset: $0.location))
|
||||
}
|
||||
}
|
||||
|
||||
private func violationMatchesRanges(in file: SwiftLintFile) -> [NSRange] {
|
||||
let contents = file.stringView
|
||||
return rawRegexResults(in: file).filter { range in
|
||||
guard let byteRange = contents.NSRangeToByteRange(start: range.location, length: range.length) else {
|
||||
return false
|
||||
}
|
||||
|
||||
return file.structureDictionary.structures(forByteOffset: byteRange.upperBound - 1)
|
||||
.contains(where: { dict -> Bool in
|
||||
return dict.expressionKind == .call && (dict.name ?? "").starts(with: "expect")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private func rawRegexResults(in file: SwiftLintFile) -> [NSRange] {
|
||||
let operandPattern = "(.(?!expect\\())+?"
|
||||
|
||||
let operatorsPattern = "(" + predicatesMapping.map { name, predicateDescription in
|
||||
let argumentsPattern = predicateDescription.arity.hasArguments
|
||||
? operandPattern
|
||||
: ""
|
||||
|
||||
return "\(name)\\(\(argumentsPattern)\\)"
|
||||
}.joined(separator: "|") + ")"
|
||||
|
||||
let pattern = "expect\\(\(operandPattern)\\)\\.to(Not)?\\(\(operatorsPattern)\\)"
|
||||
let excludingKinds = SyntaxKind.commentKinds
|
||||
|
||||
return file.match(pattern: pattern)
|
||||
.filter { _, kinds in
|
||||
excludingKinds.isDisjoint(with: kinds) && kinds.first == .identifier
|
||||
}
|
||||
.map { $0.0 }
|
||||
}
|
||||
|
||||
func correct(file: SwiftLintFile) -> [Correction] {
|
||||
let matches = violationMatchesRanges(in: file)
|
||||
.filter { file.ruleEnabled(violatingRanges: [$0], for: self).isNotEmpty }
|
||||
guard matches.isNotEmpty else { return [] }
|
||||
|
||||
let description = Self.description
|
||||
var corrections: [Correction] = []
|
||||
var contents = file.contents
|
||||
|
||||
for range in matches.sorted(by: { $0.location > $1.location }) {
|
||||
for (functionName, operatorCorrections) in predicatesMapping {
|
||||
guard let correctedString = contents.replace(function: functionName,
|
||||
with: operatorCorrections,
|
||||
in: range)
|
||||
else {
|
||||
continue
|
||||
}
|
||||
|
||||
contents = correctedString
|
||||
let correction = Correction(ruleDescription: description,
|
||||
location: Location(file: file, characterOffset: range.location))
|
||||
corrections.insert(correction, at: 0)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
file.write(contents)
|
||||
return corrections
|
||||
}
|
||||
}
|
||||
|
||||
private extension String {
|
||||
/// Returns corrected string if the correction is possible, otherwise returns nil.
|
||||
///
|
||||
/// - parameter name: The function name to replace.
|
||||
/// - parameter predicateDescription: The Nimble operators to replace functions with.
|
||||
/// - parameter range: The range in which replacements should be applied.
|
||||
///
|
||||
/// - returns: The corrected string if the correction is possible, otherwise returns nil.
|
||||
func replace(function name: NimbleOperatorRule.MatcherFunction,
|
||||
with predicateDescription: NimbleOperatorRule.PredicateDescription,
|
||||
in range: NSRange) -> String? {
|
||||
let anything = "\\s*(.*?)\\s*"
|
||||
|
||||
let toPattern = ("expect\\(\(anything)\\)\\.to\\(\(name)\\(\(anything)\\)\\)", predicateDescription.to)
|
||||
let toNotPattern = ("expect\\(\(anything)\\)\\.toNot\\(\(name)\\(\(anything)\\)\\)", predicateDescription.toNot)
|
||||
|
||||
for case let (pattern, operatorString?) in [toPattern, toNotPattern] {
|
||||
let expression = regex(pattern)
|
||||
guard expression.matches(in: self, options: [], range: range).isNotEmpty else {
|
||||
continue
|
||||
}
|
||||
|
||||
let valueReplacementPattern: String
|
||||
switch predicateDescription.arity {
|
||||
case .nullary(let analogueValue):
|
||||
valueReplacementPattern = analogueValue
|
||||
case .withArguments:
|
||||
valueReplacementPattern = "$2"
|
||||
}
|
||||
|
||||
let replacementPattern = "expect($1) \(operatorString) \(valueReplacementPattern)"
|
||||
|
||||
return expression.stringByReplacingMatches(in: self,
|
||||
options: [],
|
||||
range: range,
|
||||
withTemplate: replacementPattern)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
|
@ -1,39 +0,0 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct NoExtensionAccessModifierRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.error)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "no_extension_access_modifier",
|
||||
name: "No Extension Access Modifier",
|
||||
description: "Prefer not to use extension access modifiers",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("extension String {}"),
|
||||
Example("\n\n extension String {}")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("↓private extension String {}"),
|
||||
Example("↓public \n extension String {}"),
|
||||
Example("↓open extension String {}"),
|
||||
Example("↓internal extension String {}"),
|
||||
Example("↓fileprivate extension String {}")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension NoExtensionAccessModifierRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override var skippableDeclarations: [DeclSyntaxProtocol.Type] { .all }
|
||||
|
||||
override func visitPost(_ node: ExtensionDeclSyntax) {
|
||||
if let modifiers = node.modifiers, modifiers.isNotEmpty {
|
||||
violations.append(modifiers.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue