Skip to content

Commit

Permalink
Fix all SwiftLint warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
Jeehut committed Apr 9, 2023
1 parent d9eb674 commit fae4a6f
Show file tree
Hide file tree
Showing 39 changed files with 510 additions and 520 deletions.
7 changes: 6 additions & 1 deletion .swiftlint.yml
Expand Up @@ -85,8 +85,10 @@ excluded:
- Tests/LinuxMain.swift

disabled_rules:
- todo
- blanket_disable_command
- cyclomatic_complexity
- todo


# Rule Configurations
conditional_returns_on_newline:
Expand All @@ -107,6 +109,9 @@ identifier_name:
- db
- to

indentation_width:
indentation_width: 3

line_length:
warning: 160
ignores_comments: true
Expand Down
4 changes: 0 additions & 4 deletions Package.swift
Expand Up @@ -29,10 +29,6 @@ let package = Package(
name: "AnyLintCLITests",
dependencies: ["AnyLintCLI"]
),
.testTarget(
name: "UtilityTests",
dependencies: ["Utility"]
),
.target(
name: "Utility",
dependencies: ["Rainbow"]
Expand Down
26 changes: 13 additions & 13 deletions Sources/AnyLint/AutoCorrection.swift
Expand Up @@ -5,27 +5,27 @@ import Utility
public struct AutoCorrection {
/// The matching text before applying the autocorrection.
public let before: String

/// The matching text after applying the autocorrection.
public let after: String

var appliedMessageLines: [String] {
if useDiffOutput, #available(OSX 10.15, *) {
var lines: [String] = ["Autocorrection applied, the diff is: (+ added, - removed)"]

let beforeLines = before.components(separatedBy: .newlines)
let afterLines = after.components(separatedBy: .newlines)

for difference in afterLines.difference(from: beforeLines).sorted() {
switch difference {
case let .insert(offset, element, _):
lines.append("+ [L\(offset + 1)] \(element)".green)

case let .remove(offset, element, _):
lines.append("- [L\(offset + 1)] \(element)".red)
}
}

return lines
} else {
return [
Expand All @@ -35,12 +35,12 @@ public struct AutoCorrection {
]
}
}

var useDiffOutput: Bool {
before.components(separatedBy: .newlines).count >= Constants.newlinesRequiredForDiffing ||
after.components(separatedBy: .newlines).count >= Constants.newlinesRequiredForDiffing
}

/// Initializes an autocorrection.
public init(before: String, after: String) {
self.before = before
Expand All @@ -58,7 +58,7 @@ extension AutoCorrection: ExpressibleByDictionaryLiteral {
log.exit(status: .failure)
exit(EXIT_FAILURE) // only reachable in unit tests
}

self = AutoCorrection(before: before, after: after)
}
}
Expand All @@ -70,20 +70,20 @@ extension CollectionDifference.Change: Comparable where ChangeElement == String
switch (lhs, rhs) {
case let (.remove(leftOffset, _, _), .remove(rightOffset, _, _)), let (.insert(leftOffset, _, _), .insert(rightOffset, _, _)):
return leftOffset < rightOffset

case let (.remove(leftOffset, _, _), .insert(rightOffset, _, _)):
return leftOffset < rightOffset || true

case let (.insert(leftOffset, _, _), .remove(rightOffset, _, _)):
return leftOffset < rightOffset || false
}
}

