Skip to content
Draft
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
29 changes: 28 additions & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,33 @@ let package = Package(
.plugin(
name: "SafeDIGenerator",
capability: .buildTool(),
dependencies: ["SafeDITool"],
dependencies: [
"SafeDITool",
],
),
// A lightweight executable that performs lexical root discovery without SwiftSyntax.
// SPM plugins run this in-process via symlinked sources.
// This target exists as a standalone executable for non-SPM build systems (e.g. Buck, Bazel)
// that need to invoke root scanning as a separate process.
.executableTarget(
name: "SafeDIRootScanner",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
],
swiftSettings: [
.swiftLanguageMode(.v6),
],
),
.testTarget(
name: "SafeDIRootScannerTests",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
"SafeDICore",
"SafeDIRootScanner",
],
swiftSettings: [
.swiftLanguageMode(.v6),
],
),
.executableTarget(
name: "SafeDITool",
Expand All @@ -139,6 +165,7 @@ let package = Package(
name: "SafeDIToolTests",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
"SafeDIRootScanner",
"SafeDITool",
],
swiftSettings: [
Expand Down
1 change: 1 addition & 0 deletions Plugins/SafeDIGenerator/RelativePath.swift
1 change: 1 addition & 0 deletions Plugins/SafeDIGenerator/RootScanner.swift
66 changes: 24 additions & 42 deletions Plugins/SafeDIGenerator/SafeDIGenerateDependencyTree.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,33 +48,24 @@ struct SafeDIGenerateDependencyTree: BuildToolPlugin {
}

let allSwiftFiles = targetSwiftFiles + dependenciesSourceFiles
let rootFiles = findFilesWithRoots(in: allSwiftFiles)
guard !rootFiles.isEmpty else {
return []
}

let outputFiles = zip(rootFiles, outputFileNames(for: rootFiles)).map { _, name in
outputDirectory.appending(path: name)
}

let packageRoot = context.package.directoryURL
let inputSourcesFile = context.pluginWorkDirectoryURL.appending(path: "InputSwiftFiles.csv")
try allSwiftFiles
.map { relativePath(for: $0, relativeTo: packageRoot) }
.joined(separator: ",")
.write(
to: inputSourcesFile,
atomically: true,
encoding: .utf8,
)
try writeInputSwiftFilesCSV(
allSwiftFiles,
relativeTo: packageRoot,
to: inputSourcesFile,
)

let manifestFile = context.pluginWorkDirectoryURL.appending(path: "SafeDIManifest.json")
try writeManifest(
dependencyTreeInputFiles: rootFiles,
let outputFiles = try runRootScanner(
inputSourcesFile: inputSourcesFile,
projectRoot: packageRoot,
outputDirectory: outputDirectory,
to: manifestFile,
relativeTo: packageRoot,
manifestFile: manifestFile,
)
guard !outputFiles.isEmpty else {
return []
}

let arguments = [
inputSourcesFile.path(percentEncoded: false),
Expand Down Expand Up @@ -163,34 +154,25 @@ extension Target {
return []
}

let rootFiles = findFilesWithRoots(in: inputSwiftFiles)
guard !rootFiles.isEmpty else {
return []
}

let outputDirectory = context.pluginWorkDirectoryURL.appending(path: "SafeDIOutput")
let outputFiles = zip(rootFiles, outputFileNames(for: rootFiles)).map { _, name in
outputDirectory.appending(path: name)
}

let projectRoot = context.xcodeProject.directoryURL
let inputSourcesFile = context.pluginWorkDirectoryURL.appending(path: "InputSwiftFiles.csv")
try inputSwiftFiles
.map { relativePath(for: $0, relativeTo: projectRoot) }
.joined(separator: ",")
.write(
to: inputSourcesFile,
atomically: true,
encoding: .utf8,
)
try writeInputSwiftFilesCSV(
inputSwiftFiles,
relativeTo: projectRoot,
to: inputSourcesFile,
)

let manifestFile = context.pluginWorkDirectoryURL.appending(path: "SafeDIManifest.json")
try writeManifest(
dependencyTreeInputFiles: rootFiles,
let outputFiles = try runRootScanner(
inputSourcesFile: inputSourcesFile,
projectRoot: projectRoot,
outputDirectory: outputDirectory,
to: manifestFile,
relativeTo: projectRoot,
manifestFile: manifestFile,
)
guard !outputFiles.isEmpty else {
return []
}

let arguments = [
inputSourcesFile.path(percentEncoded: false),
Expand Down
1 change: 1 addition & 0 deletions Plugins/SafeDIGenerator/SharedRootScanner.swift
1 change: 1 addition & 0 deletions Plugins/SafeDIPrebuiltGenerator/RelativePath.swift
1 change: 1 addition & 0 deletions Plugins/SafeDIPrebuiltGenerator/RootScanner.swift
66 changes: 24 additions & 42 deletions Plugins/SafeDIPrebuiltGenerator/SafeDIGenerateDependencyTree.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,33 +48,24 @@ struct SafeDIGenerateDependencyTree: BuildToolPlugin {
}

let allSwiftFiles = targetSwiftFiles + dependenciesSourceFiles
let rootFiles = findFilesWithRoots(in: allSwiftFiles)
guard !rootFiles.isEmpty else {
return []
}

let outputFiles = zip(rootFiles, outputFileNames(for: rootFiles)).map { _, name in
outputDirectory.appending(path: name)
}

let packageRoot = context.package.directoryURL
let inputSourcesFile = context.pluginWorkDirectoryURL.appending(path: "InputSwiftFiles.csv")
try allSwiftFiles
.map { relativePath(for: $0, relativeTo: packageRoot) }
.joined(separator: ",")
.write(
to: inputSourcesFile,
atomically: true,
encoding: .utf8,
)
try writeInputSwiftFilesCSV(
allSwiftFiles,
relativeTo: packageRoot,
to: inputSourcesFile,
)

let manifestFile = context.pluginWorkDirectoryURL.appending(path: "SafeDIManifest.json")
try writeManifest(
dependencyTreeInputFiles: rootFiles,
let outputFiles = try runRootScanner(
inputSourcesFile: inputSourcesFile,
projectRoot: packageRoot,
outputDirectory: outputDirectory,
to: manifestFile,
relativeTo: packageRoot,
manifestFile: manifestFile,
)
guard !outputFiles.isEmpty else {
return []
}

let arguments = [
inputSourcesFile.path(percentEncoded: false),
Expand Down Expand Up @@ -173,34 +164,25 @@ extension Target {
return []
}

let rootFiles = findFilesWithRoots(in: inputSwiftFiles)
guard !rootFiles.isEmpty else {
return []
}

let outputDirectory = context.pluginWorkDirectoryURL.appending(path: "SafeDIOutput")
let outputFiles = zip(rootFiles, outputFileNames(for: rootFiles)).map { _, name in
outputDirectory.appending(path: name)
}

let projectRoot = context.xcodeProject.directoryURL
let inputSourcesFile = context.pluginWorkDirectoryURL.appending(path: "InputSwiftFiles.csv")
try inputSwiftFiles
.map { relativePath(for: $0, relativeTo: projectRoot) }
.joined(separator: ",")
.write(
to: inputSourcesFile,
atomically: true,
encoding: .utf8,
)
try writeInputSwiftFilesCSV(
inputSwiftFiles,
relativeTo: projectRoot,
to: inputSourcesFile,
)

let manifestFile = context.pluginWorkDirectoryURL.appending(path: "SafeDIManifest.json")
try writeManifest(
dependencyTreeInputFiles: rootFiles,
let outputFiles = try runRootScanner(
inputSourcesFile: inputSourcesFile,
projectRoot: projectRoot,
outputDirectory: outputDirectory,
to: manifestFile,
relativeTo: projectRoot,
manifestFile: manifestFile,
)
guard !outputFiles.isEmpty else {
return []
}

let arguments = [
inputSourcesFile.path(percentEncoded: false),
Expand Down
1 change: 1 addition & 0 deletions Plugins/SafeDIPrebuiltGenerator/SharedRootScanner.swift
82 changes: 0 additions & 82 deletions Plugins/Shared.swift
Original file line number Diff line number Diff line change
Expand Up @@ -112,85 +112,3 @@ extension PackagePlugin.PluginContext {
return expectedToolLocation
}
}

/// Find Swift files that contain `@Instantiable(isRoot: true)` declarations.
func findFilesWithRoots(in swiftFiles: [URL]) -> [URL] {
swiftFiles.filter { fileURL in
guard let content = try? String(contentsOf: fileURL, encoding: .utf8) else { return false }
guard content.contains("isRoot") else { return false }
guard let regex = try? Regex(#"@Instantiable\s*\([^)]*isRoot\s*:\s*true[^)]*\)"#) else { return false }
// Check each match is not inside a comment or backtick-quoted code span.
for match in content.matches(of: regex) {
let lineStart = content[content.startIndex..<match.range.lowerBound].lastIndex(of: "\n").map { content.index(after: $0) } ?? content.startIndex
let linePrefix = content[lineStart..<match.range.lowerBound]
// Skip matches inside single-line comments.
if linePrefix.contains("//") { continue }
// Skip matches inside backtick-quoted code spans.
if linePrefix.contains("`") { continue }
return true
}
return false
}
}

/// Derive unique output filenames for a set of input Swift files.
/// If two files share the same base name (e.g. `ModuleA/Root.swift` and `ModuleB/Root.swift`),
/// parent directory components are prepended to disambiguate (e.g. `ModuleA_Root+SafeDI.swift`).
func outputFileNames(for inputURLs: [URL]) -> [String] {
let baseNames = inputURLs.map { $0.deletingPathExtension().lastPathComponent }

// Count occurrences of each base name.
var nameCounts = [String: Int]()
for name in baseNames {
nameCounts[name, default: 0] += 1
}

return zip(inputURLs, baseNames).map { url, baseName in
if nameCounts[baseName, default: 1] > 1 {
// Disambiguate by prepending the parent directory name.
let parent = url.deletingLastPathComponent().lastPathComponent
return "\(parent)_\(baseName)+SafeDI.swift"
} else {
return "\(baseName)+SafeDI.swift"
}
}
}

/// Compute a path string relative to a base directory, for use in the CSV and manifest.
/// Falls back to the absolute path if the URL is not under the base directory.
func relativePath(for url: URL, relativeTo base: URL) -> String {
let urlPath = url.path(percentEncoded: false)
let basePath = base.path(percentEncoded: false).hasSuffix("/")
? base.path(percentEncoded: false)
: base.path(percentEncoded: false) + "/"
if urlPath.hasPrefix(basePath) {
return String(urlPath.dropFirst(basePath.count))
}
return urlPath
}

/// Write a SafeDIToolManifest JSON file mapping input file paths to output file paths.
/// Input paths are written relative to `relativeTo` for remote cache compatibility.
/// Output paths are absolute since they reference the build system's plugin work directory.
///
/// Note: The JSON keys here must match the property names in `SafeDIToolManifest` and
/// `SafeDIToolManifest.InputOutputMap` (in SafeDICore). Plugins cannot import SafeDICore,
/// so these are duplicated as string literals.
func writeManifest(
dependencyTreeInputFiles: [URL],
outputDirectory: URL,
to manifestURL: URL,
relativeTo base: URL,
) throws {
let fileNames = outputFileNames(for: dependencyTreeInputFiles)
var entries = [[String: String]]()
for (inputURL, fileName) in zip(dependencyTreeInputFiles, fileNames) {
entries.append([
"inputFilePath": relativePath(for: inputURL, relativeTo: base),
"outputFilePath": outputDirectory.appending(path: fileName).path(percentEncoded: false),
])
}
let manifest = ["dependencyTreeGeneration": entries]
let data = try JSONSerialization.data(withJSONObject: manifest, options: [.sortedKeys])
try data.write(to: manifestURL)
}
52 changes: 52 additions & 0 deletions Plugins/SharedRootScanner.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Distributed under the MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

import Foundation

func writeInputSwiftFilesCSV(
_ swiftFiles: [URL],
relativeTo base: URL,
to inputSourcesFile: URL,
) throws {
try swiftFiles
.map { relativePath(for: $0, relativeTo: base) }
.joined(separator: ",")
.write(
to: inputSourcesFile,
atomically: true,
encoding: .utf8,
)
}

func runRootScanner(
inputSourcesFile: URL,
projectRoot: URL,
outputDirectory: URL,
manifestFile: URL,
) throws -> [URL] {
let inputFilePaths = try RootScanner.inputFilePaths(from: inputSourcesFile)
let result = try RootScanner().scan(
inputFilePaths: inputFilePaths,
relativeTo: projectRoot,
outputDirectory: outputDirectory,
)
try result.writeManifest(to: manifestFile)
return result.outputFiles
}
Loading
Loading