Giter VIP home page Giter VIP logo

swiftlint's Introduction

SwiftLint

A tool to enforce Swift style and conventions, loosely based on the now archived GitHub Swift Style Guide. SwiftLint enforces the style guide rules that are generally accepted by the Swift community. These rules are well described in popular style guides like Kodeco's Swift Style Guide.

SwiftLint hooks into Clang and SourceKit to use the AST representation of your source files for more accurate results.

Build Status codecov.io

This project adheres to the Contributor Covenant Code of Conduct. By participating, you are expected to uphold this code. Please report unacceptable behavior to [email protected].

Language Switch: 中文, 한국어.

Installation

Replace <version> with the desired minimum version.

.package(url: "https://github.com/realm/SwiftLint.git", from: "<version>")

SwiftLint can be used as a command plugin or a build tool plugin.

Using Homebrew:

brew install swiftlint

Using CocoaPods:

Simply add the following line to your Podfile:

pod 'SwiftLint'

This will download the SwiftLint binaries and dependencies in Pods/ during your next pod install execution and will allow you to invoke it via ${PODS_ROOT}/SwiftLint/swiftlint in your Script Build Phases.

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 library distribution to the Pods/ directory, so checking in this directory to SCM such as git is discouraged.

Using Mint:

$ mint install realm/SwiftLint

Using a pre-built package:

You can also install SwiftLint by downloading SwiftLint.pkg from the latest GitHub release and running it.

Installing from source:

You can also build and install from source by cloning this project and running make install (Xcode 15.0 or later).

Using Bazel

Put this in your MODULE.bazel:

bazel_dep(name = "swiftlint", version = "0.52.4", repo_name = "SwiftLint")

Or put this in your WORKSPACE:

WORKSPACE
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

http_archive(
    name = "build_bazel_rules_apple",
    sha256 = "390841dd5f8a85fc25776684f4793d56e21b098dfd7243cd145b9831e6ef8be6",
    url = "https://github.com/bazelbuild/rules_apple/releases/download/2.4.1/rules_apple.2.4.1.tar.gz",
)

load(
    "@build_bazel_rules_apple//apple:repositories.bzl",
    "apple_rules_dependencies",
)

apple_rules_dependencies()

load(
    "@build_bazel_rules_swift//swift:repositories.bzl",
    "swift_rules_dependencies",
)

swift_rules_dependencies()

load(
    "@build_bazel_rules_swift//swift:extras.bzl",
    "swift_rules_extra_dependencies",
)

swift_rules_extra_dependencies()

http_archive(
    name = "SwiftLint",
    sha256 = "c6ea58b9c72082cdc1ada4a2d48273ecc355896ed72204cedcc586b6ccb8aca6",
    url = "https://github.com/realm/SwiftLint/releases/download/0.52.4/bazel.tar.gz",
)

load("@SwiftLint//bazel:repos.bzl", "swiftlint_repos")

swiftlint_repos()

load("@SwiftLint//bazel:deps.bzl", "swiftlint_deps")

swiftlint_deps()

Then you can run SwiftLint in the current directory with this command:

bazel run -c opt @SwiftLint//:swiftlint

Usage

Presentation

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:

Presentation

Xcode Run Script Build Phase

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:

Xcode 15 made a significant change by setting the default value of the ENABLE_USER_SCRIPT_SANDBOXING Build Setting from NO to YES. As a result, SwiftLint encounters an error related to missing file permissions, which typically manifests as follows: error: Sandbox: swiftlint(19427) deny(1) file-read-data.

To resolve this issue, it is necessary to manually set the ENABLE_USER_SCRIPT_SANDBOXING setting to NO for the specific target that SwiftLint is being configured for.

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

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

or you can create a symbolic link in /usr/local/bin pointing to the actual binary:

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:

"${PODS_ROOT}/SwiftLint/swiftlint"

Swift Package Command Plugin

The command plugin enables running SwiftLint from the command line as follows:

swift package plugin swiftlint

Swift Package Build Tool Plugins

SwiftLint can be used as a build tool plugin for both Xcode projects and Swift Package projects.