public static func == (lhs: Self, rhs: Self) -> Bool {
switch (lhs, rhs) {
case let (.remove(leftOffset, _, _), .remove(rightOffset, _, _)), let (.insert(leftOffset, _, _), .insert(rightOffset, _, _)):
return leftOffset == rightOffset

case (.remove, .insert), (.insert, .remove):
return false
}
Expand Down
48 changes: 24 additions & 24 deletions Sources/AnyLint/Checkers/FileContentsChecker.swift
Expand Up @@ -14,79 +14,79 @@ extension FileContentsChecker: Checker {
func performCheck() throws -> [Violation] { // swiftlint:disable:this function_body_length
log.message("Start checking \(checkInfo) ...", level: .debug)
var violations: [Violation] = []

for filePath in filePathsToCheck.reversed() {
log.message("Start reading contents of file at \(filePath) ...", level: .debug)

if let fileData = fileManager.contents(atPath: filePath), let fileContents = String(data: fileData, encoding: .utf8) {
var newFileContents: String = fileContents
let linesInFile: [String] = fileContents.components(separatedBy: .newlines)

// skip check in file if contains `AnyLint.skipInFile: <All or CheckInfo.ID>`
let skipInFileRegex = try Regex(#"AnyLint\.skipInFile:[^\n]*([, ]All[,\s]|[, ]\#(checkInfo.id)[,\s])"#)
guard !skipInFileRegex.matches(fileContents) else {
log.message("Skipping \(checkInfo) in file \(filePath) due to 'AnyLint.skipInFile' instruction ...", level: .debug)
continue
}

let skipHereRegex = try Regex(#"AnyLint\.skipHere:[^\n]*[, ]\#(checkInfo.id)"#)

for match in regex.matches(in: fileContents).reversed() {
let locationInfo: String.LocationInfo

switch self.violationLocation.range {
case .fullMatch:
switch self.violationLocation.bound {
case .lower:
locationInfo = fileContents.locationInfo(of: match.range.lowerBound)

case .upper:
locationInfo = fileContents.locationInfo(of: match.range.upperBound)
}

case .captureGroup(let index):
let capture = match.captures[index]!
let captureRange = NSRange(match.string.range(of: capture)!, in: match.string)

switch self.violationLocation.bound {
case .lower:
locationInfo = fileContents.locationInfo(
of: fileContents.index(match.range.lowerBound, offsetBy: captureRange.location)
)

case .upper:
locationInfo = fileContents.locationInfo(
of: fileContents.index(match.range.lowerBound, offsetBy: captureRange.location + captureRange.length)
)
}
}

log.message("Found violating match at \(locationInfo) ...", level: .debug)

// skip found match if contains `AnyLint.skipHere: <CheckInfo.ID>` in same line or one line before
guard !linesInFile.containsLine(at: [locationInfo.line - 2, locationInfo.line - 1], matchingRegex: skipHereRegex) else {
log.message("Skip reporting last match due to 'AnyLint.skipHere' instruction ...", level: .debug)
continue
}

let autoCorrection: AutoCorrection? = {
guard let autoCorrectReplacement = autoCorrectReplacement else { return nil }

let newMatchString = regex.replaceAllCaptures(in: match.string, with: autoCorrectReplacement)
return AutoCorrection(before: match.string, after: newMatchString)
}()

if let autoCorrection = autoCorrection {
guard match.string != autoCorrection.after else {
// can skip auto-correction & violation reporting because auto-correct replacement is equal to matched string
continue
}

// apply auto correction
newFileContents.replaceSubrange(match.range, with: autoCorrection.after)
log.message("Applied autocorrection for last match ...", level: .debug)
}

log.message("Reporting violation for \(checkInfo) in file \(filePath) at \(locationInfo) ...", level: .debug)
violations.append(
Violation(
Expand All @@ -98,7 +98,7 @@ extension FileContentsChecker: Checker {
)
)
}

if newFileContents != fileContents {
log.message("Rewriting contents of file \(filePath) due to autocorrection changes ...", level: .debug)
try newFileContents.write(toFile: filePath, atomically: true, encoding: .utf8)
Expand All @@ -109,18 +109,18 @@ extension FileContentsChecker: Checker {
level: .warning
)
}

Statistics.shared.checkedFiles(at: [filePath])
}

violations = violations.reversed()

if repeatIfAutoCorrected && violations.contains(where: { $0.appliedAutoCorrection != nil }) {
log.message("Repeating check \(checkInfo) because auto-corrections were applied on last run.", level: .debug)

// only paths where auto-corrections were applied need to be re-checked
let filePathsToReCheck = Array(Set(violations.filter { $0.appliedAutoCorrection != nil }.map { $0.filePath! })).sorted()

let violationsOnRechecks = try FileContentsChecker(
checkInfo: checkInfo,
regex: regex,
Expand All @@ -131,7 +131,7 @@ extension FileContentsChecker: Checker {
).performCheck()
violations.append(contentsOf: violationsOnRechecks)
}

return violations
}
}
16 changes: 8 additions & 8 deletions Sources/AnyLint/Checkers/FilePathsChecker.swift
Expand Up @@ -12,7 +12,7 @@ struct FilePathsChecker {
extension FilePathsChecker: Checker {
func performCheck() throws -> [Violation] {
var violations: [Violation] = []

if violateIfNoMatchesFound {
let matchingFilePathsCount = filePathsToCheck.filter { regex.matches($0) }.count
if matchingFilePathsCount <= 0 {
Expand All @@ -24,29 +24,29 @@ extension FilePathsChecker: Checker {
} else {
for filePath in filePathsToCheck where regex.matches(filePath) {
log.message("Found violating match for \(checkInfo) ...", level: .debug)

let appliedAutoCorrection: AutoCorrection? = try {
guard let autoCorrectReplacement = autoCorrectReplacement else { return nil }

let newFilePath = regex.replaceAllCaptures(in: filePath, with: autoCorrectReplacement)
try fileManager.moveFileSafely(from: filePath, to: newFilePath)

return AutoCorrection(before: filePath, after: newFilePath)
}()

if appliedAutoCorrection != nil {
log.message("Applied autocorrection for last match ...", level: .debug)
}

log.message("Reporting violation for \(checkInfo) in file \(filePath) ...", level: .debug)
violations.append(
Violation(checkInfo: checkInfo, filePath: filePath, locationInfo: nil, appliedAutoCorrection: appliedAutoCorrection)
)
}

Statistics.shared.checkedFiles(at: filePathsToCheck)
}

return violations
}
}
10 changes: 5 additions & 5 deletions Sources/AnyLint/Extensions/FileManagerExt.swift
Expand Up @@ -9,23 +9,23 @@ extension FileManager {
log.exit(status: .failure)
return // only reachable in unit tests
}

guard !fileExists(atPath: targetPath) || sourcePath.lowercased() == targetPath.lowercased() else {
log.message("File already exists at target path \(targetPath) – can't move from \(sourcePath).", level: .warning)
return
}

let targetParentDirectoryPath = targetPath.parentDirectoryPath
if !fileExists(atPath: targetParentDirectoryPath) {
try createDirectory(atPath: targetParentDirectoryPath, withIntermediateDirectories: true, attributes: nil)
}

guard fileExistsAndIsDirectory(atPath: targetParentDirectoryPath) else {
log.message("Expected \(targetParentDirectoryPath) to be a directory.", level: .error)
log.exit(status: .failure)
return // only reachable in unit tests
}

if sourcePath.lowercased() == targetPath.lowercased() {
// workaround issues on case insensitive file systems
let temporaryTargetPath = targetPath + UUID().uuidString
Expand All @@ -34,7 +34,7 @@ extension FileManager {
} else {
try moveItem(atPath: sourcePath, toPath: targetPath)
}

FilesSearch.shared.invalidateCache()
}
}
10 changes: 5 additions & 5 deletions Sources/AnyLint/Extensions/StringExt.swift
Expand Up @@ -7,25 +7,25 @@ public typealias Regex = Utility.Regex
extension String {
/// Info about the exact location of a character in a given file.
public typealias LocationInfo = (line: Int, charInLine: Int)

/// Returns the location info for a given line index.
public func locationInfo(of index: String.Index) -> LocationInfo {
let prefix = self[startIndex ..< index]
let prefixLines = prefix.components(separatedBy: .newlines)
guard let lastPrefixLine = prefixLines.last else { return (line: 1, charInLine: 1) }

let charInLine = prefix.last == "\n" ? 1 : lastPrefixLine.count + 1
return (line: prefixLines.count, charInLine: charInLine)
}

func showNewlines() -> String {
components(separatedBy: .newlines).joined(separator: #"\n"#)
}

func showWhitespaces() -> String {
components(separatedBy: .whitespaces).joined(separator: "")
}

func showWhitespacesAndNewlines() -> String {
showNewlines().showWhitespaces()
}
Expand Down

0 comments on commit fae4a6f

Please sign in to comment.