Skip to content

Remove use of AbsolutePath.appending(RelativePath(_:)) #4237

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 21, 2022
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
9 changes: 9 additions & 0 deletions Fixtures/CFamilyTargets/CLibraryParentSearchPath/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
.DS_Store
/.build
/Packages
/*.xcodeproj
xcuserdata/
DerivedData/
.swiftpm/config/registries.json
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
.netrc
29 changes: 29 additions & 0 deletions Fixtures/CFamilyTargets/CLibraryParentSearchPath/Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// swift-tools-version: 5.5

import PackageDescription

let package = Package(
name: "CLibraryParentSearchPath",
products: [
.library(
name: "HeaderInclude",
targets: ["HeaderInclude"]),
],
targets: [
.target(
name: "CHeaderInclude",
cSettings: [
/*
This package tests path normalization; incorrect path normalization on certain OSes (especially Windows) can lead to relative paths like these not being correctly passed to the C compiler.
*/
.headerSearchPath("../Constants")
]
),
.target(
name: "HeaderInclude",
dependencies: [
"CHeaderInclude"
]
)
]
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@

#include "answers.h"
#include "Constants.h"

int getAnswer(void) {
return kTheAnswer;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@

#ifndef answers_h
#define answers_h

extern int getAnswer(void);

#endif /* answers_h */
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@

#ifndef Constants_h
#define Constants_h

static const int kTheAnswer = 42;

#endif /* Constants_h */
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@

import CHeaderInclude

enum Answer {
var value: Int { Int(getAnswer()) }
}
12 changes: 7 additions & 5 deletions Sources/Build/BuildPlan.swift
Original file line number Diff line number Diff line change
Expand Up @@ -328,8 +328,8 @@ public final class ClangTargetBuildDescription {
return sources.flatMap { (root, relativePaths) in
relativePaths.map { source in
let path = root.appending(source)
let object = tempsPath.appending(RelativePath("\(source.pathString).o"))
let deps = tempsPath.appending(RelativePath("\(source.pathString).d"))
let object = AbsolutePath("\(source.pathString).o", relativeTo: tempsPath)
let deps = AbsolutePath("\(source.pathString).d", relativeTo: tempsPath)
return (source, path, object, deps)
}
}
Expand Down Expand Up @@ -418,7 +418,7 @@ public final class ClangTargetBuildDescription {
// Header search paths.
let headerSearchPaths = scope.evaluate(.HEADER_SEARCH_PATHS)
flags += headerSearchPaths.map({
"-I\(target.sources.root.appending(RelativePath($0)).pathString)"
"-I\(AbsolutePath($0, relativeTo: target.sources.root).pathString)"
})

// Other C flags.
Expand Down Expand Up @@ -553,7 +553,9 @@ public final class SwiftTargetBuildDescription {
/// The objects in this target.
public var objects: [AbsolutePath] {
let relativePaths = target.sources.relativePaths + derivedSources.relativePaths + pluginDerivedSources.relativePaths
return relativePaths.map{ tempsPath.appending(RelativePath("\($0.pathString).o")) }
return relativePaths.map {
AbsolutePath("\($0.pathString).o", relativeTo: tempsPath)
}
}

/// The path to the swiftmodule file after compilation.
Expand Down Expand Up @@ -1071,7 +1073,7 @@ public final class SwiftTargetBuildDescription {
// Header search paths.
let headerSearchPaths = scope.evaluate(.HEADER_SEARCH_PATHS)
flags += headerSearchPaths.flatMap({ path -> [String] in
return ["-Xcc", "-I\(target.sources.root.appending(RelativePath(path)).pathString)"]
return ["-Xcc", "-I\(AbsolutePath(path, relativeTo: target.sources.root).pathString)"]
})

// Other C flags.
Expand Down
4 changes: 2 additions & 2 deletions Sources/Commands/SwiftPackageTool.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1871,7 +1871,7 @@ extension SwiftPackageTool {
}

let files = try fileSystem.getDirectoryContents(directory)
.map { directory.appending(RelativePath($0)) }
.map { AbsolutePath($0, relativeTo: directory) }
.filter { fileSystem.isFile($0) }

guard let fileExtension = fileExtension else {
Expand All @@ -1886,7 +1886,7 @@ extension SwiftPackageTool {
return []
}
return try fileSystem.getDirectoryContents(directory)
.map { directory.appending(RelativePath($0)) }
.map { AbsolutePath($0, relativeTo: directory) }
.filter { fileSystem.isDirectory($0) }
}

Expand Down
2 changes: 1 addition & 1 deletion Sources/PackageLoading/ManifestJSONParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ enum ManifestJSONParser {
private static func sanitizeDependencyLocation(fileSystem: TSCBasic.FileSystem, packageKind: PackageReference.Kind, dependencyLocation: String) throws -> String {
if dependencyLocation.hasPrefix("~/") {
// If the dependency URL starts with '~/', try to expand it.
return fileSystem.homeDirectory.appending(RelativePath(String(dependencyLocation.dropFirst(2)))).pathString
return AbsolutePath(String(dependencyLocation.dropFirst(2)), relativeTo: fileSystem.homeDirectory).pathString
} else if dependencyLocation.hasPrefix(filePrefix) {
// FIXME: SwiftPM can't handle file locations with file:// scheme so we need to
// strip that. We need to design a Location data structure for SwiftPM.
Expand Down
2 changes: 1 addition & 1 deletion Sources/PackageLoading/MinimumDeploymentTarget.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public struct MinimumDeploymentTarget {
static func computeXCTestMinimumDeploymentTarget(with runResult: ProcessResult, platform: PackageModel.Platform) throws -> PlatformVersion? {
guard let output = try runResult.utf8Output().spm_chuzzle() else { return nil }
let sdkPath = try AbsolutePath(validating: output)
let xcTestPath = sdkPath.appending(RelativePath("Developer/Library/Frameworks/XCTest.framework/XCTest"))
let xcTestPath = AbsolutePath("Developer/Library/Frameworks/XCTest.framework/XCTest", relativeTo: sdkPath)
return try computeMinimumDeploymentTarget(of: xcTestPath, platform: platform)
}

Expand Down
10 changes: 5 additions & 5 deletions Sources/PackageLoading/TargetSourcesBuilder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public struct TargetSourcesBuilder {
let actualAdditionalRules = (toolsVersion <= ToolsVersion.v5_4 ? FileRuleDescription.xcbuildFileTypes : additionalFileRules)
self.rules = FileRuleDescription.builtinRules + actualAdditionalRules
self.toolsVersion = toolsVersion
let excludedPaths = target.exclude.map{ path.appending(RelativePath($0)) }
let excludedPaths = target.exclude.map { AbsolutePath($0, relativeTo: path) }
self.excludedPaths = Set(excludedPaths)
self.opaqueDirectoriesExtensions = FileRuleDescription.opaqueDirectoriesExtensions.union(
additionalFileRules.reduce(into: Set<String>(), { partial, item in
Expand All @@ -92,7 +92,7 @@ public struct TargetSourcesBuilder {
return metadata
}

let declaredSources = target.sources?.map{ path.appending(RelativePath($0)) }
let declaredSources = target.sources?.map { AbsolutePath($0, relativeTo: path) }
if let declaredSources = declaredSources {
// Diagnose duplicate entries.
let duplicates = declaredSources.spm_findDuplicateElements()
Expand Down Expand Up @@ -188,7 +188,7 @@ public struct TargetSourcesBuilder {

// First match any resources explicitly declared in the manifest file.
for declaredResource in target.resources {
let resourcePath = self.targetPath.appending(RelativePath(declaredResource.path))
let resourcePath = AbsolutePath(declaredResource.path, relativeTo: self.targetPath)
if path.isDescendantOfOrEqual(to: resourcePath) {
if matchedRule != .none {
self.observabilityScope.emit(error: "duplicate resource rule '\(declaredResource.rule)' found for file at '\(path)'")
Expand Down Expand Up @@ -332,7 +332,7 @@ public struct TargetSourcesBuilder {

private func diagnoseInvalidResource(in resources: [TargetDescription.Resource]) {
resources.forEach { resource in
let resourcePath = self.targetPath.appending(RelativePath(resource.path))
let resourcePath = AbsolutePath(resource.path, relativeTo: self.targetPath)
if let message = validTargetPath(at: resourcePath), self.packageKind.emitAuthorWarnings {
let warning = "Invalid Resource '\(resource.path)': \(message)."
self.observabilityScope.emit(warning: warning)
Expand Down Expand Up @@ -421,7 +421,7 @@ public struct TargetSourcesBuilder {

// Check if the directory is marked to be copied.
let directoryMarkedToBeCopied = target.resources.contains{ resource in
let resourcePath = self.targetPath.appending(RelativePath(resource.path))
let resourcePath = AbsolutePath(resource.path, relativeTo: self.targetPath)
if resource.rule == .copy && resourcePath == path {
return true
}
Expand Down
6 changes: 3 additions & 3 deletions Sources/SPMBuildCore/BinaryTarget+Extensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ extension BinaryTarget {
}
// Construct a LibraryInfo for the library.
let libraryDir = self.artifactPath.appending(component: library.libraryIdentifier)
let libraryFile = libraryDir.appending(RelativePath(library.libraryPath))
let headersDir = library.headersPath.map{ libraryDir.appending(RelativePath($0)) }
let libraryFile = AbsolutePath(library.libraryPath, relativeTo: libraryDir)
let headersDir = library.headersPath.map { AbsolutePath($0, relativeTo: libraryDir) }
return [LibraryInfo(libraryPath: libraryFile, headersPath: headersDir)]
}

Expand All @@ -73,7 +73,7 @@ extension BinaryTarget {
return tripleStrings.contains(triple.tripleString)
}
}.map{
ExecutableInfo(name: entry.key, executablePath: self.artifactPath.appending(RelativePath($0.path)))
ExecutableInfo(name: entry.key, executablePath: AbsolutePath($0.path, relativeTo: self.artifactPath))
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions Sources/SPMBuildCore/Toolchain.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,11 @@ extension Toolchain {
}

public var macosSwiftStdlib: AbsolutePath {
return resolveSymlinks(swiftCompiler).appending(RelativePath("../../lib/swift/macosx"))
return AbsolutePath("../../lib/swift/macosx", relativeTo: resolveSymlinks(swiftCompiler))
}

public var toolchainLibDir: AbsolutePath {
// FIXME: Not sure if it's better to base this off of Swift compiler or our own binary.
return resolveSymlinks(swiftCompiler).appending(RelativePath("../../lib"))
return AbsolutePath("../../lib", relativeTo: resolveSymlinks(swiftCompiler))
}
}
2 changes: 1 addition & 1 deletion Sources/SPMTestSupport/MockRegistry.swift
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ private struct MockRegistryArchiver: Archiver {
let rootPath = lines[1]
for path in lines[2..<lines.count] {
let relativePath = String(path.dropFirst(rootPath.count + 1))
let targetPath = destinationPath.appending(component: "package").appending(RelativePath(relativePath))
let targetPath = AbsolutePath(relativePath, relativeTo: destinationPath.appending(component: "package"))
if !self.fileSystem.exists(targetPath.parentDirectory) {
try self.fileSystem.createDirectory(targetPath.parentDirectory, recursive: true)
}
Expand Down
6 changes: 3 additions & 3 deletions Sources/SPMTestSupport/MockWorkspace.swift
Original file line number Diff line number Diff line change
Expand Up @@ -96,11 +96,11 @@ public final class MockWorkspace {
}

public func pathToRoot(withName name: String) -> AbsolutePath {
return self.rootsDir.appending(RelativePath(name))
return AbsolutePath(name, relativeTo: self.rootsDir)
}

public func pathToPackage(withName name: String) -> AbsolutePath {
return self.packagesDir.appending(RelativePath(name))
return AbsolutePath(name, relativeTo: self.packagesDir)
}

private func create() throws {
Expand Down Expand Up @@ -292,7 +292,7 @@ public final class MockWorkspace {
}

public func rootPaths(for packages: [String]) -> [AbsolutePath] {
return packages.map { rootsDir.appending(RelativePath($0)) }
return packages.map { AbsolutePath($0, relativeTo: rootsDir) }
}

public func checkEdit(
Expand Down
2 changes: 1 addition & 1 deletion Sources/SPMTestSupport/misc.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public func fixture(

// Construct the expected path of the fixture.
// FIXME: This seems quite hacky; we should provide some control over where fixtures are found.
let fixtureDir = AbsolutePath(#file).appending(RelativePath("../../../Fixtures")).appending(fixtureSubpath)
let fixtureDir = AbsolutePath("../../../Fixtures", relativeTo: AbsolutePath(#file)).appending(fixtureSubpath)

// Check that the fixture is really there.
guard localFileSystem.isDirectory(fixtureDir) else {
Expand Down
6 changes: 3 additions & 3 deletions Sources/Workspace/InitPackage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ public final class InitPackage {
try makeDirectories(moduleDir)

let sourceFileName = "\(typeName).swift"
let sourceFile = moduleDir.appending(RelativePath(sourceFileName))
let sourceFile = AbsolutePath(sourceFileName, relativeTo: moduleDir)

let content: String
switch packageType {
Expand Down Expand Up @@ -410,11 +410,11 @@ public final class InitPackage {
}

private func writeTestFileStubs(testsPath: AbsolutePath) throws {
let testModule = testsPath.appending(RelativePath(pkgname + Target.testModuleNameSuffix))
let testModule = AbsolutePath(pkgname + Target.testModuleNameSuffix, relativeTo: testsPath)
progressReporter?("Creating \(testModule.relative(to: destinationPath))/")
try makeDirectories(testModule)

let testClassFile = testModule.appending(RelativePath("\(moduleName)Tests.swift"))
let testClassFile = AbsolutePath("\(moduleName)Tests.swift", relativeTo: testModule)
switch packageType {
case .systemModule, .empty, .manifest, .`extension`: break
case .library:
Expand Down
4 changes: 2 additions & 2 deletions Sources/Workspace/UserToolchain.swift
Original file line number Diff line number Diff line change
Expand Up @@ -277,8 +277,8 @@ public final class UserToolchain: Toolchain {
.appending(component: "Library")
.appending(component: "XCTest-\(info.defaults.xctestVersion)")
xctest = [
"-I", path.appending(RelativePath("usr/lib/swift/windows/\(triple.arch)")).pathString,
"-L", path.appending(RelativePath("usr/lib/swift/windows")).pathString,
"-I", AbsolutePath("usr/lib/swift/windows/\(triple.arch)", relativeTo: path).pathString,
"-L", AbsolutePath("usr/lib/swift/windows", relativeTo: path).pathString,
]

extraSwiftCFlags = info.defaults.extraSwiftCFlags ?? []
Expand Down
2 changes: 1 addition & 1 deletion Sources/Workspace/Workspace.swift
Original file line number Diff line number Diff line change
Expand Up @@ -975,7 +975,7 @@ extension Workspace {
// Remove all but protected paths.
let contentsToRemove = Set(contents).subtracting(protectedAssets)
for name in contentsToRemove {
try? fileSystem.removeFileTree(self.location.scratchDirectory.appending(RelativePath(name)))
try? fileSystem.removeFileTree(AbsolutePath(name, relativeTo: self.location.scratchDirectory))
}
}

Expand Down
2 changes: 1 addition & 1 deletion Sources/XCBuildSupport/PIFBuilder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -862,7 +862,7 @@ final class PackagePIFProjectBuilder: PIFProjectBuilder {
for assignment in assignments {
var value = assignment.value
if setting == .HEADER_SEARCH_PATHS {
value = value.map { target.sources.root.appending(RelativePath($0)).pathString }
value = value.map { AbsolutePath($0, relativeTo: target.sources.root).pathString }
}

if let platforms = assignment.platforms {
Expand Down
2 changes: 1 addition & 1 deletion Sources/XCBuildSupport/XcodeBuildSystem.swift
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public final class XcodeBuildSystem: SPMBuildCore.BuildSystem {
} else {
let xcodeSelectOutput = try Process.popen(args: "xcode-select", "-p").utf8Output().spm_chomp()
let xcodeDirectory = try AbsolutePath(validating: xcodeSelectOutput)
xcbuildPath = xcodeDirectory.appending(RelativePath("../SharedFrameworks/XCBuild.framework/Versions/A/Support/xcbuild"))
xcbuildPath = AbsolutePath("../SharedFrameworks/XCBuild.framework/Versions/A/Support/xcbuild", relativeTo: xcodeDirectory)
}

guard fileSystem.exists(xcbuildPath) else {
Expand Down
8 changes: 4 additions & 4 deletions Sources/Xcodeproj/SchemesGenerator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -204,12 +204,12 @@ public final class SchemesGenerator {

"""

let file = schemesDir.appending(RelativePath(scheme.filename))
let file = AbsolutePath(scheme.filename, relativeTo: schemesDir)
try fs.writeFileContents(file, bytes: stream.bytes)
}

private func disableSchemeAutoCreation() throws {
let workspacePath = schemesDir.appending(RelativePath("../../project.xcworkspace"))
let workspacePath = AbsolutePath("../../project.xcworkspace", relativeTo: schemesDir)

// Write the settings file to disable automatic scheme creation.
var stream = BufferedOutputByteStream()
Expand All @@ -223,12 +223,12 @@ public final class SchemesGenerator {
</dict>
</plist>
"""
let settingsPlist = workspacePath.appending(RelativePath("xcshareddata/WorkspaceSettings.xcsettings"))
let settingsPlist = AbsolutePath("xcshareddata/WorkspaceSettings.xcsettings", relativeTo: workspacePath)
try fs.createDirectory(settingsPlist.parentDirectory, recursive: true)
try fs.writeFileContents(settingsPlist, bytes: stream.bytes)

// Write workspace contents file.
let contentsFile = workspacePath.appending(RelativePath("contents.xcworkspacedata"))
let contentsFile = AbsolutePath("contents.xcworkspacedata", relativeTo: workspacePath)
stream = BufferedOutputByteStream()
stream <<< """
<?xml version="1.0" encoding="UTF-8"?>
Expand Down
6 changes: 3 additions & 3 deletions Sources/Xcodeproj/generate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public enum XcodeProject {
// Determine the path of the .xcodeproj wrapper directory.
public static func makePath(outputDir: AbsolutePath, projectName: String) -> AbsolutePath {
let xcodeprojName = "\(projectName).xcodeproj"
return outputDir.appending(RelativePath(xcodeprojName))
return AbsolutePath(xcodeprojName, relativeTo: outputDir)
}

/// Generates an Xcode project and all needed support files. The .xcodeproj
Expand Down Expand Up @@ -142,7 +142,7 @@ public enum XcodeProject {
///// For framework targets, generate target.c99Name_Info.plist files in the
///// directory that Xcode project is generated
let name = target.infoPlistFileName
try open(xcodeprojPath.appending(RelativePath(name))) { print in
try open(AbsolutePath(name, relativeTo: xcodeprojPath)) { print in
print("""
<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0">
Expand Down Expand Up @@ -242,7 +242,7 @@ public enum XcodeProject {
// -Package so its name doesn't collide with any products or target with
// same name.
let schemeName = "\(graph.rootPackages[0].manifest.displayName)-Package.xcscheme" // TODO: use identity instead?
try open(schemesDir.appending(RelativePath(schemeName))) { stream in
try open(AbsolutePath(schemeName, relativeTo: schemesDir)) { stream in
legacySchemeGenerator(
container: schemeContainer,
graph: graph,
Expand Down
7 changes: 7 additions & 0 deletions Tests/FunctionalTests/CFamilyTargetTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,11 @@ class CFamilyTargetTestCase: XCTestCase {
XCTAssertSwiftTest(fixturePath)
}
}

func testCanBuildRelativeHeaderSearchPaths() throws {
try fixture(name: "CFamilyTargets/CLibraryParentSearchPath") { fixturePath in
XCTAssertBuilds(fixturePath)
XCTAssertDirectoryContainsFile(dir: fixturePath.appending(components: ".build", UserToolchain.default.triple.platformBuildPathComponent(), "debug"), filename: "HeaderInclude.swiftmodule")
}
}
}