The build tool plugin determines the SwiftLint working directory by locating the topmost config file within the package/project directory. If a config file is not found therein, the package/project directory is used as the working directory.

The plugin throws an error when it is unable to resolve the SwiftLint working directory. For example, this will occur in Xcode projects where the target's Swift files are not located within the project directory.

To maximize compatibility with the plugin, avoid project structures that require the use of the --config option.

Unexpected Project Structures

Project structures where SwiftLint's configuration file is located outside of the package/project directory are not directly supported by the build tool plugin. This is because it isn't possible to pass arguments to build tool plugins (e.g., passing the config file path).

If your project structure doesn't work directly with the build tool plugin, please consider one of the following options:

  • To use a config file located outside the package/project directory, a config file may be added to that directory specifying a parent config path to the other config file, e.g., parent_config: path/to/.swiftlint.yml.
  • You can also consider the use of a Run Script Build Phase in place of the build tool plugin.

Xcode Projects

You can integrate SwiftLint as an Xcode Build Tool Plugin if you're working with a project in Xcode.

Add SwiftLint as a package dependency to your project without linking any of the products.

Select the target you want to add linting to and open the Build Phases inspector. Open Run Build Tool Plugins and select the + button. Select SwiftLintBuildToolPlugin from the list and add it to the project.

For unattended use (e.g. on CI), you can disable the package and macro validation dialog by

  • individually passing -skipPackagePluginValidation and -skipMacroValidation to xcodebuild or
  • globally setting defaults write com.apple.dt.Xcode IDESkipPackagePluginFingerprintValidatation -bool YES and defaults write com.apple.dt.Xcode IDESkipMacroFingerprintValidation -bool YES for that user.

Note: This implicitly trusts all Xcode package plugins and macros in packages and bypasses Xcode's package validation dialogs, which has security implications.

Swift Package Projects

You can integrate SwiftLint as a Swift Package Manager Plugin 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.

.target(
    ...
    plugins: [.plugin(name: "SwiftLintBuildToolPlugin", package: "SwiftLint")]
),

Visual Studio Code

To integrate SwiftLint with vscode, install the vscode-swiftlint extension from the marketplace.

fastlane

You can use the official swiftlint fastlane action to run SwiftLint as part of your fastlane process.

swiftlint(
    mode: :lint,                            # SwiftLint mode: :lint (default) or :autocorrect
    executable: "Pods/SwiftLint/swiftlint", # The SwiftLint binary path (optional). Important if you've installed it via CocoaPods
    path: "/path/to/lint",                  # Specify path to lint (optional)
    output_file: "swiftlint.result.json",   # The path of the output file (optional)
    reporter: "json",                       # The custom reporter to use (optional)
    config_file: ".swiftlint-ci.yml",       # The path of the configuration file (optional)
    files: [                                # List of files to process (optional)
        "AppDelegate.swift",
        "path/to/project/Model.swift"
    ],
    ignore_exit_status: true,               # Allow fastlane to continue even if SwiftLint returns a non-zero exit status (Default: false)
    quiet: true,                            # Don't print status logs like 'Linting ' & 'Done linting' (Default: false)
    strict: true                            # Fail on warnings? (Default: false)
)

Docker

swiftlint is also available as a Docker image using Ubuntu. So just the first time you need to pull the docker image using the next command:

docker pull ghcr.io/realm/swiftlint:latest

Then following times, you just run swiftlint inside of the docker like:

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:

$ 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.

Command Line

$ swiftlint help
OVERVIEW: A tool to enforce Swift style and conventions.

USAGE: swiftlint <subcommand>

OPTIONS:
  --version               Show the version.
  -h, --help              Show help information.

SUBCOMMANDS:
  analyze                 Run analysis rules
  docs                    Open SwiftLint documentation website in the default web browser
  generate-docs           Generates markdown documentation for all rules
  lint (default)          Print lint warnings and errors
  reporters               Display the list of reporters and their identifiers
  rules                   Display the list of rules and their identifiers
  version                 Display the current version of SwiftLint

  See 'swiftlint help <subcommand>' for detailed help.

Run swiftlint in the directory containing the Swift files to lint. Directories will be searched recursively.

