• Stars
    star
    2,261
  • Rank 19,504 (Top 0.4 %)
  • Language
    Swift
  • License
    Apache License 2.0
  • Created almost 5 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Formatting technology for Swift source code

swift-format

swift-format provides the formatting technology for SourceKit-LSP and the building blocks for doing code formatting transformations.

This package can be used as a command line tool or linked into other applications as a Swift Package Manager dependency and invoked via an API.

NOTE: No default Swift code style guidelines have yet been proposed. The style that is currently applied by swift-format is just one possibility, and the code is provided so that it can be tested on real-world code and experiments can be made by modifying it.

Matching swift-format to Your Swift Version

Swift 5.8 and later

As of Swift 5.8, swift-format depends on the version of SwiftSyntax whose parser has been rewritten in Swift and no longer has dependencies on libraries in the Swift toolchain.

This change allows swift-format to be built, developed, and run using any version of Swift that can compile it, decoupling it from the version that supported a particular syntax. However, earlier versions of swift-format will still not be able to recognize new syntax added in later versions of the language and parser.

Note also that the version numbering scheme has changed to match SwiftSyntax; the 5.8 release of swift-format is 508.0.0, not 0.50800.0.

Swift 5.7 and earlier

swift-format versions 0.50700.0 and earlier depend on versions of SwiftSyntax that used a standalone parsing library distributed as part of the Swift toolchain. When using these versions, you should check out and build swift-format from the release tag or branch that is compatible with the version of Swift you are using.

The major and minor version components of swift-format and SwiftSyntax must be the sameβ€”this is expressed in the SwiftSyntax dependency in Package.swiftβ€”and those version components must match the Swift toolchain that is installed and used to build and run the formatter:

Xcode Release Swift Version swift-format Branch / Tags
– Swift at main main
Xcode 14.0 Swift 5.7 release/5.7 / 0.50700.x
Xcode 13.3 Swift 5.6 release/5.6 / 0.50600.x
Xcode 13.0–13.2 Swift 5.5 swift-5.5-branch / 0.50500.x
Xcode 12.5 Swift 5.4 swift-5.4-branch / 0.50400.x
Xcode 12.0–12.4 Swift 5.3 swift-5.3-branch / 0.50300.x
Xcode 11.4–11.7 Swift 5.2 swift-5.2-branch / 0.50200.x
Xcode 11.0–11.3 Swift 5.1 swift-5.1-branch

For example, if you are using Xcode 13.3 (Swift 5.6), you will need swift-format 0.50600.0.

Getting swift-format

If you are mainly interested in using swift-format (rather than developing it), then you can get swift-format either via Homebrew or by checking out the source and building it.

Installing via Homebrew

Run brew install swift-format to install the latest version.

Building from source

Install swift-format using the following commands:

VERSION=510.1.0  # replace this with the version you need
git clone https://github.com/apple/swift-format.git
cd swift-format
git checkout "tags/$VERSION"
swift build -c release

Note that the git checkout command above will leave the repository in a "detached HEAD" state. This is fine if building and running the tool is all you want to do.

Once the build has finished, the swift-format executable will be located at .build/release/swift-format.

To test that the formatter was built successfully and is compatible with your Swift toolchain, you can also run the following command:

swift test --parallel

We recommend using the --parallel flag to speed up the test run since there are a large number of tests.

Command Line Usage

The general invocation syntax for swift-format is as follows:

swift-format [SUBCOMMAND] [OPTIONS...] [FILES...]

The tool supports a number of subcommands, each of which has its own options and are described below. Descriptions of the subcommands that are available can also be obtained by running swift-format --help, and the description of a specific subcommand can be obtained by using the --help flag after the subcommand name; for example, swift-format lint --help.

Formatting

swift-format [format] [OPTIONS...] [FILES...]

The format subcommand formats one or more Swift source files (or source code from standard input if no file paths are given on the command line). Writing out the format subcommand is optional; it is the default behavior if no other subcommand is given.

This subcommand supports all of the common lint and format options, as well as the formatting-only options below:

  • -i/--in-place: Overwrites the input files when formatting instead of printing the results to standard output. No backup of the original file is made before it is overwritten.

Linting

swift-format lint [OPTIONS...] [FILES...]

The lint subcommand checks one or more Swift source files (or source code from standard input if no file paths are given on the command line) for style violations and prints diagnostics to standard error for any violations that are detected.

