diff --git a/.mise.toml b/.mise.toml new file mode 100644 index 000000000..317af7dd7 --- /dev/null +++ b/.mise.toml @@ -0,0 +1,3 @@ +[tools] +swiftlint = "0.54.0" +swiftformat = "0.54.3" diff --git a/.mise/tasks/lint b/.mise/tasks/lint new file mode 100755 index 000000000..d1a523f1d --- /dev/null +++ b/.mise/tasks/lint @@ -0,0 +1,6 @@ +#!/bin/bash +# mise description="Lint the workspace" +set -euo pipefail + +swiftformat $MISE_PROJECT_ROOT --lint +swiftlint lint --quiet --config $MISE_PROJECT_ROOT/.swiftlint.yml $MISE_PROJECT_ROOT/Sources diff --git a/.mise/tasks/lint-fix b/.mise/tasks/lint-fix new file mode 100755 index 000000000..cfc035959 --- /dev/null +++ b/.mise/tasks/lint-fix @@ -0,0 +1,6 @@ +#!/bin/bash +# mise description="Lint the workspace fixing issues" +set -euo pipefail + +swiftformat $MISE_PROJECT_ROOT +swiftlint lint --fix --quiet --config $MISE_PROJECT_ROOT/.swiftlint.yml $MISE_PROJECT_ROOT/Sources diff --git a/.swiftformat b/.swiftformat index cce74ebea..d9bc86bea 100644 --- a/.swiftformat +++ b/.swiftformat @@ -5,6 +5,8 @@ # format options +--disable wrapMultilineStatementBraces +--disable braces --allman false --binarygrouping 4,8 --commas always @@ -32,4 +34,4 @@ --stripunusedargs always --trimwhitespace always --wraparguments preserve ---wrapcollections preserve \ No newline at end of file +--wrapcollections preserve diff --git a/Fixtures/FileSharedAcrossTargets/FileSharedAcrossTargetsTests/FileSharedAcrossTargetsTests.swift b/Fixtures/FileSharedAcrossTargets/FileSharedAcrossTargetsTests/FileSharedAcrossTargetsTests.swift index 62976e867..5b957f983 100644 --- a/Fixtures/FileSharedAcrossTargets/FileSharedAcrossTargetsTests/FileSharedAcrossTargetsTests.swift +++ b/Fixtures/FileSharedAcrossTargets/FileSharedAcrossTargetsTests/FileSharedAcrossTargetsTests.swift @@ -2,7 +2,6 @@ import XCTest @testable import FileSharedAcrossTargets final class FileSharedAcrossTargetsTests: XCTestCase { - override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } @@ -21,9 +20,8 @@ final class FileSharedAcrossTargetsTests: XCTestCase { func testPerformanceExample() throws { // This is an example of a performance test case. - self.measure { + measure { // Put the code you want to measure the time of here. } } - } diff --git a/Fixtures/iOS/AppWithExtensions/AppWithExtensions/AppDelegate.swift b/Fixtures/iOS/AppWithExtensions/AppWithExtensions/AppDelegate.swift index ec501c432..5d0695c4a 100644 --- a/Fixtures/iOS/AppWithExtensions/AppWithExtensions/AppDelegate.swift +++ b/Fixtures/iOS/AppWithExtensions/AppWithExtensions/AppDelegate.swift @@ -1,6 +1,6 @@ import UIKit -@UIApplicationMain +@main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. diff --git a/Fixtures/iOS/iOS/AppDelegate.swift b/Fixtures/iOS/iOS/AppDelegate.swift index 843ae1f67..22f27cb41 100644 --- a/Fixtures/iOS/iOS/AppDelegate.swift +++ b/Fixtures/iOS/iOS/AppDelegate.swift @@ -8,7 +8,7 @@ import UIKit -@UIApplicationMain +@main class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? diff --git a/Package.swift b/Package.swift index dcd5cc927..4e4b66835 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( dependencies: [ .package(url: "https://github.com/tadija/AEXML.git", .upToNextMinor(from: "4.6.1")), .package(url: "https://github.com/kylef/PathKit.git", .upToNextMinor(from: "1.0.1")), - .package(url: "https://github.com/apple/swift-docc-plugin", from: "1.3.0") + .package(url: "https://github.com/apple/swift-docc-plugin", from: "1.3.0"), ], targets: [ .target(name: "XcodeProj", @@ -19,7 +19,7 @@ let package = Package( .product(name: "AEXML", package: "AEXML"), ], swiftSettings: [ - .enableExperimentalFeature("StrictConcurrency") + .enableExperimentalFeature("StrictConcurrency"), ]), .testTarget(name: "XcodeProjTests", dependencies: ["XcodeProj"]), ] diff --git a/Sources/XcodeProj/Extensions/AEXML+XcodeFormat.swift b/Sources/XcodeProj/Extensions/AEXML+XcodeFormat.swift index d8c4ec157..810170332 100644 --- a/Sources/XcodeProj/Extensions/AEXML+XcodeFormat.swift +++ b/Sources/XcodeProj/Extensions/AEXML+XcodeFormat.swift @@ -103,13 +103,13 @@ let attributesOrder: [String: [String]] = [ "RemoteRunnable": [ "runnableDebuggingMode", "BundleIdentifier", - "RemotePath" + "RemotePath", ], "Scheme": [ "LastUpgradeVersion", "wasCreatedForAppExtension", - "version" - ] + "version", + ], ] extension AEXMLElement { @@ -128,7 +128,7 @@ extension AEXMLElement { if !attributes.isEmpty { // insert known attributes in the specified order. - var attributes = self.attributes + var attributes = attributes for key in attributesOrder[name] ?? [] { if let value = attributes.removeValue(forKey: key) { print(key: key, value: value) diff --git a/Sources/XcodeProj/Extensions/Array+Extras.swift b/Sources/XcodeProj/Extensions/Array+Extras.swift index 310fc3e92..851c00554 100644 --- a/Sources/XcodeProj/Extensions/Array+Extras.swift +++ b/Sources/XcodeProj/Extensions/Array+Extras.swift @@ -1,13 +1,13 @@ import Foundation -extension Array where Element: Hashable { +public extension Array where Element: Hashable { /// Return the array with all duplicates removed. /// /// i.e. `[ 1, 2, 3, 1, 2 ].uniqued() == [ 1, 2, 3 ]` /// /// - note: Taken from stackoverflow.com/a/46354989/3141234, as /// per @Alexander's comment. - public func uniqued() -> [Element] { + func uniqued() -> [Element] { var seen = Set() return filter { seen.insert($0).inserted } } diff --git a/Sources/XcodeProj/Extensions/Path+Extras.swift b/Sources/XcodeProj/Extensions/Path+Extras.swift index 5279f9d0d..75d0f1547 100644 --- a/Sources/XcodeProj/Extensions/Path+Extras.swift +++ b/Sources/XcodeProj/Extensions/Path+Extras.swift @@ -1,17 +1,16 @@ import Foundation + // swiftlint:disable all import PathKit // MARK: - Path extras. - - func systemGlob(_ pattern: UnsafePointer!, _ flags: Int32, _ errfunc: (@convention(c) (UnsafePointer?, Int32) -> Int32)!, _ vector_ptr: UnsafeMutablePointer!) -> Int32 { -#if os(macOS) - return Darwin.glob(pattern, flags, errfunc, vector_ptr) -#else - return Glibc.glob(pattern, flags, errfunc, vector_ptr) -#endif + #if os(macOS) + return Darwin.glob(pattern, flags, errfunc, vector_ptr) + #else + return Glibc.glob(pattern, flags, errfunc, vector_ptr) + #endif } extension Path { @@ -39,9 +38,9 @@ extension Path { let flags = GLOB_TILDE | GLOB_BRACE | GLOB_MARK if systemGlob(cPattern, flags, nil, >) == 0 { #if os(macOS) - let matchc = gt.gl_matchc + let matchc = gt.gl_matchc #else - let matchc = gt.gl_pathc + let matchc = gt.gl_pathc #endif return (0 ..< Int(matchc)).compactMap { index in if let path = String(validatingUTF8: gt.gl_pathv[index]!) { diff --git a/Sources/XcodeProj/Extensions/String+Utils.swift b/Sources/XcodeProj/Extensions/String+Utils.swift index a9ac1a05e..51fc0bf35 100644 --- a/Sources/XcodeProj/Extensions/String+Utils.swift +++ b/Sources/XcodeProj/Extensions/String+Utils.swift @@ -4,22 +4,22 @@ import Foundation import SwiftGlibc public func arc4random_uniform(_ max: UInt32) -> Int32 { - (SwiftGlibc.rand() % Int32(max - 1)) + SwiftGlibc.rand() % Int32(max - 1) } #endif -extension String { - public var quoted: String { +public extension String { + var quoted: String { "\"\(self)\"" } - public var isQuoted: Bool { + var isQuoted: Bool { hasPrefix("\"") && hasSuffix("\"") } - public static func random(length: Int = 20) -> String { + static func random(length: Int = 20) -> String { let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" - var randomString: String = "" + var randomString = "" for _ in 0 ..< length { let randomValue = arc4random_uniform(UInt32(base.count)) diff --git a/Sources/XcodeProj/Extensions/String+md5.swift b/Sources/XcodeProj/Extensions/String+md5.swift index 8ffa9d1f5..1c0afa871 100644 --- a/Sources/XcodeProj/Extensions/String+md5.swift +++ b/Sources/XcodeProj/Extensions/String+md5.swift @@ -1,6 +1,6 @@ // swiftlint:disable all // -// String+MD5.swift +// String+md5.swift // Kingfisher // // To date, adding CommonCrypto to a Swift framework is problematic. See: @@ -22,7 +22,7 @@ import Foundation #if canImport(CryptoKit) -import CryptoKit + import CryptoKit #endif extension String { @@ -31,14 +31,14 @@ extension String { return self } #if canImport(CryptoKit) - if #available(OSX 10.15, *) { - return Insecure.MD5.hash(data: data) - .withUnsafeBytes { Array($0) }.hexString - } else { - return data.slowMD5 - } + if #available(OSX 10.15, *) { + return Insecure.MD5.hash(data: data) + .withUnsafeBytes { Array($0) }.hexString + } else { + return data.slowMD5 + } #else - return data.slowMD5 + return data.slowMD5 #endif } } @@ -48,11 +48,11 @@ private let char0 = UInt8(UnicodeScalar("0").value) private extension DataProtocol { var hexString: String { - let hexLen = self.count * 2 + let hexLen = count * 2 var hexChars = [UInt8](repeating: 0, count: hexLen) var offset = 0 - self.regions.forEach { (_) in + for _ in regions { for i in self { hexChars[Int(offset * 2)] = itoh((i >> 4) & 0xF) hexChars[Int(offset * 2 + 1)] = itoh(i & 0xF) @@ -64,7 +64,7 @@ private extension DataProtocol { } func itoh(_ value: UInt8) -> UInt8 { - return (value > 9) ? (charA + value - 10) : (char0 + value) + (value > 9) ? (charA + value - 10) : (char0 + value) } } @@ -91,7 +91,7 @@ func arrayOfBytes(_ value: T, length: Int? = nil) -> [UInt8] { let valuePointer = UnsafeMutablePointer.allocate(capacity: 1) valuePointer.pointee = value - let bytes = valuePointer.withMemoryRebound(to: UInt8.self, capacity: totalBytes) { (bytesPointer) -> [UInt8] in + let bytes = valuePointer.withMemoryRebound(to: UInt8.self, capacity: totalBytes) { bytesPointer -> [UInt8] in var bytes = [UInt8](repeating: 0, count: totalBytes) for j in 0 ..< min(MemoryLayout.size, totalBytes) { bytes[totalBytes - 1 - j] = (bytesPointer + j).pointee @@ -282,7 +282,7 @@ class MD5: HashProtocol { F = B ^ C ^ D g = (3 * j + 5) % 16 case 48 ... 63: - F = C ^ (B | (~D)) + F = C ^ (B | ~D) g = (7 * j) % 16 default: break @@ -303,8 +303,8 @@ class MD5: HashProtocol { var result = [UInt8]() result.reserveCapacity(hh.count / 4) - hh.forEach { - let itemLE = $0.littleEndian + for item in hh { + let itemLE = item.littleEndian let r1 = UInt8(itemLE & 0xFF) let r2 = UInt8((itemLE >> 8) & 0xFF) let r3 = UInt8((itemLE >> 16) & 0xFF) diff --git a/Sources/XcodeProj/Objects/BuildPhase/PBXBuildFile.swift b/Sources/XcodeProj/Objects/BuildPhase/PBXBuildFile.swift index 99e8c8445..5bf89bc25 100644 --- a/Sources/XcodeProj/Objects/BuildPhase/PBXBuildFile.swift +++ b/Sources/XcodeProj/Objects/BuildPhase/PBXBuildFile.swift @@ -114,28 +114,28 @@ extension PBXBuildFile { /// - Returns: build phase type. /// - Throws: an error if this method is called before the build file is added to any project. func getBuildPhase() throws -> PBXBuildPhase? { - if let buildPhase = buildPhase { + if let buildPhase { return buildPhase } let projectObjects = try objects() if let buildPhase = projectObjects.sourcesBuildPhases.values - .first(where: { $0.fileReferences?.map { $0.value }.contains(reference.value) == true }) { + .first(where: { $0.fileReferences?.map(\.value).contains(reference.value) == true }) { return buildPhase } else if let buildPhase = projectObjects.frameworksBuildPhases - .values.first(where: { $0.fileReferences?.map { $0.value }.contains(reference.value) == true }) { + .values.first(where: { $0.fileReferences?.map(\.value).contains(reference.value) == true }) { return buildPhase } else if let buildPhase = projectObjects .resourcesBuildPhases.values - .first(where: { $0.fileReferences?.map { $0.value }.contains(reference.value) == true }) { + .first(where: { $0.fileReferences?.map(\.value).contains(reference.value) == true }) { return buildPhase } else if let buildPhase = projectObjects.copyFilesBuildPhases - .values.first(where: { $0.fileReferences?.map { $0.value }.contains(reference.value) == true }) { + .values.first(where: { $0.fileReferences?.map(\.value).contains(reference.value) == true }) { return buildPhase } else if let buildPhase = projectObjects.headersBuildPhases - .values.first(where: { $0.fileReferences?.map { $0.value }.contains(reference.value) == true }) { + .values.first(where: { $0.fileReferences?.map(\.value).contains(reference.value) == true }) { return buildPhase } else if let buildPhase = projectObjects.carbonResourcesBuildPhases - .values.first(where: { $0.fileReferences?.map { $0.value }.contains(reference.value) == true }) { + .values.first(where: { $0.fileReferences?.map(\.value).contains(reference.value) == true }) { return buildPhase } return nil @@ -186,7 +186,7 @@ final class PBXBuildPhaseFile: PlistSerializable, Equatable { if let platformFilters = buildFile.platformFilters { dictionary["platformFilters"] = .array(platformFilters.map { .string(.init($0)) }) } - let comment = try buildPhase.name().flatMap { "\(try buildFile.fileName() ?? "(null)") in \($0)" } + let comment = try buildPhase.name().flatMap { try "\(buildFile.fileName() ?? "(null)") in \($0)" } return (key: CommentedString(reference, comment: comment), value: .dictionary(dictionary)) } diff --git a/Sources/XcodeProj/Objects/BuildPhase/PBXBuildPhase.swift b/Sources/XcodeProj/Objects/BuildPhase/PBXBuildPhase.swift index b6f261a19..953be5c8b 100644 --- a/Sources/XcodeProj/Objects/BuildPhase/PBXBuildPhase.swift +++ b/Sources/XcodeProj/Objects/BuildPhase/PBXBuildPhase.swift @@ -86,7 +86,7 @@ public class PBXBuildPhase: PBXContainerItem { override func plistValues(proj: PBXProj, reference: String) throws -> [CommentedString: PlistValue] { var dictionary = try super.plistValues(proj: proj, reference: reference) dictionary["buildActionMask"] = .string(CommentedString("\(buildActionMask)")) - if let fileReferences = fileReferences { + if let fileReferences { let files: PlistValue = .array(fileReferences.map { fileReference in let buildFile: PBXBuildFile? = fileReference.getObject() let name = buildFile.flatMap { try? $0.fileName() } ?? nil @@ -97,10 +97,10 @@ public class PBXBuildPhase: PBXContainerItem { }) dictionary["files"] = files } - if let inputFileListPaths = inputFileListPaths { + if let inputFileListPaths { dictionary["inputFileListPaths"] = .array(inputFileListPaths.map { .string(CommentedString($0)) }) } - if let outputFileListPaths = outputFileListPaths { + if let outputFileListPaths { dictionary["outputFileListPaths"] = .array(outputFileListPaths.map { .string(CommentedString($0)) }) } dictionary["runOnlyForDeploymentPostprocessing"] = .string(CommentedString("\(runOnlyForDeploymentPostprocessing.int)")) diff --git a/Sources/XcodeProj/Objects/BuildPhase/PBXBuildRule.swift b/Sources/XcodeProj/Objects/BuildPhase/PBXBuildRule.swift index 592cded4a..45b498078 100644 --- a/Sources/XcodeProj/Objects/BuildPhase/PBXBuildRule.swift +++ b/Sources/XcodeProj/Objects/BuildPhase/PBXBuildRule.swift @@ -18,7 +18,7 @@ public final class PBXBuildRule: PBXObject { /// Element name. public var name: String? - + /// The discovered dependency file to use public var dependencyFile: String? @@ -111,28 +111,28 @@ extension PBXBuildRule: PlistSerializable { var dictionary: [CommentedString: PlistValue] = [:] dictionary["isa"] = .string(CommentedString(PBXBuildRule.isa)) dictionary["compilerSpec"] = .string(CommentedString(compilerSpec)) - if let dependencyFile = dependencyFile { + if let dependencyFile { dictionary["dependencyFile"] = .string(CommentedString(dependencyFile)) } - if let filePatterns = filePatterns { + if let filePatterns { dictionary["filePatterns"] = .string(CommentedString(filePatterns)) } dictionary["fileType"] = .string(CommentedString(fileType)) dictionary["isEditable"] = .string(CommentedString("\(isEditable.int)")) - if let name = name { + if let name { dictionary["name"] = .string(CommentedString(name)) } dictionary["outputFiles"] = .array(outputFiles.map { .string(CommentedString($0)) }) - if let inputFiles = inputFiles { + if let inputFiles { dictionary["inputFiles"] = .array(inputFiles.map { .string(CommentedString($0)) }) } - if let outputFilesCompilerFlags = outputFilesCompilerFlags { + if let outputFilesCompilerFlags { dictionary["outputFilesCompilerFlags"] = .array(outputFilesCompilerFlags.map { PlistValue.string(CommentedString($0)) }) } - if let script = script { + if let script { dictionary["script"] = .string(CommentedString(script)) } - if let runOncePerArchitecture = runOncePerArchitecture { + if let runOncePerArchitecture { dictionary["runOncePerArchitecture"] = .string(CommentedString("\(runOncePerArchitecture.int)")) } return (key: CommentedString(reference, comment: PBXBuildRule.isa), diff --git a/Sources/XcodeProj/Objects/BuildPhase/PBXCopyFilesBuildPhase.swift b/Sources/XcodeProj/Objects/BuildPhase/PBXCopyFilesBuildPhase.swift index 2c30cc9ae..0fa51e1cf 100644 --- a/Sources/XcodeProj/Objects/BuildPhase/PBXCopyFilesBuildPhase.swift +++ b/Sources/XcodeProj/Objects/BuildPhase/PBXCopyFilesBuildPhase.swift @@ -84,13 +84,13 @@ extension PBXCopyFilesBuildPhase: PlistSerializable { func plistKeyAndValue(proj: PBXProj, reference: String) throws -> (key: CommentedString, value: PlistValue) { var dictionary: [CommentedString: PlistValue] = try plistValues(proj: proj, reference: reference) dictionary["isa"] = .string(CommentedString(PBXCopyFilesBuildPhase.isa)) - if let dstPath = dstPath { + if let dstPath { dictionary["dstPath"] = .string(CommentedString(dstPath)) } - if let name = name { + if let name { dictionary["name"] = .string(CommentedString(name)) } - if let dstSubfolderSpec = dstSubfolderSpec { + if let dstSubfolderSpec { dictionary["dstSubfolderSpec"] = .string(CommentedString("\(dstSubfolderSpec.rawValue)")) } return (key: CommentedString(reference, comment: name ?? "CopyFiles"), value: .dictionary(dictionary)) diff --git a/Sources/XcodeProj/Objects/BuildPhase/PBXShellScriptBuildPhase.swift b/Sources/XcodeProj/Objects/BuildPhase/PBXShellScriptBuildPhase.swift index 6cfc30fc7..4790dc45f 100644 --- a/Sources/XcodeProj/Objects/BuildPhase/PBXShellScriptBuildPhase.swift +++ b/Sources/XcodeProj/Objects/BuildPhase/PBXShellScriptBuildPhase.swift @@ -91,8 +91,8 @@ public final class PBXShellScriptBuildPhase: PBXBuildPhase { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) name = try container.decodeIfPresent(.name) - inputPaths = (try container.decodeIfPresent(.inputPaths)) ?? [] - outputPaths = (try container.decodeIfPresent(.outputPaths)) ?? [] + inputPaths = try (container.decodeIfPresent(.inputPaths)) ?? [] + outputPaths = try (container.decodeIfPresent(.outputPaths)) ?? [] shellPath = try container.decodeIfPresent(.shellPath) shellScript = try container.decodeIfPresent(.shellScript) showEnvVarsInLog = try container.decodeIntBoolIfPresent(.showEnvVarsInLog) ?? true @@ -113,18 +113,18 @@ extension PBXShellScriptBuildPhase: PlistSerializable { func plistKeyAndValue(proj: PBXProj, reference: String) throws -> (key: CommentedString, value: PlistValue) { var dictionary: [CommentedString: PlistValue] = try plistValues(proj: proj, reference: reference) dictionary["isa"] = .string(CommentedString(PBXShellScriptBuildPhase.isa)) - if let shellPath = shellPath { + if let shellPath { dictionary["shellPath"] = .string(CommentedString(shellPath)) } dictionary["inputPaths"] = .array(inputPaths.map { .string(CommentedString($0)) }) - if let name = name { + if let name { dictionary["name"] = .string(CommentedString(name)) } dictionary["outputPaths"] = .array(outputPaths.map { .string(CommentedString($0)) }) - if let shellScript = shellScript { + if let shellScript { dictionary["shellScript"] = .string(CommentedString(shellScript)) } - if let dependencyFile = dependencyFile { + if let dependencyFile { dictionary["dependencyFile"] = .string(CommentedString(dependencyFile)) } if !showEnvVarsInLog { diff --git a/Sources/XcodeProj/Objects/Configuration/XCBuildConfiguration.swift b/Sources/XcodeProj/Objects/Configuration/XCBuildConfiguration.swift index 468984cc4..71e05c3dc 100644 --- a/Sources/XcodeProj/Objects/Configuration/XCBuildConfiguration.swift +++ b/Sources/XcodeProj/Objects/Configuration/XCBuildConfiguration.swift @@ -13,7 +13,7 @@ public final class XCBuildConfiguration: PBXObject { baseConfigurationReference?.getObject() } set { - if let newValue = newValue { + if let newValue { baseConfigurationReference = newValue.reference } } @@ -104,7 +104,7 @@ extension XCBuildConfiguration: PlistSerializable { dictionary["isa"] = .string(CommentedString(XCBuildConfiguration.isa)) dictionary["name"] = .string(CommentedString(name)) dictionary["buildSettings"] = buildSettings.plist() - if let baseConfigurationReference = baseConfigurationReference { + if let baseConfigurationReference { let fileElement: PBXFileElement? = baseConfigurationReference.getObject() dictionary["baseConfigurationReference"] = .string(CommentedString(baseConfigurationReference.value, comment: fileElement?.fileName())) } diff --git a/Sources/XcodeProj/Objects/Configuration/XCConfigurationList.swift b/Sources/XcodeProj/Objects/Configuration/XCConfigurationList.swift index 0bf2cfe35..8cf06af86 100644 --- a/Sources/XcodeProj/Objects/Configuration/XCConfigurationList.swift +++ b/Sources/XcodeProj/Objects/Configuration/XCConfigurationList.swift @@ -68,19 +68,19 @@ public final class XCConfigurationList: PBXObject { // MARK: - Helpers -extension XCConfigurationList { +public extension XCConfigurationList { /// Returns the build configuration with the given name (if it exists) /// /// - Parameter name: configuration name. /// - Returns: build configuration if it exists. - public func configuration(name: String) -> XCBuildConfiguration? { + func configuration(name: String) -> XCBuildConfiguration? { buildConfigurations.first(where: { $0.name == name }) } /// Adds the default configurations, debug and release /// /// - Returns: the created configurations. - public func addDefaultConfigurations() throws -> [XCBuildConfiguration] { + func addDefaultConfigurations() throws -> [XCBuildConfiguration] { var configurations: [XCBuildConfiguration] = [] let debug = XCBuildConfiguration(name: "Debug") @@ -99,7 +99,7 @@ extension XCConfigurationList { /// /// - Parameter reference: configuration list reference. /// - Returns: target or project with the given configuration list. - public func objectWithConfigurationList() throws -> PBXObject? { + func objectWithConfigurationList() throws -> PBXObject? { let projectObjects = try objects() return projectObjects.projects.first(where: { $0.value.buildConfigurationListReference == reference })?.value ?? projectObjects.nativeTargets.first(where: { $0.value.buildConfigurationListReference == reference })?.value ?? @@ -120,11 +120,11 @@ extension XCConfigurationList: PlistSerializable { return .string(CommentedString(configReference.value, comment: config?.name)) }) dictionary["defaultConfigurationIsVisible"] = .string(CommentedString("\(defaultConfigurationIsVisible.int)")) - if let defaultConfigurationName = defaultConfigurationName { + if let defaultConfigurationName { dictionary["defaultConfigurationName"] = .string(CommentedString(defaultConfigurationName)) } - return (key: CommentedString(reference, comment: try plistComment()), - value: .dictionary(dictionary)) + return try (key: CommentedString(reference, comment: plistComment()), + value: .dictionary(dictionary)) } private func plistComment() throws -> String? { diff --git a/Sources/XcodeProj/Objects/Files/PBXContainerItem.swift b/Sources/XcodeProj/Objects/Files/PBXContainerItem.swift index 2e11f9039..dfc68661e 100644 --- a/Sources/XcodeProj/Objects/Files/PBXContainerItem.swift +++ b/Sources/XcodeProj/Objects/Files/PBXContainerItem.swift @@ -26,7 +26,7 @@ public class PBXContainerItem: PBXObject { func plistValues(proj _: PBXProj, reference _: String) throws -> [CommentedString: PlistValue] { var dictionary = [CommentedString: PlistValue]() - if let comments = comments { + if let comments { dictionary["comments"] = .string(CommentedString(comments)) } return dictionary diff --git a/Sources/XcodeProj/Objects/Files/PBXContainerItemProxy.swift b/Sources/XcodeProj/Objects/Files/PBXContainerItemProxy.swift index f244aeada..014bc3eea 100644 --- a/Sources/XcodeProj/Objects/Files/PBXContainerItemProxy.swift +++ b/Sources/XcodeProj/Objects/Files/PBXContainerItemProxy.swift @@ -156,13 +156,13 @@ extension PBXContainerItemProxy: PlistSerializable { var dictionary: [CommentedString: PlistValue] = [:] dictionary["isa"] = .string(CommentedString(PBXContainerItemProxy.isa)) dictionary["containerPortal"] = .string(CommentedString(containerPortalReference.value, comment: containerPortal.comment)) - if let proxyType = proxyType { + if let proxyType { dictionary["proxyType"] = .string(CommentedString("\(proxyType.rawValue)")) } - if let remoteGlobalID = remoteGlobalID { + if let remoteGlobalID { dictionary["remoteGlobalIDString"] = .string(CommentedString(remoteGlobalID.uuid)) } - if let remoteInfo = remoteInfo { + if let remoteInfo { dictionary["remoteInfo"] = .string(CommentedString(remoteInfo)) } return (key: CommentedString(reference, diff --git a/Sources/XcodeProj/Objects/Files/PBXFileElement.swift b/Sources/XcodeProj/Objects/Files/PBXFileElement.swift index 573e8ee8e..5f3e80dca 100644 --- a/Sources/XcodeProj/Objects/Files/PBXFileElement.swift +++ b/Sources/XcodeProj/Objects/Files/PBXFileElement.swift @@ -98,29 +98,29 @@ public class PBXFileElement: PBXContainerItem, PlistSerializable { func plistKeyAndValue(proj _: PBXProj, reference: String) throws -> (key: CommentedString, value: PlistValue) { var dictionary: [CommentedString: PlistValue] = [:] dictionary["isa"] = .string(CommentedString(PBXFileElement.isa)) - if let name = name { + if let name { dictionary["name"] = .string(CommentedString(name)) } - if let path = path { + if let path { dictionary["path"] = .string(CommentedString(path)) } - if let sourceTree = sourceTree { + if let sourceTree { dictionary["sourceTree"] = sourceTree.plist() } - if let includeInIndex = includeInIndex { + if let includeInIndex { dictionary["includeInIndex"] = .string(CommentedString("\(includeInIndex.int)")) } - if let usesTabs = usesTabs { + if let usesTabs { dictionary["usesTabs"] = .string(CommentedString("\(usesTabs.int)")) } - if let indentWidth = indentWidth { + if let indentWidth { dictionary["indentWidth"] = .string(CommentedString("\(indentWidth)")) } - if let tabWidth = tabWidth { + if let tabWidth { dictionary["tabWidth"] = .string(CommentedString("\(tabWidth)")) } - if let wrapsLines = wrapsLines { + if let wrapsLines { dictionary["wrapsLines"] = .string(CommentedString("\(wrapsLines.int)")) } return (key: CommentedString(reference, @@ -173,7 +173,7 @@ public extension PBXFileElement { let projectObjects = try objects() let isThisElementRoot = projectObjects.projects.values.first(where: { $0.mainGroup == self }) != nil if isThisElementRoot { - if let path = path { + if let path { return sourceRoot + Path(path) } return sourceRoot diff --git a/Sources/XcodeProj/Objects/Files/PBXFileReference.swift b/Sources/XcodeProj/Objects/Files/PBXFileReference.swift index a1a0ff35f..9595e2536 100644 --- a/Sources/XcodeProj/Objects/Files/PBXFileReference.swift +++ b/Sources/XcodeProj/Objects/Files/PBXFileReference.swift @@ -110,25 +110,25 @@ public final class PBXFileReference: PBXFileElement { override func plistKeyAndValue(proj: PBXProj, reference: String) throws -> (key: CommentedString, value: PlistValue) { var dictionary: [CommentedString: PlistValue] = try super.plistKeyAndValue(proj: proj, reference: reference).value.dictionary ?? [:] dictionary["isa"] = .string(CommentedString(PBXFileReference.isa)) - if let lastKnownFileType = lastKnownFileType { + if let lastKnownFileType { dictionary["lastKnownFileType"] = .string(CommentedString(lastKnownFileType)) } - if let fileEncoding = fileEncoding { + if let fileEncoding { dictionary["fileEncoding"] = .string(CommentedString("\(fileEncoding)")) } - if let explicitFileType = self.explicitFileType { + if let explicitFileType { dictionary["explicitFileType"] = .string(CommentedString(explicitFileType)) } - if let lineEnding = lineEnding { + if let lineEnding { dictionary["lineEnding"] = .string(CommentedString("\(lineEnding)")) } - if let languageSpecificationIdentifier = languageSpecificationIdentifier { + if let languageSpecificationIdentifier { dictionary["languageSpecificationIdentifier"] = .string(CommentedString(languageSpecificationIdentifier)) } - if let xcLanguageSpecificationIdentifier = xcLanguageSpecificationIdentifier { + if let xcLanguageSpecificationIdentifier { dictionary["xcLanguageSpecificationIdentifier"] = .string(CommentedString(xcLanguageSpecificationIdentifier)) } - if let plistStructureDefinitionIdentifier = plistStructureDefinitionIdentifier { + if let plistStructureDefinitionIdentifier { dictionary["plistStructureDefinitionIdentifier"] = .string(CommentedString(plistStructureDefinitionIdentifier)) } return (key: CommentedString(reference, comment: name ?? path), diff --git a/Sources/XcodeProj/Objects/Files/PBXGroup.swift b/Sources/XcodeProj/Objects/Files/PBXGroup.swift index 34add940c..05cece653 100644 --- a/Sources/XcodeProj/Objects/Files/PBXGroup.swift +++ b/Sources/XcodeProj/Objects/Files/PBXGroup.swift @@ -61,7 +61,7 @@ public class PBXGroup: PBXFileElement { let objects = decoder.context.objects let objectReferenceRepository = decoder.context.objectReferenceRepository let container = try decoder.container(keyedBy: CodingKeys.self) - let childrenReferences: [String] = (try container.decodeIfPresent(.children)) ?? [] + let childrenReferences: [String] = try (container.decodeIfPresent(.children)) ?? [] self.childrenReferences = childrenReferences.map { objectReferenceRepository.getOrCreate(reference: $0, objects: objects) } try super.init(from: decoder) } @@ -71,7 +71,7 @@ public class PBXGroup: PBXFileElement { override func plistKeyAndValue(proj: PBXProj, reference: String) throws -> (key: CommentedString, value: PlistValue) { var dictionary: [CommentedString: PlistValue] = try super.plistKeyAndValue(proj: proj, reference: reference).value.dictionary ?? [:] dictionary["isa"] = .string(CommentedString(type(of: self).isa)) - dictionary["children"] = .array(childrenReferences.map { (fileReference) -> PlistValue in + dictionary["children"] = .array(childrenReferences.map { fileReference -> PlistValue in let fileElement: PBXFileElement? = fileReference.getObject() return .string(CommentedString(fileReference.value, comment: fileElement?.fileName())) }) @@ -134,7 +134,7 @@ public extension PBXGroup { /// - Returns: created groups. @discardableResult func addGroup(named groupName: String, options: GroupAddingOptions = []) throws -> [PBXGroup] { - let objects = try self.objects() + let objects = try objects() return groupName.components(separatedBy: "/").reduce(into: [PBXGroup]()) { groups, name in let group = groups.last ?? self let newGroup = PBXGroup(children: [], sourceTree: .group, name: name, path: options.contains(.withoutFolder) ? nil : name) @@ -152,7 +152,7 @@ public extension PBXGroup { /// - Returns: created groups. @discardableResult func addVariantGroup(named groupName: String) throws -> [PBXVariantGroup] { - let objects = try self.objects() + let objects = try objects() return groupName.components(separatedBy: "/").reduce(into: [PBXVariantGroup]()) { groups, name in let group = groups.last ?? self diff --git a/Sources/XcodeProj/Objects/Files/XCVersionGroup.swift b/Sources/XcodeProj/Objects/Files/XCVersionGroup.swift index 3087294f2..d548a01ec 100644 --- a/Sources/XcodeProj/Objects/Files/XCVersionGroup.swift +++ b/Sources/XcodeProj/Objects/Files/XCVersionGroup.swift @@ -87,10 +87,10 @@ public final class XCVersionGroup: PBXGroup { override func plistKeyAndValue(proj: PBXProj, reference: String) throws -> (key: CommentedString, value: PlistValue) { var dictionary: [CommentedString: PlistValue] = try super.plistKeyAndValue(proj: proj, reference: reference).value.dictionary ?? [:] dictionary["isa"] = .string(CommentedString(XCVersionGroup.isa)) - if let versionGroupType = versionGroupType { + if let versionGroupType { dictionary["versionGroupType"] = .string(CommentedString(versionGroupType)) } - if let currentVersionReference = currentVersionReference { + if let currentVersionReference { let fileElement: PBXFileElement? = currentVersionReference.getObject() dictionary["currentVersion"] = .string(CommentedString(currentVersionReference.value, comment: fileElement?.fileName())) } diff --git a/Sources/XcodeProj/Objects/Project/PBXObjectReference.swift b/Sources/XcodeProj/Objects/Project/PBXObjectReference.swift index c72a943af..3f544af26 100644 --- a/Sources/XcodeProj/Objects/Project/PBXObjectReference.swift +++ b/Sources/XcodeProj/Objects/Project/PBXObjectReference.swift @@ -54,7 +54,7 @@ class PBXObjectReference: NSObject, Comparable, NSCopying { let object = objects?.delete(reference: self) self.value = value temporary = false - if let object = object { + if let object { objects?.add(object: object) } } @@ -64,7 +64,7 @@ class PBXObjectReference: NSObject, Comparable, NSCopying { let object = objects?.delete(reference: self) value = "TEMP_\(UUID().uuidString)" temporary = true - if let object = object { + if let object { objects?.add(object: object) } } @@ -130,7 +130,7 @@ class PBXObjectReference: NSObject, Comparable, NSCopying { if let object = object as? T { return object } - guard let objects = objects else { + guard let objects else { throw PBXObjectError.objectsReleased } guard let object = objects.get(reference: self) as? T else { @@ -143,7 +143,7 @@ class PBXObjectReference: NSObject, Comparable, NSCopying { extension Array where Element: PBXObject { func references() -> [PBXObjectReference] { - map { $0.reference } + map(\.reference) } } diff --git a/Sources/XcodeProj/Objects/Project/PBXObjects.swift b/Sources/XcodeProj/Objects/Project/PBXObjects.swift index 5f8a568f4..5fbf74e1a 100644 --- a/Sources/XcodeProj/Objects/Project/PBXObjects.swift +++ b/Sources/XcodeProj/Objects/Project/PBXObjects.swift @@ -142,8 +142,8 @@ class PBXObjects: Equatable { /// - Parameters: /// - objects: project objects init(objects: [PBXObject] = []) { - objects.forEach { - self.add(object: $0) + for item in objects { + add(object: item) } } @@ -194,7 +194,6 @@ class PBXObjects: Equatable { // subclasses of PBXGroup; must be tested before PBXGroup case let object as PBXVariantGroup: _variantGroups[objectReference] = object case let object as XCVersionGroup: _versionGroups[objectReference] = object - // everything else case let object as PBXBuildFile: _buildFiles[objectReference] = object case let object as PBXAggregateTarget: _aggregateTargets[objectReference] = object @@ -219,7 +218,6 @@ class PBXObjects: Equatable { case let object as XCRemoteSwiftPackageReference: _remoteSwiftPackageReferences[objectReference] = object case let object as XCLocalSwiftPackageReference: _localSwiftPackageReferences[objectReference] = object case let object as XCSwiftPackageProductDependency: _swiftPackageProductDependencies[objectReference] = object - default: fatalError("Unhandled PBXObject type for \(object), this is likely a bug / todo") } } diff --git a/Sources/XcodeProj/Objects/Project/PBXOutputSettings.swift b/Sources/XcodeProj/Objects/Project/PBXOutputSettings.swift index 77bf7b7ec..0d82fb228 100644 --- a/Sources/XcodeProj/Objects/Project/PBXOutputSettings.swift +++ b/Sources/XcodeProj/Objects/Project/PBXOutputSettings.swift @@ -39,12 +39,12 @@ public enum PBXFileOrder { /// Sort files by their file name. This is a case sensistive sort with lower case names coming after uppercase names. case byFilename - internal func sort(lhs: (PBXObjectReference, Object), rhs: (PBXObjectReference, Object)) -> Bool + func sort(lhs: (PBXObjectReference, Object), rhs: (PBXObjectReference, Object)) -> Bool where Object: PlistSerializable & Equatable { lhs.0 < rhs.0 } - internal func sort(lhs: (PBXObjectReference, PBXBuildFile), rhs: (PBXObjectReference, PBXBuildFile)) -> Bool { + func sort(lhs: (PBXObjectReference, PBXBuildFile), rhs: (PBXObjectReference, PBXBuildFile)) -> Bool { switch self { case .byFilename: return sortBuildFilesByName(lhs.1, rhs.1) @@ -53,7 +53,7 @@ public enum PBXFileOrder { } } - internal func sort(lhs: (PBXObjectReference, PBXBuildPhaseFile), rhs: (PBXObjectReference, PBXBuildPhaseFile)) -> Bool { + func sort(lhs: (PBXObjectReference, PBXBuildPhaseFile), rhs: (PBXObjectReference, PBXBuildPhaseFile)) -> Bool { switch self { case .byFilename: return sortBuildFilesByName(lhs.1.buildFile, rhs.1.buildFile) @@ -62,7 +62,7 @@ public enum PBXFileOrder { } } - internal func sort(lhs: (PBXObjectReference, PBXFileReference), rhs: (PBXObjectReference, PBXFileReference)) -> Bool { + func sort(lhs: (PBXObjectReference, PBXFileReference), rhs: (PBXObjectReference, PBXFileReference)) -> Bool { switch self { case .byFilename: return sortFileElementsByName(lhs.1, rhs.1) @@ -94,7 +94,7 @@ public enum PBXNavigatorFileOrder { /// Sorts the files by their file names with all groups appear at the top of the list. case byFilenameGroupsFirst - internal var sort: ((PBXFileElement, PBXFileElement) -> Bool)? { + var sort: ((PBXFileElement, PBXFileElement) -> Bool)? { switch self { case .byFilename: return { sortFileElementsByName($0, $1) } @@ -122,7 +122,7 @@ public enum PBXBuildPhaseFileOrder { /// Sort the files by their file name. This is a case sensitive sort with uppercase names appearing before lowercase names. case byFilename - internal var sort: ((PBXBuildFile, PBXBuildFile) -> Bool)? { + var sort: ((PBXBuildFile, PBXBuildFile) -> Bool)? { switch self { case .byFilename: return { lhs, rhs in diff --git a/Sources/XcodeProj/Objects/Project/PBXProj.swift b/Sources/XcodeProj/Objects/Project/PBXProj.swift index 6248aed4e..48a6ee367 100644 --- a/Sources/XcodeProj/Objects/Project/PBXProj.swift +++ b/Sources/XcodeProj/Objects/Project/PBXProj.swift @@ -66,7 +66,7 @@ public final class PBXProj: Decodable { objects: pbxproj.objects ) } - + /// Initializes the project with the data representation of pbxproj file. /// /// - Parameters: @@ -331,7 +331,7 @@ extension PBXProj: Writable { let encoder = PBXProjEncoder(outputSettings: PBXOutputSettings()) return try encoder.encode(proj: self).data(using: .utf8) } - + public func write(path: Path, override: Bool) throws { try write(path: path, override: override, outputSettings: PBXOutputSettings()) } diff --git a/Sources/XcodeProj/Objects/Project/PBXProjEncoder.swift b/Sources/XcodeProj/Objects/Project/PBXProjEncoder.swift index 771e38973..9b0dd2f26 100644 --- a/Sources/XcodeProj/Objects/Project/PBXProjEncoder.swift +++ b/Sources/XcodeProj/Objects/Project/PBXProjEncoder.swift @@ -238,7 +238,7 @@ final class PBXProjEncoder { rootObject.value, comment: "Project object" ) - ), stateHolder: &stateHolder, to: &output) + ), stateHolder: &stateHolder, to: &output) writeDictionaryEnd(stateHolder: &stateHolder, to: &output) writeNewLine(stateHolder: &stateHolder, to: &output) @@ -287,12 +287,12 @@ final class PBXProjEncoder { output.append("/* \(comment) */") } - private func write(section: String, - proj: PBXProj, - objects: [PBXObjectReference: T], - outputSettings: PBXOutputSettings, - stateHolder: inout StateHolder, - to output: inout [String]) throws where T: PlistSerializable & Equatable { + private func write(section: String, + proj: PBXProj, + objects: [PBXObjectReference: some PlistSerializable & Equatable], + outputSettings: PBXOutputSettings, + stateHolder: inout StateHolder, + to output: inout [String]) throws { try write(section: section, proj: proj, objects: objects, sort: outputSettings.projFileListOrder.sort, stateHolder: &stateHolder, to: &output) } @@ -367,7 +367,7 @@ final class PBXProjEncoder { stateHolder: inout StateHolder, to output: inout [String]) { writeDictionaryStart(stateHolder: &stateHolder, to: &output) - let sorted = dictionary.sorted(by: { (left, right) -> Bool in + let sorted = dictionary.sorted(by: { left, right -> Bool in if left.key == "isa" { return true } else if right.key == "isa" { @@ -376,9 +376,9 @@ final class PBXProjEncoder { return left.key.string < right.key.string } }) - sorted.forEach { - write(dictionaryKey: $0.key, - dictionaryValue: $0.value, + for item in sorted { + write(dictionaryKey: item.key, + dictionaryValue: item.value, multiline: stateHolder.multiline, stateHolder: &stateHolder, to: &output) diff --git a/Sources/XcodeProj/Objects/Project/PBXProject.swift b/Sources/XcodeProj/Objects/Project/PBXProject.swift index 9a2ccd661..79a3e1485 100644 --- a/Sources/XcodeProj/Objects/Project/PBXProject.swift +++ b/Sources/XcodeProj/Objects/Project/PBXProject.swift @@ -111,14 +111,14 @@ public final class PBXProject: PBXObject { public var targetAttributes: [PBXTarget: [String: Any]] { set { targetAttributeReferences = [:] - newValue.forEach { - targetAttributeReferences[$0.key.reference] = $0.value + for item in newValue { + targetAttributeReferences[item.key.reference] = item.value } } get { var attributes: [PBXTarget: [String: Any]] = [:] - targetAttributeReferences.forEach { - if let object: PBXTarget = $0.key.getObject() { - attributes[object] = $0.value + for targetAttributeReference in targetAttributeReferences { + if let object: PBXTarget = targetAttributeReference.key.getObject() { + attributes[object] = targetAttributeReference.value } } return attributes @@ -205,7 +205,7 @@ public final class PBXProject: PBXObject { productName: String, versionRequirement: XCRemoteSwiftPackageReference.VersionRequirement, targetName: String) throws -> XCRemoteSwiftPackageReference { - let objects = try self.objects() + let objects = try objects() guard let target = targets.first(where: { $0.name == targetName }) else { throw PBXProjError.targetNotFound(targetName: targetName) } @@ -243,7 +243,7 @@ public final class PBXProject: PBXObject { addFileReference: Bool = true) throws -> XCSwiftPackageProductDependency { guard path.isRelative else { throw PBXProjError.pathIsAbsolute(path) } - let objects = try self.objects() + let objects = try objects() guard let target = targets.first(where: { $0.name == targetName }) else { throw PBXProjError.targetNotFound(targetName: targetName) } @@ -356,14 +356,14 @@ public final class PBXProject: PBXObject { let container = try decoder.container(keyedBy: CodingKeys.self) let referenceRepository = decoder.context.objectReferenceRepository let objects = decoder.context.objects - name = (try container.decodeIfPresent(.name)) ?? "" + name = try (container.decodeIfPresent(.name)) ?? "" let buildConfigurationListReference: String = try container.decode(.buildConfigurationList) self.buildConfigurationListReference = referenceRepository.getOrCreate(reference: buildConfigurationListReference, objects: objects) compatibilityVersion = try container.decode(.compatibilityVersion) developmentRegion = try container.decodeIfPresent(.developmentRegion) let hasScannedForEncodingsString: String? = try container.decodeIfPresent(.hasScannedForEncodings) hasScannedForEncodings = hasScannedForEncodingsString.flatMap { Int($0) } ?? 0 - knownRegions = (try container.decodeIfPresent(.knownRegions)) ?? [] + knownRegions = try (container.decodeIfPresent(.knownRegions)) ?? [] let mainGroupReference: String = try container.decode(.mainGroup) self.mainGroupReference = referenceRepository.getOrCreate(reference: mainGroupReference, objects: objects) if let productRefGroupReference: String = try container.decodeIfPresent(.productRefGroup) { @@ -372,7 +372,7 @@ public final class PBXProject: PBXObject { productsGroupReference = nil } projectDirPath = try container.decodeIfPresent(.projectDirPath) ?? "" - let projectReferences: [[String: String]] = (try container.decodeIfPresent(.projectReferences)) ?? [] + let projectReferences: [[String: String]] = try (container.decodeIfPresent(.projectReferences)) ?? [] self.projectReferences = projectReferences.map { references in references.mapValues { referenceRepository.getOrCreate(reference: $0, objects: objects) } } @@ -383,13 +383,13 @@ public final class PBXProject: PBXObject { } else { projectRoots = [] } - let targetReferences: [String] = (try container.decodeIfPresent(.targets)) ?? [] + let targetReferences: [String] = try (container.decodeIfPresent(.targets)) ?? [] self.targetReferences = targetReferences.map { referenceRepository.getOrCreate(reference: $0, objects: objects) } let packageRefeferenceStrings: [String] = try container.decodeIfPresent(.packageReferences) ?? [] packageReferences = packageRefeferenceStrings.map { referenceRepository.getOrCreate(reference: $0, objects: objects) } - var attributes = (try container.decodeIfPresent([String: Any].self, forKey: .attributes) ?? [:]) + var attributes = try (container.decodeIfPresent([String: Any].self, forKey: .attributes) ?? [:]) var targetAttributeReferences: [PBXObjectReference: [String: Any]] = [:] if let targetAttributes = attributes[PBXProject.targetAttributesKey] as? [String: [String: Any]] { targetAttributes.forEach { targetAttributeReferences[referenceRepository.getOrCreate(reference: $0.key, objects: objects)] = $0.value } @@ -433,7 +433,7 @@ extension PBXProject { private func addSwiftPackageProduct(reference: XCRemoteSwiftPackageReference, productName: String, target: PBXTarget) throws -> XCSwiftPackageProductDependency { - let objects = try self.objects() + let objects = try objects() let productDependency: XCSwiftPackageProductDependency // Avoid duplication @@ -452,7 +452,7 @@ extension PBXProject { private func addLocalSwiftPackageProduct(path: Path, productName: String, target: PBXTarget) throws -> XCSwiftPackageProductDependency { - let objects = try self.objects() + let objects = try objects() let productDependency: XCSwiftPackageProductDependency // Avoid duplication @@ -483,7 +483,7 @@ extension PBXProject: PlistSerializable { comment: buildConfigurationListComment) dictionary["buildConfigurationList"] = .string(buildConfigurationListCommentedString) dictionary["compatibilityVersion"] = .string(CommentedString(compatibilityVersion)) - if let developmentRegion = developmentRegion { + if let developmentRegion { dictionary["developmentRegion"] = .string(CommentedString(developmentRegion)) } dictionary["hasScannedForEncodings"] = .string(CommentedString("\(hasScannedForEncodings)")) @@ -494,7 +494,7 @@ extension PBXProject: PlistSerializable { } let mainGroupObject: PBXGroup? = mainGroupReference.getObject() dictionary["mainGroup"] = .string(CommentedString(mainGroupReference.value, comment: mainGroupObject?.fileName())) - if let productsGroupReference = productsGroupReference { + if let productsGroupReference { let productRefGroupObject: PBXGroup? = productsGroupReference.getObject() dictionary["productRefGroup"] = .string(CommentedString(productsGroupReference.value, comment: productRefGroupObject?.fileName())) @@ -550,7 +550,8 @@ extension PBXProject: PlistSerializable { } return .array(projectReferences.compactMap { reference in guard let productGroupReference = reference[Xcode.ProjectReference.productGroupKey], - let projectRef = reference[Xcode.ProjectReference.projectReferenceKey] else { + let projectRef = reference[Xcode.ProjectReference.projectReferenceKey] + else { return nil } let producGroup: PBXGroup? = productGroupReference.getObject() diff --git a/Sources/XcodeProj/Objects/Sourcery/Equality.generated.swift b/Sources/XcodeProj/Objects/Sourcery/Equality.generated.swift index 5d2a1943f..c20d93c20 100644 --- a/Sources/XcodeProj/Objects/Sourcery/Equality.generated.swift +++ b/Sources/XcodeProj/Objects/Sourcery/Equality.generated.swift @@ -6,7 +6,7 @@ import Foundation extension PBXAggregateTarget { /// :nodoc: func isEqual(to rhs: PBXAggregateTarget) -> Bool { - return super.isEqual(to: rhs) + super.isEqual(to: rhs) } } @@ -113,7 +113,7 @@ extension PBXFileReference { extension PBXFrameworksBuildPhase { /// :nodoc: func isEqual(to rhs: PBXFrameworksBuildPhase) -> Bool { - return super.isEqual(to: rhs) + super.isEqual(to: rhs) } } @@ -128,7 +128,7 @@ extension PBXGroup { extension PBXHeadersBuildPhase { /// :nodoc: func isEqual(to rhs: PBXHeadersBuildPhase) -> Bool { - return super.isEqual(to: rhs) + super.isEqual(to: rhs) } } @@ -187,14 +187,14 @@ extension PBXReferenceProxy { extension PBXResourcesBuildPhase { /// :nodoc: func isEqual(to rhs: PBXResourcesBuildPhase) -> Bool { - return super.isEqual(to: rhs) + super.isEqual(to: rhs) } } extension PBXRezBuildPhase { /// :nodoc: func isEqual(to rhs: PBXRezBuildPhase) -> Bool { - return super.isEqual(to: rhs) + super.isEqual(to: rhs) } } @@ -216,7 +216,7 @@ extension PBXShellScriptBuildPhase { extension PBXSourcesBuildPhase { /// :nodoc: func isEqual(to rhs: PBXSourcesBuildPhase) -> Bool { - return super.isEqual(to: rhs) + super.isEqual(to: rhs) } } @@ -251,7 +251,7 @@ extension PBXTargetDependency { extension PBXVariantGroup { /// :nodoc: func isEqual(to rhs: PBXVariantGroup) -> Bool { - return super.isEqual(to: rhs) + super.isEqual(to: rhs) } } diff --git a/Sources/XcodeProj/Objects/SwiftPackage/XCRemoteSwiftPackageReference.swift b/Sources/XcodeProj/Objects/SwiftPackage/XCRemoteSwiftPackageReference.swift index 78b4a86f3..3f8a40001 100644 --- a/Sources/XcodeProj/Objects/SwiftPackage/XCRemoteSwiftPackageReference.swift +++ b/Sources/XcodeProj/Objects/SwiftPackage/XCRemoteSwiftPackageReference.swift @@ -131,10 +131,10 @@ public class XCRemoteSwiftPackageReference: PBXContainerItem, PlistSerializable func plistKeyAndValue(proj: PBXProj, reference: String) throws -> (key: CommentedString, value: PlistValue) { var dictionary = try super.plistValues(proj: proj, reference: reference) dictionary["isa"] = .string(CommentedString(XCRemoteSwiftPackageReference.isa)) - if let repositoryURL = repositoryURL { + if let repositoryURL { dictionary["repositoryURL"] = .string(.init(repositoryURL)) } - if let versionRequirement = versionRequirement { + if let versionRequirement { dictionary["requirement"] = PlistValue.dictionary(versionRequirement.plistValues()) } return (key: CommentedString(reference, comment: "XCRemoteSwiftPackageReference \"\(name ?? "")\""), diff --git a/Sources/XcodeProj/Objects/SwiftPackage/XCSwiftPackageProductDependency.swift b/Sources/XcodeProj/Objects/SwiftPackage/XCSwiftPackageProductDependency.swift index 238e31f9a..cb0abc3d9 100644 --- a/Sources/XcodeProj/Objects/SwiftPackage/XCSwiftPackageProductDependency.swift +++ b/Sources/XcodeProj/Objects/SwiftPackage/XCSwiftPackageProductDependency.swift @@ -57,7 +57,7 @@ public class XCSwiftPackageProductDependency: PBXContainerItem, PlistSerializabl func plistKeyAndValue(proj: PBXProj, reference: String) throws -> (key: CommentedString, value: PlistValue) { var dictionary = try super.plistValues(proj: proj, reference: reference) dictionary["isa"] = .string(CommentedString(XCSwiftPackageProductDependency.isa)) - if let package = package { + if let package { dictionary["package"] = .string(.init(package.reference.value, comment: "XCRemoteSwiftPackageReference \"\(package.name ?? "")\"")) } if isPlugin { diff --git a/Sources/XcodeProj/Objects/Targets/PBXAggregateTarget.swift b/Sources/XcodeProj/Objects/Targets/PBXAggregateTarget.swift index ec87371fe..9bfd5674c 100644 --- a/Sources/XcodeProj/Objects/Targets/PBXAggregateTarget.swift +++ b/Sources/XcodeProj/Objects/Targets/PBXAggregateTarget.swift @@ -12,7 +12,7 @@ public final class PBXAggregateTarget: PBXTarget { extension PBXAggregateTarget: PlistSerializable { func plistKeyAndValue(proj: PBXProj, reference: String) throws -> (key: CommentedString, value: PlistValue) { - return try plistValues(proj: proj, isa: PBXAggregateTarget.isa, reference: reference) + try plistValues(proj: proj, isa: PBXAggregateTarget.isa, reference: reference) } } diff --git a/Sources/XcodeProj/Objects/Targets/PBXLegacyTarget.swift b/Sources/XcodeProj/Objects/Targets/PBXLegacyTarget.swift index 1b858e8ca..6d9a5e566 100644 --- a/Sources/XcodeProj/Objects/Targets/PBXLegacyTarget.swift +++ b/Sources/XcodeProj/Objects/Targets/PBXLegacyTarget.swift @@ -79,16 +79,16 @@ public final class PBXLegacyTarget: PBXTarget { switch value { case let .dictionary(dictValue): dict = dictValue - if let buildToolPath = buildToolPath { + if let buildToolPath { dict["buildToolPath"] = PlistValue.string(CommentedString(buildToolPath)) } - if let buildArgumentsString = buildArgumentsString { + if let buildArgumentsString { dict["buildArgumentsString"] = PlistValue.string(CommentedString(buildArgumentsString)) } dict["passBuildSettingsInEnvironment"] = PlistValue.string(CommentedString(passBuildSettingsInEnvironment.int.description)) - if let buildWorkingDirectory = buildWorkingDirectory { + if let buildWorkingDirectory { dict["buildWorkingDirectory"] = PlistValue.string(CommentedString(buildWorkingDirectory)) } @@ -108,6 +108,6 @@ public final class PBXLegacyTarget: PBXTarget { extension PBXLegacyTarget: PlistSerializable { func plistKeyAndValue(proj: PBXProj, reference: String) throws -> (key: CommentedString, value: PlistValue) { - return try plistValues(proj: proj, isa: PBXLegacyTarget.isa, reference: reference) + try plistValues(proj: proj, isa: PBXLegacyTarget.isa, reference: reference) } } diff --git a/Sources/XcodeProj/Objects/Targets/PBXNativeTarget.swift b/Sources/XcodeProj/Objects/Targets/PBXNativeTarget.swift index 45c4bbcb3..c3705422e 100644 --- a/Sources/XcodeProj/Objects/Targets/PBXNativeTarget.swift +++ b/Sources/XcodeProj/Objects/Targets/PBXNativeTarget.swift @@ -54,7 +54,7 @@ public final class PBXNativeTarget: PBXTarget { guard case var PlistValue.dictionary(dict) = value else { throw XcodeprojWritingError.invalidType(class: String(describing: type(of: self)), expected: "Dictionary") } - if let productInstallPath = productInstallPath { + if let productInstallPath { dict["productInstallPath"] = .string(CommentedString(productInstallPath)) } return (key: key, value: .dictionary(dict)) @@ -70,7 +70,7 @@ public final class PBXNativeTarget: PBXTarget { extension PBXNativeTarget: PlistSerializable { func plistKeyAndValue(proj: PBXProj, reference: String) throws -> (key: CommentedString, value: PlistValue) { - return try plistValues(proj: proj, isa: PBXNativeTarget.isa, reference: reference) + try plistValues(proj: proj, isa: PBXNativeTarget.isa, reference: reference) } } diff --git a/Sources/XcodeProj/Objects/Targets/PBXProductType.swift b/Sources/XcodeProj/Objects/Targets/PBXProductType.swift index 21dbf8b78..785d1ec1c 100644 --- a/Sources/XcodeProj/Objects/Targets/PBXProductType.swift +++ b/Sources/XcodeProj/Objects/Targets/PBXProductType.swift @@ -49,7 +49,7 @@ public enum PBXProductType: String, Decodable { case .unitTestBundle, .uiTestBundle: return "xctest" case .appExtension, .extensionKitExtension, .tvExtension, .watchExtension, .watch2Extension, .messagesExtension, .stickerPack, .xcodeExtension, - .intentsServiceExtension: + .intentsServiceExtension: return "appex" case .commandLineTool: return nil diff --git a/Sources/XcodeProj/Objects/Targets/PBXReferenceProxy.swift b/Sources/XcodeProj/Objects/Targets/PBXReferenceProxy.swift index 67363c585..9c34421ed 100644 --- a/Sources/XcodeProj/Objects/Targets/PBXReferenceProxy.swift +++ b/Sources/XcodeProj/Objects/Targets/PBXReferenceProxy.swift @@ -64,10 +64,10 @@ public final class PBXReferenceProxy: PBXFileElement { fatalError("super implementation changed and we didn’t realise!") } dictionary["isa"] = .string(CommentedString(PBXReferenceProxy.isa)) - if let fileType = fileType { + if let fileType { dictionary["fileType"] = .string(CommentedString(fileType)) } - if let remoteReference = remoteReference { + if let remoteReference { dictionary["remoteRef"] = .string(CommentedString(remoteReference.value, comment: "PBXContainerItemProxy")) } return (key: CommentedString(reference, comment: path), diff --git a/Sources/XcodeProj/Objects/Targets/PBXTarget.swift b/Sources/XcodeProj/Objects/Targets/PBXTarget.swift index 07d255493..86646cfd8 100644 --- a/Sources/XcodeProj/Objects/Targets/PBXTarget.swift +++ b/Sources/XcodeProj/Objects/Targets/PBXTarget.swift @@ -174,7 +174,7 @@ public class PBXTarget: PBXContainerItem { var dictionary = try super.plistValues(proj: proj, reference: reference) dictionary["isa"] = .string(CommentedString(isa)) let buildConfigurationListComment = "Build configuration list for \(isa) \"\(name)\"" - if let buildConfigurationListReference = buildConfigurationListReference { + if let buildConfigurationListReference { dictionary["buildConfigurationList"] = .string(CommentedString(buildConfigurationListReference.value, comment: buildConfigurationListComment)) } @@ -191,13 +191,13 @@ public class PBXTarget: PBXContainerItem { dictionary["dependencies"] = .array(dependencyReferences.map { .string(CommentedString($0.value, comment: PBXTargetDependency.isa)) }) dictionary["name"] = .string(CommentedString(name)) - if let productName = productName { + if let productName { dictionary["productName"] = .string(CommentedString(productName)) } - if let productType = productType { + if let productType { dictionary["productType"] = .string(CommentedString(productType.rawValue)) } - if let productReference = productReference { + if let productReference { let fileElement: PBXFileElement? = productReference.getObject() dictionary["productReference"] = .string(CommentedString(productReference.value, comment: fileElement?.fileName())) } @@ -225,7 +225,7 @@ public extension PBXTarget { /// /// - Returns: product name with extension. func productNameWithExtension() -> String? { - guard let productName = self.productName else { return nil } + guard let productName else { return nil } guard let fileExtension = productType?.fileExtension else { return nil } return "\(productName).\(fileExtension)" } diff --git a/Sources/XcodeProj/Objects/Targets/PBXTargetDependency.swift b/Sources/XcodeProj/Objects/Targets/PBXTargetDependency.swift index 22603e5b3..6da6ba0aa 100644 --- a/Sources/XcodeProj/Objects/Targets/PBXTargetDependency.swift +++ b/Sources/XcodeProj/Objects/Targets/PBXTargetDependency.swift @@ -120,23 +120,23 @@ extension PBXTargetDependency: PlistSerializable { func plistKeyAndValue(proj _: PBXProj, reference: String) throws -> (key: CommentedString, value: PlistValue) { var dictionary: [CommentedString: PlistValue] = [:] dictionary["isa"] = .string(CommentedString(PBXTargetDependency.isa)) - if let name = name { + if let name { dictionary["name"] = .string(CommentedString(name)) } - if let platformFilter = platformFilter { + if let platformFilter { dictionary["platformFilter"] = .string(CommentedString(platformFilter)) } - if let platformFilters = platformFilters { + if let platformFilters { dictionary["platformFilters"] = .array(platformFilters.map { .string(.init($0)) }) } - if let targetReference = targetReference { + if let targetReference { let targetObject: PBXTarget? = targetReference.getObject() dictionary["target"] = .string(CommentedString(targetReference.value, comment: targetObject?.name)) } - if let targetProxyReference = targetProxyReference { + if let targetProxyReference { dictionary["targetProxy"] = .string(CommentedString(targetProxyReference.value, comment: "PBXContainerItemProxy")) } - if let productReference = productReference { + if let productReference { dictionary["productRef"] = .string(CommentedString(productReference.value, comment: product?.productName)) } return (key: CommentedString(reference, diff --git a/Sources/XcodeProj/Project/WorkspaceSettings.swift b/Sources/XcodeProj/Project/WorkspaceSettings.swift index 343090fb9..25eee3029 100644 --- a/Sources/XcodeProj/Project/WorkspaceSettings.swift +++ b/Sources/XcodeProj/Project/WorkspaceSettings.swift @@ -59,8 +59,7 @@ public class WorkspaceSettings: Codable, Equatable, Writable { public init(buildSystem: BuildSystem = .new, derivedDataLocationStyle: DerivedDataLocationStyle? = nil, derivedDataCustomLocation: String? = nil, - autoCreateSchemes: Bool? = nil) - { + autoCreateSchemes: Bool? = nil) { self.buildSystem = buildSystem self.derivedDataLocationStyle = derivedDataLocationStyle self.derivedDataCustomLocation = derivedDataCustomLocation @@ -74,15 +73,13 @@ public class WorkspaceSettings: Codable, Equatable, Writable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if let buildSystemString: String = try container.decodeIfPresent(.buildSystem), - let buildSystem = BuildSystem(rawValue: buildSystemString) - { + let buildSystem = BuildSystem(rawValue: buildSystemString) { self.buildSystem = buildSystem } else { buildSystem = .new } if let derivedDataLocationStyleString: String = try container.decodeIfPresent(.derivedDataLocationStyle), - let derivedDataLocationStyle = DerivedDataLocationStyle(rawValue: derivedDataLocationStyleString) - { + let derivedDataLocationStyle = DerivedDataLocationStyle(rawValue: derivedDataLocationStyleString) { self.derivedDataLocationStyle = derivedDataLocationStyle } else { derivedDataLocationStyle = .default @@ -100,13 +97,13 @@ public class WorkspaceSettings: Codable, Equatable, Writable { if buildSystem == .original { try container.encode(buildSystem.rawValue, forKey: .buildSystem) } - if let derivedDataLocationStyle = derivedDataLocationStyle { + if let derivedDataLocationStyle { try container.encode(derivedDataLocationStyle.rawValue, forKey: .derivedDataLocationStyle) } - if let derivedDataCustomLocation = derivedDataCustomLocation { + if let derivedDataCustomLocation { try container.encode(derivedDataCustomLocation, forKey: .derivedDataCustomLocation) } - if let autoCreateSchemes = autoCreateSchemes { + if let autoCreateSchemes { try container.encode(autoCreateSchemes, forKey: .autoCreateSchemes) } } @@ -152,7 +149,7 @@ public class WorkspaceSettings: Codable, Equatable, Writable { } try path.write(data) } - + /// Get the workspace settings. /// /// - Throws: reading error if something goes wrong. diff --git a/Sources/XcodeProj/Project/XCBreakpointList.swift b/Sources/XcodeProj/Project/XCBreakpointList.swift index 361ce3e9f..d253b5336 100644 --- a/Sources/XcodeProj/Project/XCBreakpointList.swift +++ b/Sources/XcodeProj/Project/XCBreakpointList.swift @@ -70,7 +70,7 @@ public final class XCBreakpointList: Equatable, Writable { attributes["conveyanceType"] = conveyanceType attributes["command"] = command attributes["arguments"] = arguments - if let waitUntilDone = waitUntilDone { + if let waitUntilDone { attributes["waitUntilDone"] = waitUntilDone ? "YES" : "NO" } attributes["script"] = script @@ -123,7 +123,8 @@ public final class XCBreakpointList: Equatable, Writable { init(element: AEXMLElement) throws { guard let actionExtensionIDString = element.attributes["ActionExtensionID"], - let actionExtensionID = ActionExtensionID(rawValue: actionExtensionIDString) else { + let actionExtensionID = ActionExtensionID(rawValue: actionExtensionIDString) + else { throw XCBreakpointListError.missing(property: "ActionExtensionID") } self.actionExtensionID = actionExtensionID @@ -334,7 +335,8 @@ public final class XCBreakpointList: Equatable, Writable { init(element: AEXMLElement) throws { guard let breakpointExtensionIDString = element.attributes["BreakpointExtensionID"], - let breakpointExtensionID = BreakpointExtensionID(rawValue: breakpointExtensionIDString) else { + let breakpointExtensionID = BreakpointExtensionID(rawValue: breakpointExtensionIDString) + else { throw XCBreakpointListError.missing(property: "BreakpointExtensionID") } self.breakpointExtensionID = breakpointExtensionID @@ -375,7 +377,7 @@ public final class XCBreakpointList: Equatable, Writable { if !path.exists { throw XCBreakpointListError.notFound(path: path) } - let document = try AEXMLDocument(xml: try path.read()) + let document = try AEXMLDocument(xml: path.read()) let bucket = document["Bucket"] type = bucket.attributes["type"] version = bucket.attributes["version"] @@ -395,7 +397,7 @@ public final class XCBreakpointList: Equatable, Writable { // MARK: - Helpers public func add(breakpointProxy: BreakpointProxy) -> XCBreakpointList { - var breakpoints = self.breakpoints + var breakpoints = breakpoints breakpoints.append(breakpointProxy) return XCBreakpointList(type: type, version: version, breakpoints: breakpoints) } @@ -404,7 +406,7 @@ public final class XCBreakpointList: Equatable, Writable { public func write(path: Path, override: Bool) throws { let document = getAEXMLDocument() - + if override, path.exists { try path.delete() } @@ -437,12 +439,12 @@ public final class XCBreakpointList: Equatable, Writable { } } -extension XCBreakpointList { +public extension XCBreakpointList { /// Returns breakpoints plist path relative to the given path. /// /// - Parameter path: debugger folder /// - Returns: breakpoints plist path relative to the given path. - public static func path(_ path: Path) -> Path { + static func path(_ path: Path) -> Path { path + "Breakpoints_v2.xcbkptlist" } } diff --git a/Sources/XcodeProj/Project/XCSharedData.swift b/Sources/XcodeProj/Project/XCSharedData.swift index 9469970c9..312a3913c 100644 --- a/Sources/XcodeProj/Project/XCSharedData.swift +++ b/Sources/XcodeProj/Project/XCSharedData.swift @@ -87,12 +87,12 @@ public final class XCSharedData: Equatable, Writable { try debuggerPath.delete() } - guard let breakpoints = breakpoints else { return } + guard let breakpoints else { return } try debuggerPath.mkpath() try breakpoints.write(path: XCBreakpointList.path(debuggerPath), override: override) } - + func writeWorkspaceSettings(path: Path, override: Bool) throws { /** * We don't want to delete this path when `override` is `true` because @@ -103,17 +103,17 @@ public final class XCSharedData: Equatable, Writable { if !path.exists { try path.mkpath() } - + try workspaceSettings?.write(path: WorkspaceSettings.path(path), override: override) } } -extension XCSharedData { +public extension XCSharedData { /// Returns shared data path relative to the given path. /// /// - Parameter path: `.xcodeproj` file path /// - Returns: shared data path relative to the given path. - public static func path(_ path: Path) -> Path { + static func path(_ path: Path) -> Path { path + "xcshareddata" } } diff --git a/Sources/XcodeProj/Project/XCUserData.swift b/Sources/XcodeProj/Project/XCUserData.swift index 1d3bf328d..272152b54 100644 --- a/Sources/XcodeProj/Project/XCUserData.swift +++ b/Sources/XcodeProj/Project/XCUserData.swift @@ -1,6 +1,6 @@ +import AEXML import Foundation import PathKit -import AEXML public final class XCUserData: Equatable, Writable { // MARK: - Attributes @@ -82,7 +82,7 @@ public final class XCUserData: Equatable, Writable { } func writeSchemeManagement(path: Path, override: Bool) throws { - guard let schemeManagement = schemeManagement else { return } + guard let schemeManagement else { return } let schemesPath = XCScheme.schemesPath(path) try schemesPath.mkpath() @@ -90,7 +90,7 @@ public final class XCUserData: Equatable, Writable { } func writeBreakpoints(path: Path, override: Bool) throws { - guard let breakpoints = breakpoints else { return } + guard let breakpoints else { return } let debuggerPath = XCDebugger.path(path) try debuggerPath.mkpath() @@ -98,12 +98,12 @@ public final class XCUserData: Equatable, Writable { } } -extension XCUserData { +public extension XCUserData { /// Returns user data path relative to the given path. /// /// - Parameter path: `.xcodeproj` file path /// - Returns: user data path relative to the given path. - public static func path(_ path: Path) -> Path { + static func path(_ path: Path) -> Path { path + "xcuserdata" } @@ -111,7 +111,7 @@ extension XCUserData { /// /// - Parameter path: `.xcodeproj` file path /// - Returns: user data path relative to the given path. - public static func path(_ path: Path, userName: String) -> Path { + static func path(_ path: Path, userName: String) -> Path { XCUserData.path(path) + "\(userName).xcuserdatad" } } diff --git a/Sources/XcodeProj/Project/Xcode.swift b/Sources/XcodeProj/Project/Xcode.swift index 5b2b17477..907fc5a00 100644 --- a/Sources/XcodeProj/Project/Xcode.swift +++ b/Sources/XcodeProj/Project/Xcode.swift @@ -1,11 +1,11 @@ import Foundation /// Class that contains Xcode constants. -public struct Xcode { +public enum Xcode { /// Last known constants. - public struct LastKnown { + public enum LastKnown { /// Last known SDKs. - public struct SDK { + public enum SDK { /// Last known SDK for iOS. public static let ios: String = "14.0" @@ -36,7 +36,7 @@ public struct Xcode { } /// Default values. - public struct Default { + public enum Default { /// The default object version for Xcodeproj. public static let objectVersion: UInt = 46 @@ -45,13 +45,13 @@ public struct Xcode { /// Default development region. public static let developmentRegion: String = "en" - + /// Default XCScheme format version public static let xcschemeFormatVersion: String = "1.3" - + /// The last Swift upgrade check version public static let lastSwiftUpgradeCheck: String = "1300" - + /// The last known Xcode upgrade check version. public static let lastUpgradeCheck: String = "1300" } @@ -63,7 +63,7 @@ public struct Xcode { public static let headersExtensions = [".h", ".hh", ".hpp", ".ipp", ".tpp", ".hxx", ".def", ".inl", ".inc", ".pch"] /// Supported values. - public struct Supported { + public enum Supported { /// The version of `.xcscheme` files supported by Xcodeproj public static let xcschemeFormatVersion = "1.3" } @@ -350,7 +350,7 @@ public struct Xcode { ] /// Remote project reference dictionary keys. - public struct ProjectReference { + public enum ProjectReference { public static let projectReferenceKey = "ProjectRef" public static let productGroupKey = "ProductGroup" } diff --git a/Sources/XcodeProj/Protocols/Writable.swift b/Sources/XcodeProj/Protocols/Writable.swift index b21456756..f4a7016d3 100644 --- a/Sources/XcodeProj/Protocols/Writable.swift +++ b/Sources/XcodeProj/Protocols/Writable.swift @@ -23,11 +23,11 @@ public protocol Writable { func dataRepresentation() throws -> Data? } -extension Writable { - public func write(pathString: String, override: Bool) throws { +public extension Writable { + func write(pathString: String, override: Bool) throws { let path = Path(pathString) try write(path: path, override: override) } - public func dataRepresentation() throws -> Data? { nil } + func dataRepresentation() throws -> Data? { nil } } diff --git a/Sources/XcodeProj/Scheme/XCScheme+AditionalOption.swift b/Sources/XcodeProj/Scheme/XCScheme+AditionalOption.swift index 5e643047a..3f4122099 100644 --- a/Sources/XcodeProj/Scheme/XCScheme+AditionalOption.swift +++ b/Sources/XcodeProj/Scheme/XCScheme+AditionalOption.swift @@ -2,8 +2,8 @@ import AEXML import Foundation import PathKit -extension XCScheme { - public final class AdditionalOption: Equatable { +public extension XCScheme { + final class AdditionalOption: Equatable { // MARK: - Attributes public var key: String diff --git a/Sources/XcodeProj/Scheme/XCScheme+AnalyzeAction.swift b/Sources/XcodeProj/Scheme/XCScheme+AnalyzeAction.swift index 2a295e7e3..6dd25fb99 100644 --- a/Sources/XcodeProj/Scheme/XCScheme+AnalyzeAction.swift +++ b/Sources/XcodeProj/Scheme/XCScheme+AnalyzeAction.swift @@ -2,8 +2,8 @@ import AEXML import Foundation import PathKit -extension XCScheme { - public final class AnalyzeAction: Equatable { +public extension XCScheme { + final class AnalyzeAction: Equatable { // MARK: - Static // Xcode disables PreActions and PostActions for Analyze actions, so this Action diff --git a/Sources/XcodeProj/Scheme/XCScheme+ArchiveAction.swift b/Sources/XcodeProj/Scheme/XCScheme+ArchiveAction.swift index 92ddab9c6..73cbae330 100644 --- a/Sources/XcodeProj/Scheme/XCScheme+ArchiveAction.swift +++ b/Sources/XcodeProj/Scheme/XCScheme+ArchiveAction.swift @@ -2,8 +2,8 @@ import AEXML import Foundation import PathKit -extension XCScheme { - public final class ArchiveAction: SerialAction { +public extension XCScheme { + final class ArchiveAction: SerialAction { // MARK: - Static private static let defaultBuildConfiguration = "Release" diff --git a/Sources/XcodeProj/Scheme/XCScheme+BuildAction.swift b/Sources/XcodeProj/Scheme/XCScheme+BuildAction.swift index f6e81bfd4..8cc9ed15a 100644 --- a/Sources/XcodeProj/Scheme/XCScheme+BuildAction.swift +++ b/Sources/XcodeProj/Scheme/XCScheme+BuildAction.swift @@ -2,8 +2,8 @@ import AEXML import Foundation import PathKit -extension XCScheme { - public final class BuildAction: SerialAction { +public extension XCScheme { + final class BuildAction: SerialAction { public final class Entry: Equatable { public enum BuildFor: Sendable { case running, testing, profiling, archiving, analyzing @@ -140,7 +140,7 @@ extension XCScheme { // MARK: - Helpers public func add(buildActionEntry: Entry) -> BuildAction { - var buildActionEntries = self.buildActionEntries + var buildActionEntries = buildActionEntries buildActionEntries.append(buildActionEntry) return BuildAction(buildActionEntries: buildActionEntries, parallelizeBuild: parallelizeBuild) @@ -158,7 +158,7 @@ extension XCScheme { attributes["buildArchitectures"] = buildArchitecturesXMLString } - if let runPostActionsOnFailure = runPostActionsOnFailure { + if let runPostActionsOnFailure { attributes["runPostActionsOnFailure"] = runPostActionsOnFailure.xmlString } @@ -167,7 +167,7 @@ extension XCScheme { attributes: attributes) super.writeXML(parent: element) let entries = element.addChild(name: "BuildActionEntries") - buildActionEntries.forEach { entry in + for entry in buildActionEntries { entries.addChild(entry.xmlElement()) } return element diff --git a/Sources/XcodeProj/Scheme/XCScheme+BuildableProductRunnable.swift b/Sources/XcodeProj/Scheme/XCScheme+BuildableProductRunnable.swift index 2dffa070b..e590e8f37 100644 --- a/Sources/XcodeProj/Scheme/XCScheme+BuildableProductRunnable.swift +++ b/Sources/XcodeProj/Scheme/XCScheme+BuildableProductRunnable.swift @@ -1,8 +1,8 @@ import AEXML import Foundation -extension XCScheme { - public final class BuildableProductRunnable: Runnable { +public extension XCScheme { + final class BuildableProductRunnable: Runnable { // MARK: - XML override func xmlElement() -> AEXMLElement { diff --git a/Sources/XcodeProj/Scheme/XCScheme+BuildableReference.swift b/Sources/XcodeProj/Scheme/XCScheme+BuildableReference.swift index f35011ed7..5ded8df2f 100644 --- a/Sources/XcodeProj/Scheme/XCScheme+BuildableReference.swift +++ b/Sources/XcodeProj/Scheme/XCScheme+BuildableReference.swift @@ -1,8 +1,8 @@ import AEXML import Foundation -extension XCScheme { - public final class BuildableReference: Equatable, Hashable { +public extension XCScheme { + final class BuildableReference: Equatable, Hashable { // MARK: - Attributes public var referencedContainer: String @@ -52,7 +52,7 @@ extension XCScheme { blueprintName: String, buildableIdentifier: String = "primary") { self.referencedContainer = referencedContainer - self.blueprint = blueprintIdentifier.map(Blueprint.string) + blueprint = blueprintIdentifier.map(Blueprint.string) self.buildableName = buildableName self.buildableIdentifier = buildableIdentifier self.blueprintName = blueprintName @@ -75,7 +75,7 @@ extension XCScheme { } self.buildableIdentifier = buildableIdentifier let blueprintIdentifier = element.attributes["BlueprintIdentifier"] - self.blueprint = blueprintIdentifier.map(Blueprint.string) + blueprint = blueprintIdentifier.map(Blueprint.string) self.buildableName = buildableName self.blueprintName = blueprintName self.referencedContainer = referencedContainer diff --git a/Sources/XcodeProj/Scheme/XCScheme+CommandLineArguments.swift b/Sources/XcodeProj/Scheme/XCScheme+CommandLineArguments.swift index 80330a24a..862299b33 100644 --- a/Sources/XcodeProj/Scheme/XCScheme+CommandLineArguments.swift +++ b/Sources/XcodeProj/Scheme/XCScheme+CommandLineArguments.swift @@ -1,8 +1,8 @@ import AEXML import Foundation -extension XCScheme { - public final class CommandLineArguments: Equatable { +public extension XCScheme { + final class CommandLineArguments: Equatable { // MARK: - Attributes public let arguments: [CommandLineArgument] @@ -30,7 +30,7 @@ extension XCScheme { func xmlElement() -> AEXMLElement { let element = AEXMLElement(name: "CommandLineArguments", value: nil) - arguments.forEach { arg in + for arg in arguments { element.addChild(arg.xmlElement()) } return element @@ -44,8 +44,8 @@ extension XCScheme { } } -extension XCScheme.CommandLineArguments { - public struct CommandLineArgument: Equatable { +public extension XCScheme.CommandLineArguments { + struct CommandLineArgument: Equatable { // MARK: - Attributes public let name: String diff --git a/Sources/XcodeProj/Scheme/XCScheme+EnvironmentVariable.swift b/Sources/XcodeProj/Scheme/XCScheme+EnvironmentVariable.swift index 2f6251063..7fe613ee0 100644 --- a/Sources/XcodeProj/Scheme/XCScheme+EnvironmentVariable.swift +++ b/Sources/XcodeProj/Scheme/XCScheme+EnvironmentVariable.swift @@ -1,8 +1,8 @@ import AEXML import Foundation -extension XCScheme { - public struct EnvironmentVariable: Equatable { +public extension XCScheme { + struct EnvironmentVariable: Equatable { // MARK: - Attributes public let variable: String @@ -44,7 +44,7 @@ extension XCScheme { static func xmlElement(from variables: [EnvironmentVariable]) -> AEXMLElement { let element = AEXMLElement(name: "EnvironmentVariables", value: nil) - variables.forEach { arg in + for arg in variables { element.addChild(arg.xmlElement()) } diff --git a/Sources/XcodeProj/Scheme/XCScheme+ExecutionAction.swift b/Sources/XcodeProj/Scheme/XCScheme+ExecutionAction.swift index 484e99aaa..2a9aed87b 100644 --- a/Sources/XcodeProj/Scheme/XCScheme+ExecutionAction.swift +++ b/Sources/XcodeProj/Scheme/XCScheme+ExecutionAction.swift @@ -1,8 +1,8 @@ import AEXML import Foundation -extension XCScheme { - public final class ExecutionAction: Equatable { +public extension XCScheme { + final class ExecutionAction: Equatable { private static let ActionType = "Xcode.IDEStandardExecutionActionsCore.ExecutionActionType.ShellScriptAction" // MARK: - Attributes @@ -45,14 +45,14 @@ extension XCScheme { "title": title, "scriptText": scriptText, ] - if let shellToInvoke = shellToInvoke { + if let shellToInvoke { attributes["shellToInvoke"] = shellToInvoke } let content = AEXMLElement(name: "ActionContent", value: nil, attributes: attributes) element.addChild(content) - if let environmentBuildable = environmentBuildable { + if let environmentBuildable { let environment = content.addChild(name: "EnvironmentBuildable") environment.addChild(environmentBuildable.xmlElement()) } diff --git a/Sources/XcodeProj/Scheme/XCScheme+LaunchAction.swift b/Sources/XcodeProj/Scheme/XCScheme+LaunchAction.swift index a8770502f..4edd89770 100644 --- a/Sources/XcodeProj/Scheme/XCScheme+LaunchAction.swift +++ b/Sources/XcodeProj/Scheme/XCScheme+LaunchAction.swift @@ -2,9 +2,9 @@ import AEXML import Foundation import PathKit -extension XCScheme { +public extension XCScheme { // swiftlint:disable:next type_body_length - public final class LaunchAction: SerialAction { + final class LaunchAction: SerialAction { public enum Style: String, Sendable { case auto = "0" case wait = "1" @@ -18,7 +18,7 @@ extension XCScheme { case disabled = "3" } - // The value used to disable 'API Validation'. + // The value used to disable 'API Validation'. // If this feature is not being disabled, this value will not be present. public let gpuValidationModeDisableValue = "1" @@ -263,7 +263,7 @@ extension XCScheme { "allowLocationSimulation": allowLocationSimulation.xmlString, ] - if let askForAppToLaunch = askForAppToLaunch { + if let askForAppToLaunch { attributes["askForAppToLaunch"] = askForAppToLaunch.xmlString } if enableGPUFrameCaptureMode != LaunchAction.defaultGPUFrameCaptureMode { @@ -308,7 +308,7 @@ extension XCScheme { if stopOnEveryMainThreadCheckerIssue { attributes["stopOnEveryMainThreadCheckerIssue"] = stopOnEveryMainThreadCheckerIssue.xmlString } - if let customWorkingDirectory = customWorkingDirectory { + if let customWorkingDirectory { attributes["customWorkingDirectory"] = customWorkingDirectory } @@ -320,36 +320,36 @@ extension XCScheme { value: nil, attributes: xmlAttributes) super.writeXML(parent: element) - if let runnable = runnable { + if let runnable { element.addChild(runnable.xmlElement()) } - if let pathRunnable = pathRunnable { + if let pathRunnable { element.addChild(pathRunnable.xmlElement()) } - if let locationScenarioReference = locationScenarioReference { + if let locationScenarioReference { element.addChild(locationScenarioReference.xmlElement()) } - if let macroExpansion = macroExpansion { + if let macroExpansion { let macro = element.addChild(name: "MacroExpansion") macro.addChild(macroExpansion.xmlElement()) } - if let commandlineArguments = commandlineArguments { + if let commandlineArguments { element.addChild(commandlineArguments.xmlElement()) } - if let environmentVariables = environmentVariables { + if let environmentVariables { element.addChild(EnvironmentVariable.xmlElement(from: environmentVariables)) } - if let language = language { + if let language { element.attributes["language"] = language } - if let region = region { + if let region { element.attributes["region"] = region } @@ -357,25 +357,25 @@ extension XCScheme { element.attributes["showNonLocalizedStrings"] = showNonLocalizedStrings.xmlString } - if let launchAutomaticallySubstyle = launchAutomaticallySubstyle { + if let launchAutomaticallySubstyle { element.attributes["launchAutomaticallySubstyle"] = launchAutomaticallySubstyle } - if let storeKitConfigurationFileReference = storeKitConfigurationFileReference { + if let storeKitConfigurationFileReference { element.addChild(storeKitConfigurationFileReference.xmlElement()) } - if let customLaunchCommand = customLaunchCommand { + if let customLaunchCommand { element.attributes["customLaunchCommand"] = customLaunchCommand } - if let customLLDBInitFile = customLLDBInitFile { + if let customLLDBInitFile { element.attributes["customLLDBInitFile"] = customLLDBInitFile } if !additionalOptions.isEmpty { let additionalOptionsElement = element.addChild(AEXMLElement(name: "AdditionalOptions")) - additionalOptions.forEach { additionalOption in + for additionalOption in additionalOptions { additionalOptionsElement.addChild(additionalOption.xmlElement()) } } diff --git a/Sources/XcodeProj/Scheme/XCScheme+LocationScenarioReference.swift b/Sources/XcodeProj/Scheme/XCScheme+LocationScenarioReference.swift index 23e13bb83..64bb69dbd 100644 --- a/Sources/XcodeProj/Scheme/XCScheme+LocationScenarioReference.swift +++ b/Sources/XcodeProj/Scheme/XCScheme+LocationScenarioReference.swift @@ -1,8 +1,8 @@ import AEXML import Foundation -extension XCScheme { - public final class LocationScenarioReference: Equatable { +public extension XCScheme { + final class LocationScenarioReference: Equatable { // MARK: - Attributes public var identifier: String diff --git a/Sources/XcodeProj/Scheme/XCScheme+PathRunnable.swift b/Sources/XcodeProj/Scheme/XCScheme+PathRunnable.swift index d47a19252..220de342d 100644 --- a/Sources/XcodeProj/Scheme/XCScheme+PathRunnable.swift +++ b/Sources/XcodeProj/Scheme/XCScheme+PathRunnable.swift @@ -2,8 +2,8 @@ import AEXML import Foundation import PathKit -extension XCScheme { - public class PathRunnable: Equatable { +public extension XCScheme { + class PathRunnable: Equatable { // MARK: - Attributes public var runnableDebuggingMode: String diff --git a/Sources/XcodeProj/Scheme/XCScheme+ProfileAction.swift b/Sources/XcodeProj/Scheme/XCScheme+ProfileAction.swift index 023b79576..6c4864996 100644 --- a/Sources/XcodeProj/Scheme/XCScheme+ProfileAction.swift +++ b/Sources/XcodeProj/Scheme/XCScheme+ProfileAction.swift @@ -2,8 +2,8 @@ import AEXML import Foundation import PathKit -extension XCScheme { - public final class ProfileAction: SerialAction { +public extension XCScheme { + final class ProfileAction: SerialAction { // MARK: - Static private static let defaultBuildConfiguration = "Release" @@ -15,6 +15,7 @@ extension XCScheme { // For backwards compatibility - can be removed in the next major version runnable as? BuildableProductRunnable } + public var buildConfiguration: String public var shouldUseLaunchSchemeArgsEnv: Bool public var savedToolIdentifier: String @@ -80,8 +81,8 @@ extension XCScheme { commandlineArguments: CommandLineArguments? = nil, environmentVariables: [EnvironmentVariable]? = nil, enableTestabilityWhenProfilingTests: Bool = true, - launchAutomaticallySubstyle: String? = nil) - { + launchAutomaticallySubstyle: String? = nil + ) { self.init( runnable: buildableProductRunnable, buildConfiguration: buildConfiguration, @@ -98,7 +99,8 @@ extension XCScheme { commandlineArguments: commandlineArguments, environmentVariables: environmentVariables, enableTestabilityWhenProfilingTests: enableTestabilityWhenProfilingTests, - launchAutomaticallySubstyle: launchAutomaticallySubstyle) + launchAutomaticallySubstyle: launchAutomaticallySubstyle + ) } override init(element: AEXMLElement) throws { @@ -152,10 +154,10 @@ extension XCScheme { "debugDocumentVersioning": debugDocumentVersioning.xmlString, ]) super.writeXML(parent: element) - if let runnable = runnable { + if let runnable { element.addChild(runnable.xmlElement()) } - if let askForAppToLaunch = askForAppToLaunch { + if let askForAppToLaunch { element.attributes["askForAppToLaunch"] = askForAppToLaunch.xmlString } if ignoresPersistentStateOnLaunch { @@ -164,20 +166,20 @@ extension XCScheme { if !enableTestabilityWhenProfilingTests { element.attributes["enableTestabilityWhenProfilingTests"] = "No" } - if let commandlineArguments = commandlineArguments { + if let commandlineArguments { element.addChild(commandlineArguments.xmlElement()) } - if let environmentVariables = environmentVariables { + if let environmentVariables { element.addChild(EnvironmentVariable.xmlElement(from: environmentVariables)) } - if let launchAutomaticallySubstyle = launchAutomaticallySubstyle { + if let launchAutomaticallySubstyle { element.attributes["launchAutomaticallySubstyle"] = launchAutomaticallySubstyle } - if let customWorkingDirectory = customWorkingDirectory { + if let customWorkingDirectory { element.attributes["customWorkingDirectory"] = customWorkingDirectory } - if let macroExpansion = macroExpansion { + if let macroExpansion { let macro = element.addChild(name: "MacroExpansion") macro.addChild(macroExpansion.xmlElement()) } diff --git a/Sources/XcodeProj/Scheme/XCScheme+RemoteRunnable.swift b/Sources/XcodeProj/Scheme/XCScheme+RemoteRunnable.swift index 67413e5c7..b66cadd64 100644 --- a/Sources/XcodeProj/Scheme/XCScheme+RemoteRunnable.swift +++ b/Sources/XcodeProj/Scheme/XCScheme+RemoteRunnable.swift @@ -1,8 +1,8 @@ import AEXML import Foundation -extension XCScheme { - public final class RemoteRunnable: Runnable { +public extension XCScheme { + final class RemoteRunnable: Runnable { // MARK: - Attributes public var bundleIdentifier: String diff --git a/Sources/XcodeProj/Scheme/XCScheme+Runnable.swift b/Sources/XcodeProj/Scheme/XCScheme+Runnable.swift index b7173dc2c..27471e9f3 100644 --- a/Sources/XcodeProj/Scheme/XCScheme+Runnable.swift +++ b/Sources/XcodeProj/Scheme/XCScheme+Runnable.swift @@ -1,8 +1,8 @@ import AEXML import Foundation -extension XCScheme { - public class Runnable: Equatable { +public extension XCScheme { + class Runnable: Equatable { // MARK: - Attributes public var runnableDebuggingMode: String @@ -27,7 +27,7 @@ extension XCScheme { let element = AEXMLElement(name: "Runnable", value: nil, attributes: ["runnableDebuggingMode": runnableDebuggingMode]) - if let buildableReference = buildableReference { + if let buildableReference { element.addChild(buildableReference.xmlElement()) } return element diff --git a/Sources/XcodeProj/Scheme/XCScheme+SerialAction.swift b/Sources/XcodeProj/Scheme/XCScheme+SerialAction.swift index 4a02b06b3..fb842834b 100644 --- a/Sources/XcodeProj/Scheme/XCScheme+SerialAction.swift +++ b/Sources/XcodeProj/Scheme/XCScheme+SerialAction.swift @@ -1,8 +1,8 @@ import AEXML import Foundation -extension XCScheme { - public class SerialAction: Equatable { +public extension XCScheme { + class SerialAction: Equatable { // MARK: - Attributes public var preActions: [ExecutionAction] @@ -25,13 +25,13 @@ extension XCScheme { func writeXML(parent element: AEXMLElement) { if !preActions.isEmpty { let preActions = element.addChild(name: "PreActions") - self.preActions.forEach { preAction in + for preAction in self.preActions { preActions.addChild(preAction.xmlElement()) } } if !postActions.isEmpty { let postActions = element.addChild(name: "PostActions") - self.postActions.forEach { postAction in + for postAction in self.postActions { postActions.addChild(postAction.xmlElement()) } } diff --git a/Sources/XcodeProj/Scheme/XCScheme+StoreKitConfigurationFileReference.swift b/Sources/XcodeProj/Scheme/XCScheme+StoreKitConfigurationFileReference.swift index ab42e2af5..4edc620d1 100644 --- a/Sources/XcodeProj/Scheme/XCScheme+StoreKitConfigurationFileReference.swift +++ b/Sources/XcodeProj/Scheme/XCScheme+StoreKitConfigurationFileReference.swift @@ -1,8 +1,8 @@ import AEXML import Foundation -extension XCScheme { - public final class StoreKitConfigurationFileReference: Equatable { +public extension XCScheme { + final class StoreKitConfigurationFileReference: Equatable { // MARK: - Attributes public var identifier: String diff --git a/Sources/XcodeProj/Scheme/XCScheme+TestAction.swift b/Sources/XcodeProj/Scheme/XCScheme+TestAction.swift index 0c7c3f706..735e699b1 100644 --- a/Sources/XcodeProj/Scheme/XCScheme+TestAction.swift +++ b/Sources/XcodeProj/Scheme/XCScheme+TestAction.swift @@ -2,12 +2,12 @@ import AEXML import Foundation import PathKit -extension XCScheme { - public final class TestAction: SerialAction { +public extension XCScheme { + final class TestAction: SerialAction { public enum AttachmentLifetime: String { case keepAlways, keepNever } - + public enum ScreenCaptureFormat: String { case screenshots, screenRecording } @@ -159,7 +159,7 @@ extension XCScheme { attributes["buildConfiguration"] = buildConfiguration attributes["selectedDebuggerIdentifier"] = selectedDebuggerIdentifier attributes["selectedLauncherIdentifier"] = selectedLauncherIdentifier - if let language = language { + if let language { attributes["language"] = language } attributes["region"] = region @@ -167,7 +167,7 @@ extension XCScheme { if codeCoverageEnabled { attributes["codeCoverageEnabled"] = codeCoverageEnabled.xmlString } - if let onlyGenerateCoverageForSpecifiedTargets = onlyGenerateCoverageForSpecifiedTargets { + if let onlyGenerateCoverageForSpecifiedTargets { attributes["onlyGenerateCoverageForSpecifiedTargets"] = onlyGenerateCoverageForSpecifiedTargets.xmlString } if enableAddressSanitizer { @@ -186,59 +186,59 @@ extension XCScheme { attributes["disableMainThreadChecker"] = disableMainThreadChecker.xmlString } attributes["systemAttachmentLifetime"] = systemAttachmentLifetime?.rawValue - + switch preferredScreenCaptureFormat { case .screenshots: attributes["preferredScreenCaptureFormat"] = preferredScreenCaptureFormat?.rawValue case .none, .screenRecording: break } - + if case .keepAlways? = userAttachmentLifetime { attributes["userAttachmentLifetime"] = userAttachmentLifetime?.rawValue } - if let customLLDBInitFile = customLLDBInitFile { + if let customLLDBInitFile { attributes["customLLDBInitFile"] = customLLDBInitFile } let element = AEXMLElement(name: "TestAction", value: nil, attributes: attributes) super.writeXML(parent: element) - if let testPlans = testPlans { + if let testPlans { let testPlansElement = element.addChild(name: "TestPlans") - testPlans.forEach { testPlan in + for testPlan in testPlans { testPlansElement.addChild(testPlan.xmlElement()) } } - if let macroExpansion = macroExpansion { + if let macroExpansion { let macro = element.addChild(name: "MacroExpansion") macro.addChild(macroExpansion.xmlElement()) } let testablesElement = element.addChild(name: "Testables") - testables.forEach { testable in + for testable in testables { testablesElement.addChild(testable.xmlElement()) } - if let commandlineArguments = commandlineArguments { + if let commandlineArguments { element.addChild(commandlineArguments.xmlElement()) } - if let environmentVariables = environmentVariables { + if let environmentVariables { element.addChild(EnvironmentVariable.xmlElement(from: environmentVariables)) } if !additionalOptions.isEmpty { let additionalOptionsElement = element.addChild(AEXMLElement(name: "AdditionalOptions")) - additionalOptions.forEach { additionalOption in + for additionalOption in additionalOptions { additionalOptionsElement.addChild(additionalOption.xmlElement()) } } if !codeCoverageTargets.isEmpty { let codeCoverageTargetsElement = element.addChild(AEXMLElement(name: "CodeCoverageTargets")) - codeCoverageTargets.forEach { target in + for target in codeCoverageTargets { codeCoverageTargetsElement.addChild(target.xmlElement()) } } diff --git a/Sources/XcodeProj/Scheme/XCScheme+TestItem.swift b/Sources/XcodeProj/Scheme/XCScheme+TestItem.swift index 02934909e..9ede59f03 100644 --- a/Sources/XcodeProj/Scheme/XCScheme+TestItem.swift +++ b/Sources/XcodeProj/Scheme/XCScheme+TestItem.swift @@ -1,8 +1,8 @@ import AEXML import Foundation -extension XCScheme { - public final class TestItem: Equatable { +public extension XCScheme { + final class TestItem: Equatable { // MARK: - Attributes public var identifier: String diff --git a/Sources/XcodeProj/Scheme/XCScheme+TestPlanReference.swift b/Sources/XcodeProj/Scheme/XCScheme+TestPlanReference.swift index 1397391f4..0c8e3f19f 100644 --- a/Sources/XcodeProj/Scheme/XCScheme+TestPlanReference.swift +++ b/Sources/XcodeProj/Scheme/XCScheme+TestPlanReference.swift @@ -1,8 +1,8 @@ import AEXML import Foundation -extension XCScheme { - public final class TestPlanReference: Equatable { +public extension XCScheme { + final class TestPlanReference: Equatable { // MARK: - Attributes public var reference: String diff --git a/Sources/XcodeProj/Scheme/XCScheme+TestableReference.swift b/Sources/XcodeProj/Scheme/XCScheme+TestableReference.swift index ac73ba3ac..88b5bd1b3 100644 --- a/Sources/XcodeProj/Scheme/XCScheme+TestableReference.swift +++ b/Sources/XcodeProj/Scheme/XCScheme+TestableReference.swift @@ -1,8 +1,8 @@ import AEXML import Foundation -extension XCScheme { - public final class TestableReference: Equatable { +public extension XCScheme { + final class TestableReference: Equatable { // MARK: - Attributes public var skipped: Bool @@ -40,7 +40,7 @@ extension XCScheme { useTestSelectionWhitelist = element.attributes["useTestSelectionWhitelist"] == "YES" randomExecutionOrdering = element.attributes["testExecutionOrdering"] == "random" buildableReference = try BuildableReference(element: element["BuildableReference"]) - + if element["LocationScenarioReference"].all?.first != nil { locationScenarioReference = try LocationScenarioReference(element: element["LocationScenarioReference"]) } else { @@ -64,7 +64,7 @@ extension XCScheme { func xmlElement() -> AEXMLElement { var attributes: [String: String] = ["skipped": skipped.xmlString] attributes["parallelizable"] = parallelizable ? parallelizable.xmlString : nil - if let useTestSelectionWhitelist = useTestSelectionWhitelist { + if let useTestSelectionWhitelist { attributes["useTestSelectionWhitelist"] = useTestSelectionWhitelist.xmlString } attributes["testExecutionOrdering"] = randomExecutionOrdering ? "random" : nil @@ -73,21 +73,21 @@ extension XCScheme { attributes: attributes) element.addChild(buildableReference.xmlElement()) - if let locationScenarioReference = locationScenarioReference { + if let locationScenarioReference { element.addChild(locationScenarioReference.xmlElement()) } - + if useTestSelectionWhitelist == true { if !selectedTests.isEmpty { let selectedTestsElement = element.addChild(name: "SelectedTests") - selectedTests.forEach { selectedTest in + for selectedTest in selectedTests { selectedTestsElement.addChild(selectedTest.xmlElement()) } } } else { if !skippedTests.isEmpty { let skippedTestsElement = element.addChild(name: "SkippedTests") - skippedTests.forEach { skippedTest in + for skippedTest in skippedTests { skippedTestsElement.addChild(skippedTest.xmlElement()) } } diff --git a/Sources/XcodeProj/Scheme/XCScheme.swift b/Sources/XcodeProj/Scheme/XCScheme.swift index 7a805c25a..33130c9fe 100644 --- a/Sources/XcodeProj/Scheme/XCScheme.swift +++ b/Sources/XcodeProj/Scheme/XCScheme.swift @@ -42,7 +42,7 @@ public final class XCScheme: Writable, Equatable { throw XCSchemeError.notFound(path: path) } name = path.lastComponentWithoutExtension - let document = try AEXMLDocument(xml: try path.read()) + let document = try AEXMLDocument(xml: path.read()) let scheme = document["Scheme"] lastUpgradeVersion = scheme.attributes["LastUpgradeVersion"] version = scheme.attributes["version"] @@ -93,36 +93,36 @@ public final class XCScheme: Writable, Equatable { } try path.write(document.xmlXcodeFormat) } - + public func dataRepresentation() throws -> Data? { getAEXMLDocument().xmlXcodeFormat.data(using: .utf8) } - + private func getAEXMLDocument() -> AEXMLDocument { let document = AEXMLDocument() var schemeAttributes: [String: String] = [:] schemeAttributes["LastUpgradeVersion"] = lastUpgradeVersion schemeAttributes["version"] = version let scheme = document.addChild(name: "Scheme", value: nil, attributes: schemeAttributes) - if let buildAction = buildAction { + if let buildAction { scheme.addChild(buildAction.xmlElement()) } - if let testAction = testAction { + if let testAction { scheme.addChild(testAction.xmlElement()) } - if let launchAction = launchAction { + if let launchAction { scheme.addChild(launchAction.xmlElement()) } - if let profileAction = profileAction { + if let profileAction { scheme.addChild(profileAction.xmlElement()) } - if let analyzeAction = analyzeAction { + if let analyzeAction { scheme.addChild(analyzeAction.xmlElement()) } - if let archiveAction = archiveAction { + if let archiveAction { scheme.addChild(archiveAction.xmlElement()) } - if let wasCreatedForAppExtension = wasCreatedForAppExtension { + if let wasCreatedForAppExtension { scheme.attributes["wasCreatedForAppExtension"] = wasCreatedForAppExtension.xmlString } return document diff --git a/Sources/XcodeProj/Scheme/XCSchemeManagement.swift b/Sources/XcodeProj/Scheme/XCSchemeManagement.swift index d9c068831..992c8f7d9 100644 --- a/Sources/XcodeProj/Scheme/XCSchemeManagement.swift +++ b/Sources/XcodeProj/Scheme/XCSchemeManagement.swift @@ -4,16 +4,16 @@ import Foundation public enum XCSchemeManagementError: Error, Equatable, LocalizedError, CustomStringConvertible, Sendable { /// Thrown when the user tries to initialize a XCSchemeManagement instace passing a path to a file that doesn't exist. case notFound(path: Path) - + public var description: String { switch self { case let .notFound(path): return "Couldn't initialize XCSchemeManagement because the file at path \(path.string) was not found." } } - + public var errorDescription: String? { - return description + description } } @@ -24,10 +24,9 @@ public struct XCSchemeManagement: Codable, Equatable, Writable { public struct AutocreationBuildable: Equatable, Codable { var primary: Bool } - + /// Scheme configuration object. public struct UserStateScheme: Equatable, Codable { - /// Coding keys public enum CodingKeys: String, CodingKey { case shared @@ -38,25 +37,25 @@ public struct XCSchemeManagement: Codable, Equatable, Writable { /// Name of the scheme (with the .xcscheme extension) public var name: String - + /// True if the scheme should be shared. public var shared: Bool - + /// Attribute used by Xcode to sort the schemes. public var orderHint: Int? - + /// True if the scheme should be shown in the list of schemes. public var isShown: Bool? - + /// The key that should be used when encoding the scheme configuration. var key: String { - var key = name - if shared { - key.append("_^#shared#^_") - } - return key - } - + var key = name + if shared { + key.append("_^#shared#^_") + } + return key + } + /// It initializes the scheme configuration with its attributes. /// - Parameters: /// - name: Name of the scheme (with the .xcscheme extension) @@ -72,23 +71,23 @@ public struct XCSchemeManagement: Codable, Equatable, Writable { self.orderHint = orderHint self.isShown = isShown } - + // MARK: - Codable - + public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.orderHint = try container.decodeIfPresent(.orderHint) - self.isShown = try container.decodeIfPresent(.isShown) - self.shared = try container.decodeIfPresent(.shared) ?? false - self.name = try container.decode(.name) + orderHint = try container.decodeIfPresent(.orderHint) + isShown = try container.decodeIfPresent(.isShown) + shared = try container.decodeIfPresent(.shared) ?? false + name = try container.decode(.name) } - + public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - if let orderHint = orderHint { + if let orderHint { try container.encode(orderHint, forKey: .orderHint) } - if let isShown = isShown { + if let isShown { try container.encode(isShown, forKey: .isShown) } } @@ -99,10 +98,10 @@ public struct XCSchemeManagement: Codable, Equatable, Writable { case schemeUserState = "SchemeUserState" case suppressBuildableAutocreation = "SuppressBuildableAutocreation" } - + /// An array that contains the configuration of the schemes. public var schemeUserState: [XCSchemeManagement.UserStateScheme]? - + /// A dictionary where the key is the object reference of the target, and the value the configuration for auto-creating schemes. public var suppressBuildableAutocreation: [String: XCSchemeManagement.AutocreationBuildable]? @@ -115,7 +114,7 @@ public struct XCSchemeManagement: Codable, Equatable, Writable { self.schemeUserState = schemeUserState self.suppressBuildableAutocreation = suppressBuildableAutocreation } - + /// Initializes the XCSchemeManagement instance by parsing an existing xcschememanagement.plist /// - Parameter path: Path to the xcschememanagement.plist file. /// - Throws: An error if the file is malformated. @@ -124,9 +123,9 @@ public struct XCSchemeManagement: Codable, Equatable, Writable { throw XCSchemeManagementError.notFound(path: path) } let decoder = XcodeprojPropertyListDecoder() - self = try decoder.decode(XCSchemeManagement.self, from: try path.read()) + self = try decoder.decode(XCSchemeManagement.self, from: path.read()) } - + /// Converts the object into a property list and writes it at the given path. /// - Parameter path: Path to the file where it should be written. /// - Parameter override: if project should be overridden. Default is false. @@ -141,12 +140,12 @@ public struct XCSchemeManagement: Codable, Equatable, Writable { let encoder = getEncoder() try encoder.encode(self).write(to: path.url) } - + /// Gets the data representation of the property list representation of the object. /// /// - Throws: Error if encoding fails. public func dataRepresentation() throws -> Data? { - return try getEncoder().encode(self) + try getEncoder().encode(self) } private func getEncoder() -> PropertyListEncoder { @@ -160,35 +159,35 @@ public struct XCSchemeManagement: Codable, Equatable, Writable { public init(from decoder: Decoder) throws { let plistDecoder = XcodeprojPropertyListDecoder() let container = try decoder.container(keyedBy: CodingKeys.self) - self.suppressBuildableAutocreation = try container.decodeIfPresent(.suppressBuildableAutocreation) + suppressBuildableAutocreation = try container.decodeIfPresent(.suppressBuildableAutocreation) if let schemeUserStateDictionary = try container.decodeIfPresent([String: Any].self, forKey: .schemeUserState) { - self.schemeUserState = try schemeUserStateDictionary + schemeUserState = try schemeUserStateDictionary .sorted(by: { $0.key < $1.key }) - .compactMap({ (key, value) -> XCSchemeManagement.UserStateScheme? in - var name = key - guard var valueDictionary = value as? [String: Any] else { return nil } - if key.contains("_^#shared#^_") { - valueDictionary["shared"] = true - name = key.replacingOccurrences(of: "_^#shared#^_", with: "") + .compactMap { key, value -> XCSchemeManagement.UserStateScheme? in + var name = key + guard var valueDictionary = value as? [String: Any] else { return nil } + if key.contains("_^#shared#^_") { + valueDictionary["shared"] = true + name = key.replacingOccurrences(of: "_^#shared#^_", with: "") + } + valueDictionary["name"] = name + + let data = try PropertyListSerialization.data(fromPropertyList: valueDictionary, format: .xml, options: 0) + return try plistDecoder.decode(XCSchemeManagement.UserStateScheme.self, from: data) } - valueDictionary["name"] = name - - let data = try PropertyListSerialization.data(fromPropertyList: valueDictionary, format: .xml, options: 0) - return try plistDecoder.decode(XCSchemeManagement.UserStateScheme.self, from: data) - }) } else { - self.suppressBuildableAutocreation = nil + suppressBuildableAutocreation = nil } } - + public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - - if let suppressBuildableAutocreation = suppressBuildableAutocreation { + + if let suppressBuildableAutocreation { try container.encode(suppressBuildableAutocreation, forKey: .suppressBuildableAutocreation) } - - if let schemeUserState = schemeUserState { + + if let schemeUserState { let encodableSchemeUserState = schemeUserState .reduce(into: [String: XCSchemeManagement.UserStateScheme]()) { $0[$1.key] = $1 } try container.encode(encodableSchemeUserState, forKey: .schemeUserState) diff --git a/Sources/XcodeProj/Utils/BuildSettingsProvider.swift b/Sources/XcodeProj/Utils/BuildSettingsProvider.swift index 574f50ca2..82a845c36 100644 --- a/Sources/XcodeProj/Utils/BuildSettingsProvider.swift +++ b/Sources/XcodeProj/Utils/BuildSettingsProvider.swift @@ -48,31 +48,31 @@ public class BuildSettingsProvider { public static func targetDefault(variant: Variant? = nil, platform: Platform?, product: Product?, swift: Bool? = nil) -> BuildSettings { var buildSettings: [String: Any] = [:] - if let platform = platform { + if let platform { buildSettings.merge(targetSettings(platform: platform), uniquingKeysWith: { $1 }) } - if let product = product { + if let product { buildSettings.merge(targetSettings(product: product), uniquingKeysWith: { $1 }) } - if let platform = platform, let product = product { + if let platform, let product { buildSettings.merge(targetSettings(platform: platform, product: product), uniquingKeysWith: { $1 }) } - if let platform = platform, let variant = variant { + if let platform, let variant { buildSettings.merge(targetSettings(variant: variant, platform: platform), uniquingKeysWith: { $1 }) } - if let variant = variant, let swift = swift, swift == true { + if let variant, let swift, swift == true { buildSettings.merge(targetSwiftSettings(variant: variant), uniquingKeysWith: { $1 }) } - if let product = product, let swift = swift, swift == true { + if let product, let swift, swift == true { buildSettings.merge(targetSwiftSettings(product: product), uniquingKeysWith: { $1 }) } - if let platform = platform, let product = product, let swift = swift, swift == true { + if let platform, let product, let swift, swift == true { buildSettings.merge(targetSwiftSettings(platform: platform, product: product), uniquingKeysWith: { $1 }) } diff --git a/Sources/XcodeProj/Utils/CommentedString.swift b/Sources/XcodeProj/Utils/CommentedString.swift index d543d975e..2420f8e05 100644 --- a/Sources/XcodeProj/Utils/CommentedString.swift +++ b/Sources/XcodeProj/Utils/CommentedString.swift @@ -43,7 +43,7 @@ struct CommentedString { if string.rangeOfCharacter(from: CommentedString.invalidCharacters) == nil { if string.rangeOfCharacter(from: CommentedString.specialCheckCharacters) == nil { return string - } else if !string.contains("//") && !string.contains("___") { + } else if !string.contains("//"), !string.contains("___") { return string } } diff --git a/Sources/XcodeProj/Utils/Decoders.swift b/Sources/XcodeProj/Utils/Decoders.swift index f298d1d5b..1bf6522cd 100644 --- a/Sources/XcodeProj/Utils/Decoders.swift +++ b/Sources/XcodeProj/Utils/Decoders.swift @@ -44,7 +44,7 @@ class ProjectDecodingContext { extension CodingUserInfoKey { /// Context user info key. - static let context: CodingUserInfoKey = CodingUserInfoKey(rawValue: "context")! + static let context: CodingUserInfoKey = .init(rawValue: "context")! } /// Xcodeproj JSON decoder. diff --git a/Sources/XcodeProj/Utils/JSONDecoding.swift b/Sources/XcodeProj/Utils/JSONDecoding.swift index ac3311694..2e80a6074 100644 --- a/Sources/XcodeProj/Utils/JSONDecoding.swift +++ b/Sources/XcodeProj/Utils/JSONDecoding.swift @@ -21,8 +21,8 @@ extension KeyedDecodingContainer { func decode(_ type: [String: Any].Type, forKey key: K) throws -> [String: Any] { // Optimization for root dictionary decoding if let decoder = try? superDecoder().context, - let pbxProjValueReader = decoder.pbxProjValueReader, - let result = pbxProjValueReader(key.stringValue) as? [String: Any] { + let pbxProjValueReader = decoder.pbxProjValueReader, + let result = pbxProjValueReader(key.stringValue) as? [String: Any] { return result } let container = try nestedContainer(keyedBy: JSONCodingKeys.self, forKey: key) @@ -95,7 +95,7 @@ extension UnkeyedDecodingContainer { } mutating func decode(_ type: [String: Any].Type) throws -> [String: Any] { - let nestedContainer = try self.nestedContainer(keyedBy: JSONCodingKeys.self) + let nestedContainer = try nestedContainer(keyedBy: JSONCodingKeys.self) return try nestedContainer.decode(type) } } diff --git a/Sources/XcodeProj/Utils/PBXBatchUpdater.swift b/Sources/XcodeProj/Utils/PBXBatchUpdater.swift index a00d30c5a..d23a49262 100644 --- a/Sources/XcodeProj/Utils/PBXBatchUpdater.swift +++ b/Sources/XcodeProj/Utils/PBXBatchUpdater.swift @@ -28,17 +28,17 @@ public final class PBXBatchUpdater { sourceTree: PBXSourceTree = .group ) throws -> PBXFileReference { - let (group, groupPath) = try groupAndGroupPathForFile( - at: filePath, - project: project - ) - return try addFile( - to: group, - groupPath: groupPath, - filePath: filePath, - sourceTree: sourceTree - ) - } + let (group, groupPath) = try groupAndGroupPathForFile( + at: filePath, + project: project + ) + return try addFile( + to: group, + groupPath: groupPath, + filePath: filePath, + sourceTree: sourceTree + ) + } /// Adds file at the give path to the project or returns existing file and its reference. /// @@ -54,15 +54,15 @@ public final class PBXBatchUpdater { sourceTree: PBXSourceTree = .group ) throws -> PBXFileReference { - let groupPath = try group.fullPath(sourceRoot: sourceRoot)! - let filePath = groupPath + Path(fileName) - return try addFile( - to: group, - groupPath: groupPath, - filePath: filePath, - sourceTree: sourceTree - ) - } + let groupPath = try group.fullPath(sourceRoot: sourceRoot)! + let filePath = groupPath + Path(fileName) + return try addFile( + to: group, + groupPath: groupPath, + filePath: filePath, + sourceTree: sourceTree + ) + } private func addFile( to group: PBXGroup, @@ -71,41 +71,41 @@ public final class PBXBatchUpdater { sourceTree: PBXSourceTree = .group ) throws -> PBXFileReference { - if let existing = try existingFileReference(at: filePath, in: group) { - return existing - } + if let existing = try existingFileReference(at: filePath, in: group) { + return existing + } - let path: String? - switch sourceTree { - case .group: - path = filePath.relative(to: groupPath).string - case .sourceRoot: - path = filePath.relative(to: sourceRoot).string - case .absolute: - path = filePath.string - default: - path = nil - } - let fileReference = PBXFileReference( - sourceTree: sourceTree, - name: filePath.lastComponent, - explicitFileType: filePath.extension.flatMap(Xcode.filetype), - lastKnownFileType: filePath.extension.flatMap(Xcode.filetype), - path: path - ) - objects.add(object: fileReference) - fileReference.parent = group - references?[filePath] = fileReference.reference - if !group.childrenReferences.contains(fileReference.reference) { - group.childrenReferences.append(fileReference.reference) - } - return fileReference + let path: String? + switch sourceTree { + case .group: + path = filePath.relative(to: groupPath).string + case .sourceRoot: + path = filePath.relative(to: sourceRoot).string + case .absolute: + path = filePath.string + default: + path = nil + } + let fileReference = PBXFileReference( + sourceTree: sourceTree, + name: filePath.lastComponent, + explicitFileType: filePath.extension.flatMap(Xcode.filetype), + lastKnownFileType: filePath.extension.flatMap(Xcode.filetype), + path: path + ) + objects.add(object: fileReference) + fileReference.parent = group + references?[filePath] = fileReference.reference + if !group.childrenReferences.contains(fileReference.reference) { + group.childrenReferences.append(fileReference.reference) } + return fileReference + } private func existingFileReference(at filePath: Path, in group: PBXGroup) throws -> PBXFileReference? { let objectReferences = try lazilyInstantiateObjectReferences() if let existingObjectReference = objectReferences[filePath], - let existingFileReference = objects.fileReferences[existingObjectReference] { + let existingFileReference = objects.fileReferences[existingObjectReference] { if !group.childrenReferences.contains(existingObjectReference) { group.childrenReferences.append(existingObjectReference) } @@ -155,23 +155,23 @@ public final class PBXBatchUpdater { with names: [String] ) throws -> PBXGroup { - var parent = group - for (index, name) in names.enumerated() { - let path = groupPath + Path(components: names[0 ... index]) - parent = try parent.addGroup(named: name).last! - groups?[path] = parent - } - return parent + var parent = group + for (index, name) in names.enumerated() { + let path = groupPath + Path(components: names[0 ... index]) + parent = try parent.addGroup(named: name).last! + groups?[path] = parent } + return parent + } private func lazilyInstantiateObjectReferences() throws -> [Path: PBXObjectReference] { let objectReferences: [Path: PBXObjectReference] - if let references = self.references { + if let references { objectReferences = references } else { - objectReferences = Dictionary(uniqueKeysWithValues: - try objects.fileReferences.compactMap { + objectReferences = try Dictionary(uniqueKeysWithValues: + objects.fileReferences.compactMap { let fullPath = try $0.value.fullPath(sourceRoot: sourceRoot)! return (fullPath, $0.key) }) @@ -182,11 +182,11 @@ public final class PBXBatchUpdater { private func lazilyInstantiateGroups() throws -> [Path: PBXGroup] { let unwrappedGroups: [Path: PBXGroup] - if let groups = self.groups { + if let groups { unwrappedGroups = groups } else { - unwrappedGroups = Dictionary(uniqueKeysWithValues: - try objects.groups.compactMap { + unwrappedGroups = try Dictionary(uniqueKeysWithValues: + objects.groups.compactMap { let fullPath = try $0.value.fullPath(sourceRoot: sourceRoot)! return (fullPath, $0.value) }) diff --git a/Sources/XcodeProj/Utils/PlistValue.swift b/Sources/XcodeProj/Utils/PlistValue.swift index abd99a51b..d36496c50 100644 --- a/Sources/XcodeProj/Utils/PlistValue.swift +++ b/Sources/XcodeProj/Utils/PlistValue.swift @@ -105,7 +105,7 @@ extension Dictionary where Key == String { extension Array { func plist() -> PlistValue { - .array(compactMap { (element) -> PlistValue? in + .array(compactMap { element -> PlistValue? in if let array = element as? [Any] { return array.plist() } else if let dictionary = element as? [String: Any] { diff --git a/Sources/XcodeProj/Utils/ReferenceGenerator.swift b/Sources/XcodeProj/Utils/ReferenceGenerator.swift index e4a5f3da9..07fdb262d 100644 --- a/Sources/XcodeProj/Utils/ReferenceGenerator.swift +++ b/Sources/XcodeProj/Utils/ReferenceGenerator.swift @@ -31,7 +31,7 @@ final class ReferenceGenerator: ReferenceGenerating { // cache current reference values var references: Set = [] - proj.objects.forEach { object in + for object in proj.objects { if !object.reference.temporary { references.insert(object.reference.value) } @@ -53,7 +53,7 @@ final class ReferenceGenerator: ReferenceGenerating { // Project references try project.projectReferences.forEach { objectReferenceDict in guard let projectReference = objectReferenceDict[Xcode.ProjectReference.projectReferenceKey]?.getObject() as? PBXFileReference, - let productsGroup = objectReferenceDict[Xcode.ProjectReference.productGroupKey]?.getObject() as? PBXGroup else { return } + let productsGroup = objectReferenceDict[Xcode.ProjectReference.productGroupKey]?.getObject() as? PBXGroup else { return } try generateFileReference(projectReference, identifiers: identifiers) try generateGroupReferences(productsGroup, identifiers: identifiers + [projectReference.name ?? projectReference.path ?? ""]) } @@ -79,31 +79,30 @@ final class ReferenceGenerator: ReferenceGenerating { fixReference(for: project, identifiers: identifiers) // Packages - project.remotePackages.forEach { + for remotePackage in project.remotePackages { var identifiers = identifiers - identifiers.append($0.repositoryURL ?? $0.name ?? "") - fixReference(for: $0, identifiers: identifiers) + identifiers.append(remotePackage.repositoryURL ?? remotePackage.name ?? "") + fixReference(for: remotePackage, identifiers: identifiers) } // Packages - project.localPackages.forEach { + for localPackage in project.localPackages { var identifiers = identifiers - identifiers.append($0.relativePath) - fixReference(for: $0, identifiers: identifiers) + identifiers.append(localPackage.relativePath) + fixReference(for: localPackage, identifiers: identifiers) } // Targets let targets: [PBXTarget] = project.targetReferences.objects() - targets.forEach { target in - + for target in targets { var identifiers = identifiers identifiers.append(target.name) // Packages - target.packageProductDependencies.forEach { + for packageProductDependency in target.packageProductDependencies { var identifiers = identifiers - identifiers.append($0.productName) - fixReference(for: $0, identifiers: identifiers) + identifiers.append(packageProductDependency.productName) + fixReference(for: packageProductDependency, identifiers: identifiers) } // Build Tool Plug-ins @@ -223,9 +222,9 @@ final class ReferenceGenerator: ReferenceGenerating { // Target proxy if let targetProxyReference = targetDependency.targetProxyReference, - targetProxyReference.temporary, - let targetProxy = targetDependency.targetProxy, - let remoteGlobalIDString = targetProxy.remoteGlobalID?.uuid { + targetProxyReference.temporary, + let targetProxy = targetDependency.targetProxy, + let remoteGlobalIDString = targetProxy.remoteGlobalID?.uuid { var identifiers = identifiers identifiers.append(remoteGlobalIDString) fixReference(for: targetProxy, identifiers: identifiers) @@ -302,7 +301,7 @@ final class ReferenceGenerator: ReferenceGenerating { var identifiers = identifiers if let fileReference = buildFile.fileReference, - let fileReferenceObject: PBXObject = fileReference.getObject() { + let fileReferenceObject: PBXObject = fileReference.getObject() { identifiers.append(fileReferenceObject.reference.value) } @@ -333,8 +332,8 @@ extension ReferenceGenerator { /// - Parameters: /// - object: The object to generate a reference for /// - identifiers: list of identifiers used to generate the reference of the object. - func fixReference(for object: T, - identifiers: [String]) { + func fixReference(for object: some PBXObject, + identifiers: [String]) { if object.reference.temporary { var identifiers = identifiers if let context = object.context { diff --git a/Sources/XcodeProj/Utils/XCConfig.swift b/Sources/XcodeProj/Utils/XCConfig.swift index 7f7a119a1..e1e585ea6 100644 --- a/Sources/XcodeProj/Utils/XCConfig.swift +++ b/Sources/XcodeProj/Utils/XCConfig.swift @@ -43,7 +43,7 @@ public final class XCConfig { } } -final class XCConfigParser { +enum XCConfigParser { /// Given the path the line is being parsed from, it returns a function that parses a line, /// and returns the include path and the config that the include is pointing to. /// @@ -56,19 +56,19 @@ final class XCConfigParser { options: [], range: NSRange(location: 0, length: line.count)) - .compactMap { (match) -> String? in + .compactMap { match -> String? in if match.numberOfRanges == 2 { return NSString(string: line).substring(with: match.range(at: 1)) } return nil } .compactMap { pathString in - let includePath: Path = Path(pathString) + let includePath: Path = .init(pathString) var config: XCConfig? do { // first try to load the included xcconfig relative to the current xcconfig config = try XCConfig(path: path.parent() + includePath, projectPath: projectPath) - } catch (XCConfigError.notFound(_)) where projectPath != nil { + } catch XCConfigError.notFound(_) where projectPath != nil { // if that fails, try to load the included xcconfig relative to the project config = try? XCConfig(path: projectPath!.parent() + includePath, projectPath: projectPath) } catch { @@ -85,7 +85,7 @@ final class XCConfigParser { options: [], range: NSRange(location: 0, length: line.count)) - .compactMap { (match) -> (key: String, value: String)? in + .compactMap { match -> (key: String, value: String)? in if match.numberOfRanges == 3 { let key: String = NSString(string: line).substring(with: match.range(at: 1)) let value: String = NSString(string: line).substring(with: match.range(at: 2)) @@ -120,18 +120,18 @@ extension XCConfig: Equatable { // MARK: - XCConfig Extension (Helpers) -extension XCConfig { +public extension XCConfig { /// It returns the build settings after flattening all the includes. /// /// - Returns: build settings flattening all the includes. - public func flattenedBuildSettings() -> [String: Any] { + func flattenedBuildSettings() -> [String: Any] { var content: [String: Any] = buildSettings includes - .map { $0.1 } + .map(\.1) .flattened() - .map { $0.buildSettings } + .map(\.buildSettings) .forEach { configDictionary in - configDictionary.forEach { key, value in + for (key, value) in configDictionary { if content[key] == nil { content[key] = value } } } @@ -149,11 +149,11 @@ extension XCConfig: Writable { } try path.write(content) } - + public func dataRepresentation() throws -> Data? { getContent().data(using: .utf8) } - + private func getContent() -> String { var content = "" content.append(writeIncludes()) @@ -164,7 +164,7 @@ extension XCConfig: Writable { private func writeIncludes() -> String { var content = "" - includes.forEach { include in + for include in includes { content.append("#include \"\(include.0.string)\"\n") } content.append("\n") @@ -173,7 +173,7 @@ extension XCConfig: Writable { private func writeBuildSettings() -> String { var content = "" - buildSettings.forEach { key, value in + for (key, value) in buildSettings { content.append("\(key) = \(value)\n") } content.append("\n") @@ -183,15 +183,15 @@ extension XCConfig: Writable { // MARK: - Array Extension (XCConfig) -extension Array where Element == XCConfig { +extension [XCConfig] { /// It returns an array with the XCConfig reversely flattened. It's useful for resolving the build settings. /// /// - Returns: flattened configurations array. func flattened() -> [XCConfig] { - let reversed = self.reversed() - .flatMap { (config) -> [XCConfig] in + let reversed = reversed() + .flatMap { config -> [XCConfig] in var configs = [XCConfig(includes: [], buildSettings: config.buildSettings)] - configs.append(contentsOf: config.includes.map { $0.1 }.flattened()) + configs.append(contentsOf: config.includes.map(\.1).flattened()) return configs } return reversed diff --git a/Sources/XcodeProj/Workspace/XCWorkspace.swift b/Sources/XcodeProj/Workspace/XCWorkspace.swift index 4707d9305..7f99f6c0a 100644 --- a/Sources/XcodeProj/Workspace/XCWorkspace.swift +++ b/Sources/XcodeProj/Workspace/XCWorkspace.swift @@ -67,9 +67,9 @@ public final class XCWorkspace: Writable, Equatable { try dataPath.mkpath() try data.write(path: dataPath) } - + public func dataRepresentation() throws -> Data? { - self.data.rawContents().data(using: .utf8) + data.rawContents().data(using: .utf8) } // MARK: - Equatable diff --git a/Sources/XcodeProj/Workspace/XCWorkspaceData.swift b/Sources/XcodeProj/Workspace/XCWorkspaceData.swift index 9cd95c7c9..13c413bbe 100644 --- a/Sources/XcodeProj/Workspace/XCWorkspaceData.swift +++ b/Sources/XcodeProj/Workspace/XCWorkspaceData.swift @@ -36,7 +36,7 @@ extension XCWorkspaceData: Writable { self.init(children: children) } - + func rawContents() -> String { let document = AEXMLDocument() let workspace = document.addChild(name: "Workspace", value: nil, attributes: ["version": "1.0"]) @@ -47,7 +47,7 @@ extension XCWorkspaceData: Writable { } // MARK: - - + public func write(path: Path, override: Bool = true) throws { let rawXml = rawContents() if override, path.exists { @@ -55,7 +55,7 @@ extension XCWorkspaceData: Writable { } try path.write(rawXml) } - + public func dataRepresentation() throws -> Data? { rawContents().data(using: .utf8) } @@ -134,7 +134,7 @@ private extension XCWorkspaceDataFileRef { guard let location = element.attributes["location"] else { throw Error.missingLocationAttribute } - self.init(location: try XCWorkspaceDataElementLocationType(string: location)) + try self.init(location: XCWorkspaceDataElementLocationType(string: location)) } func xmlElement() -> AEXMLElement { diff --git a/Tests/XcodeProjTests/Extensions/AEXML+XcodeFormatTests.swift b/Tests/XcodeProjTests/Extensions/AEXML+XcodeFormatTests.swift index bbae0766e..d7836dffc 100644 --- a/Tests/XcodeProjTests/Extensions/AEXML+XcodeFormatTests.swift +++ b/Tests/XcodeProjTests/Extensions/AEXML+XcodeFormatTests.swift @@ -123,7 +123,7 @@ class AEXML_XcodeFormatTests: XCTestCase { "buildConfiguration": "Debug", "selectedLauncherIdentifier": "Xcode.DebuggerFoundation.Launcher.LLDB", "launchStyle": "0", - "askForAppToLaunch": "YES" + "askForAppToLaunch": "YES", ] ) } @@ -151,7 +151,7 @@ class AEXML_XcodeFormatTests: XCTestCase { "shouldUseLaunchSchemeArgsEnv": "YES", "buildConfiguration": "Debug", "customLLDBInitFile": "$(BAZEL_LLDB_INIT)", - "selectedLauncherIdentifier": "Xcode.DebuggerFoundation.Launcher.LLDB" + "selectedLauncherIdentifier": "Xcode.DebuggerFoundation.Launcher.LLDB", ] ) } @@ -163,7 +163,7 @@ class AEXML_XcodeFormatTests: XCTestCase { attributes: [ "LastUpgradeVersion": "1320", "wasCreatedForAppExtension": "YES", - "version": "1.7" + "version": "1.7", ] ) } @@ -175,7 +175,7 @@ class AEXML_XcodeFormatTests: XCTestCase { attributes: [ "wasCreatedForAppExtension": "YES", "LastUpgradeVersion": "1320", - "version": "1.7" + "version": "1.7", ] ) } @@ -187,7 +187,7 @@ class AEXML_XcodeFormatTests: XCTestCase { attributes: [ "BundleIdentifier": "BundleID", "RemotePath": "REMOTE_PATH", - "runnableDebuggingMode": "2" + "runnableDebuggingMode": "2", ] ) } diff --git a/Tests/XcodeProjTests/Extensions/XCTestCase+Assertions.swift b/Tests/XcodeProjTests/Extensions/XCTestCase+Assertions.swift index 67df9c183..9d1330dd1 100644 --- a/Tests/XcodeProjTests/Extensions/XCTestCase+Assertions.swift +++ b/Tests/XcodeProjTests/Extensions/XCTestCase+Assertions.swift @@ -2,7 +2,7 @@ import Foundation import XCTest extension XCTestCase { - typealias EquatableError = Error & Equatable + typealias EquatableError = Equatable & Error func XCTAssertNotNilAndUnwrap(_ obj: T?, message: String = "") -> T { guard let unwrappedObj = obj else { @@ -12,7 +12,7 @@ extension XCTestCase { return unwrappedObj } - func XCTAssertThrowsSpecificError(_ expression: @autoclosure () throws -> T, _ error: E, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { + func XCTAssertThrowsSpecificError(_ expression: @autoclosure () throws -> some Any, _ error: E, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { XCTAssertThrowsError(try expression(), message(), file: file, line: line) { actualError in let message = "Expected \(error) got \(actualError)" diff --git a/Tests/XcodeProjTests/Objects/BuildPhase/PBXBuildFileTests.swift b/Tests/XcodeProjTests/Objects/BuildPhase/PBXBuildFileTests.swift index 517dad192..5dbd1cd22 100644 --- a/Tests/XcodeProjTests/Objects/BuildPhase/PBXBuildFileTests.swift +++ b/Tests/XcodeProjTests/Objects/BuildPhase/PBXBuildFileTests.swift @@ -8,7 +8,7 @@ final class PBXBuildFileTests: XCTestCase { } func test_platformFilterIsSet() { - let pbxBuildFile: PBXBuildFile = PBXBuildFile( + let pbxBuildFile = PBXBuildFile( platformFilter: "platformFilter" ) XCTAssertEqual(pbxBuildFile.platformFilter, "platformFilter") diff --git a/Tests/XcodeProjTests/Objects/BuildPhase/PBXShellScriptBuildPhaseTests.swift b/Tests/XcodeProjTests/Objects/BuildPhase/PBXShellScriptBuildPhaseTests.swift index 86692b49a..18de54b2c 100644 --- a/Tests/XcodeProjTests/Objects/BuildPhase/PBXShellScriptBuildPhaseTests.swift +++ b/Tests/XcodeProjTests/Objects/BuildPhase/PBXShellScriptBuildPhaseTests.swift @@ -16,7 +16,8 @@ final class PBXShellScriptBuildPhaseTests: XCTestCase { let (_, doNotShowPlistValue) = try doNotShow.plistKeyAndValue(proj: proj, reference: "ref") if case let PlistValue.dictionary(showDictionary) = showPlistValue, - case let PlistValue.dictionary(doNotShowDictionary) = doNotShowPlistValue { + case let PlistValue.dictionary(doNotShowDictionary) = doNotShowPlistValue + { XCTAssertNil(showDictionary["showEnvVarsInLog"]) XCTAssertEqual(doNotShowDictionary["showEnvVarsInLog"]?.string, "0") } else { @@ -35,7 +36,8 @@ final class PBXShellScriptBuildPhaseTests: XCTestCase { guard case let .dictionary(valuesWhenNotPresent) = try alwaysOutOfDateNotPresent.plistKeyAndValue(proj: proj, reference: "ref").value, case let .dictionary(valuesWhenFalse) = try alwaysOutOfDateFalse.plistKeyAndValue(proj: proj, reference: "ref").value, - case let .dictionary(valuesWhenTrue) = try alwaysOutOfDateTrue.plistKeyAndValue(proj: proj, reference: "ref").value else { + case let .dictionary(valuesWhenTrue) = try alwaysOutOfDateTrue.plistKeyAndValue(proj: proj, reference: "ref").value + else { XCTFail("Plist should contain dictionary") return } @@ -45,7 +47,7 @@ final class PBXShellScriptBuildPhaseTests: XCTestCase { XCTAssertFalse(valuesWhenFalse.keys.contains("alwaysOutOfDate")) XCTAssertEqual(valuesWhenTrue["alwaysOutOfDate"], "1") } - + func test_write_dependencyFile() throws { let discoveryPath = "$(DERIVED_FILE_DIR)/target.d" let discovery = PBXShellScriptBuildPhase(dependencyFile: discoveryPath) diff --git a/Tests/XcodeProjTests/Objects/Configuration/XCConfigurationList+Fixtures.swift b/Tests/XcodeProjTests/Objects/Configuration/XCConfigurationList+Fixtures.swift index f3b6e28ee..975838b02 100644 --- a/Tests/XcodeProjTests/Objects/Configuration/XCConfigurationList+Fixtures.swift +++ b/Tests/XcodeProjTests/Objects/Configuration/XCConfigurationList+Fixtures.swift @@ -5,7 +5,8 @@ extension XCConfigurationList { static func fixture(buildConfigurations: [XCBuildConfiguration] = [XCBuildConfiguration.fixture(name: "Debug"), XCBuildConfiguration.fixture(name: "Release")], defaultConfigurationName: String? = "Debug", - defaultConfigurationIsVisible _: Bool = true) -> XCConfigurationList { + defaultConfigurationIsVisible _: Bool = true) -> XCConfigurationList + { XCConfigurationList(buildConfigurations: buildConfigurations, defaultConfigurationName: defaultConfigurationName) } diff --git a/Tests/XcodeProjTests/Objects/Configuration/XCConfigurationListTests.swift b/Tests/XcodeProjTests/Objects/Configuration/XCConfigurationListTests.swift index 447ed7e5d..1a3824506 100644 --- a/Tests/XcodeProjTests/Objects/Configuration/XCConfigurationListTests.swift +++ b/Tests/XcodeProjTests/Objects/Configuration/XCConfigurationListTests.swift @@ -12,7 +12,7 @@ final class XCConfigurationListTests: XCTestCase { let configurationList = XCConfigurationList(buildConfigurations: []) objects.add(object: configurationList) let configurations = try configurationList.addDefaultConfigurations() - let names = configurations.map { $0.name } + let names = configurations.map(\.name) XCTAssertEqual(configurations.count, 2) XCTAssertTrue(names.contains("Debug")) diff --git a/Tests/XcodeProjTests/Objects/Files/PBXFileReference+Fixtures.swift b/Tests/XcodeProjTests/Objects/Files/PBXFileReference+Fixtures.swift index 042d56e11..58c650873 100644 --- a/Tests/XcodeProjTests/Objects/Files/PBXFileReference+Fixtures.swift +++ b/Tests/XcodeProjTests/Objects/Files/PBXFileReference+Fixtures.swift @@ -4,7 +4,8 @@ import Foundation extension PBXFileReference { static func fixture(sourceTree _: PBXSourceTree = .group, - name: String? = "Test") -> PBXFileReference { + name: String? = "Test") -> PBXFileReference + { PBXFileReference(sourceTree: .group, name: name) } } diff --git a/Tests/XcodeProjTests/Objects/Files/PBXGroup+Fixtures.swift b/Tests/XcodeProjTests/Objects/Files/PBXGroup+Fixtures.swift index 0f95e2b45..fb617bd00 100644 --- a/Tests/XcodeProjTests/Objects/Files/PBXGroup+Fixtures.swift +++ b/Tests/XcodeProjTests/Objects/Files/PBXGroup+Fixtures.swift @@ -4,7 +4,8 @@ import Foundation extension PBXGroup { static func fixture(children _: [PBXFileElement] = [], sourceTree: PBXSourceTree = .group, - name: String = "test") -> PBXGroup { + name: String = "test") -> PBXGroup + { PBXGroup(children: [], sourceTree: sourceTree, name: name) diff --git a/Tests/XcodeProjTests/Objects/Files/PBXGroupTests.swift b/Tests/XcodeProjTests/Objects/Files/PBXGroupTests.swift index 6fd5360d5..915a714da 100644 --- a/Tests/XcodeProjTests/Objects/Files/PBXGroupTests.swift +++ b/Tests/XcodeProjTests/Objects/Files/PBXGroupTests.swift @@ -71,7 +71,7 @@ final class PBXGroupTests: XCTestCase { XCTAssertEqual(childVariantGroups.count, expectedGroupNames.count) - childVariantGroups.enumerated().forEach { index, variantGroup in + for (index, variantGroup) in childVariantGroups.enumerated() { let parentGroup = (index == 0) ? group : childVariantGroups[index - 1] if index == childVariantGroups.count - 1 { diff --git a/Tests/XcodeProjTests/Objects/Files/XCVersionGroup+Fixtures.swift b/Tests/XcodeProjTests/Objects/Files/XCVersionGroup+Fixtures.swift index 604c1a277..310a5da4f 100644 --- a/Tests/XcodeProjTests/Objects/Files/XCVersionGroup+Fixtures.swift +++ b/Tests/XcodeProjTests/Objects/Files/XCVersionGroup+Fixtures.swift @@ -8,14 +8,15 @@ extension XCVersionGroup { name: String? = "name", sourceTree: PBXSourceTree = .group, versionGroupType: String = "versionGroupType", - children: [PBXFileReference] = [PBXFileReference(name: "currentVersion")]) -> XCVersionGroup { + children: [PBXFileReference] = [PBXFileReference(name: "currentVersion")]) -> XCVersionGroup + { let group = XCVersionGroup(currentVersion: currentVersion, path: path, name: name, sourceTree: sourceTree, versionGroupType: versionGroupType, children: children) - if let currentVersion = currentVersion { + if let currentVersion { objects.add(object: currentVersion) } children.forEach { objects.add(object: $0) } diff --git a/Tests/XcodeProjTests/Objects/Project/PBXOutputSettingsTests.swift b/Tests/XcodeProjTests/Objects/Project/PBXOutputSettingsTests.swift index 33c5fc8f3..03fbc0222 100644 --- a/Tests/XcodeProjTests/Objects/Project/PBXOutputSettingsTests.swift +++ b/Tests/XcodeProjTests/Objects/Project/PBXOutputSettingsTests.swift @@ -6,28 +6,28 @@ class PBXOutputSettingsTests: XCTestCase { // MARK: - PBXFileOrder - PBXBuldFile func test_PBXFileOrder_PBXBuildFile_by_uuid_when_iosProject() { - let iosProject = self.iosProject() + let iosProject = iosProject() XCTAssertFalse(PBXFileOrder.byUUID.sort(lhs: iosProject.objectBuildFileAssets, rhs: iosProject.objectBuildFileMain)) XCTAssertTrue(PBXFileOrder.byUUID.sort(lhs: iosProject.objectBuildFileMain, rhs: iosProject.objectBuildFileAssets)) } func test_PBXFileOrder_PBXBuildFile_by_filename_when_iosProject() { - let iosProject = self.iosProject() + let iosProject = iosProject() XCTAssertTrue(PBXFileOrder.byFilename.sort(lhs: iosProject.objectBuildFileAssets, rhs: iosProject.objectBuildFileMain)) XCTAssertFalse(PBXFileOrder.byFilename.sort(lhs: iosProject.objectBuildFileMain, rhs: iosProject.objectBuildFileAssets)) } func test_PBXFileOrder_PBXBuildFile_by_filename_when_fileSharedAcrossTargetsProject() { - let fileSharedAcrossTargetsProject = self.fileSharedAcrossTargetsProject() + let fileSharedAcrossTargetsProject = fileSharedAcrossTargetsProject() let sameNameByFilename = fileSharedAcrossTargetsProject.objectBuildFileSameName.sorted(by: PBXFileOrder.byFilename.sort) XCTAssertLessThan(sameNameByFilename.first!.1.uuid, sameNameByFilename.last!.1.uuid) } func test_PBXFileOrder_PBXBuildFile_by_filename_when_nil_name_and_path_when_iosProject() { - let iosProject = self.iosProject() + let iosProject = iosProject() iosProject.buildFileAssets.file?.name = nil iosProject.buildFileMain.file?.name = nil @@ -38,7 +38,7 @@ class PBXOutputSettingsTests: XCTestCase { } func test_PBXFileOrder_PBXBuildFile_by_filename_when_no_file_when_iosProject() { - let iosProject = self.iosProject() + let iosProject = iosProject() let ref1 = iosProject.buildFileAssets.reference let ref2 = iosProject.buildFileMain.reference @@ -51,14 +51,14 @@ class PBXOutputSettingsTests: XCTestCase { // MARK: - PBXFileOrder - PBXBuildPhaseFile func test_PBXFileOrder_PBXBuildPhaseFile_by_uuid_when_iosProject() { - let iosProject = self.iosProject() + let iosProject = iosProject() XCTAssertFalse(PBXFileOrder.byUUID.sort(lhs: iosProject.objectBuildPhaseFileAssets, rhs: iosProject.objectBuildPhaseFileMain)) XCTAssertTrue(PBXFileOrder.byUUID.sort(lhs: iosProject.objectBuildPhaseFileMain, rhs: iosProject.objectBuildPhaseFileAssets)) } func test_PBXFileOrder_PBXBuildPhaseFile_by_filename_when_iosProject() { - let iosProject = self.iosProject() + let iosProject = iosProject() XCTAssertTrue(PBXFileOrder.byFilename.sort(lhs: iosProject.objectBuildPhaseFileAssets, rhs: iosProject.objectBuildPhaseFileMain)) XCTAssertFalse(PBXFileOrder.byFilename.sort(lhs: iosProject.objectBuildPhaseFileMain, rhs: iosProject.objectBuildPhaseFileAssets)) @@ -67,28 +67,28 @@ class PBXOutputSettingsTests: XCTestCase { // MARK: - PBXFileOrder - PBXFileReference func test_PBXFileOrder_PBXFileReference_by_uuid_when_iosProject() { - let iosProject = self.iosProject() + let iosProject = iosProject() XCTAssertFalse(PBXFileOrder.byUUID.sort(lhs: iosProject.objectFileReferenceAssets, rhs: iosProject.objectFileReferenceCoreData)) XCTAssertTrue(PBXFileOrder.byUUID.sort(lhs: iosProject.objectFileReferenceCoreData, rhs: iosProject.objectFileReferenceAssets)) } func test_PBXFileOrder_PBXFileReference_by_filename_when_iosProject() { - let iosProject = self.iosProject() + let iosProject = iosProject() XCTAssertTrue(PBXFileOrder.byFilename.sort(lhs: iosProject.objectFileReferenceAssets, rhs: iosProject.objectFileReferenceCoreData)) XCTAssertFalse(PBXFileOrder.byFilename.sort(lhs: iosProject.objectFileReferenceCoreData, rhs: iosProject.objectFileReferenceAssets)) } func test_PBXFileOrder_PBXFileReference_by_filename_when_fileSharedAcrossTargetsProject() { - let fileSharedAcrossTargetsProject = self.fileSharedAcrossTargetsProject() + let fileSharedAcrossTargetsProject = fileSharedAcrossTargetsProject() let sameNameByFilename = fileSharedAcrossTargetsProject.objectFileReferenceSameName.sorted(by: PBXFileOrder.byFilename.sort) XCTAssertLessThan(sameNameByFilename.first!.1.uuid, sameNameByFilename.last!.1.uuid) } func test_PBXFileOrder_PBXFileReference_by_filename_when_nil_name_and_path_when_iosProject() { - let iosProject = self.iosProject() + let iosProject = iosProject() iosProject.fileReferenceAssets.name = nil iosProject.fileReferenceCoreData.name = nil @@ -101,14 +101,14 @@ class PBXOutputSettingsTests: XCTestCase { // MARK: - PBXFileOrder - Other func test_PBXFileOrder_Other_by_uuid_when_iosProject() { - let iosProject = self.iosProject() + let iosProject = iosProject() XCTAssertTrue(PBXFileOrder.byUUID.sort(lhs: iosProject.objectGroupFrameworks, rhs: iosProject.objectGroupProducts)) XCTAssertFalse(PBXFileOrder.byUUID.sort(lhs: iosProject.objectGroupProducts, rhs: iosProject.objectGroupFrameworks)) } func test_PBXFileOrder_Other_by_filename_when_iosProject() { - let iosProject = self.iosProject() + let iosProject = iosProject() XCTAssertTrue(PBXFileOrder.byFilename.sort(lhs: iosProject.objectGroupFrameworks, rhs: iosProject.objectGroupProducts)) XCTAssertFalse(PBXFileOrder.byFilename.sort(lhs: iosProject.objectGroupProducts, rhs: iosProject.objectGroupFrameworks)) @@ -121,7 +121,7 @@ class PBXOutputSettingsTests: XCTestCase { } func test_PBXNavigatorFileOrder_by_filename_when_iosProject() { - let iosProject = self.iosProject() + let iosProject = iosProject() let sort: (PBXFileElement, PBXFileElement) -> Bool = PBXNavigatorFileOrder.byFilename.sort! let sorted = iosProject.navigatorFileGroup.children.sorted(by: sort).map { $0.fileName()! } @@ -141,7 +141,7 @@ class PBXOutputSettingsTests: XCTestCase { } func test_PBXNavigatorFileOrder_by_filename_groups_first_when_iosProject() { - let iosProject = self.iosProject() + let iosProject = iosProject() let sort: (PBXFileElement, PBXFileElement) -> Bool = PBXNavigatorFileOrder.byFilenameGroupsFirst.sort! let sorted = iosProject.navigatorFileGroup.children.sorted(by: sort).map { $0.fileName()! } @@ -167,7 +167,7 @@ class PBXOutputSettingsTests: XCTestCase { } func test_PBXBuildPhaseFileOrder_by_filename_when_iosProject() { - let iosProject = self.iosProject() + let iosProject = iosProject() XCTAssertTrue(PBXBuildPhaseFileOrder.byFilename.sort!(iosProject.buildFileAssets, iosProject.buildFileMain)) XCTAssertFalse(PBXBuildPhaseFileOrder.byFilename.sort!(iosProject.buildFileMain, iosProject.buildFileAssets)) diff --git a/Tests/XcodeProjTests/Objects/Project/PBXProj+Fixtures.swift b/Tests/XcodeProjTests/Objects/Project/PBXProj+Fixtures.swift index 8a397023b..ade46a2a2 100644 --- a/Tests/XcodeProjTests/Objects/Project/PBXProj+Fixtures.swift +++ b/Tests/XcodeProjTests/Objects/Project/PBXProj+Fixtures.swift @@ -6,7 +6,8 @@ extension PBXProj { objectVersion: UInt = Xcode.LastKnown.objectVersion, archiveVersion: UInt = Xcode.LastKnown.archiveVersion, classes: [String: Any] = [:], - objects: [PBXObject] = []) -> PBXProj { + objects: [PBXObject] = []) -> PBXProj + { PBXProj(rootObject: rootObject, objectVersion: objectVersion, archiveVersion: archiveVersion, diff --git a/Tests/XcodeProjTests/Objects/Project/PBXProjEncoderTests.swift b/Tests/XcodeProjTests/Objects/Project/PBXProjEncoderTests.swift index e7ebb6296..d60e08380 100644 --- a/Tests/XcodeProjTests/Objects/Project/PBXProjEncoderTests.swift +++ b/Tests/XcodeProjTests/Objects/Project/PBXProjEncoderTests.swift @@ -11,7 +11,7 @@ class PBXProjEncoderTests: XCTestCase { func test_writeHeaders_when_iOSProject() throws { try loadiOSProject() - let lines = self.lines(fromFile: encodeProject()) + let lines = lines(fromFile: encodeProject()) XCTAssertEqual(583, lines.count) XCTAssertEqual("// !$*UTF8*$!", lines[0]) } @@ -21,7 +21,7 @@ class PBXProjEncoderTests: XCTestCase { func test_buildFiles_in_default_uuid_order_when_iOSProject() throws { try loadiOSProject() - let lines = self.lines(fromFile: encodeProject()) + let lines = lines(fromFile: encodeProject()) var line = lines.validate(line: "/* Begin PBXBuildFile section */") line = lines.validate(lineContaining: "04D5C09F1F153824008A2F98 /* CoreData.framework in Frameworks */", onLineAfter: line) line = lines.validate(lineContaining: "04D5C0A31F153924008A2F98 /* Public.h in Headers */", onLineAfter: line) @@ -43,7 +43,7 @@ class PBXProjEncoderTests: XCTestCase { try loadiOSProject() let settings = PBXOutputSettings(projFileListOrder: .byFilename) - let lines = self.lines(fromFile: encodeProject(settings: settings)) + let lines = lines(fromFile: encodeProject(settings: settings)) var line = lines.validate(line: "/* Begin PBXBuildFile section */") line = lines.validate(lineContaining: "23766C161EAA3484007A9026 /* AppDelegate.swift in Sources */", onLineAfter: line) line = lines.validate(lineContaining: "23766C1D1EAA3484007A9026 /* Assets.xcassets in Resources */", onLineAfter: line) @@ -65,7 +65,7 @@ class PBXProjEncoderTests: XCTestCase { try loadFileSharedAcrossTargetsProject() let settings = PBXOutputSettings(projFileListOrder: .byFilename) - let lines = self.lines(fromFile: encodeProject(settings: settings)) + let lines = lines(fromFile: encodeProject(settings: settings)) var line = lines.validate(line: "/* Begin PBXBuildFile section */") line = lines.validate(lineContaining: "6C103C032A49CC5400D7EFE4 /* FileSharedAcrossTargets.framework in Frameworks */", onLineAfter: line) @@ -79,7 +79,7 @@ class PBXProjEncoderTests: XCTestCase { func test_file_references_in_default_uuid_order_when_iOSProject() throws { try loadiOSProject() - let lines = self.lines(fromFile: encodeProject()) + let lines = lines(fromFile: encodeProject()) var line = lines.validate(line: "/* Begin PBXFileReference section */") line = lines.validate(lineContaining: "04D5C09E1F153824008A2F98 /* CoreData.framework */", onLineAfter: line) line = lines.validate(lineContaining: "04D5C0A01F153915008A2F98 /* Public.h */", onLineAfter: line) @@ -105,7 +105,7 @@ class PBXProjEncoderTests: XCTestCase { func test_file_references_in_default_uuid_order_when_fileSharedAcrossTargetsProject() throws { try loadFileSharedAcrossTargetsProject() - let lines = self.lines(fromFile: encodeProject()) + let lines = lines(fromFile: encodeProject()) var line = lines.validate(line: "/* Begin PBXFileReference section */") line = lines.validate(lineContaining: "6C103BFA2A49CC5300D7EFE4 /* FileSharedAcrossTargets.framework */", onLineAfter: line) line = lines.validate(lineContaining: "6C103BFD2A49CC5300D7EFE4 /* FileSharedAcrossTargets.h */", onLineAfter: line) @@ -121,7 +121,7 @@ class PBXProjEncoderTests: XCTestCase { try loadiOSProject() let settings = PBXOutputSettings(projFileListOrder: .byFilename) - let lines = self.lines(fromFile: encodeProject(settings: settings)) + let lines = lines(fromFile: encodeProject(settings: settings)) var line = lines.validate(line: "/* Begin PBXFileReference section */") line = lines.validate(lineContaining: "23766C151EAA3484007A9026 /* AppDelegate.swift */", onLineAfter: line) line = lines.validate(lineContaining: "23766C1C1EAA3484007A9026 /* Assets.xcassets */", onLineAfter: line) @@ -147,7 +147,7 @@ class PBXProjEncoderTests: XCTestCase { try loadFileSharedAcrossTargetsProject() let settings = PBXOutputSettings(projFileListOrder: .byFilename) - let lines = self.lines(fromFile: encodeProject(settings: settings)) + let lines = lines(fromFile: encodeProject(settings: settings)) var line = lines.validate(line: "/* Begin PBXFileReference section */") line = lines.validate(lineContaining: "6C103BFA2A49CC5300D7EFE4 /* FileSharedAcrossTargets.framework */", onLineAfter: line) line = lines.validate(lineContaining: "6C103BFD2A49CC5300D7EFE4 /* FileSharedAcrossTargets.h */", onLineAfter: line) @@ -163,7 +163,7 @@ class PBXProjEncoderTests: XCTestCase { func test_navigator_groups_in_default_order_when_iOSProject() throws { try loadiOSProject() - let lines = self.lines(fromFile: encodeProject()) + let lines = lines(fromFile: encodeProject()) let beginGroup = lines.findLine("/* Begin PBXGroup section */") @@ -207,7 +207,7 @@ class PBXProjEncoderTests: XCTestCase { try loadiOSProject() let settings = PBXOutputSettings(projNavigatorFileOrder: .byFilename) - let lines = self.lines(fromFile: encodeProject(settings: settings)) + let lines = lines(fromFile: encodeProject(settings: settings)) let beginGroup = lines.findLine("/* Begin PBXGroup section */") @@ -248,7 +248,7 @@ class PBXProjEncoderTests: XCTestCase { try loadiOSProject() let settings = PBXOutputSettings(projNavigatorFileOrder: .byFilenameGroupsFirst) - let lines = self.lines(fromFile: encodeProject(settings: settings)) + let lines = lines(fromFile: encodeProject(settings: settings)) let beginGroup = lines.findLine("/* Begin PBXGroup section */") @@ -290,7 +290,7 @@ class PBXProjEncoderTests: XCTestCase { func test_build_phase_sources_unsorted_when_iOSProject() throws { try loadiOSProject() - let lines = self.lines(fromFile: encodeProject()) + let lines = lines(fromFile: encodeProject()) let beginGroup = lines.findLine("/* Begin PBXSourcesBuildPhase section */") let files = lines.findLine("files = (", after: beginGroup) let endGroup = lines.findLine("/* End PBXSourcesBuildPhase section */") @@ -303,7 +303,7 @@ class PBXProjEncoderTests: XCTestCase { try loadiOSProject() let settings = PBXOutputSettings(projBuildPhaseFileOrder: .byFilename) - let lines = self.lines(fromFile: encodeProject(settings: settings)) + let lines = lines(fromFile: encodeProject(settings: settings)) let beginGroup = lines.findLine("/* Begin PBXSourcesBuildPhase section */") var line = lines.findLine("files = (", after: beginGroup) line = lines.validate(line: "23766C161EAA3484007A9026 /* AppDelegate.swift in Sources */,", after: line) @@ -315,7 +315,7 @@ class PBXProjEncoderTests: XCTestCase { func test_build_phase_headers_unsorted_when_iOSProject() throws { try loadiOSProject() - let lines = self.lines(fromFile: encodeProject()) + let lines = lines(fromFile: encodeProject()) let beginGroup = lines.findLine("/* Begin PBXHeadersBuildPhase section */") let files = lines.findLine("files = (", after: beginGroup) let endGroup = lines.findLine("/* End PBXHeadersBuildPhase section */") @@ -328,7 +328,7 @@ class PBXProjEncoderTests: XCTestCase { try loadiOSProject() let settings = PBXOutputSettings(projBuildPhaseFileOrder: .byFilename) - let lines = self.lines(fromFile: encodeProject(settings: settings)) + let lines = lines(fromFile: encodeProject(settings: settings)) let beginGroup = lines.findLine("/* Begin PBXHeadersBuildPhase section */") var line = lines.findLine("files = (", after: beginGroup) line = lines.validate(line: "04D5C0A51F153924008A2F98 /* Private.h in Headers */,", after: line) @@ -340,7 +340,7 @@ class PBXProjEncoderTests: XCTestCase { func test_build_phase_resources_unsorted_when_iOSProject() throws { try loadiOSProject() - let lines = self.lines(fromFile: encodeProject()) + let lines = lines(fromFile: encodeProject()) let beginGroup = lines.findLine("/* Begin PBXResourcesBuildPhase section */") let files = lines.findLine("files = (", after: beginGroup) let endGroup = lines.findLine("/* End PBXResourcesBuildPhase section */") @@ -353,7 +353,7 @@ class PBXProjEncoderTests: XCTestCase { try loadiOSProject() let settings = PBXOutputSettings(projBuildPhaseFileOrder: .byFilename) - let lines = self.lines(fromFile: encodeProject(settings: settings)) + let lines = lines(fromFile: encodeProject(settings: settings)) let beginGroup = lines.findLine("/* Begin PBXResourcesBuildPhase section */") var line = lines.findLine("files = (", after: beginGroup) line = lines.validate(line: "23766C1D1EAA3484007A9026 /* Assets.xcassets in Resources */,", after: line) @@ -361,12 +361,12 @@ class PBXProjEncoderTests: XCTestCase { line = lines.validate(line: "23766C1B1EAA3484007A9026 /* Main.storyboard in Resources */,", after: line) line = lines.validate(line: "/* End PBXResourcesBuildPhase section */", after: line) } - + func test_build_rules_when_targetWithCustomBuildRulesProject() throws { try loadTargetWithCustomBuildRulesProject() let settings = PBXOutputSettings(projBuildPhaseFileOrder: .byFilename) - let lines = self.lines(fromFile: encodeProject(settings: settings)) + let lines = lines(fromFile: encodeProject(settings: settings)) let beginGroup = lines.findLine("6CAD68202A56E31400662D8A /* PBXBuildRule */ = {") var line = lines.validate(line: "isa = PBXBuildRule;", after: beginGroup) line = lines.validate(line: "compilerSpec = com.apple.compilers.proxy.script;", after: line) @@ -386,7 +386,7 @@ class PBXProjEncoderTests: XCTestCase { try loadProjectWithXCLocalSwiftPackageReference() let settings = PBXOutputSettings(projBuildPhaseFileOrder: .byFilename) - let lines = self.lines(fromFile: encodeProject(settings: settings)) + let lines = lines(fromFile: encodeProject(settings: settings)) let beginGroup = lines.findLine("/* Begin XCLocalSwiftPackageReference section */") var line = lines.validate(line: "C9FDF5C52AD604310096A37A /* XCLocalSwiftPackageReference \"MyLocalPackage\" */ = {", after: beginGroup) line = lines.validate(line: "isa = XCLocalSwiftPackageReference;", after: line) @@ -399,7 +399,7 @@ class PBXProjEncoderTests: XCTestCase { try loadProjectWithXCLocalSwiftPackageReference() let settings = PBXOutputSettings(projBuildPhaseFileOrder: .byFilename) - let lines = self.lines(fromFile: encodeProject(settings: settings)) + let lines = lines(fromFile: encodeProject(settings: settings)) let beginGroup = lines.findLine("packageReferences = (") var line = lines.validate(line: "42AA19FF22AAF0D600428760 /* XCRemoteSwiftPackageReference \"RxSwift\" */,", after: beginGroup) line = lines.validate(line: "C9FDF5C52AD604310096A37A /* XCLocalSwiftPackageReference \"MyLocalPackage\" */,", after: line) @@ -410,7 +410,7 @@ class PBXProjEncoderTests: XCTestCase { try loadProjectWithRelativeXCLocalSwiftPackageReference() let settings = PBXOutputSettings(projBuildPhaseFileOrder: .byFilename) - let lines = self.lines(fromFile: encodeProject(settings: settings)) + let lines = lines(fromFile: encodeProject(settings: settings)) let beginGroup = lines.findLine("packageReferences = (") var line = lines.validate(line: "C9FDF5C82AD8AE400096A37A /* XCLocalSwiftPackageReference \"../MyLocalPackage\" */,", after: beginGroup) line = lines.validate(line: ");", after: line) @@ -420,7 +420,7 @@ class PBXProjEncoderTests: XCTestCase { try loadProjectWithXCLocalSwiftPackageReferences() let settings = PBXOutputSettings(projBuildPhaseFileOrder: .byFilename) - let lines = self.lines(fromFile: encodeProject(settings: settings)) + let lines = lines(fromFile: encodeProject(settings: settings)) let beginGroup = lines.findLine("packageReferences = (") var line = lines.validate(line: "C9FDF5C52AD604310096A37A /* XCLocalSwiftPackageReference \"MyLocalPackage\" */,", after: beginGroup) line = lines.validate(line: "C9FDF5CB2AD8B3B50096A37A /* XCLocalSwiftPackageReference \"MyOtherLocalPackage/MyOtherLocalPackage\" */,", after: line) @@ -438,7 +438,7 @@ class PBXProjEncoderTests: XCTestCase { } } - private func encodeProjectThrows(error expectedError: E, line: UInt = #line) where E: Error { + private func encodeProjectThrows(error expectedError: some Error, line: UInt = #line) { do { _ = try PBXProjEncoder(outputSettings: PBXOutputSettings()).encode(proj: proj) XCTFail("Expected '\(expectedError)' to be thrown", line: line) @@ -460,7 +460,7 @@ class PBXProjEncoderTests: XCTestCase { private func loadFileSharedAcrossTargetsProject() throws { proj = try PBXProj(jsonDictionary: fileSharedAcrossTargetsDictionary().1) } - + private func loadTargetWithCustomBuildRulesProject() throws { proj = try PBXProj(jsonDictionary: targetWithCustomBuildRulesDictionary().1) } @@ -480,7 +480,7 @@ class PBXProjEncoderTests: XCTestCase { // MARK: - Line validations -private extension Array where Element == String { +private extension [String] { @discardableResult func validate(line string: String, betweenLine lineAbove: Int, andLine lineBelow: Int, line: UInt = #line) -> Int { validate(string, using: { $0 == $1 }, betweenLine: lineAbove, andLine: lineBelow, line: line) } diff --git a/Tests/XcodeProjTests/Objects/Project/PBXProjIntegrationTests.swift b/Tests/XcodeProjTests/Objects/Project/PBXProjIntegrationTests.swift index 93838e4d0..fc442ca7d 100644 --- a/Tests/XcodeProjTests/Objects/Project/PBXProjIntegrationTests.swift +++ b/Tests/XcodeProjTests/Objects/Project/PBXProjIntegrationTests.swift @@ -9,7 +9,7 @@ final class PBXProjIntegrationTests: XCTestCase { let decoder = XcodeprojPropertyListDecoder() let proj = try? decoder.decode(PBXProj.self, from: data) XCTAssertNotNil(proj) - if let proj = proj { + if let proj { assert(proj: proj) } } @@ -30,7 +30,7 @@ final class PBXProjIntegrationTests: XCTestCase { try? tmpDir.delete() } - let fixturePath = self.fixturePath().parent() + let fixturePath = fixturePath().parent() let xcodeprojPath = tmpDir + "Project.xcodeproj" try fixturePath.copy(xcodeprojPath) @@ -40,7 +40,7 @@ final class PBXProjIntegrationTests: XCTestCase { try checkedOutput("git", ["add", "."]) try checkedOutput("git", [ "-c", "user.email=test@example.com", "-c", "user.name=Test User", - "commit", "-m", "test" + "commit", "-m", "test", ]) // Read/write the project diff --git a/Tests/XcodeProjTests/Objects/Project/PBXProject+Fixtures.swift b/Tests/XcodeProjTests/Objects/Project/PBXProject+Fixtures.swift index 66e8f9164..695215927 100644 --- a/Tests/XcodeProjTests/Objects/Project/PBXProject+Fixtures.swift +++ b/Tests/XcodeProjTests/Objects/Project/PBXProject+Fixtures.swift @@ -5,7 +5,8 @@ extension PBXProject { static func fixture(name: String = "test", buildConfigurationList: XCConfigurationList = XCConfigurationList.fixture(), compatibilityVersion: String = Xcode.Default.compatibilityVersion, - mainGroup: PBXGroup = PBXGroup.fixture()) -> PBXProject { + mainGroup: PBXGroup = PBXGroup.fixture()) -> PBXProject + { PBXProject(name: name, buildConfigurationList: buildConfigurationList, compatibilityVersion: compatibilityVersion, diff --git a/Tests/XcodeProjTests/Objects/SwiftPackage/XCLocalSwiftPackageReferenceTests.swift b/Tests/XcodeProjTests/Objects/SwiftPackage/XCLocalSwiftPackageReferenceTests.swift index 9586ae352..119b96fce 100644 --- a/Tests/XcodeProjTests/Objects/SwiftPackage/XCLocalSwiftPackageReferenceTests.swift +++ b/Tests/XcodeProjTests/Objects/SwiftPackage/XCLocalSwiftPackageReferenceTests.swift @@ -30,7 +30,7 @@ final class XCLocalSwiftPackageReferenceTests: XCTestCase { // Then XCTAssertEqual(got.value, .dictionary([ "isa": "XCLocalSwiftPackageReference", - "relativePath": "repository" + "relativePath": "repository", ])) } diff --git a/Tests/XcodeProjTests/Objects/Targets/PBXTarget+Fixtures.swift b/Tests/XcodeProjTests/Objects/Targets/PBXTarget+Fixtures.swift index 84e882f5d..07da826aa 100644 --- a/Tests/XcodeProjTests/Objects/Targets/PBXTarget+Fixtures.swift +++ b/Tests/XcodeProjTests/Objects/Targets/PBXTarget+Fixtures.swift @@ -10,7 +10,8 @@ extension PBXTarget { dependencies: [PBXTargetDependency] = [], productName: String? = "Test", product: PBXFileReference = PBXFileReference.fixture(name: "Test.app"), - productType: PBXProductType = PBXProductType.application) -> PBXTarget { + productType: PBXProductType = PBXProductType.application) -> PBXTarget + { PBXTarget(name: name, buildConfigurationList: buildConfigurationList, buildPhases: buildPhases, diff --git a/Tests/XcodeProjTests/Project/XCBreakpointListTests.swift b/Tests/XcodeProjTests/Project/XCBreakpointListTests.swift index 44783730a..1d1da4d8b 100644 --- a/Tests/XcodeProjTests/Project/XCBreakpointListTests.swift +++ b/Tests/XcodeProjTests/Project/XCBreakpointListTests.swift @@ -12,7 +12,7 @@ final class XCBreakpointListIntegrationTests: XCTestCase { func test_init_initializesTheBreakpointListCorrectly() { XCTAssertNotNil(subject) - if let subject = subject { + if let subject { assert(breakpointList: subject) } } diff --git a/Tests/XcodeProjTests/Project/XCUserDataTests.swift b/Tests/XcodeProjTests/Project/XCUserDataTests.swift index 0f3b76d01..1918584f1 100644 --- a/Tests/XcodeProjTests/Project/XCUserDataTests.swift +++ b/Tests/XcodeProjTests/Project/XCUserDataTests.swift @@ -14,11 +14,11 @@ final class XCUserDataTests: XCTestCase { initModel: { try? XCUserData(path: $0) }, modify: { userData in // XCScheme's that are already in place (the removed element) should not be removed by a write - userData.schemes = userData.schemes.filter { $0.name != "iOS-other"} + userData.schemes = userData.schemes.filter { $0.name != "iOS-other" } return userData }, assertion: { - assert(userData: $1, userName: "copy") + assert(userData: $1, userName: "copy") }) } diff --git a/Tests/XcodeProjTests/Project/XcodeProjTests.swift b/Tests/XcodeProjTests/Project/XcodeProjTests.swift index 3f4a81948..424767edd 100644 --- a/Tests/XcodeProjTests/Project/XcodeProjTests.swift +++ b/Tests/XcodeProjTests/Project/XcodeProjTests.swift @@ -24,7 +24,7 @@ final class XcodeProjIntegrationTests: XCTestCase { try testReadWriteProducesNoDiff(from: iosProjectPath, initModel: XcodeProj.init(path:)) } - + func test_initialize_PBXProj_with_data() throws { // Given let pbxprojPath = iosProjectPath + "project.pbxproj" @@ -38,7 +38,7 @@ final class XcodeProjIntegrationTests: XCTestCase { // Then XCTAssertEqual(pbxprojFromData, pbxprojFromDisk) } - + func test_write_includes_workspace_settings() throws { // Define workspace settings that should be written let workspaceSettings = WorkspaceSettings(buildSystem: .new, derivedDataLocationStyle: .default, autoCreateSchemes: false) diff --git a/Tests/XcodeProjTests/Scheme/XCScheme+BuildableReferenceTests.swift b/Tests/XcodeProjTests/Scheme/XCScheme+BuildableReferenceTests.swift index d1ee337dc..776803adb 100644 --- a/Tests/XcodeProjTests/Scheme/XCScheme+BuildableReferenceTests.swift +++ b/Tests/XcodeProjTests/Scheme/XCScheme+BuildableReferenceTests.swift @@ -1,5 +1,5 @@ -@testable import XcodeProj import XCTest +@testable import XcodeProj final class XCSchemeBuildableReferenceTests: XCTestCase { func test_hash() throws { diff --git a/Tests/XcodeProjTests/Scheme/XCSchemeManagementTests.swift b/Tests/XcodeProjTests/Scheme/XCSchemeManagementTests.swift index f94252f48..ed33c9749 100644 --- a/Tests/XcodeProjTests/Scheme/XCSchemeManagementTests.swift +++ b/Tests/XcodeProjTests/Scheme/XCSchemeManagementTests.swift @@ -1,17 +1,17 @@ -import Foundation -import XCTest import AEXML +import Foundation import PathKit +import XCTest @testable import XcodeProj final class XCSchemeManagementTests: XCTestCase { func test_init_from_path() throws { // Given let path = xcschememanagementPath - + // When - let got = try XCSchemeManagement.init(path: path) - + let got = try XCSchemeManagement(path: path) + // Then XCTAssertEqual(got.suppressBuildableAutocreation, [ "E525238B16245A900012E2BA": .init(primary: true), @@ -35,7 +35,7 @@ final class XCSchemeManagementTests: XCTestCase { let path = xcschememanagementPath // When - let reads = try (0..<10).map { _ in + let reads = try (0 ..< 10).map { _ in try XCSchemeManagement(path: path) } @@ -65,12 +65,12 @@ final class XCSchemeManagementTests: XCTestCase { ] ) try subject.write(path: plistPath, override: true) - + // Create a commit try checkedOutput("git", ["init"]) try checkedOutput("git", ["add", "."]) try checkedOutput("git", ["commit", "-m", "test"]) - + // Write again try subject.write(path: plistPath, override: true) diff --git a/Tests/XcodeProjTests/Scheme/XCSchemeTests.swift b/Tests/XcodeProjTests/Scheme/XCSchemeTests.swift index 1c79171d5..d4ed343c2 100644 --- a/Tests/XcodeProjTests/Scheme/XCSchemeTests.swift +++ b/Tests/XcodeProjTests/Scheme/XCSchemeTests.swift @@ -25,7 +25,7 @@ final class XCSchemeIntegrationTests: XCTestCase { let subject = try? XCScheme(path: runnableWithoutBuildableReferenceSchemePath) XCTAssertNotNil(subject) - if let subject = subject { + if let subject { assert(runnableWithoutBuildableReferenceScheme: subject) } } @@ -53,7 +53,7 @@ final class XCSchemeIntegrationTests: XCTestCase { let subject = try? XCScheme(path: minimalSchemePath) XCTAssertNotNil(subject) - if let subject = subject { + if let subject { assert(minimalScheme: subject) } } @@ -331,7 +331,7 @@ final class XCSchemeIntegrationTests: XCTestCase { // Then XCTAssertEqual(reconstructedSubject, subject) } - + func test_buildAction_buildArchitectures() throws { // Given / When let subject = try XCScheme(path: buildArchitecturesSchemePath) @@ -340,7 +340,7 @@ final class XCSchemeIntegrationTests: XCTestCase { let buildAction = try XCTUnwrap(subject.buildAction) XCTAssertTrue(buildAction.buildArchitectures == .matchRunDestination) } - + func test_buildAction_buildArchitectures_whenXMLElementDoesNotExist() throws { // Given / When let subject = try XCScheme(path: minimalSchemePath) @@ -349,7 +349,7 @@ final class XCSchemeIntegrationTests: XCTestCase { let buildAction = try XCTUnwrap(subject.buildAction) XCTAssertTrue(buildAction.buildArchitectures == .useTargetSettings) } - + func test_buildAction_buildArchitectures_serializingAndDeserializing() throws { // Given let scheme = try XCScheme(path: buildArchitecturesSchemePath) @@ -774,7 +774,7 @@ final class XCSchemeIntegrationTests: XCTestCase { // A scheme with the `runPostActionsOnFailure` enabled fixturesPath() + "Schemes/RunPostActionsOnFailure.xcscheme" } - + /// A scheme that `buildArchitectures` is specified "Automatic". private var buildArchitecturesSchemePath: Path { fixturesPath() + "Schemes/BuildArchitectures.xcscheme" diff --git a/Tests/XcodeProjTests/Tests/Fixtures.swift b/Tests/XcodeProjTests/Tests/Fixtures.swift index b90f5d149..40cc343f9 100644 --- a/Tests/XcodeProjTests/Tests/Fixtures.swift +++ b/Tests/XcodeProjTests/Tests/Fixtures.swift @@ -16,7 +16,6 @@ func fileSharedAcrossTargetsDictionary() -> (Path, [String: Any]) { return (fileSharedAcrossTargetsProject, loadPlist(path: fileSharedAcrossTargetsProject.string)!) } - func targetWithCustomBuildRulesDictionary() -> (Path, [String: Any]) { let targetWithCustomBuildRulesProject = fixturesPath() + "TargetWithCustomBuildRules/TargetWithCustomBuildRules.xcodeproj/project.pbxproj" return (targetWithCustomBuildRulesProject, loadPlist(path: targetWithCustomBuildRulesProject.string)!) diff --git a/Tests/XcodeProjTests/Tests/testWrite.swift b/Tests/XcodeProjTests/Tests/testWrite.swift index 01e8ebfc3..44d719d58 100644 --- a/Tests/XcodeProjTests/Tests/testWrite.swift +++ b/Tests/XcodeProjTests/Tests/testWrite.swift @@ -7,7 +7,8 @@ func testWrite(file _: StaticString = #file, line _: UInt = #line, from path: Path, initModel: (Path) -> T?, - modify: (T) -> T) { + modify: (T) -> T) +{ testWrite(from: path, initModel: initModel, modify: modify, assertion: { XCTAssertEqual($0, $1) }) } @@ -16,19 +17,20 @@ func testWrite(file: StaticString = #file, from path: Path, initModel: (Path) -> T?, modify: (T) -> T, - assertion: (_ before: T, _ after: T) -> Void) { + assertion: (_ before: T, _ after: T) -> Void) +{ let copyPath = path.parent() + "copy.\(path.extension!)" try? copyPath.delete() try? path.copy(copyPath) let got = initModel(copyPath) XCTAssertNotNil(got, file: file, line: line) - if let got = got { + if let got { let modified = modify(got) do { try modified.write(path: copyPath, override: true) let gotAfterWriting = initModel(copyPath) XCTAssertNotNil(gotAfterWriting, file: file, line: line) - if let gotAfterWriting = gotAfterWriting { + if let gotAfterWriting { assertion(got, gotAfterWriting) } } catch { @@ -38,10 +40,11 @@ func testWrite(file: StaticString = #file, try? copyPath.delete() } -func testReadWriteProducesNoDiff(file: StaticString = #file, - line: UInt = #line, - from path: Path, - initModel: (Path) throws -> T) throws { +func testReadWriteProducesNoDiff(file _: StaticString = #file, + line _: UInt = #line, + from path: Path, + initModel: (Path) throws -> some Writable) throws +{ let tmpDir = try Path.uniqueTemporary() defer { try? tmpDir.delete() @@ -57,13 +60,13 @@ func testReadWriteProducesNoDiff(file: StaticString = #file, try checkedOutput("git", ["add", "."]) try checkedOutput("git", [ "-c", "user.email=test@example.com", "-c", "user.name=Test User", - "commit", "-m", "test" + "commit", "-m", "test", ]) let object = try initModel(tmpPath) try object.write(path: tmpPath, override: true) - let diff = try XCTUnwrap(try checkedOutput("git", ["diff"])) + let diff = try XCTUnwrap(checkedOutput("git", ["diff"])) XCTAssertEqual(diff, "") } } diff --git a/Tests/XcodeProjTests/Utils/ReferenceGeneratorTests.swift b/Tests/XcodeProjTests/Utils/ReferenceGeneratorTests.swift index 08a3f9760..e16035d81 100644 --- a/Tests/XcodeProjTests/Utils/ReferenceGeneratorTests.swift +++ b/Tests/XcodeProjTests/Utils/ReferenceGeneratorTests.swift @@ -49,7 +49,7 @@ class ReferenceGeneratorTests: XCTestCase { try referenceGenerator.generateReferences(proj: project) return [remoteProjectFileReference, containerItemProxy, productReferenceProxy, productsGroup, buildFile, pluginDependency.productReference!.getObject()!] - .map { $0.reference.value } + .map(\.reference.value) } let firstUUIDs = try generateProject() diff --git a/Tests/XcodeProjTests/Utils/XCConfigTests.swift b/Tests/XcodeProjTests/Utils/XCConfigTests.swift index ade947b42..afb249cd4 100644 --- a/Tests/XcodeProjTests/Utils/XCConfigTests.swift +++ b/Tests/XcodeProjTests/Utils/XCConfigTests.swift @@ -13,7 +13,7 @@ final class XCConfigTests: XCTestCase { (Path("testA"), configA), (Path("testB"), configB), ], - buildSettings: ["a": "b"]) + buildSettings: ["a": "b"]) XCTAssertEqual(config.buildSettings as! [String: String], ["a": "b"]) XCTAssertEqual(config.includes[0].config, configA) XCTAssertEqual(config.includes[1].config, configB) @@ -26,7 +26,7 @@ final class XCConfigTests: XCTestCase { (Path("testA"), configA), (Path("testB"), configB), ], - buildSettings: ["b": "3"]) + buildSettings: ["b": "3"]) let buildSettings = config.flattenedBuildSettings() XCTAssertEqual(buildSettings["a"] as? String, "2") XCTAssertEqual(buildSettings["b"] as? String, "3") @@ -81,7 +81,7 @@ final class XCConfigIntegrationTests: XCTestCase { func test_init_initializesXCConfigWithTheRightProperties() { let subject = try? XCConfig(path: childrenPath()) XCTAssertNotNil(subject) - if let subject = subject { + if let subject { assert(config: subject) } }