Skip to content

Commit e113695

Browse files
authored
Merge pull request #830 from allevato/reformat
Reformat swift-format and enforce it on PRs.
2 parents 6e4c4b5 + 40d3f3e commit e113695

File tree

150 files changed

+2611
-1942
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

150 files changed

+2611
-1942
lines changed

.github/workflows/pull_request.yml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,5 @@ jobs:
1212
name: Soundness
1313
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
1414
with:
15-
format_check_enabled: false
1615
license_header_check_enabled: false
1716
license_header_check_project_name: "Swift.org"

.swift-format

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
{
2+
"version": 1,
3+
"lineLength": 120,
4+
"indentation": {
5+
"spaces": 2
6+
},
7+
"lineBreakBeforeEachArgument": true,
8+
"indentConditionalCompilationBlocks": false,
9+
"prioritizeKeepingFunctionOutputTogether": true,
10+
"rules": {
11+
"AlwaysUseLowerCamelCase": false,
12+
"AmbiguousTrailingClosureOverload": false,
13+
"NoBlockComments": false,
14+
"OrderedImports": true,
15+
"UseLetInEveryBoundCaseVariable": false,
16+
"UseSynthesizedInitializer": false
17+
}
18+
}

Package.swift

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ let package = Package(
1818
name: "swift-format",
1919
platforms: [
2020
.macOS("12.0"),
21-
.iOS("13.0")
21+
.iOS("13.0"),
2222
],
2323
products: [
2424
.executable(
@@ -131,7 +131,7 @@ let package = Package(
131131
.product(name: "SwiftSyntax", package: "swift-syntax"),
132132
.product(name: "SwiftSyntaxBuilder", package: "swift-syntax"),
133133
]
134-
)
134+
),
135135
]
136136
)
137137

@@ -167,15 +167,12 @@ var dependencies: [Package.Dependency] {
167167
}
168168
}
169169

170-
171-
172170
// MARK: - Compute custom build settings
173171