This subcommand supports all of the common lint and format options, as well as the linting-only options below:

  • -s/--strict: If this option is specified, lint warnings will cause the tool to exit with a non-zero exit code (failure). By default, lint warnings do not prevent a successful exit; only fatal errors (for example, trying to lint a file that does not exist) cause the tool to exit unsuccessfully.

Options Supported by Formatting and Linting

The following options are supported by both the format and lint subcommands:

  • --assume-filename <path>: The file path that should be used in diagnostics when linting or formatting from standard input. If this option is not provided, then <stdin> will be used as the filename printed in diagnostics.

  • --color-diagnostics/--no-color-diagnostics: By default, swift-format will print diagnostics in color if standard error is connected to a terminal and without color otherwise (for example, if standard error is being redirected to a file). These flags can be used to force colors on or off respectively, regardless of whether the output is going to a terminal.

  • --configuration <file>: The path to a JSON file that contains configurable settings for swift-format. If omitted, a default configuration is use (which can be seen by running swift-format dump-configuration).

  • --ignore-unparsable-files: If this option is specified and a source file contains syntax errors or can otherwise not be parsed successfully by the Swift syntax parser, it will be ignored (no diagnostics will be emitted and it will not be formatted). Without this option, an error will be emitted for any unparsable files.

  • -p/--parallel: Process files in parallel, simultaneously across multiple cores.

  • -r/--recursive: If specified, then the tool will process .swift source files in any directories listed on the command line and their descendants. Without this flag, it is an error to list a directory on the command line.

Viewing the Default Configuration

swift-format dump-configuration

The dump-configuration subcommand dumps the default configuration in JSON format to standard output. This can be used to simplify generating a custom configuration, by redirecting it to a file and editing it.

Configuring the Command Line Tool

For any source file being checked or formatted, swift-format looks for a JSON-formatted file named .swift-format in the same directory. If one is found, then that file is loaded to determine the tool's configuration. If the file is not found, then it looks in the parent directory, and so on.

If no configuration file is found, a default configuration is used. The settings in the default configuration can be viewed by running swift-format dump-configuration, which will dump it to standard output.

If the --configuration <file> option is passed to swift-format, then that configuration will be used unconditionally and the file system will not be searched.

See Documentation/Configuration.md for a description of the configuration file format and the settings that are available.

Miscellaneous

Running swift-format -v or swift-format --version will print version information about swift-format version and then exit.

API Usage

swift-format can be easily integrated into other tools written in Swift. Instead of invoking the formatter by spawning a subprocess, users can depend on swift-format as a Swift Package Manager dependency and import the SwiftFormat module, which contains the entry points into the formatter's diagnostic and correction behavior.

Formatting behavior is provided by the SwiftFormatter class and linting behavior is provided by the SwiftLinter class. These APIs can be passed either a Swift source file URL or a Syntax node representing a SwiftSyntax syntax tree. The latter capability is particularly useful for writing code generators, since it significantly reduces the amount of trivia that the generator needs to be concerned about adding to the syntax nodes it creates. Instead, it can pass the in-memory syntax tree to the SwiftFormat API and receive perfectly formatted code as output.

Please see the documentation in the SwiftFormatter and SwiftLinter classes for more information about their usage.

Checking Out the Source Code for Development

The main branch is used for development. Pull requests should be created to merge into the main branch; changes that are low-risk and compatible with the latest release branch may be cherry-picked into that branch after they have been merged into main.

If you are interested in developing swift-format, there is additional documentation about that here.

More Repositories

1

swift

The Swift Programming Language
C++
65,899
star
2

ml-stable-diffusion

Stable Diffusion with Core ML on Apple Silicon
Python
16,002
star
3

swift-evolution

This maintains proposals for changes and user-visible enhancements to the Swift Programming Language.
Markdown
15,013
star
4

foundationdb

FoundationDB - the open source, distributed, transactional key-value store
C++
13,947
star
5

turicreate

Turi Create simplifies the development of custom machine learning models.
C++
11,153
star
6

darwin-xnu

The Darwin Kernel (mirror). This repository is a pure mirror and contributions are currently not accepted via pull-requests, please submit your contributions via https://developer.apple.com/bug-reporting/
C
10,558
star
7

swift-package-manager

The Package Manager for the Swift Programming Language
Swift
9,592
star
8

ml-ferret