To specify a list of files when using lint or analyze (like the list of files modified by Xcode specified by the 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}.

These are same environment variables set for input files to custom Xcode script phases.

Working With Multiple Swift Versions

SwiftLint hooks into SourceKit so it continues working even as Swift evolves!

This also keeps SwiftLint lean, as it doesn't need to ship with a full Swift compiler, it just communicates with the official one you already have installed on your machine.

You should always run SwiftLint with the same toolchain you use to compile your code.

You may want to override SwiftLint's default Swift toolchain if you have multiple toolchains or Xcodes installed.

Here's the order in which SwiftLint determines which Swift toolchain to use:

  • $XCODE_DEFAULT_TOOLCHAIN_OVERRIDE
  • $TOOLCHAIN_DIR or $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 is expected to be found in the usr/lib/ subdirectory of the value passed in the paths above.

You may also set the TOOLCHAINS environment variable to the reverse-DNS notation that identifies a Swift toolchain version:

$ TOOLCHAINS=com.apple.dt.toolchain.Swift_2_3 swiftlint --fix

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 hook. Once installed, add this to the .pre-commit-config.yaml in the root of your repository:

repos:
  - repo: https://github.com/realm/SwiftLint
    rev: 0.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:

-   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!) continues to contribute more over time. Pull requests are encouraged.

You can find an updated list of rules and more information about them here.

You can also check Source/SwiftLintBuiltInRules/Rules directory to see their implementation.

Opt-In Rules

opt_in_rules are disabled by default (i.e., you have to explicitly enable them in your configuration file).

Guidelines on when to mark a rule as opt-in:

  • A rule that can have many false positives (e.g. empty_count)
  • A rule that is too slow
  • A rule that is not general consensus or is only useful in some cases (e.g. force_unwrapping)

Disable rules in code

Rules can be disabled with a comment inside a source file with the following format:

// swiftlint:disable <rule1> [<rule2> <rule3>...]

The rules will be disabled until the end of the file or until the linter sees a matching enable comment:

// swiftlint:enable <rule1> [<rule2> <rule3>...]

For example:

// swiftlint:disable colon
let noWarning :String = "" // No warning about colons immediately after variable names!
// swiftlint:enable colon
let hasWarning :String = "" // Warning generated about colons immediately after variable names

Including the all keyword will disable all rules until the linter sees a matching enable comment:

// swiftlint:disable all // swiftlint:enable all

For example:

// swiftlint:disable all
let noWarning :String = "" // No warning about colons immediately after variable names!
let i = "" // Also no warning about short identifier names
// swiftlint:enable all
let hasWarning :String = "" // Warning generated about colons immediately after variable names
let y = "" // Warning generated about short identifier names

It's also possible to modify a disable or enable command by appending :previous, :this or :next for only applying the command to the previous, this (current) or next line respectively.

For example:

// swiftlint:disable:next force_cast
let noWarning = NSNumber() as! Int
let hasWarning = NSNumber() as! Int
let noWarning2 = NSNumber() as! Int // swiftlint:disable:this force_cast
let noWarning3 = NSNumber() as! Int
// swiftlint:disable:previous force_cast

Run swiftlint rules to print a list of all available rules and their identifiers.

Configuration

Configure SwiftLint by adding a .swiftlint.yml file from the directory you'll run SwiftLint from. The following parameters can be configured:

Rule inclusion:

  • disabled_rules: Disable rules from the default enabled set.
  • opt_in_rules: Enable rules that are not part of the default set. The 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 and only_rules. The special all identifier can also be used here to enable all analyzer rules, except the ones listed in disabled_rules.
# By default, SwiftLint uses a set of sensible default rules you can adjust:
disabled_rules: # rule identifiers turned on by default to exclude from running
  - colon
  - comma
  - control_statement
opt_in_rules: # some rules are turned off by default, so you need to opt-in
  - empty_count # find all the available rules by running: `swiftlint rules`

# Alternatively, specify all rules explicitly by uncommenting this option:
# only_rules: # delete `disabled_rules` & `opt_in_rules` if using this
#   - empty_parameters
#   - vertical_whitespace

analyzer_rules: # rules run by `swiftlint analyze`
  - explicit_self