174-
var swiftformatLinkSettings: [LinkerSetting] {
172+
var swiftformatLinkSettings: [LinkerSetting] {
175173
if installAction {
176174
return [.unsafeFlags(["-no-toolchain-stdlib-rpath"], .when(platforms: [.linux, .android]))]
177175
} else {
178176
return []
179177
}
180178
}
181-

Plugins/FormatPlugin/plugin.swift

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,27 @@
1-
import PackagePlugin
21
import Foundation
2+
import PackagePlugin
33

44
@main
55
struct FormatPlugin {
66
func format(tool: PluginContext.Tool, targetDirectories: [String], configurationFilePath: String?) throws {
77
let swiftFormatExec = URL(fileURLWithPath: tool.path.string)
8-
8+
99
var arguments: [String] = ["format"]
10-
10+
1111
arguments.append(contentsOf: targetDirectories)
12-
12+
1313
arguments.append(contentsOf: ["--recursive", "--parallel", "--in-place"])
14-
14+
1515
if let configurationFilePath = configurationFilePath {
1616
arguments.append(contentsOf: ["--configuration", configurationFilePath])
1717
}
18-
18+
1919
let process = try Process.run(swiftFormatExec, arguments: arguments)
2020
process.waitUntilExit()
21-
21+
2222
if process.terminationReason == .exit && process.terminationStatus == 0 {
2323
print("Formatted the source code.")
24-
}
25-
else {
24+
} else {
2625
let problem = "\(process.terminationReason):\(process.terminationStatus)"
2726
Diagnostics.error("swift-format invocation failed: \(problem)")
2827
}
@@ -35,15 +34,16 @@ extension FormatPlugin: CommandPlugin {
3534
arguments: [String]
3635
) async throws {
3736
let swiftFormatTool = try context.tool(named: "swift-format")
38-
37+
3938
var argExtractor = ArgumentExtractor(arguments)
4039
let targetNames = argExtractor.extractOption(named: "target")
41-
let targetsToFormat = targetNames.isEmpty ? context.package.targets : try context.package.targets(named: targetNames)
42-
40+
let targetsToFormat =
41+
targetNames.isEmpty ? context.package.targets : try context.package.targets(named: targetNames)
42+
4343
let configurationFilePath = argExtractor.extractOption(named: "swift-format-configuration").first
44-
45-
let sourceCodeTargets = targetsToFormat.compactMap{ $0 as? SourceModuleTarget }
46-
44+
45+
let sourceCodeTargets = targetsToFormat.compactMap { $0 as? SourceModuleTarget }
46+
4747
try format(
4848
tool: swiftFormatTool,
4949
targetDirectories: sourceCodeTargets.map(\.directory.string),
@@ -58,10 +58,10 @@ import XcodeProjectPlugin
5858
extension FormatPlugin: XcodeCommandPlugin {
5959
func performCommand(context: XcodeProjectPlugin.XcodePluginContext, arguments: [String]) throws {
6060
let swiftFormatTool = try context.tool(named: "swift-format")
61-
61+
6262
var argExtractor = ArgumentExtractor(arguments)
6363
let configurationFilePath = argExtractor.extractOption(named: "swift-format-configuration").first
64-
64+
6565
try format(
6666
tool: swiftFormatTool,
6767
targetDirectories: [context.xcodeProject.directory.string],

Plugins/LintPlugin/plugin.swift

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,27 @@
1-
import PackagePlugin
21
import Foundation
2+
import PackagePlugin
33

44
@main
55
struct LintPlugin {
66
func lint(tool: PluginContext.Tool, targetDirectories: [String], configurationFilePath: String?) throws {
77
let swiftFormatExec = URL(fileURLWithPath: tool.path.string)
8-
8+
99
var arguments: [String] = ["lint"]
10-
10+
1111
arguments.append(contentsOf: targetDirectories)
12-
12+
1313
arguments.append(contentsOf: ["--recursive", "--parallel", "--strict"])
14-
14+
1515
if let configurationFilePath = configurationFilePath {
1616
arguments.append(contentsOf: ["--configuration", configurationFilePath])
1717
}
18-
18+
1919
let process = try Process.run(swiftFormatExec, arguments: arguments)
2020
process.waitUntilExit()
21-
21+
2222
if process.terminationReason == .exit && process.terminationStatus == 0 {
2323
print("Linted the source code.")
24-
}
25-
else {
24+
} else {
2625
let problem = "\(process.terminationReason):\(process.terminationStatus)"
2726
Diagnostics.error("swift-format invocation failed: \(problem)")
2827
}
@@ -35,16 +34,17 @@ extension LintPlugin: CommandPlugin {
3534
arguments: [String]
3635
) async throws {
3736
let swiftFormatTool = try context.tool(named: "swift-format")
38-
37+
3938
// Extract the arguments that specify what targets to format.
4039
var argExtractor = ArgumentExtractor(arguments)
4140
let targetNames = argExtractor.extractOption(named: "target")
42-
43-
let targetsToFormat = targetNames.isEmpty ? context.package.targets : try context.package.targets(named: targetNames)
41+
42+
let targetsToFormat =
43+
targetNames.isEmpty ? context.package.targets : try context.package.targets(named: targetNames)
4444
let configurationFilePath = argExtractor.extractOption(named: "swift-format-configuration").first
45-
45+
4646
let sourceCodeTargets = targetsToFormat.compactMap { $0 as? SourceModuleTarget }
47-
47+
4848
try lint(
4949
tool: swiftFormatTool,
5050
targetDirectories: sourceCodeTargets.map(\.directory.string),
@@ -61,7 +61,7 @@ extension LintPlugin: XcodeCommandPlugin {
6161
let swiftFormatTool = try context.tool(named: "swift-format")
6262
var argExtractor = ArgumentExtractor(arguments)
6363
let configurationFilePath = argExtractor.extractOption(named: "swift-format-configuration").first
64-
64+
6565
try lint(
6666
tool: swiftFormatTool,
6767
targetDirectories: [context.xcodeProject.directory.string],

Sources/SwiftFormat/API/Configuration.swift

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -278,9 +278,11 @@ public struct Configuration: Codable, Equatable {
278278
self.version = try container.decodeIfPresent(Int.self, forKey: .version) ?? 1
279279
guard version <= highestSupportedConfigurationVersion else {
280280
throw DecodingError.dataCorruptedError(
281-
forKey: .version, in: container,
281+
forKey: .version,
282+
in: container,
282283
debugDescription:
283-
"This version of the formatter does not support configuration version \(version).")
284+
"This version of the formatter does not support configuration version \(version)."
285+
)
284286
}
285287

286288
// If we ever introduce a new version, this is where we should switch on the decoded version
@@ -328,30 +330,40 @@ public struct Configuration: Codable, Equatable {
328330
?? defaults.prioritizeKeepingFunctionOutputTogether
329331
self.indentConditionalCompilationBlocks =
330332
try container.decodeIfPresent(Bool.self, forKey: .indentConditionalCompilationBlocks)
331-
?? defaults.indentConditionalCompilationBlocks
333+
?? defaults.indentConditionalCompilationBlocks
332334
self.lineBreakAroundMultilineExpressionChainComponents =
333335
try container.decodeIfPresent(
334-
Bool.self, forKey: .lineBreakAroundMultilineExpressionChainComponents)
336+
Bool.self,
337+
forKey: .lineBreakAroundMultilineExpressionChainComponents
338+
)
335339
?? defaults.lineBreakAroundMultilineExpressionChainComponents
336340
self.spacesAroundRangeFormationOperators =
337341
try container.decodeIfPresent(
338-
Bool.self, forKey: .spacesAroundRangeFormationOperators)
342+
Bool.self,
343+
forKey: .spacesAroundRangeFormationOperators
344+
)
339345
?? defaults.spacesAroundRangeFormationOperators
340346
self.fileScopedDeclarationPrivacy =
341347
try container.decodeIfPresent(
342-
FileScopedDeclarationPrivacyConfiguration.self, forKey: .fileScopedDeclarationPrivacy)
348+
FileScopedDeclarationPrivacyConfiguration.self,
349+
forKey: .fileScopedDeclarationPrivacy
350+
)
343351
?? defaults.fileScopedDeclarationPrivacy
344352
self.indentSwitchCaseLabels =
345353
try container.decodeIfPresent(Bool.self, forKey: .indentSwitchCaseLabels)
346-
?? defaults.indentSwitchCaseLabels
354+
?? defaults.indentSwitchCaseLabels
347355
self.noAssignmentInExpressions =
348356
try container.decodeIfPresent(
349-
NoAssignmentInExpressionsConfiguration.self, forKey: .noAssignmentInExpressions)
357+
NoAssignmentInExpressionsConfiguration.self,
358+
forKey: .noAssignmentInExpressions
359+
)
350360
?? defaults.noAssignmentInExpressions
351361
self.multiElementCollectionTrailingCommas =
352362
try container.decodeIfPresent(
353-
Bool.self, forKey: .multiElementCollectionTrailingCommas)
354-
?? defaults.multiElementCollectionTrailingCommas
363+
Bool.self,
364+
forKey: .multiElementCollectionTrailingCommas
365+
)
366+
?? defaults.multiElementCollectionTrailingCommas
355367

356368
self.reflowMultilineStringLiterals =
357369
try container.decodeIfPresent(MultilineStringReflowBehavior.self, forKey: .reflowMultilineStringLiterals)
@@ -384,9 +396,12 @@ public struct Configuration: Codable, Equatable {
384396
try container.encode(lineBreakBetweenDeclarationAttributes, forKey: .lineBreakBetweenDeclarationAttributes)
385397
try container.encode(
386398
lineBreakAroundMultilineExpressionChainComponents,
387-
forKey: .lineBreakAroundMultilineExpressionChainComponents)
399+
forKey: .lineBreakAroundMultilineExpressionChainComponents
400+
)
388401
try container.encode(
389-
spacesAroundRangeFormationOperators, forKey: .spacesAroundRangeFormationOperators)
402+
spacesAroundRangeFormationOperators,
403+
forKey: .spacesAroundRangeFormationOperators
404+
)
390405
try container.encode(fileScopedDeclarationPrivacy, forKey: .fileScopedDeclarationPrivacy)
391406
try container.encode(indentSwitchCaseLabels, forKey: .indentSwitchCaseLabels)
392407
try container.encode(noAssignmentInExpressions, forKey: .noAssignmentInExpressions)

Sources/SwiftFormat/API/Indent.swift

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,9 @@ public enum Indent: Hashable, Codable {
3636
throw DecodingError.dataCorrupted(
3737
DecodingError.Context(
3838
codingPath: decoder.codingPath,
39-
debugDescription: "Only one of \"tabs\" or \"spaces\" may be specified"))
39+
debugDescription: "Only one of \"tabs\" or \"spaces\" may be specified"
40+
)
41+
)
4042
}
4143
if let spacesCount = spacesCount {
4244
self = .spaces(spacesCount)
@@ -50,7 +52,9 @@ public enum Indent: Hashable, Codable {
5052
throw DecodingError.dataCorrupted(
5153
DecodingError.Context(
5254
codingPath: decoder.codingPath,
53-
debugDescription: "One of \"tabs\" or \"spaces\" must be specified"))
55+
debugDescription: "One of \"tabs\" or \"spaces\" must be specified"
56+
)
57+
)
5458
}
5559

5660
public func encode(to encoder: Encoder) throws {

Sources/SwiftFormat/API/Selection.swift

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ public enum Selection {
2424
self = .infinite
2525
} else {
2626
let ranges = offsetRanges.map {
27-
AbsolutePosition(utf8Offset: $0.lowerBound) ..< AbsolutePosition(utf8Offset: $0.upperBound)
27+
AbsolutePosition(utf8Offset: $0.lowerBound)..<AbsolutePosition(utf8Offset: $0.upperBound)
2828
}
2929
self = .ranges(ranges)
3030
}
@@ -49,7 +49,6 @@ public enum Selection {
4949
}
5050
}
5151

52-
5352
public extension Syntax {
5453
/// - Returns: `true` if the node is _completely_ inside any range in the selection
5554
func isInsideSelection(_ selection: Selection) -> Bool {

Sources/SwiftFormat/API/SwiftFormatter.swift

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,8 @@ public final class SwiftFormatter {
7272
assumingFileURL: url,
7373
selection: .infinite,
7474
to: &outputStream,
75-
parsingDiagnosticHandler: parsingDiagnosticHandler)
75+
parsingDiagnosticHandler: parsingDiagnosticHandler
76+
)
7677
}
7778

7879
/// Formats the given Swift source code and writes the result to an output stream.
@@ -109,10 +110,16 @@ public final class SwiftFormatter {
109110
source: source,
110111
operatorTable: .standardOperators,
111112
assumingFileURL: url,
112-
parsingDiagnosticHandler: parsingDiagnosticHandler)
113+
parsingDiagnosticHandler: parsingDiagnosticHandler
114+
)
113115
try format(
114-
syntax: sourceFile, source: source, operatorTable: .standardOperators, assumingFileURL: url,
115-
selection: selection, to: &outputStream)
116+
syntax: sourceFile,
117+
source: source,
118+
operatorTable: .standardOperators,
119+
assumingFileURL: url,
120+
selection: selection,
121+
to: &outputStream
122+
)
116123
}
117124

118125
/// Formats the given Swift syntax tree and writes the result to an output stream.
@@ -137,14 +144,24 @@ public final class SwiftFormatter {
137144
/// be written.
138145
/// - Throws: If an unrecoverable error occurs when formatting the code.
139146
public func format<Output: TextOutputStream>(
140-
syntax: SourceFileSyntax, source: String, operatorTable: OperatorTable,
141-
assumingFileURL url: URL?, selection: Selection, to outputStream: inout Output
147+
syntax: SourceFileSyntax,
148+
source: String,
149+
operatorTable: OperatorTable,
150+
assumingFileURL url: URL?,
151+
selection: Selection,
152+
to outputStream: inout Output
142153
) throws {
143154
let assumedURL = url ?? URL(fileURLWithPath: "source")
144155
let context = Context(
145-
configuration: configuration, operatorTable: operatorTable, findingConsumer: findingConsumer,
146-
fileURL: assumedURL, selection: selection, sourceFileSyntax: syntax, source: source,
147-
ruleNameCache: ruleNameCache)
156+
configuration: configuration,
157+
operatorTable: operatorTable,
158+
findingConsumer: findingConsumer,
159+
fileURL: assumedURL,
160+
selection: selection,
161+
sourceFileSyntax: syntax,
162+
source: source,
163+
ruleNameCache: ruleNameCache
164+
)
148165
let pipeline = FormatPipeline(context: context)
149166
let transformedSyntax = pipeline.rewrite(Syntax(syntax))
150167

@@ -158,7 +175,8 @@ public final class SwiftFormatter {
158175
source: source,
159176
node: transformedSyntax,
160177
printTokenStream: debugOptions.contains(.dumpTokenStream),
161-
whitespaceOnly: false)
178+
whitespaceOnly: false
179+
)
162180
outputStream.write(printer.prettyPrint())
163181
}
164182
}

0 commit comments

Comments
 (0)