Python
7,576
star
9

swift-nio

Event-driven network application framework for high performance protocol servers & clients, non-blocking.
Swift
7,274
star
10

swift-algorithms

Commonly used sequence and collection algorithms for Swift
Swift
5,622
star
11

swift-corelibs-foundation

The Foundation Project, providing core utilities, internationalization, and OS independence
Swift
5,189
star
12

swift-protobuf

Plugin and runtime library for using protobuf with Swift
Swift
4,446
star
13

password-manager-resources

A place for creators and users of password managers to collaborate on resources to make password management better.
JavaScript
4,010
star
14

coremltools

Core ML tools contain supporting tools for Core ML model conversion, editing, and validation.
Python
3,974
star
15

ml-mgie

Python
3,682
star
16

tensorflow_macos

TensorFlow for macOS 11.0+ accelerated using Apple's ML Compute framework.
Shell
3,643
star
17

swift-collections

Commonly used data structures for Swift
Swift
3,434
star
18

pkl

A configuration as code language with rich validation and tooling.
Java
3,360
star
19

swift-argument-parser

Straightforward, type-safe argument parsing for Swift
Swift
3,163
star
20

sourcekit-lsp

Language Server Protocol implementation for Swift and C-based languages
Swift
3,110
star
21

swift-log

A Logging API for Swift
Swift
2,931
star
22

swift-syntax

A set of Swift libraries for parsing, inspecting, generating, and transforming Swift source code.
Swift
2,887
star
23

swift-async-algorithms

Async Algorithms for Swift
Swift
2,695
star
24

swift-markdown

A Swift package for parsing, building, editing, and analyzing Markdown documents.
Swift
2,586
star
25

HomeKitADK

C
2,456
star
26

ml-ane-transformers

Reference implementation of the Transformer architecture optimized for Apple Neural Engine (ANE)
Python
2,431
star
27

swift-corelibs-libdispatch

The libdispatch Project, (a.k.a. Grand Central Dispatch), for concurrency on multicore hardware
C
2,420
star
28

homebrew-apple

Ruby
2,227
star
29

swift-foundation

The Foundation project
Swift
2,088
star
30

cups

Apple CUPS Sources
C
1,828
star
31

sample-food-truck

SwiftUI sample code from WWDC22
Swift
1,695
star
32

ml-fastvit

This repository contains the official implementation of the research paper, "FastViT: A Fast Hybrid Vision Transformer using Structural Reparameterization" ICCV 2023
Python
1,693
star
33

ml-cvnets

CVNets: A library for training computer vision networks
Python
1,664
star
34

swift-book

The Swift Programming Language book
Markdown
1,616
star
35

swift-numerics

Advanced mathematical types and functions for Swift
Swift
1,602
star
36

ml-hypersim

Hypersim: A Photorealistic Synthetic Dataset for Holistic Indoor Scene Understanding
Python
1,495
star
37

swift-crypto

Open-source implementation of a substantial portion of the API of Apple CryptoKit suitable for use on Linux platforms.
C
1,400
star
38

swift-docker

Docker Official Image packaging for Swift
Dockerfile
1,331
star
39

ml-neuman

Official repository of NeuMan: Neural Human Radiance Field from a Single Video (ECCV 2022)
Python
1,233
star
40

swift-openapi-generator

Generate Swift client and server code from an OpenAPI document.
Swift
1,142
star
41

swift-system

Low-level system calls and types for Swift
Swift
1,137
star
42

swift-corelibs-xctest

The XCTest Project, A Swift core library for providing unit test support
Swift
1,120
star
43

swift-docc

Documentation compiler that produces rich API reference documentation and interactive tutorials for your Swift framework or package.
Swift
1,093
star
44

swift-llbuild

A low-level build system, used by Xcode and the Swift Package Manager
C++
1,067
star
45

swift-atomics

Low-level atomic operations for Swift
Swift
1,004
star
46

swift-testing

Swift
981
star
47

servicetalk

A networking framework that evolves with your application
Java
881
star
48

swift-http-types

Version-independent HTTP currency types for Swift
Swift
815
star
49

swift-llvm

LLVM
815
star
50

swift-driver

Swift compiler driver reimplementation in Swift
Swift
764
star
51

swift-protobuf-plugin

Moved to apple/swift-protobuf
757
star
52

swift-lldb

This is the version of LLDB that supports the Swift programming language & REPL.
C++
673
star
53

