diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d0aa728db..7898ce860 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -56,6 +56,14 @@ As part of the tests there is a [TestProject](/Tests/Fixtures/TestProject) fixtu > Note that sometimes having the `TestProject` open in Xcode will generate it's own diffs, so make sure to have it closed when running the tests. +#### Spec keys +XcodeGen warns about spec keys it never reads, by tracking every key read through `json(atKeyPath:)` while the spec is decoded. When parsing a new spec option: +- Read keys with `json(atKeyPath:)`. If you need to read one directly, like `jsonDictionary["key"]`, also call `KeyAccessTracking.markRead("key")`. +- If an object's keys are data rather than spec keys (like a dictionary of build settings), call `KeyAccessTracking.markAllRead()` in its decoder. +- If you decode a nested object yourself with `Type(jsonDictionary:)`, wrap it in `KeyAccessTracking.scope(dictionary, at: "key") { ... }` so its own keys are checked too. + +The fixture specs must load without any unknown keys, which `testFixturesHaveNoUnknownKeys` checks. + If your change contains any new features or logic changes please add a unit test of your own to cover it. If it's a new feature, see if it can be integrated into the `TestProject` by adding any required files and then editing the [project spec](/Tests/Fixtures/TestProject/project.yml). ### Submitting your PR diff --git a/Docs/ProjectSpec.md b/Docs/ProjectSpec.md index 2de1dd24f..2d33d21bd 100644 --- a/Docs/ProjectSpec.md +++ b/Docs/ProjectSpec.md @@ -74,6 +74,13 @@ You can also use environment variables in your configuration file, by using `${S - [ ] **packages**: **[String: [Swift Package](#swift-package)]** - a map of Swift packages by name. - [ ] **projectReferences**: **[String: [Project Reference](#project-reference)]** - a map of project references by name +XcodeGen prints a warning for any key in the spec that it doesn't recognize, for example `Unknown key "resources" in targets.App will be ignored`, so typos don't go unnoticed. Keys starting with `x-` are never warned about, so they can be used to hold things like YAML anchors: + +```yaml +x-common-settings: &common-settings + SWIFT_VERSION: 6.0 +``` + ### Include One or more specs can be included in the project spec. This can be used to split your project spec into multiple files, for easier structuring or sharing between multiple specs. Included specs can also include other specs and so on. diff --git a/Package.resolved b/Package.resolved index da49b5b86..262af587f 100644 --- a/Package.resolved +++ b/Package.resolved @@ -23,8 +23,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/yonaskolb/JSONUtilities.git", "state" : { - "revision" : "128d2ffc22467f69569ef8ff971683e2393191a0", - "version" : "4.2.0" + "revision" : "9b5a95553a0598a59477b33286e394999c5bd382", + "version" : "4.3.0" } }, { diff --git a/Package.swift b/Package.swift index 04e4170cd..ddc6b92e2 100644 --- a/Package.swift +++ b/Package.swift @@ -13,7 +13,7 @@ let package = Package( dependencies: [ .package(url: "https://github.com/kylef/PathKit.git", from: "1.0.1"), .package(url: "https://github.com/jpsim/Yams.git", from: "5.0.0"), - .package(url: "https://github.com/yonaskolb/JSONUtilities.git", from: "4.2.0"), + .package(url: "https://github.com/yonaskolb/JSONUtilities.git", from: "4.3.0"), .package(url: "https://github.com/kylef/Spectre.git", from: "0.9.2"), .package(url: "https://github.com/onevcat/Rainbow.git", from: "4.0.0"), .package(url: "https://github.com/tuist/XcodeProj.git", exact: "9.17.8"), @@ -79,6 +79,7 @@ let package = Package( ]), .testTarget(name: "ProjectSpecTests", dependencies: [ "ProjectSpec", + .product(name: "JSONUtilities", package: "JSONUtilities"), .product(name: "Spectre", package: "Spectre"), .product(name: "PathKit", package: "PathKit"), "TestSupport", diff --git a/Sources/ProjectSpec/Decoding.swift b/Sources/ProjectSpec/Decoding.swift index e193a7f10..c5c192cd0 100644 --- a/Sources/ProjectSpec/Decoding.swift +++ b/Sources/ProjectSpec/Decoding.swift @@ -8,7 +8,16 @@ extension Dictionary where Key: JSONKey { guard let dictionary = json(atKeyPath: keyPath) as JSONDictionary? else { return [] } + // the keys of this dictionary are names, so mark them all as read + return try KeyAccessTracking.scope(dictionary, at: .key(keyPath.key), allKeysRead: true) { + try decodeNamedItems(dictionary, parallel: parallel) + } + } + + private func decodeNamedItems(_ dictionary: JSONDictionary, parallel: Bool) throws -> [T] { if parallel { + // worker threads don't inherit the key tracking scope, so hand it over + let context = KeyAccessTracking.currentContext let defaultError = NSError(domain: "Unspecified error", code: 0, userInfo: nil) let keys = Array(dictionary.keys) var itemResults: [Result] = Array(repeating: .failure(defaultError), count: keys.count) @@ -18,7 +27,11 @@ extension Dictionary where Key: JSONKey { do { let key = keys[idx] let jsonDictionary: JSONDictionary = try dictionary.json(atKeyPath: .key(key)) - let item = try T(name: key, jsonDictionary: jsonDictionary) + let item = try KeyAccessTracking.withContext(context) { + try KeyAccessTracking.scope(jsonDictionary, at: .key(key)) { + try T(name: key, jsonDictionary: jsonDictionary) + } + } bufferWrapper.buffer[idx] = .success(item) } catch { bufferWrapper.buffer[idx] = .failure(error) @@ -30,7 +43,9 @@ extension Dictionary where Key: JSONKey { var items: [T] = [] for (key, _) in dictionary { let jsonDictionary: JSONDictionary = try dictionary.json(atKeyPath: .key(key)) - let item = try T(name: key, jsonDictionary: jsonDictionary) + let item = try KeyAccessTracking.scope(jsonDictionary, at: .key(key)) { + try T(name: key, jsonDictionary: jsonDictionary) + } items.append(item) } return items diff --git a/Sources/ProjectSpec/Dependency.swift b/Sources/ProjectSpec/Dependency.swift index f7a72c0a9..6222a587c 100644 --- a/Sources/ProjectSpec/Dependency.swift +++ b/Sources/ProjectSpec/Dependency.swift @@ -155,7 +155,7 @@ extension Dependency: JSONObjectConvertible { } if let object: JSONDictionary = jsonDictionary.json(atKeyPath: "copy") { - copyPhase = try BuildPhaseSpec.CopyFilesSettings(jsonDictionary: object) + copyPhase = try KeyAccessTracking.scope(object, at: "copy") { try BuildPhaseSpec.CopyFilesSettings(jsonDictionary: object) } } } } diff --git a/Sources/ProjectSpec/FileType.swift b/Sources/ProjectSpec/FileType.swift index d256d4aa9..35dd25bcc 100644 --- a/Sources/ProjectSpec/FileType.swift +++ b/Sources/ProjectSpec/FileType.swift @@ -42,7 +42,7 @@ extension FileType: JSONObjectConvertible { if let string: String = jsonDictionary.json(atKeyPath: "buildPhase") { buildPhase = try BuildPhaseSpec(string: string) } else if let dict: JSONDictionary = jsonDictionary.json(atKeyPath: "buildPhase") { - buildPhase = try BuildPhaseSpec(jsonDictionary: dict) + buildPhase = try KeyAccessTracking.scope(dict, at: "buildPhase") { try BuildPhaseSpec(jsonDictionary: dict) } } file = jsonDictionary.json(atKeyPath: "file") ?? Defaults.file attributes = jsonDictionary.json(atKeyPath: "attributes") ?? [] diff --git a/Sources/ProjectSpec/Project.swift b/Sources/ProjectSpec/Project.swift index 06f3d398c..aa756ff55 100644 --- a/Sources/ProjectSpec/Project.swift +++ b/Sources/ProjectSpec/Project.swift @@ -174,6 +174,9 @@ extension Project { public init(basePath: Path = "", jsonDictionary: JSONDictionary, targetDeclarationOrder: [String] = []) throws { self.basePath = basePath + // keys that are used while resolving templates, before the project is decoded + KeyAccessTracking.markRead("targetTemplates", "schemeTemplates") + var jsonDictionary = jsonDictionary if var rawTargets = jsonDictionary["targets"] as? [String: JSONDictionary] { for (index, key) in targetDeclarationOrder.enumerated() where rawTargets[key] != nil { diff --git a/Sources/ProjectSpec/Scheme.swift b/Sources/ProjectSpec/Scheme.swift index 8ec56bc56..98350cce3 100644 --- a/Sources/ProjectSpec/Scheme.swift +++ b/Sources/ProjectSpec/Scheme.swift @@ -658,12 +658,15 @@ extension Scheme.Test: JSONObjectConvertible { config = jsonDictionary.json(atKeyPath: "config") gatherCoverageData = jsonDictionary.json(atKeyPath: "gatherCoverageData") ?? Scheme.Test.gatherCoverageDataDefault + KeyAccessTracking.markRead("coverageTargets", "targets") if let coverages = jsonDictionary["coverageTargets"] as? [Any] { - coverageTargets = try coverages.compactMap { target in + coverageTargets = try coverages.enumerated().compactMap { index, target in if let string = target as? String { return try TestableTargetReference(string) } else if let dictionary = target as? JSONDictionary, - let target: TestableTargetReference = try? .init(jsonDictionary: dictionary) { + let target: TestableTargetReference = try? KeyAccessTracking.scope(dictionary, at: ["coverageTargets", .index(index)], { + try .init(jsonDictionary: dictionary) + }) { return target } else { return nil @@ -680,11 +683,13 @@ extension Scheme.Test: JSONObjectConvertible { disableMainThreadChecker = jsonDictionary.json(atKeyPath: "disableMainThreadChecker") ?? Scheme.Test.disableMainThreadCheckerDefault commandLineArguments = jsonDictionary.json(atKeyPath: "commandLineArguments") ?? [:] if let targets = jsonDictionary["targets"] as? [Any] { - self.targets = try targets.compactMap { target in + self.targets = try targets.enumerated().compactMap { index, target in if let string = target as? String { return try TestTarget(targetReference: TestableTargetReference(string)) } else if let dictionary = target as? JSONDictionary { - return try TestTarget(jsonDictionary: dictionary) + return try KeyAccessTracking.scope(dictionary, at: ["targets", .index(index)]) { + try TestTarget(jsonDictionary: dictionary) + } } else { return nil } @@ -695,7 +700,9 @@ extension Scheme.Test: JSONObjectConvertible { preActions = jsonDictionary.json(atKeyPath: "preActions") ?? [] postActions = jsonDictionary.json(atKeyPath: "postActions") ?? [] environmentVariables = try XCScheme.EnvironmentVariable.parseAll(jsonDictionary: jsonDictionary) - testPlans = try (jsonDictionary.json(atKeyPath: "testPlans") ?? []).map { try TestPlan(jsonDictionary: $0) } + testPlans = try ((jsonDictionary.json(atKeyPath: "testPlans") as [JSONDictionary]?) ?? []).enumerated().map { index, testPlan in + try KeyAccessTracking.scope(testPlan, at: ["testPlans", .index(index)]) { try TestPlan(jsonDictionary: testPlan) } + } language = jsonDictionary.json(atKeyPath: "language") region = jsonDictionary.json(atKeyPath: "region") debugEnabled = jsonDictionary.json(atKeyPath: "debugEnabled") ?? Scheme.Test.debugEnabledDefault @@ -895,6 +902,9 @@ extension Scheme.Archive: JSONEncodable { extension Scheme: NamedJSONDictionaryConvertible { public init(name: String, jsonDictionary: JSONDictionary) throws { + // keys used by scheme templates before a scheme is decoded + KeyAccessTracking.markRead("templates", "templateAttributes") + self.name = name build = try jsonDictionary.json(atKeyPath: "build") run = jsonDictionary.json(atKeyPath: "run") @@ -1052,6 +1062,7 @@ extension XCScheme.EnvironmentVariable: JSONUtilities.JSONObjectConvertible { public init(jsonDictionary: JSONDictionary) throws { let value: String + KeyAccessTracking.markRead("value") if let jsonValue = jsonDictionary["value"] { value = XCScheme.EnvironmentVariable.parseValue(jsonValue) } else { @@ -1069,7 +1080,11 @@ extension XCScheme.EnvironmentVariable: JSONUtilities.JSONObjectConvertible { .map { XCScheme.EnvironmentVariable(variable: $0.key, value: $0.value, enabled: true) } .sorted { $0.variable < $1.variable } } else if let variablesArray: [JSONDictionary] = jsonDictionary.json(atKeyPath: "environmentVariables") { - return try variablesArray.map(XCScheme.EnvironmentVariable.init) + return try variablesArray.enumerated().map { index, variable in + try KeyAccessTracking.scope(variable, at: ["environmentVariables", .index(index)]) { + try XCScheme.EnvironmentVariable(jsonDictionary: variable) + } + } } else { return [] } diff --git a/Sources/ProjectSpec/Settings.swift b/Sources/ProjectSpec/Settings.swift index 05cc48e83..347838af2 100644 --- a/Sources/ProjectSpec/Settings.swift +++ b/Sources/ProjectSpec/Settings.swift @@ -19,12 +19,15 @@ public struct Settings: Equatable, JSONObjectConvertible, CustomStringConvertibl public init(jsonDictionary: JSONDictionary) throws { if jsonDictionary["configs"] != nil || jsonDictionary["groups"] != nil || jsonDictionary["base"] != nil { + KeyAccessTracking.markRead("configs") groups = jsonDictionary.json(atKeyPath: "groups") ?? jsonDictionary.json(atKeyPath: "presets") ?? [] let buildSettingsDictionary: JSONDictionary = jsonDictionary.json(atKeyPath: "base") ?? [:] buildSettings = buildSettingsDictionary.mapValues { BuildSetting(any: $0) } self.configSettings = try Self.extractValidConfigs(from: jsonDictionary) } else { + // every key is a build setting + KeyAccessTracking.markAllRead() buildSettings = jsonDictionary.mapValues { BuildSetting(any: $0) } configSettings = [:] groups = [] diff --git a/Sources/ProjectSpec/SpecLoader.swift b/Sources/ProjectSpec/SpecLoader.swift index 56c31a5c3..3a2f400e7 100644 --- a/Sources/ProjectSpec/SpecLoader.swift +++ b/Sources/ProjectSpec/SpecLoader.swift @@ -9,6 +9,8 @@ public class SpecLoader { var project: Project! public private(set) var projectDictionary: [String: Any]? + /// Keys in the spec that were never read while loading the project + public private(set) var unusedKeys: [UnusedKey] = [] let version: Version public init(version: Version) { @@ -19,20 +21,32 @@ public class SpecLoader { let projectRoot = projectRoot?.absolute() let spec = try SpecFile(path: path, projectRoot: projectRoot, variables: variables) let resolvedDictionary = spec.resolvedDictionary() - let project = try Project( - basePath: projectRoot ?? spec.basePath, - jsonDictionary: resolvedDictionary, - targetDeclarationOrder: spec.resolvedTargetDeclarationOrder() - ) + let (project, unusedKeys) = try KeyAccessTracking.record(root: resolvedDictionary) { + try Project( + basePath: projectRoot ?? spec.basePath, + jsonDictionary: resolvedDictionary, + targetDeclarationOrder: spec.resolvedTargetDeclarationOrder() + ) + } self.project = project + // keys starting with `x-` can hold anything, like YAML anchors + self.unusedKeys = unusedKeys.filter { !$0.key.hasPrefix("x-") } projectDictionary = resolvedDictionary return project } public func validateProjectDictionaryWarnings() throws { - try projectDictionary?.validateWarnings() + var errors: [SpecValidationError.ValidationError] = unusedKeys.map { .unknownKey($0) } + do { + try projectDictionary?.validateWarnings() + } catch let error as SpecValidationError { + errors += error.errors + } + if !errors.isEmpty { + throw SpecValidationError(errors: errors) + } } public func generateCacheFile() throws -> CacheFile? { diff --git a/Sources/ProjectSpec/SpecValidationError.swift b/Sources/ProjectSpec/SpecValidationError.swift index a4c7f3675..ead18d4ec 100644 --- a/Sources/ProjectSpec/SpecValidationError.swift +++ b/Sources/ProjectSpec/SpecValidationError.swift @@ -1,4 +1,5 @@ import Foundation +import JSONUtilities import Version public struct SpecValidationError: Error, CustomStringConvertible { @@ -46,6 +47,7 @@ public struct SpecValidationError: Error, CustomStringConvertible { case invalidProjectFormat(String) case invalidProjectFileFormat(String) case unsupportedProjectFormatForProjectFileFormat(projectFormat: ProjectFormat, projectFileFormat: ProjectFileFormat) + case unknownKey(UnusedKey) public var description: String { switch self { @@ -124,6 +126,12 @@ public struct SpecValidationError: Error, CustomStringConvertible { case let .unsupportedProjectFormatForProjectFileFormat(projectFormat, projectFileFormat): let minimumProjectFormat = projectFileFormat.minimumProjectFormat?.rawValue ?? "" return "projectFileFormat \(projectFileFormat.rawValue.quoted) requires projectFormat \(minimumProjectFormat) or newer, but projectFormat is \(projectFormat.rawValue.quoted)" + case let .unknownKey(unusedKey): + if unusedKey.path.isEmpty { + return "Unknown key \(unusedKey.key.quoted) will be ignored" + } else { + return "Unknown key \(unusedKey.key.quoted) in \(JSONPathComponent.format(unusedKey.path)) will be ignored" + } } } } diff --git a/Sources/ProjectSpec/Target.swift b/Sources/ProjectSpec/Target.swift index 566efe5e3..f7a505c4d 100644 --- a/Sources/ProjectSpec/Target.swift +++ b/Sources/ProjectSpec/Target.swift @@ -280,6 +280,13 @@ extension LegacyTarget: JSONEncodable { extension Target: NamedJSONDictionaryConvertible { public init(name: String, jsonDictionary: JSONDictionary) throws { + // keys that are used before a target is decoded + KeyAccessTracking.markRead( + "platformPrefix", "platformSuffix", // multi-platform target expansion + "templates", "templateAttributes", // target templates + Target.declarationIndexKey + ) + let resolvedName: String = jsonDictionary.json(atKeyPath: "name") ?? name self.name = resolvedName productName = jsonDictionary.json(atKeyPath: "productName") ?? resolvedName @@ -319,8 +326,11 @@ extension Target: NamedJSONDictionaryConvertible { } if let dictionary = jsonDictionary["deploymentTarget"] as? JSONDictionary { + KeyAccessTracking.markRead("deploymentTarget") deploymentTarget = nil - deploymentTargets = try DeploymentTarget(jsonDictionary: dictionary) + deploymentTargets = try KeyAccessTracking.scope(dictionary, at: "deploymentTarget") { + try DeploymentTarget(jsonDictionary: dictionary) + } } else if let string: String = jsonDictionary.json(atKeyPath: "deploymentTarget") { deploymentTarget = try Version.parse(string) deploymentTargets = nil @@ -337,11 +347,13 @@ extension Target: NamedJSONDictionaryConvertible { if let source: String = jsonDictionary.json(atKeyPath: "sources") { sources = [TargetSource(path: source)] } else if let array = jsonDictionary["sources"] as? [Any] { - sources = try array.compactMap { source in + sources = try array.enumerated().compactMap { index, source in if let string = source as? String { return TargetSource(path: string) } else if let dictionary = source as? [String: Any] { - return try TargetSource(jsonDictionary: dictionary) + return try KeyAccessTracking.scope(dictionary, at: ["sources", .index(index)]) { + try TargetSource(jsonDictionary: dictionary) + } } else { return nil } diff --git a/Sources/ProjectSpec/TargetScheme.swift b/Sources/ProjectSpec/TargetScheme.swift index 27fdd76cf..a08ed6073 100644 --- a/Sources/ProjectSpec/TargetScheme.swift +++ b/Sources/ProjectSpec/TargetScheme.swift @@ -74,12 +74,15 @@ public struct TargetScheme: Equatable { extension TargetScheme: JSONObjectConvertible { public init(jsonDictionary: JSONDictionary) throws { + KeyAccessTracking.markRead("testTargets", "coverageTargets") if let targets = jsonDictionary["testTargets"] as? [Any] { - testTargets = try targets.compactMap { target in + testTargets = try targets.enumerated().compactMap { index, target in if let string = target as? String { return .init(targetReference: try TestableTargetReference(string)) } else if let dictionary = target as? JSONDictionary, - let target: Scheme.Test.TestTarget = try? .init(jsonDictionary: dictionary) { + let target: Scheme.Test.TestTarget = try? KeyAccessTracking.scope(dictionary, at: ["testTargets", .index(index)], { + try .init(jsonDictionary: dictionary) + }) { return target } else { return nil @@ -90,11 +93,13 @@ extension TargetScheme: JSONObjectConvertible { } if let targets = jsonDictionary["coverageTargets"] as? [Any] { - coverageTargets = try targets.compactMap { target in + coverageTargets = try targets.enumerated().compactMap { index, target in if let string = target as? String { return try TestableTargetReference(string) } else if let dictionary = target as? JSONDictionary, - let target: TestableTargetReference = try? .init(jsonDictionary: dictionary) { + let target: TestableTargetReference = try? KeyAccessTracking.scope(dictionary, at: ["coverageTargets", .index(index)], { + try .init(jsonDictionary: dictionary) + }) { return target } else { return nil @@ -104,7 +109,9 @@ extension TargetScheme: JSONObjectConvertible { coverageTargets = [] } - testPlans = try (jsonDictionary.json(atKeyPath: "testPlans") ?? []).map { try TestPlan(jsonDictionary: $0) } + testPlans = try ((jsonDictionary.json(atKeyPath: "testPlans") as [JSONDictionary]?) ?? []).enumerated().map { index, testPlan in + try KeyAccessTracking.scope(testPlan, at: ["testPlans", .index(index)]) { try TestPlan(jsonDictionary: testPlan) } + } configVariants = jsonDictionary.json(atKeyPath: "configVariants") ?? [] gatherCoverageData = jsonDictionary.json(atKeyPath: "gatherCoverageData") ?? TargetScheme.gatherCoverageDataDefault storeKitConfiguration = jsonDictionary.json(atKeyPath: "storeKitConfiguration") diff --git a/Sources/ProjectSpec/TargetSource.swift b/Sources/ProjectSpec/TargetSource.swift index 6cfe7e7cc..0a2eb290b 100644 --- a/Sources/ProjectSpec/TargetSource.swift +++ b/Sources/ProjectSpec/TargetSource.swift @@ -116,7 +116,7 @@ extension TargetSource: JSONObjectConvertible { if let string: String = jsonDictionary.json(atKeyPath: "buildPhase") { buildPhase = try BuildPhaseSpec(string: string) } else if let dict: JSONDictionary = jsonDictionary.json(atKeyPath: "buildPhase") { - buildPhase = try BuildPhaseSpec(jsonDictionary: dict) + buildPhase = try KeyAccessTracking.scope(dict, at: "buildPhase") { try BuildPhaseSpec(jsonDictionary: dict) } } createIntermediateGroups = jsonDictionary.json(atKeyPath: "createIntermediateGroups") diff --git a/Sources/XcodeGenCLI/Commands/GenerateCommand.swift b/Sources/XcodeGenCLI/Commands/GenerateCommand.swift index a6ac7c8a1..75fc26f9a 100644 --- a/Sources/XcodeGenCLI/Commands/GenerateCommand.swift +++ b/Sources/XcodeGenCLI/Commands/GenerateCommand.swift @@ -33,6 +33,10 @@ class GenerateCommand: ProjectCommand { // validate project dictionary do { try specLoader.validateProjectDictionaryWarnings() + } catch let error as SpecValidationError { + for validationError in error.errors { + warning("Warning: \(validationError)") + } } catch { warning("\(error)") } diff --git a/Tests/Fixtures/TestProject/Project.xcodeproj/xcshareddata/xcdebugger/Breakpoints_v2.xcbkptlist b/Tests/Fixtures/TestProject/Project.xcodeproj/xcshareddata/xcdebugger/Breakpoints_v2.xcbkptlist index 4b3e82723..6ece93bb5 100644 --- a/Tests/Fixtures/TestProject/Project.xcodeproj/xcshareddata/xcdebugger/Breakpoints_v2.xcbkptlist +++ b/Tests/Fixtures/TestProject/Project.xcodeproj/xcshareddata/xcdebugger/Breakpoints_v2.xcbkptlist @@ -50,7 +50,7 @@ ignoreCount = "0" continueAfterRunningActions = "No" scope = "0" - stopOnStyle = "0"> + stopOnStyle = "1"> diff --git a/Tests/Fixtures/TestProject/project.yml b/Tests/Fixtures/TestProject/project.yml index 977ef7310..ad4d8771c 100644 --- a/Tests/Fixtures/TestProject/project.yml +++ b/Tests/Fixtures/TestProject/project.yml @@ -46,7 +46,7 @@ breakpoints: column: 13 - type: Exception scope: All - stopOnStype: Catch + stopOnStyle: Catch actions: - type: DebuggerCommand command: po $arg1 diff --git a/Tests/ProjectSpecTests/SpecLoadingTests.swift b/Tests/ProjectSpecTests/SpecLoadingTests.swift index 2e9acc47f..e072af0f6 100644 --- a/Tests/ProjectSpecTests/SpecLoadingTests.swift +++ b/Tests/ProjectSpecTests/SpecLoadingTests.swift @@ -5,6 +5,7 @@ import Spectre import XcodeProj import XCTest import Yams +import JSONUtilities import TestSupport import Version @@ -370,7 +371,7 @@ class SpecLoadingTests: XCTestCase { $0.it("fails validating warnings for deprecated placeholder usage") { let dictionary: [String: Any] = [ "name": "TestSpecWarningValidation", - "templates": [ + "targetTemplates": [ "Framework": [ "type": "framework", "sources": ["${target_name}/${platform}/Sources"], @@ -396,7 +397,7 @@ class SpecLoadingTests: XCTestCase { $0.it("successfully validates warnings for new placeholder usage") { let dictionary: [String: Any] = [ "name": "TestSpecWarningValidation", - "templates": [ + "targetTemplates": [ "Framework": [ "type": "framework", "sources": ["${target_name}/${platform}/Sources"], @@ -426,6 +427,161 @@ class SpecLoadingTests: XCTestCase { } } + func testUnknownKeyWarnings() { + describe { + let path = Path(components: [NSTemporaryDirectory(), "unknown_keys_test.yml"]) + + func unknownKeys(_ dictionary: [String: Any]) throws -> [String] { + try Yams.dump(object: dictionary).write(toFile: path.string, atomically: true, encoding: .utf8) + let specLoader = SpecLoader(version: "1.1.0") + _ = try specLoader.loadProject(path: path) + do { + try specLoader.validateProjectDictionaryWarnings() + return [] + } catch let error as SpecValidationError { + return error.errors.compactMap { + guard case let .unknownKey(key) = $0 else { return nil } + return key.description + } + } + } + + $0.it("warns on unknown keys at every level") { + let keys = try unknownKeys([ + "name": "UnknownKeys", + "targts": [String: Any](), + "options": ["bundleIdPrefx": "com.example"], + "settings": ["bse": ["SWIFT_VERSION": "5"], "configs": [String: Any]()], + "targets": [ + "App": [ + "type": "application", + "platform": "iOS", + "sources": [["path": "Sources", "buildphase": "resources"]], + "resources": ["Resources"], + "dependencies": [["target": "Framework", "embedd": true]], + ], + "Framework": [ + "type": "framework", + "supportedDestinations": ["iOS", "tvOS"], + "deploymentTarget": ["iOS": "17.0", "iOSS": "17.0"], + ], + ], + "schemes": [ + "App": [ + "build": ["targets": ["App": "all"]], + "test": ["targets": [["name": "App", "parallelizabl": true]]], + "runn": [String: Any](), + ], + ], + ]) + try expect(keys) == [ + "options.bundleIdPrefx", + "schemes.App.runn", + "schemes.App.test.targets[0].parallelizabl", + "settings.bse", + "targets.App.dependencies[0].embedd", + "targets.App.resources", + "targets.App.sources[0].buildphase", + "targets.Framework.deploymentTarget.iOSS", + "targts", + ] + } + + $0.it("formats the warning with the path") { + let targetKey = SpecValidationError.ValidationError.unknownKey(UnusedKey(path: ["targets", "App"], key: "resources")) + try expect(targetKey.description) == "Unknown key \"resources\" in targets.App will be ignored" + let rootKey = SpecValidationError.ValidationError.unknownKey(UnusedKey(path: [], key: "targts")) + try expect(rootKey.description) == "Unknown key \"targts\" will be ignored" + } + + $0.it("doesn't warn on YAML anchors and merge keys") { + let yaml = """ + name: Anchors + x-common: &common + type: framework + platform: iOS + targets: + Framework: + <<: *common + sources: [Sources] + """ + try yaml.write(toFile: path.string, atomically: true, encoding: .utf8) + let specLoader = SpecLoader(version: "1.1.0") + _ = try specLoader.loadProject(path: path) + try expect(specLoader.unusedKeys.map(\.description)) == [] + } + + $0.it("doesn't warn on keys that are used before decoding or are data") { + let keys = try unknownKeys([ + "name": "KnownKeys", + "x-common": ["anything": 1], + "settings": ["SWIFT_VERSION": "5", "ANY_SETTING": "YES"], + "settingGroups": ["group": ["OTHER_SETTING": "1"]], + "targetTemplates": [ + "Base": ["sources": ["${target_name}"], "templateAttributes": ["foo": "bar"]], + ], + "schemeTemplates": [ + "BaseScheme": ["build": ["targets": ["${scheme_name}": "all"]]], + ], + "targets": [ + "App": [ + "type": "application", + "platform": ["iOS", "tvOS"], + "platformPrefix": "Pre", + "platformSuffix": "Suf", + "templates": ["Base"], + "templateAttributes": ["foo": "baz"], + "settings": [ + "base": ["A": "1"], + "configs": ["Debug": ["B": "2"]], + ], + "info": ["path": "Info.plist", "properties": ["AnyKey": "Value"]], + "attributes": ["AnyAttribute": "Value"], + "scheme": [ + "environmentVariables": ["ANY_VAR": "1"], + "commandLineArguments": ["-arg": true], + "testTargets": [["name": "App", "parallelizable": true]], + ], + ], + ], + "schemes": [ + "App": [ + "templates": ["BaseScheme"], + "run": ["environmentVariables": [["variable": "VAR", "value": "1", "isEnabled": false]]], + ], + ], + ]) + try expect(keys) == [] + } + } + } + + func testFixturesHaveNoUnknownKeys() throws { + let specs = [ + "TestProject/project.yml", + "TestProject/AnotherProject/project.yml", + "CarthageProject/project.yml", + "SPM/project.yml", + "XCProjProject/project.yml", + "scheme_test/test_project.yml", + "settings_test.yml", + "include_test.yml", + "paths_test.yml", + "legacy_paths_test.yml", + "variables_test.yml", + "target_ordering_test.yml", + "target_ordering_template_test.yml", + "target_ordering_template_name_test.yml", + "target_ordering_variable_test.yml", + "duplicated_include/duplicated_import_sut.yml", + ] + for spec in specs { + let specLoader = SpecLoader(version: "1.1.0") + _ = try specLoader.loadProject(path: fixturePath + spec, variables: ["FIRST_TARGET": "Zebra"]) + XCTAssertEqual(specLoader.unusedKeys.map(\.description), [], "Unknown keys in \(spec)") + } + } + func testProjectSpecParser() { let validTarget: [String: Any] = ["type": "application", "platform": "iOS"] let validBreakpoint: [String: Any] = ["type": "Exception", "scope": "All", "stopOnStyle": "Catch"]