This repository was archived by the owner on Feb 26, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathXcodeGraphMapper.swift
More file actions
291 lines (251 loc) · 10.5 KB
/
XcodeGraphMapper.swift
File metadata and controls
291 lines (251 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import FileSystem
import Foundation
import Path
import PathKit
import XcodeGraph
import XcodeProj
/// A protocol defining how to map a given file path to a `Graph`.
public protocol XcodeGraphMapping {
/// Builds a `Graph` from the specified path.
/// - Parameter path: The absolute path to a `.xcworkspace`, `.xcodeproj`, or directory containing them.
/// - Returns: A `Graph` representing the projects, targets, and dependencies found at `pathString`.
/// - Throws: If the path doesn't exist or no projects are found.
func map(at path: AbsolutePath) async throws -> Graph
}
/// An error type for `XcodeGraphMapper` when the path is invalid or no projects are found.
public enum XcodeGraphMapperError: LocalizedError {
case pathNotFound(String)
case noProjectsFound(String)
public var errorDescription: String? {
switch self {
case let .pathNotFound(path):
return "The specified path does not exist: \(path)"
case let .noProjectsFound(path):
return "No `.xcworkspace` or `.xcodeproj` was found at: \(path)"
}
}
}
/// Specifies whether we’re mapping a single `.xcodeproj` or an `.xcworkspace`.
enum XcodeMapperGraphType {
case workspace(XCWorkspace)
case project(XcodeProj)
}
/// A unified entry point that locates `.xcworkspace` or `.xcodeproj` files—even within directories—and
/// constructs a comprehensive `Graph` of projects, targets, and dependencies.
///
/// Specifically, this mapper:
/// 1. Detects whether the input path is a single project, a workspace, or a directory.
/// 2. Enumerates all discovered targets and dependencies to assemble the final `Graph`.
///
/// This replaces old parsers/providers with a single approach. For example:
/// ```swift
/// let mapper: XcodeGraphMapping = XcodeGraphMapper()
/// let graph = try await mapper.map(at: "/path/to/MyApp")
/// ```
public struct XcodeGraphMapper: XcodeGraphMapping {
private let fileSystem: FileSysteming
// MARK: - Initialization
public init(fileSystem: FileSysteming = FileSystem()) {
self.fileSystem = fileSystem
}
// MARK: - Public API
public func map(at path: AbsolutePath) async throws -> Graph {
guard try await fileSystem.exists(path) else {
throw XcodeGraphMapperError.pathNotFound(path.pathString)
}
let graphType = try await determineGraphType(at: path)
return try await buildGraph(from: graphType)
}
// MARK: - Determine Graph Type
private func determineGraphType(at path: AbsolutePath) async throws -> XcodeMapperGraphType {
// Try a direct match for .xcworkspace / .xcodeproj
if let directType = try detectDirectGraphType(at: path) {
return directType
}
// Otherwise look inside the directory
return try await detectGraphTypeInDirectory(at: path)
}
private func detectDirectGraphType(at path: AbsolutePath) throws -> XcodeMapperGraphType? {
guard let ext = path.extension?.lowercased() else {
return nil
}
switch ext {
case "xcworkspace":
let xcworkspace = try XCWorkspace(path: Path(path.pathString))
return .workspace(xcworkspace)
case "xcodeproj":
let xcodeProj = try XcodeProj(pathString: path.pathString)
return .project(xcodeProj)
default:
return nil
}
}
private func detectGraphTypeInDirectory(at path: AbsolutePath) async throws -> XcodeMapperGraphType {
let patterns = ["**/*.xcworkspace", "**/*.xcodeproj"]
let contents = try fileSystem.glob(directory: path, include: patterns)
if let workspacePath = try await contents.first(where: { $0.extension?.lowercased() == "xcworkspace" }) {
let xcworkspace = try XCWorkspace(path: Path(workspacePath.pathString))
return .workspace(xcworkspace)
}
if let projectPath = try await contents.first(where: { $0.extension?.lowercased() == "xcodeproj" }) {
let xcodeProj = try XcodeProj(pathString: projectPath.pathString)
return .project(xcodeProj)
}
throw XcodeGraphMapperError.noProjectsFound(path.pathString)
}
// MARK: - Build Graph
func buildGraph(from graphType: XcodeMapperGraphType) async throws -> Graph {
let projectPaths = try await identifyProjectPaths(from: graphType)
let workspace = assembleWorkspace(graphType: graphType, projectPaths: projectPaths)
let projects = try await loadProjects(projectPaths)
let packages = extractPackages(from: projects)
let (dependencies, dependencyConditions) = try await resolveDependencies(for: projects)
return assembleFinalGraph(
workspace: workspace,
projects: projects,
packages: packages,
dependencies: dependencies,
dependencyConditions: dependencyConditions
)
}
private func identifyProjectPaths(from graphType: XcodeMapperGraphType) async throws -> [AbsolutePath] {
switch graphType {
case let .workspace(xcworkspace):
return try await extractProjectPaths(
from: xcworkspace.data.children,
srcPath: xcworkspace.workspacePath.parentDirectory
)
case let .project(xcodeProj):
return [xcodeProj.projectPath]
}
}
private func assembleWorkspace(
graphType: XcodeMapperGraphType,
projectPaths: [AbsolutePath]
) -> Workspace {
let workspacePath: AbsolutePath
let name: String
switch graphType {
case let .workspace(xcworkspace):
workspacePath = xcworkspace.workspacePath
name = workspacePath.basenameWithoutExt
case let .project(xcodeProj):
workspacePath = xcodeProj.projectPath.parentDirectory
name = "Workspace"
}
return Workspace(
path: workspacePath,
xcWorkspacePath: workspacePath,
name: name,
projects: projectPaths
)
}
private func loadProjects(_ projectPaths: [AbsolutePath]) async throws -> [AbsolutePath: Project] {
var projects = [AbsolutePath: Project]()
for path in projectPaths {
let xcodeProj = try XcodeProj(pathString: path.pathString)
let projectMapper = PBXProjectMapper()
let project = try await projectMapper.map(xcodeProj: xcodeProj)
projects[path.parentDirectory] = project
}
return projects
}
private func extractPackages(
from projects: [AbsolutePath: Project]
) -> [AbsolutePath: [String: Package]] {
projects.compactMapValues { project in
guard !project.packages.isEmpty else { return nil }
return Dictionary(
uniqueKeysWithValues: project.packages.map { ($0.url, $0) }
)
}
}
private func resolveDependencies(
for projects: [AbsolutePath: Project]
) async throws -> ([GraphDependency: Set<GraphDependency>], [GraphEdge: PlatformCondition]) {
let allTargetsMap = Dictionary(
projects.values.flatMap(\.targets),
uniquingKeysWith: { existing, _ in existing }
)
return try await buildDependencies(for: projects, using: allTargetsMap)
}
private func buildDependencies(
for projects: [AbsolutePath: Project],
using allTargetsMap: [String: Target]
) async throws -> ([GraphDependency: Set<GraphDependency>], [GraphEdge: PlatformCondition]) {
var dependencies = [GraphDependency: Set<GraphDependency>]()
var dependencyConditions = [GraphEdge: PlatformCondition]()
for (path, project) in projects {
for (name, target) in project.targets {
let sourceDependency = GraphDependency.target(name: name, path: path)
print("Adding dependency")
print(name)
print(path)
print(path.parentDirectory)
print("---")
// Build edges for each target dependency
let edgesAndDeps = try await target.dependencies.serialCompactMap { (dep: TargetDependency) async throws -> (
GraphEdge,
PlatformCondition?,
GraphDependency
) in
let graphDep = try await dep.graphDependency(
sourceDirectory: path,
allTargetsMap: allTargetsMap,
target: target
)
return (GraphEdge(from: sourceDependency, to: graphDep), dep.condition, graphDep)
}
// Update conditions dictionary
for (edge, condition, _) in edgesAndDeps {
if let condition {
dependencyConditions[edge] = condition
}
}
// Update dependencies dictionary
let targetDeps = edgesAndDeps.map(\.2)
if !targetDeps.isEmpty {
dependencies[sourceDependency] = Set(targetDeps)
}
}
}
return (dependencies, dependencyConditions)
}
private func assembleFinalGraph(
workspace: Workspace,
projects: [AbsolutePath: Project],
packages: [AbsolutePath: [String: Package]],
dependencies: [GraphDependency: Set<GraphDependency>],
dependencyConditions: [GraphEdge: PlatformCondition]
) -> Graph {
Graph(
name: workspace.name,
path: workspace.path,
workspace: workspace,
projects: projects,
packages: packages,
dependencies: dependencies,
dependencyConditions: dependencyConditions
)
}
// MARK: - Project Path Extraction
private func extractProjectPaths(
from elements: [XCWorkspaceDataElement],
srcPath: AbsolutePath
) async throws -> [AbsolutePath] {
var paths: [AbsolutePath] = []
for element in elements {
switch element {
case let .file(ref):
let refPath = try await ref.path(srcPath: srcPath)
if refPath.extension == "xcodeproj" {
paths.append(refPath)
}
case let .group(group):
let nestedPaths = try await extractProjectPaths(from: group.children, srcPath: srcPath)
paths.append(contentsOf: nestedPaths)
}
}
return paths
}
}