swift-clang

C++
673
star
54

unityplugins

C#
645
star
55

ml-mobileone

This repository contains the official implementation of the research paper, "An Improved One millisecond Mobile Backbone".
Swift
641
star
56

ml-gaudi

602
star
57

ml-aim

This repository provides the code and model checkpoints of the research paper: Scalable Pre-training of Large Autoregressive Image Models
Python
602
star
58

swift-metrics

Metrics API for Swift
Swift
602
star
59

axlearn

Python
564
star
60

swift-distributed-actors

Peer-to-peer cluster implementation for Swift Distributed Actors
Swift
562
star
61

ARKitScenes

This repo accompanies the research paper, ARKitScenes - A Diverse Real-World Dataset for 3D Indoor Scene Understanding Using Mobile RGB-D Data and contains the data, scripts to visualize and process assets, and training code described in our paper.
Python
552
star
62

sample-backyard-birds

Swift
506
star
63

device-management

Device management schema data for MDM.
506
star
64

ccs-calendarserver

The Calendar and Contacts Server.
Python
470
star
65

ml-facelit

Official repository of FaceLit: Neural 3D Relightable Faces (CVPR 2023)
Python
457
star
66

swift-3-api-guidelines-review

Swift
452
star
67

swift-org-website

Swift.org website
SCSS
438
star
68

GCGC

Jupyter Notebook
436
star
69

swift-nio-http2

HTTP/2 support for SwiftNIO
Swift
405
star
70

swift-tools-support-core

Contains common infrastructural code for both SwiftPM and llbuild.
Swift
390
star
71

swift-nio-ssh

SwiftNIO SSH is a programmatic implementation of SSH using SwiftNIO
Swift
364
star
72

swift-nio-ssl

TLS Support for SwiftNIO, based on BoringSSL.
C
345
star
73

ml-gmpi

Official PyTorch implementation of GMPI (ECCV 2022, Oral Presentation)
Python
329
star
74

example-package-dealer

Example package for use with the Swift Package Manager
Swift
319
star
75

swift-collections-benchmark

A benchmarking tool for Swift Collection algorithms
Swift
316
star
76

example-package-playingcard

Example package for use with the Swift Package Manager
Swift
308
star
77

swift-docc-render

Web renderer for Swift-DocC documentation.
JavaScript
300
star
78

indexstore-db

Index database library for use with sourcekit-lsp
C++
299
star
79

swift-playdate-examples

A technical demonstration of Embedded Swift running on Playdate by Panic
Swift
295
star
80

swift-docc-plugin

Swift Package Manager command plugin for Swift-DocC
Swift
295
star
81

ml-hierarchical-confusion-matrix

Neo: Hierarchical Confusion Matrix Visualization (CHI 2022)
TypeScript
292
star
82

ml-gsn

Python
284
star
83

swift-llbuild2

A fresh take on a low-level build system API.
Swift
280
star
84

swift-source-compat-suite

The infrastructure and project index comprising the Swift source compatibility suite.
Python
278
star
85

sample-cloudkit-sharing

Swift
275
star
86

swift-xcode-playground-support

Logging and communication to allow Swift toolchains to communicate with Xcode.
Swift
270
star
87

swift-experimental-string-processing

An early experimental general-purpose pattern matching engine for Swift.
Swift
263
star
88

ml-sigma-reparam

Python
255
star
89

swift-standard-library-preview

Swift
253
star
90

swift-nio-transport-services

Extensions for SwiftNIO to support Apple platforms as first-class citizens.
Swift
252
star
91

swift-stress-tester

Stress testing utilities for Swift's tooling
Swift
207
star
92

swift-service-discovery

A service discovery API for Swift.
Swift
203
star
93

swift-certificates

An implementation of X.509 for Swift
Swift
195
star
94

swift-nio-examples

examples of how to use swift-nio
Swift
195
star
95

swift-cluster-membership

Distributed Membership Protocol implementations in Swift
Swift
191
star
96

swift-aoc-starter-example

Swift starter project for solving Advent of Code challenges.
Swift
189
star
97

sample-cloudkit-coredatasync

Swift
187
star
98

swift-distributed-tracing

Instrumentation library for Swift server applications
Swift
186
star
99

pfl-research

Simulation framework for accelerating research in Private Federated Learning
Python
186
star
100

swift-internals

HTML
182
star