Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions Docs/ProjectSpec.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions Package.resolved

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down Expand Up @@ -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",
Expand Down
19 changes: 17 additions & 2 deletions Sources/ProjectSpec/Decoding.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<T: NamedJSONDictionaryConvertible>(_ 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<T, Error>] = Array(repeating: .failure(defaultError), count: keys.count)
Expand All @@ -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)
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion Sources/ProjectSpec/Dependency.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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) }
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/ProjectSpec/FileType.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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") ?? []
Expand Down
3 changes: 3 additions & 0 deletions Sources/ProjectSpec/Project.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
27 changes: 21 additions & 6 deletions Sources/ProjectSpec/Scheme.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
}
Expand All @@ -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
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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 {
Expand All @@ -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 []
}
Expand Down
3 changes: 3 additions & 0 deletions Sources/ProjectSpec/Settings.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 = []
Expand Down
26 changes: 20 additions & 6 deletions Sources/ProjectSpec/SpecLoader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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? {
Expand Down
8 changes: 8 additions & 0 deletions Sources/ProjectSpec/SpecValidationError.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Foundation
import JSONUtilities
import Version

public struct SpecValidationError: Error, CustomStringConvertible {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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"
}
}
}
}
Expand Down
18 changes: 15 additions & 3 deletions Sources/ProjectSpec/Target.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
}
Expand Down
Loading
Loading