included: # case-sensitive paths to include during linting. `--path` is ignored if present
  - Sources
excluded: # case-sensitive paths to ignore during linting. Takes precedence over `included`
  - Carthage
  - Pods
  - Sources/ExcludedFolder
  - Sources/ExcludedFile.swift
  - Sources/*/ExcludedFile.swift # exclude files with a wildcard

# If true, SwiftLint will not fail if no lintable files are found.
allow_zero_lintable_files: false

# If true, SwiftLint will treat all warnings as errors.
strict: false

# configurable rules can be customized from this configuration file
# binary rules can set their severity level
force_cast: warning # implicitly
force_try:
  severity: warning # explicitly
# rules that have both warning and error levels, can set just the warning level
# implicitly
line_length: 110
# they can set both implicitly with an array
type_body_length:
  - 300 # warning
  - 400 # error
# or they can set both explicitly
file_length:
  warning: 500
  error: 1200
# naming rules can set warnings/errors for min_length and max_length
# additionally they can set excluded names
type_name:
  min_length: 4 # only warning
  max_length: # warning and error
    warning: 40
    error: 50
  excluded: iPhone # excluded via string
  allowed_symbols: ["_"] # these are allowed in type names
identifier_name:
  min_length: # only min_length
    error: 4 # only error
  excluded: # excluded via string array
    - id
    - URL
    - GlobalAPIKey
reporter: "xcode" # reporter type (xcode, json, csv, checkstyle, codeclimate, junit, html, emoji, sonarqube, markdown, github-actions-logging, summary)

You can also use environment variables in your configuration file, by using ${SOME_VARIABLE} in a string.

Defining Custom Rules

In addition to the rules that the main SwiftLint project ships with, SwiftLint can also run two types of custom rules that you can define yourself in your own projects:

1. Swift Custom Rules

These rules are written the same way as the Swift-based rules that ship with SwiftLint so they're fast, accurate, can leverage SwiftSyntax, can be unit tested, and more.

Using these requires building SwiftLint with Bazel as described in this video or its associated code in github.com/jpsim/swiftlint-bazel-example.

2. Regex Custom Rules

You can define custom regex-based rules in your configuration file using the following syntax:

custom_rules:
  pirates_beat_ninjas: # rule identifier
    included: 
      - ".*\\.swift" # regex that defines paths to include during linting. optional.
    excluded: 
      - ".*Test\\.swift" # regex that defines paths to exclude during linting. optional
    name: "Pirates Beat Ninjas" # rule name. optional.
    regex: "([nN]inja)" # matching pattern
    capture_group: 0 # number of regex capture group to highlight the rule violation at. optional.
    match_kinds: # SyntaxKinds to match. optional.
      - comment
      - identifier
    message: "Pirates are better than ninjas." # violation message. optional.
    severity: error # violation severity. optional.
  no_hiding_in_strings:
    regex: "([nN]inja)"
    match_kinds: string

This is what the output would look like:

It is important to note that the regular expression pattern is used with the flags s and m enabled, that is . matches newlines and ^/$ match the start and end of lines, respectively. If you do not want to have . match newlines, for example, the regex can be prepended by (?-s).

You can filter the matches by providing one or more match_kinds, which will reject matches that include syntax kinds that are not present in this list. Here are all the possible syntax kinds:

  • argument
  • attribute.builtin
  • attribute.id
  • buildconfig.id
  • buildconfig.keyword
  • comment
  • comment.mark
  • comment.url
  • doccomment
  • doccomment.field
  • identifier
  • keyword
  • number
  • objectliteral
  • parameter
  • placeholder
  • string
  • string_interpolation_anchor
  • typeidentifier

All syntax kinds used in a snippet of Swift code can be extracted asking SourceKitten. For example, sourcekitten syntax --text "struct S {}" delivers

  • source.lang.swift.syntaxtype.keyword for the struct keyword and
  • source.lang.swift.syntaxtype.identifier for its name S

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.

Auto-correct

SwiftLint can automatically correct certain violations. Files on disk are overwritten with a corrected version.

Please make sure to have backups of these files before running swiftlint --fix, otherwise important data may be lost.

Standard linting is disabled while correcting because of the high likelihood of violations (or their offsets) being incorrect after modifying a file while applying corrections.

Analyze

The swiftlint analyze command can lint Swift files using the full type-checked AST. The compiler log path containing the clean swiftc build command invocation (incremental builds will fail) must be passed to analyze via the --compiler-log-path flag. e.g. --compiler-log-path /path/to/xcodebuild.log

This can be obtained by

  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:

disabled_rules:
- force_cast

Project-Specific Configuration:

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:

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:

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.

About

SwiftLint is maintained and funded by Realm Inc. The names and logos for Realm are trademarks of Realm Inc.

We ❤️ open source software! See our other open source projects, read our blog, or say hi on twitter (@realm).

Our thanks to MacStadium for providing a Mac Mini to run our performance tests.

swiftlint's People

Contributors

ams-twelker avatar angelolloqui avatar blaisesarr avatar cfilipov avatar chriseidhof avatar daltonclaybrook avatar elliottwilliams avatar erichoracek avatar freak4pc avatar fredpi avatar github-actions[bot] avatar jaherhi avatar jamieedge avatar jeehut avatar jpsim avatar keith avatar marcelofabri avatar masters3d avatar mildm8nnered avatar mlwelles avatar norio-nomura avatar ornithocoder avatar paultaykalo avatar rakaramos avatar sammy-sc avatar scottrhoyt avatar sdggiesbrecht avatar simplydanny avatar uncommon avatar yhkaplan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swiftlint's Issues

Homebrew install "dyld: Library not loaded:" Error

$ brew install swiftlint
==> Downloading https://homebrew.bintray.com/bottles/swiftlint-0.1.0.yosemite.bottle.tar.gz

################################################################## 100.0%

==> Pouring swiftlint-0.1.0.yosemite.bottle.tar.gz
🍺 /usr/local/Cellar/swiftlint/0.1.0: 161 files, 36M
$ swiftlint
dyld: Library not loaded: @rpath/libclang.dylib
Referenced from: /usr/local/Cellar/swiftlint/0.1.0/Frameworks/SwiftLintFramework.framework/SwiftLintFramework
Reason: image not found
Trace/BPT trap: 5
$

Print nicer error messages on dynamic linking errors

brew install succeeded, but I get the following whenever attempting to invoke swiftlint

dyld: Symbol not found: __TWPCSo8NSObjectSs8Hashable
  Referenced from: /Library/Frameworks/LlamaKit.framework/Versions/A/LlamaKit
  Expected in: /usr/local/Cellar/swiftlint/0.1.0/bin/../Frameworks/SwiftLintFramework.framework/Versions/Current/Frameworks//libswiftFoundation.dylib
 in /Library/Frameworks/LlamaKit.framework/Versions/A/LlamaKit
[1]    25787 trace trap  swiftlint

Line length to 120

On a 27-inch display, you can comfortable fit two 120 wide files at 14pt with sidebars and all. On a 13" rMBP, you can fit one. I've had my guide set at 120 for years. Personally, I think 100 is overly narrow. Almost all of the warnings for one of my projects was length being over 100 but less 120.

I'm guessing there's a reason you picked 100 though. I'd love to know why!

I'm tempted to ask for a way to configure it, but I think one of the biggest benefits of this is we can all start doing things the same as a community.

Support Xcode Fix-Its

Not sure if you can provide fix its, but that would be super cool. For some rules (i.e. whitespace only on a line) it would be pretty easy to figure out what to change. Obviously for stuff like as! you shouldn't suggest one.

Can't build from source

I cloned this repo and, seeing Cartfile, ran carthage update. This is what I saw in workspace navigator once the command completed:

screen shot 2015-05-26 at 10 41 54

Needless to say, the build failed. Is there some other command I need to run in terminal?

Don't check cocoapods

Maybe make it optional by specifying it in the config file (#3), but it's probably a sensible default as well. Unless this already shouldn't be happening and I messed it up 😁

Add ability to Lint subregions of a file

A Linter should be able to create a sub-Linter when we enter a region of code that has comment modifiers applied to it (e.g. // swift-lint:enable-rule).

Suggested implementation hints: Linter takes a File as an initializer, we can create a File with a contents String. If a Linter does a pass over that string to find each sub-region it can map those sub-regions into a [Linter] and then flatMap styleViolations over the resultant [Linter].

Couldn't run by dyld error

I installed swiftlint via homebrew, but couldn't run swiftlint with this error.
Is any other steps required?

~ % swiftlint help                                                                                                                                               
dyld: Library not loaded: @rpath/libclang.dylib
  Referenced from: /usr/local/Cellar/swiftlint/0.1.0/Frameworks/SwiftLintFramework.framework/SwiftLintFramework
  Reason: image not found
zsh: trace trap  swiftlint help

FYI : My environment is below

OS : OS X 10.10.3
Xcode : v6.3.1 (6D1002)
Shell : zsh 5.0.7 (installed via homebrew)
Location of swiftlint : /usr/local/bin/swiftlint

Can't run the 'sourcekitten' scheme from Xcode

This is because @executable/../Frameworks needs to be added to the runtime search paths for the application to find the Swift libraries, but doing so interferes with the Makefile's install_name_tool steps to re-add that path. A simple solution would be to make the Makefile remove that path before re-adding it.

TrailingNewlineRule.swift doesn't seem to work

I've tried adding multiple ending new lines and having 0 extra new lines at the end of my file, but I never get a warning for this. I know the swiftlint library is active though, because I'm getting other warnings.

Dynamic Linking Error

Installing fresh using Homebrew, the .pkg download and compiling from source all leads to the same linking error message:

dyld: Library not loaded: @rpath/libclang.dylib
  Referenced from: /Library/Frameworks/SwiftLintFramework.framework/SwiftLintFramework
  Reason: image not found
[1]    49802 trace trap  swiftlint

Tell me if there is anything I can do to help.

Status code is 0 when high-severity errors found.

In the example file ok.swift, containing:

import UIKit
class Foo {
    var _badVariable = 0
}

The bash command:

swiftlint lint
echo "Return Status = $?"

Returns

Finding Swift files in current directory...
Linting 'ok.swift' (1/1)
/tmp/ok.swift:3: error: Name Format Violation (High Severity): Variable name should only contain alphanumeric characters: '_badVariable'
Done linting! Found 1 violation in 1 file.
Return Status = 0

The return status of a shell script which generates error messages should not be 0. Xcode gives the following message at the end of the build process:

Command /bin/sh emitted errors but did not return a nonzero exit code to indicate failure

Currently the swiftlint command-line application only returns a non-zero exit code when swiftlint itself had errors, not when it discovers style violations in the source files it looks at. Please can you change it so that it returns a non-zero exit status when it finds style violations?

Rule instances only have static properties/methods

Since all functions/properties on Rule instances are static, we have to validate each rule against the file then remove irrelevant results.

Would it be better to construct an array of Rules, filter that, then call map on the resulting subarray?

Implementations of ASTRule are quite repetitive

I'm not sure what an appropriate solution to this would be but ASTRule implementations have a fair bit of code overlap.

  func validateFile(file: File) 

just calls

  func validateFile(file: File, dictionary: XPCDictionary)

which just calls

  func validateFile(file:File, kind: SwiftDeclarationKind, dictionary: XPCDictionary)

repeatedly for some substructures.

Support configuration file

Something like a .swiftlint.yml or similar that could be used to override rule parameters or turn off certain rules globally. See #1.

Ability to mark something as okay?

In X, I have the following code:

extension NSImage {
        public var CGImage: CGImageRef! {
            return CGImageForProposedRect(nil, context: nil, hints: nil)?.takeUnretainedValue()
        }
}

This now produces an error because the name starts with a capital letter. I definitely want this to be capital here so it matches iOS (that's the point of this extension). Is there a way to mark this as okay?

Remove StyleViolationType

StyleViolationType seems a bit redundant with the identifier of each Rule – we could have StyleViolations instead have a copy of the Rule they violate. That would also simplify a stack based approach to #4.

Remove typealias on Rule

It's not terribly useful at the moment anyway, and it's causing problems due to being unable to constrain over a type using Rule.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.