Skip to content

Commit

Permalink
Merge branch 'develop' into cal--organize-decls-improvements-0.46.1
Browse files Browse the repository at this point in the history
  • Loading branch information
calda committed Aug 29, 2020
2 parents e5fc040 + fb4787c commit 138302e
Show file tree
Hide file tree
Showing 8 changed files with 83 additions and 17 deletions.
19 changes: 18 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -418,20 +418,37 @@ You can disable rules individually using `--disable` followed by a list of one o
--enable isEmpty
```

If you prefer, you can place your enabled/disabled rules on separate lines instead of using commas:
If you prefer, you can place your enabled/disabled rules on separate lines instead of using commas

```bash
--disable indent
--disable linebreaks
--disable redundantSelf
```

or use the line continuation character `\` to omit the `--disable` for each rule:

```bash
--disable \
indent, \
linebreaks, \
redundantSelf
```

To avoid automatically opting-in to new rules when SwiftFormat is updated, you can use the`--rules` argument to *only* enable the rules you specify:

```bash
--rules indent,linebreaks
```

Like before, you may use the line continuation character `\` to list the rules on separate lines:

```bash
--rules \
indent, \
linebreaks
```

To see exactly which rules were applied to a given file, you can use the `--verbose` command-line option to force SwiftFormat to print a more detailed log as it applies the formatting. **NOTE:** running in verbose mode is slower than the default mode.

You can disable rules for specific files or code ranges by using `swiftformat:` directives in comments inside your Swift file. To temporarily disable one or more rules inside a source file, use:
Expand Down
18 changes: 17 additions & 1 deletion Sources/Arguments.swift
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ func parseConfigFile(_ data: Data) throws -> [String: String] {
guard let input = String(data: data, encoding: .utf8) else {
throw FormatError.reading("Unable to read data for configuration file")
}
let lines = input.components(separatedBy: .newlines)
let lines = try cumulate(successiveLines: input.components(separatedBy: .newlines))
let arguments = try lines.flatMap { line -> [String] in
// TODO: parseArguments isn't a perfect fit here - should we use a different approach?
let line = line.replacingOccurrences(of: "\\n", with: "\n")
Expand All @@ -336,6 +336,22 @@ func parseConfigFile(_ data: Data) throws -> [String: String] {
}
}

private func cumulate(successiveLines: [String]) throws -> [String] {
var cumulatedLines = [String]()
var iterator = successiveLines.makeIterator()
while let currentLine = iterator.next() {
var cumulatedLine = currentLine.trimmingCharacters(in: .whitespaces)
while cumulatedLine.hasSuffix("\\") {
guard let nextLine = iterator.next() else {
throw FormatError.reading("Configuration file ends with an illegal line continuation character '\'")
}
cumulatedLine = cumulatedLine.dropLast() + nextLine
}
cumulatedLines.append(cumulatedLine)
}
return cumulatedLines
}

// Serialize a set of options into either an arguments string or a file
func serialize(options: Options,
swiftVersion: Version = .undefined,
Expand Down
6 changes: 4 additions & 2 deletions Sources/ParsingHelpers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -509,12 +509,14 @@ extension Formatter {
case "in", "as", "is", "try":
return indexOfLastSignificantKeyword(at: index - 1, excluding: excluding)
default:
guard let braceIndex = self.index(of: .startOfScope("{"), in: index ..< i) else {
guard let braceIndex = self.index(of: .startOfScope("{"), in: index ..< i),
let endIndex = endOfScope(at: braceIndex),
next(.nonSpaceOrComment, after: endIndex) != .startOfScope("(")
else {
return index
}
if keyword == "if" || ["var", "let"].contains(keyword) &&
last(.nonSpaceOrCommentOrLinebreak, before: index) == .keyword("if"),
let endIndex = endOfScope(at: braceIndex),
self.index(of: .startOfScope("{"), in: endIndex ..< i) == nil
{
return index
Expand Down
3 changes: 0 additions & 3 deletions Sources/Rules.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1276,9 +1276,6 @@ public struct _FormatRules {
{
indent += formatter.options.indent
}
if case let .space(s) = formatter.tokens[start], s != indent {
print("")
}
let stringIndent = stringBodyIndentStack.last!
i += formatter.insertSpaceIfEnabled(stringIndent + indent, at: start)
}
Expand Down
28 changes: 28 additions & 0 deletions Tests/ArgumentsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,34 @@ class ArgumentsTests: XCTestCase {
XCTAssertEqual(args["rules"], "braces, fileHeader, consecutiveSpaces")
}

func testParseArgumentsOnMultipleLines() throws {
let config = """
--rules braces, \\
fileHeader, \\
andOperator, typeSugar
--allman true
--hexgrouping \\
4, \\
8
"""
let data = Data(config.utf8)
let args = try parseConfigFile(data)
XCTAssertEqual(args["rules"], "braces, fileHeader, andOperator, typeSugar")
XCTAssertEqual(args["allman"], "true")
XCTAssertEqual(args["hexgrouping"], "4, 8")
}

func testLineContinuationCharacterOnLastLine() throws {
let config = """
--rules braces,\\
fileHeader\\
"""
let data = Data(config.utf8)
XCTAssertThrowsError(try parseConfigFile(data)) {
XCTAssert($0.localizedDescription.contains("line continuation character"))
}
}

func testParseArgumentsContainingEscapedCharacters() throws {
let config = "--header hello\\ world\\ngoodbye\\ world"
let data = Data(config.utf8)
Expand Down
19 changes: 9 additions & 10 deletions Tests/ParsingHelpersTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -456,16 +456,15 @@ class ParsingHelpersTests: XCTestCase {
XCTAssertFalse(formatter.isStartOfClosure(at: 22))
}

// TODO: fix in next release
// func testParameterBodyAfterExecutedClosureIsNotClosure() {
// let formatter = Formatter(tokenize("""
// var withBody6: String = { "bar" }() {
// didSet { print("didSet") }
// }
// """))
//
// XCTAssertFalse(formatter.isStartOfClosure(at: 19))
// }
func testParameterBodyAfterExecutedClosureIsNotClosure() {
let formatter = Formatter(tokenize("""
var withBody6: String = { "bar" }() {
didSet { print("didSet") }
}
"""))

XCTAssertFalse(formatter.isStartOfClosure(at: 19))
}

// MARK: isAccessorKeyword

Expand Down
4 changes: 4 additions & 0 deletions Tests/RulesTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14346,6 +14346,10 @@ class RulesTests: XCTestCase {
var withBody5: () -> String = { "bar" } {
didSet { print("didSet") }
}
var withBody6: String = { "bar" }() {
didSet { print("didSet") }
}
}
"""

Expand Down
3 changes: 3 additions & 0 deletions Tests/XCTestManifests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ extension ArgumentsTests {
("testFileHeaderOptionToArguments", testFileHeaderOptionToArguments),
("testFormattingArgumentsAreAllImplemented", testFormattingArgumentsAreAllImplemented),
("testHMatchesHelp", testHMatchesHelp),
("testLineContinuationCharacterOnLastLine", testLineContinuationCharacterOnLastLine),
("testMergeDisableRules", testMergeDisableRules),
("testMergeEmptyRules", testMergeEmptyRules),
("testMergeEnableRules", testMergeEnableRules),
Expand All @@ -48,6 +49,7 @@ extension ArgumentsTests {
("testParseArgumentsContainingQuotedCharacters", testParseArgumentsContainingQuotedCharacters),
("testParseArgumentsContainingSpaces", testParseArgumentsContainingSpaces),
("testParseArgumentsContainingSwiftVersion", testParseArgumentsContainingSwiftVersion),
("testParseArgumentsOnMultipleLines", testParseArgumentsOnMultipleLines),
("testParseDeprecatedOption", testParseDeprecatedOption),
("testParseEmptyOptions", testParseEmptyOptions),
("testParseEscapedN", testParseEscapedN),
Expand Down Expand Up @@ -375,6 +377,7 @@ extension ParsingHelpersTests {
("testOptionalInitNotTreatedAsClosure", testOptionalInitNotTreatedAsClosure),
("testOptionalReturningFunctionBracesNotTreatedAsClosure", testOptionalReturningFunctionBracesNotTreatedAsClosure),
("testParameterBodyAfterClosureIsNotClosure", testParameterBodyAfterClosureIsNotClosure),
("testParameterBodyAfterExecutedClosureIsNotClosure", testParameterBodyAfterExecutedClosureIsNotClosure),
("testParameterBodyAfterNumberIsNotClosure", testParameterBodyAfterNumberIsNotClosure),
("testParameterBodyAfterStringIsNotClosure", testParameterBodyAfterStringIsNotClosure),
("testParseClassFuncDeclarationCorrectly", testParseClassFuncDeclarationCorrectly),
Expand Down

0 comments on commit 138302e

Please sign in to comment.