diff --git a/Examples/package-info/Sources/package-info/example.swift b/Examples/package-info/Sources/package-info/example.swift index e483315ef7a..0ec45d4ecf5 100644 --- a/Examples/package-info/Sources/package-info/example.swift +++ b/Examples/package-info/Sources/package-info/example.swift @@ -1,5 +1,4 @@ import Basics -import TSCBasic import Workspace @main diff --git a/Sources/Basics/Archiver/Archiver.swift b/Sources/Basics/Archiver/Archiver.swift index 7b54407fe7f..64d6edc9717 100644 --- a/Sources/Basics/Archiver/Archiver.swift +++ b/Sources/Basics/Archiver/Archiver.swift @@ -11,7 +11,6 @@ //===----------------------------------------------------------------------===// import _Concurrency -import TSCBasic /// The `Archiver` protocol abstracts away the different operations surrounding archives. public protocol Archiver { diff --git a/Sources/Basics/Archiver/TarArchiver.swift b/Sources/Basics/Archiver/TarArchiver.swift index 5d4a210a3f2..d1da7ed0c15 100644 --- a/Sources/Basics/Archiver/TarArchiver.swift +++ b/Sources/Basics/Archiver/TarArchiver.swift @@ -12,8 +12,6 @@ import class Dispatch.DispatchQueue import struct Dispatch.DispatchTime -import struct TSCBasic.AbsolutePath -import protocol TSCBasic.FileSystem import struct TSCBasic.FileSystemError import class TSCBasic.Process @@ -53,11 +51,11 @@ public struct TarArchiver: Archiver { ) { do { guard self.fileSystem.exists(archivePath) else { - throw FileSystemError(.noEntry, archivePath) + throw FileSystemError(.noEntry, archivePath.underlying) } guard self.fileSystem.isDirectory(destinationPath) else { - throw FileSystemError(.notDirectory, destinationPath) + throw FileSystemError(.notDirectory, destinationPath.underlying) } let process = TSCBasic.Process( @@ -90,12 +88,12 @@ public struct TarArchiver: Archiver { ) { do { guard self.fileSystem.isDirectory(directory) else { - throw FileSystemError(.notDirectory, directory) + throw FileSystemError(.notDirectory, directory.underlying) } let process = TSCBasic.Process( arguments: [self.tarCommand, "acf", destinationPath.pathString, directory.basename], - workingDirectory: directory.parentDirectory + workingDirectory: directory.parentDirectory.underlying ) guard let registrationKey = self.cancellator.register(process) else { @@ -120,7 +118,7 @@ public struct TarArchiver: Archiver { public func validate(path: AbsolutePath, completion: @escaping (Result) -> Void) { do { guard self.fileSystem.exists(path) else { - throw FileSystemError(.noEntry, path) + throw FileSystemError(.noEntry, path.underlying) } let process = TSCBasic.Process(arguments: [self.tarCommand, "tf", path.pathString]) diff --git a/Sources/Basics/Archiver/UniversalArchiver.swift b/Sources/Basics/Archiver/UniversalArchiver.swift index 58e26323e94..cbd5d5d742f 100644 --- a/Sources/Basics/Archiver/UniversalArchiver.swift +++ b/Sources/Basics/Archiver/UniversalArchiver.swift @@ -10,9 +10,6 @@ // //===----------------------------------------------------------------------===// -import struct TSCBasic.AbsolutePath -import protocol TSCBasic.FileSystem - /// An `Archiver` that handles multiple formats by delegating to other existing archivers each dedicated to its own /// format. public struct UniversalArchiver: Archiver { diff --git a/Sources/Basics/Archiver/ZipArchiver.swift b/Sources/Basics/Archiver/ZipArchiver.swift index b4549a9e059..1bc05ffb8e3 100644 --- a/Sources/Basics/Archiver/ZipArchiver.swift +++ b/Sources/Basics/Archiver/ZipArchiver.swift @@ -10,8 +10,9 @@ // //===----------------------------------------------------------------------===// -import TSCBasic import Dispatch +import struct TSCBasic.FileSystemError +import class TSCBasic.Process /// An `Archiver` that handles ZIP archives using the command-line `zip` and `unzip` tools. public struct ZipArchiver: Archiver, Cancellable { @@ -40,18 +41,20 @@ public struct ZipArchiver: Archiver, Cancellable { ) { do { guard self.fileSystem.exists(archivePath) else { - throw FileSystemError(.noEntry, archivePath) + throw FileSystemError(.noEntry, archivePath.underlying) } guard self.fileSystem.isDirectory(destinationPath) else { - throw FileSystemError(.notDirectory, destinationPath) + throw FileSystemError(.notDirectory, destinationPath.underlying) } -#if os(Windows) - let process = TSCBasic.Process(arguments: ["tar.exe", "xf", archivePath.pathString, "-C", destinationPath.pathString]) -#else - let process = TSCBasic.Process(arguments: ["unzip", archivePath.pathString, "-d", destinationPath.pathString]) -#endif + #if os(Windows) + let process = TSCBasic + .Process(arguments: ["tar.exe", "xf", archivePath.pathString, "-C", destinationPath.pathString]) + #else + let process = TSCBasic + .Process(arguments: ["unzip", archivePath.pathString, "-d", destinationPath.pathString]) + #endif guard let registrationKey = self.cancellator.register(process) else { throw CancellationError.failedToRegisterProcess(process) } @@ -78,21 +81,21 @@ public struct ZipArchiver: Archiver, Cancellable { ) { do { guard self.fileSystem.isDirectory(directory) else { - throw FileSystemError(.notDirectory, directory) + throw FileSystemError(.notDirectory, directory.underlying) } -#if os(Windows) + #if os(Windows) let process = TSCBasic.Process( // FIXME: are these the right arguments? arguments: ["tar.exe", "-a", "-c", "-f", destinationPath.pathString, directory.basename], - workingDirectory: directory.parentDirectory + workingDirectory: directory.parentDirectory.underlying ) -#else + #else let process = TSCBasic.Process( arguments: ["zip", "-r", destinationPath.pathString, directory.basename], - workingDirectory: directory.parentDirectory + workingDirectory: directory.parentDirectory.underlying ) -#endif + #endif guard let registrationKey = self.cancellator.register(process) else { throw CancellationError.failedToRegisterProcess(process) @@ -116,14 +119,14 @@ public struct ZipArchiver: Archiver, Cancellable { public func validate(path: AbsolutePath, completion: @escaping (Result) -> Void) { do { guard self.fileSystem.exists(path) else { - throw FileSystemError(.noEntry, path) + throw FileSystemError(.noEntry, path.underlying) } -#if os(Windows) + #if os(Windows) let process = TSCBasic.Process(arguments: ["tar.exe", "tf", path.pathString]) -#else + #else let process = TSCBasic.Process(arguments: ["unzip", "-t", path.pathString]) -#endif + #endif guard let registrationKey = self.cancellator.register(process) else { throw CancellationError.failedToRegisterProcess(process) } diff --git a/Sources/Basics/AuthorizationProvider.swift b/Sources/Basics/AuthorizationProvider.swift index 3da310605fa..e44b7fbe2f2 100644 --- a/Sources/Basics/AuthorizationProvider.swift +++ b/Sources/Basics/AuthorizationProvider.swift @@ -16,8 +16,6 @@ import struct Foundation.URL import Security #endif -import TSCBasic - public protocol AuthorizationProvider { @Sendable func authentication(for url: URL) -> (user: String, password: String)? diff --git a/Sources/Basics/ByteString+Extensions.swift b/Sources/Basics/ByteString+Extensions.swift index 18283e53c56..9d2d1226cbb 100644 --- a/Sources/Basics/ByteString+Extensions.swift +++ b/Sources/Basics/ByteString+Extensions.swift @@ -10,7 +10,8 @@ // //===----------------------------------------------------------------------===// -import TSCBasic +import struct TSCBasic.ByteString +import struct TSCBasic.SHA256 extension ByteString { /// A lowercase, hexadecimal representation of the SHA256 hash @@ -20,6 +21,6 @@ extension ByteString { /// Secure Hashing Algorithm 2 (SHA-2) hashing with a 256-bit digest, when available, /// falling back on a native implementation in Swift provided by TSCBasic. public var sha256Checksum: String { - return SHA256().hash(self).hexadecimalRepresentation + SHA256().hash(self).hexadecimalRepresentation } } diff --git a/Sources/Basics/CMakeLists.txt b/Sources/Basics/CMakeLists.txt index 29894453712..df992624da1 100644 --- a/Sources/Basics/CMakeLists.txt +++ b/Sources/Basics/CMakeLists.txt @@ -25,9 +25,11 @@ add_library(Basics DispatchTimeInterval+Extensions.swift EnvironmentVariables.swift Errors.swift + FileSystem/AbsolutePath.swift FileSystem/FileSystem+Extensions.swift - FileSystem/Path+Extensions.swift + FileSystem/RelativePath.swift FileSystem/TemporaryFile.swift + FileSystem/TSCAdapters.swift FileSystem/VFSOverlay.swift HTTPClient/HTTPClient.swift HTTPClient/HTTPClientConfiguration.swift @@ -51,7 +53,7 @@ add_library(Basics String+Extensions.swift SwiftVersion.swift SQLiteBackedCache.swift - Triple.swift + Triple.swift Version+Extensions.swift WritableByteStream+Extensions.swift) target_link_libraries(Basics PUBLIC diff --git a/Sources/Basics/Cancellator.swift b/Sources/Basics/Cancellator.swift index e0be24e55de..f1ead5c0316 100644 --- a/Sources/Basics/Cancellator.swift +++ b/Sources/Basics/Cancellator.swift @@ -12,8 +12,8 @@ import Dispatch import Foundation -import TSCBasic - +import class TSCBasic.Process +import class TSCBasic.Thread #if canImport(WinSDK) import WinSDK #endif diff --git a/Sources/Basics/Concurrency/SendableBox.swift b/Sources/Basics/Concurrency/SendableBox.swift index bf983e982d0..0af62417dbb 100644 --- a/Sources/Basics/Concurrency/SendableBox.swift +++ b/Sources/Basics/Concurrency/SendableBox.swift @@ -12,7 +12,7 @@ import struct Foundation.Date -/// A `Sendable` storage that allows access from concurrently running tasks in +/// A `Sendable` storage that allows access from concurrently running tasks in /// an `async` closure. This type serves as a replacement for `ThreadSafeBox` /// implemented with Swift Concurrency primitives. public actor SendableBox { diff --git a/Sources/Basics/Concurrency/ThreadSafeBox.swift b/Sources/Basics/Concurrency/ThreadSafeBox.swift index 9b0c0917736..75b9a1542a9 100644 --- a/Sources/Basics/Concurrency/ThreadSafeBox.swift +++ b/Sources/Basics/Concurrency/ThreadSafeBox.swift @@ -111,9 +111,9 @@ extension ThreadSafeBox where Value == String { public func append(_ value: String) { self.mutate { existingValue in if let existingValue { - return existingValue + value + return existingValue + value } else { - return value + return value } } } diff --git a/Sources/Basics/Dictionary+Extensions.swift b/Sources/Basics/Dictionary+Extensions.swift index 05dcd93271a..fdc6046999b 100644 --- a/Sources/Basics/Dictionary+Extensions.swift +++ b/Sources/Basics/Dictionary+Extensions.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import TSCBasic +import OrderedCollections extension Dictionary { @inlinable @@ -37,12 +37,14 @@ extension Dictionary { } } -extension OrderedDictionary { - public subscript(key: Key, `default` `default`: Value) -> Value { - set { - self[key] = newValue - } get { - self[key] ?? `default` - } - } -} +/* + extension OrderedDictionary { + public subscript(key: Key, `default` `default`: Value) -> Value { + set { + self[key] = newValue + } get { + self[key] ?? `default` + } + } + } + */ diff --git a/Sources/Basics/DispatchTimeInterval+Extensions.swift b/Sources/Basics/DispatchTimeInterval+Extensions.swift index e5eb85f4cda..2f37d472994 100644 --- a/Sources/Basics/DispatchTimeInterval+Extensions.swift +++ b/Sources/Basics/DispatchTimeInterval+Extensions.swift @@ -79,17 +79,17 @@ extension DispatchTimeInterval { case .seconds(let value): return "\(value)s" case .milliseconds(let value): - return String(format: "%.2f", Double(value)/Double(1000)) + "s" + return String(format: "%.2f", Double(value) / Double(1000)) + "s" case .microseconds(let value): - return String(format: "%.2f", Double(value)/Double(1_000_000)) + "s" + return String(format: "%.2f", Double(value) / Double(1_000_000)) + "s" case .nanoseconds(let value): - return String(format: "%.2f", Double(value)/Double(1_000_000_000)) + "s" + return String(format: "%.2f", Double(value) / Double(1_000_000_000)) + "s" case .never: return "n/a" -#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) + #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) @unknown default: return "n/a" -#endif + #endif } } } @@ -100,9 +100,8 @@ extension DispatchTime { public func distance(to: DispatchTime) -> DispatchTimeInterval { let final = to.uptimeNanoseconds let point = self.uptimeNanoseconds - let duration: Int64 = Int64(bitPattern: final.subtractingReportingOverflow(point).partialValue) + let duration = Int64(bitPattern: final.subtractingReportingOverflow(point).partialValue) return .nanoseconds(duration >= Int.max ? Int.max : Int(duration)) } } #endif - diff --git a/Sources/Basics/EnvironmentVariables.swift b/Sources/Basics/EnvironmentVariables.swift index 6e018efa17c..bb24179f4b8 100644 --- a/Sources/Basics/EnvironmentVariables.swift +++ b/Sources/Basics/EnvironmentVariables.swift @@ -10,19 +10,17 @@ // //===----------------------------------------------------------------------===// -import TSCBasic import Foundation public typealias EnvironmentVariables = [String: String] extension EnvironmentVariables { - public static func empty() -> EnvironmentVariables { - return [:] + [:] } public static func process() -> EnvironmentVariables { - return ProcessInfo.processInfo.environment + ProcessInfo.processInfo.environment } public mutating func prependPath(_ key: String, value: String) { @@ -52,11 +50,11 @@ extension EnvironmentVariables { /// `PATH` variable in the process's environment (`Path` under Windows). public var path: String? { -#if os(Windows) + #if os(Windows) let pathArg = "Path" -#else + #else let pathArg = "PATH" -#endif + #endif return self[pathArg] } } diff --git a/Sources/Basics/FileSystem/AbsolutePath.swift b/Sources/Basics/FileSystem/AbsolutePath.swift new file mode 100644 index 00000000000..32e8ba1eb01 --- /dev/null +++ b/Sources/Basics/FileSystem/AbsolutePath.swift @@ -0,0 +1,332 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift open source project +// +// Copyright (c) 2023 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See http://swift.org/LICENSE.txt for license information +// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +import struct Foundation.URL +import struct TSCBasic.AbsolutePath + +// public for transition +public typealias TSCAbsolutePath = TSCBasic.AbsolutePath + +/// Represents an absolute file system path, independently of what (or whether +/// anything at all) exists at that path in the file system at any given time. +/// An absolute path always starts with a `/` character, and holds a normalized +/// string representation. This normalization is strictly syntactic, and does +/// not access the file system in any way. +/// +/// The absolute path string is normalized by: +/// - Collapsing `..` path components +/// - Removing `.` path components +/// - Removing any trailing path separator +/// - Removing any redundant path separators +/// +/// This string manipulation may change the meaning of a path if any of the +/// path components are symbolic links on disk. However, the file system is +/// never accessed in any way when initializing an AbsolutePath. +/// +/// Note that `~` (home directory resolution) is *not* done as part of path +/// normalization, because it is normally the responsibility of the shell and +/// not the program being invoked (e.g. when invoking `cd ~`, it is the shell +/// that evaluates the tilde; the `cd` command receives an absolute path). +public struct AbsolutePath: Hashable, Sendable { + /// Root directory (whose string representation is just a path separator). + public static let root = Self(TSCAbsolutePath.root) + + internal let underlying: TSCAbsolutePath + + // public for transition + public init(_ underlying: TSCAbsolutePath) { + self.underlying = underlying + } + + /// Initializes the AbsolutePath from `absStr`, which must be an absolute + /// path (i.e. it must begin with a path separator; this initializer does + /// not interpret leading `~` characters as home directory specifiers). + /// The input string will be normalized if needed, as described in the + /// documentation for AbsolutePath. + public init(validating pathString: String) throws { + self.underlying = try .init(validating: pathString) + } + + /// Initializes an AbsolutePath from a string that may be either absolute + /// or relative; if relative, `basePath` is used as the anchor; if absolute, + /// it is used as is, and in this case `basePath` is ignored. + public init(validating pathString: String, relativeTo basePath: AbsolutePath) throws { + self.underlying = try .init(validating: pathString, relativeTo: basePath.underlying) + } + + /// Initializes the AbsolutePath by concatenating a relative path to an + /// existing absolute path, and renormalizing if necessary. + public init(_ absolutePath: AbsolutePath, _ relativeTo: RelativePath) { + self.underlying = .init(absolutePath.underlying, relativeTo.underlying) + } + + /// Convenience initializer that appends a string to a relative path. + public init(_ absolutePath: AbsolutePath, validating relativePathString: String) throws { + try self.init(absolutePath, RelativePath(validating: relativePathString)) + } + + /// Directory component. An absolute path always has a non-empty directory + /// component (the directory component of the root path is the root itself). + public var dirname: String { + self.underlying.dirname + } + + /// Last path component (including the suffix, if any). it is never empty. + public var basename: String { + self.underlying.basename + } + + /// Returns the basename without the extension. + public var basenameWithoutExt: String { + self.underlying.basenameWithoutExt + } + + /// Suffix (including leading `.` character) if any. Note that a basename + /// that starts with a `.` character is not considered a suffix, nor is a + /// trailing `.` character. + public var suffix: String? { + self.underlying.suffix + } + + /// Extension of the give path's basename. This follow same rules as + /// suffix except that it doesn't include leading `.` character. + public var `extension`: String? { + self.underlying.extension + } + + /// Absolute path of parent directory. This always returns a path, because + /// every directory has a parent (the parent directory of the root directory + /// is considered to be the root directory itself). + public var parentDirectory: AbsolutePath { + Self(self.underlying.parentDirectory) + } + + /// True if the path is the root directory. + public var isRoot: Bool { + self.underlying.isRoot + } + + /// NOTE: We will most likely want to add other `appending()` methods, such + /// as `appending(suffix:)`, and also perhaps `replacing()` methods, + /// such as `replacing(suffix:)` or `replacing(basename:)` for some + /// of the more common path operations. + + /// NOTE: We may want to consider adding operators such as `+` for appending + /// a path component. + + /// NOTE: We will want to add a method to return the lowest common ancestor + /// path. + + /// Normalized string representation (the normalization rules are described + /// in the documentation of the initializer). This string is never empty. + public var pathString: String { + self.underlying.pathString + } +} + +extension AbsolutePath { + /// Returns an array of strings that make up the path components of the + /// absolute path. This is the same sequence of strings as the basenames + /// of each successive path component, starting from the root. Therefore + /// the first path component of an absolute path is always `/`. + public var components: [String] { + self.underlying.components + } + + /// Returns the absolute path with the relative path applied. + public func appending(_ relativePath: RelativePath) -> AbsolutePath { + Self(self.underlying.appending(relativePath.underlying)) + } + + /// Returns the absolute path with an additional literal component appended. + /// + /// This method accepts pseudo-path like '.' or '..', but should not contain "/". + public func appending(component: String) -> AbsolutePath { + Self(self.underlying.appending(component: component)) + } + + /// Returns the absolute path with additional literal components appended. + /// + /// This method should only be used in cases where the input is guaranteed + /// to be a valid path component (i.e., it cannot be empty, contain a path + /// separator, or be a pseudo-path like '.' or '..'). + public func appending(components: [String]) -> AbsolutePath { + Self(self.underlying.appending(components: components)) + } + + /// Returns the absolute path with additional literal components appended. + /// + /// This method should only be used in cases where the input is guaranteed + /// to be a valid path component (i.e., it cannot be empty, contain a path + /// separator, or be a pseudo-path like '.' or '..'). + public func appending(components: String...) -> AbsolutePath { + Self(self.underlying.appending(components: components)) + } + + /// Returns the absolute path with additional literal components appended. + /// + /// This method should only be used in cases where the input is guaranteed + /// to be a valid path component (i.e., it cannot be empty, contain a path + /// separator, or be a pseudo-path like '.' or '..'). + public func appending(_ component: String) -> AbsolutePath { + self.appending(component: component) + } + + /// Returns the absolute path with additional literal components appended. + /// + /// This method should only be used in cases where the input is guaranteed + /// to be a valid path component (i.e., it cannot be empty, contain a path + /// separator, or be a pseudo-path like '.' or '..'). + public func appending(_ components: String...) -> AbsolutePath { + self.appending(components: components) + } + + /// Returns the absolute path with additional extension appended. + /// + public func appending(extension: String) -> AbsolutePath { + guard !self.isRoot else { return self } + let `extension` = `extension`.spm_dropPrefix(".") + return self.parentDirectory.appending("\(basename).\(`extension`)") + } +} + +extension AbsolutePath { + /// Returns a relative path that, when concatenated to `base`, yields the + /// callee path itself. If `base` is not an ancestor of the callee, the + /// returned path will begin with one or more `..` path components. + /// + /// Because both paths are absolute, they always have a common ancestor + /// (the root path, if nothing else). Therefore, any path can be made + /// relative to any other path by using a sufficient number of `..` path + /// components. + /// + /// This method is strictly syntactic and does not access the file system + /// in any way. Therefore, it does not take symbolic links into account. + public func relative(to base: AbsolutePath) -> RelativePath { + RelativePath(self.underlying.relative(to: base.underlying)) + } + + /// Returns true if the path is an ancestor of the given path. + /// + /// This method is strictly syntactic and does not access the file system + /// in any way. + public func isAncestor(of descendant: AbsolutePath) -> Bool { + self.underlying.isAncestor(of: descendant.underlying) + } + + /// Returns true if the path is an ancestor of or equal to the given path. + /// + /// This method is strictly syntactic and does not access the file system + /// in any way. + public func isAncestorOfOrEqual(to descendant: AbsolutePath) -> Bool { + self.underlying.isAncestorOfOrEqual(to: descendant.underlying) + } + + /// Returns true if the path is a descendant of the given path. + /// + /// This method is strictly syntactic and does not access the file system + /// in any way. + public func isDescendant(of ancestor: AbsolutePath) -> Bool { + self.underlying.isDescendant(of: ancestor.underlying) + } + + /// Returns true if the path is a descendant of or equal to the given path. + /// + /// This method is strictly syntactic and does not access the file system + /// in any way. + public func isDescendantOfOrEqual(to ancestor: AbsolutePath) -> Bool { + self.underlying.isDescendantOfOrEqual(to: ancestor.underlying) + } +} + +extension AbsolutePath { + /// Unlike ``AbsolutePath//extension``, this property returns all characters after the first `.` character in a + /// filename. If no dot character is present in the filename or first dot is the last character, `nil` is returned. + public var allExtensions: [String]? { + guard let firstDot = self.basename.firstIndex(of: ".") else { + return nil + } + + var extensions = String(self.basename[firstDot ..< self.basename.endIndex]) + + guard extensions.count > 1 else { + return nil + } + + extensions.removeFirst() + + return extensions.split(separator: ".").map(String.init) + } + + /// Returns the basename dropping any possible extension. + public func basenameWithoutAnyExtension() -> String { + var basename = self.basename + if let index = basename.firstIndex(of: ".") { + basename.removeSubrange(index ..< basename.endIndex) + } + return String(basename) + } +} + +extension AbsolutePath: Codable { + public func encode(to encoder: Encoder) throws { + try self.underlying.encode(to: encoder) + } + + public init(from decoder: Decoder) throws { + try self = .init(TSCAbsolutePath(from: decoder)) + } +} + +// Make absolute paths Comparable. +extension AbsolutePath: Comparable { + public static func < (lhs: AbsolutePath, rhs: AbsolutePath) -> Bool { + lhs.underlying < rhs.underlying + } +} + +/// Make absolute paths CustomStringConvertible and CustomDebugStringConvertible. +extension AbsolutePath: CustomStringConvertible, CustomDebugStringConvertible { + public var description: String { + self.underlying.description + } + + public var debugDescription: String { + self.underlying.debugDescription + } +} + +extension AbsolutePath { + public var asURL: Foundation.URL { + self.underlying.asURL + } +} + +extension AbsolutePath { + /// Returns a path suitable for display to the user (if possible, it is made + /// to be relative to the current working directory). + public func prettyPath(cwd: AbsolutePath? = localFileSystem.currentWorkingDirectory) -> String { + self.underlying.prettyPath(cwd: cwd?.underlying) + } +} + +extension AbsolutePath { + public func escapedPathString() -> String { + self.pathString.replacingOccurrences(of: "\\", with: "\\\\") + } +} + +extension TSCAbsolutePath { + public init(_ path: AbsolutePath) { + self = path.underlying + } +} diff --git a/Sources/Basics/FileSystem/FileSystem+Extensions.swift b/Sources/Basics/FileSystem/FileSystem+Extensions.swift index d669a14029d..af926941b3b 100644 --- a/Sources/Basics/FileSystem/FileSystem+Extensions.swift +++ b/Sources/Basics/FileSystem/FileSystem+Extensions.swift @@ -10,11 +10,194 @@ // //===----------------------------------------------------------------------===// -import class Foundation.FileManager import struct Foundation.Data +import class Foundation.FileManager import struct Foundation.UUID import SystemPackage -import TSCBasic + +import struct TSCBasic.ByteString +import struct TSCBasic.FileInfo +import class TSCBasic.FileLock +import enum TSCBasic.FileMode +import protocol TSCBasic.FileSystem +import var TSCBasic.localFileSystem +import protocol TSCBasic.WritableByteStream + +public typealias FileSystem = TSCBasic.FileSystem +public var localFileSystem = TSCBasic.localFileSystem + +// MARK: - Custom path + +extension FileSystem { + /// Check whether the given path exists and is accessible. + public func exists(_ path: AbsolutePath, followSymlink: Bool) -> Bool { + self.exists(path.underlying, followSymlink: followSymlink) + } + + /// exists override with default value. + public func exists(_ path: AbsolutePath) -> Bool { + self.exists(path.underlying) + } + + /// Check whether the given path is accessible and a directory. + public func isDirectory(_ path: AbsolutePath) -> Bool { + self.isDirectory(path.underlying) + } + + /// Check whether the given path is accessible and a file. + public func isFile(_ path: AbsolutePath) -> Bool { + self.isFile(path.underlying) + } + + /// Check whether the given path is an accessible and executable file. + public func isExecutableFile(_ path: AbsolutePath) -> Bool { + self.isExecutableFile(path.underlying) + } + + /// Check whether the given path is accessible and is a symbolic link. + public func isSymlink(_ path: AbsolutePath) -> Bool { + self.isSymlink(path.underlying) + } + + /// Check whether the given path is accessible and readable. + public func isReadable(_ path: AbsolutePath) -> Bool { + self.isReadable(path.underlying) + } + + /// Check whether the given path is accessible and writable. + public func isWritable(_ path: AbsolutePath) -> Bool { + self.isWritable(path.underlying) + } + + /// Returns `true` if a given path has a quarantine attribute applied if when file system supports this attribute. + /// Returns `false` if such attribute is not applied or it isn't supported. + public func hasQuarantineAttribute(_ path: AbsolutePath) -> Bool { + self.hasQuarantineAttribute(path.underlying) + } + + /// Get the contents of the given directory, in an undefined order. + public func getDirectoryContents(_ path: AbsolutePath) throws -> [String] { + try self.getDirectoryContents(path.underlying) + } + + /// Get the current working directory (similar to `getcwd(3)`), which can be + /// different for different (virtualized) implementations of a FileSystem. + /// The current working directory can be empty if e.g. the directory became + /// unavailable while the current process was still working in it. + /// This follows the POSIX `getcwd(3)` semantics. + public var currentWorkingDirectory: AbsolutePath? { + self.currentWorkingDirectory.flatMap { AbsolutePath($0) } + } + + /// Change the current working directory. + /// - Parameters: + /// - path: The path to the directory to change the current working directory to. + public func changeCurrentWorkingDirectory(to path: AbsolutePath) throws { + try self.changeCurrentWorkingDirectory(to: path.underlying) + } + + /// Get the home directory of current user + public var homeDirectory: AbsolutePath { + get throws { + try AbsolutePath(self.homeDirectory) + } + } + + /// Get the caches directory of current user + public var cachesDirectory: AbsolutePath? { + self.cachesDirectory.flatMap { AbsolutePath($0) } + } + + /// Get the temp directory + public var tempDirectory: AbsolutePath { + get throws { + try AbsolutePath(self.tempDirectory) + } + } + + /// Create the given directory. + public func createDirectory(_ path: AbsolutePath) throws { + try self.createDirectory(path.underlying) + } + + /// Create the given directory. + /// + /// - recursive: If true, create missing parent directories if possible. + public func createDirectory(_ path: AbsolutePath, recursive: Bool) throws { + try self.createDirectory(path.underlying, recursive: recursive) + } + + /// Creates a symbolic link of the source path at the target path + /// - Parameters: + /// - path: The path at which to create the link. + /// - destination: The path to which the link points to. + /// - relative: If `relative` is true, the symlink contents will be a relative path, otherwise it will be absolute. + public func createSymbolicLink(_ path: AbsolutePath, pointingAt destination: AbsolutePath, relative: Bool) throws { + try self.createSymbolicLink(path.underlying, pointingAt: destination.underlying, relative: relative) + } + + /// Get the contents of a file. + /// + /// - Returns: The file contents as bytes, or nil if missing. + public func readFileContents(_ path: AbsolutePath) throws -> ByteString { + try self.readFileContents(path.underlying) + } + + /// Write the contents of a file. + public func writeFileContents(_ path: AbsolutePath, bytes: ByteString) throws { + try self.writeFileContents(path.underlying, bytes: bytes) + } + + /// Write the contents of a file. + public func writeFileContents(_ path: AbsolutePath, bytes: ByteString, atomically: Bool) throws { + try self.writeFileContents(path.underlying, bytes: bytes, atomically: atomically) + } + + /// Write to a file from a stream producer. + public func writeFileContents(_ path: AbsolutePath, body: (WritableByteStream) -> Void) throws { + try self.writeFileContents(path.underlying, body: body) + } + + /// Recursively deletes the file system entity at `path`. + /// + /// If there is no file system entity at `path`, this function does nothing (in particular, this is not considered + /// to be an error). + public func removeFileTree(_ path: AbsolutePath) throws { + try self.removeFileTree(path.underlying) + } + + /// Change file mode. + public func chmod(_ mode: FileMode, path: AbsolutePath, options: Set) throws { + try self.chmod(mode, path: path.underlying, options: options) + } + + // Change file mode. + public func chmod(_ mode: FileMode, path: AbsolutePath) throws { + try self.chmod(mode, path: path.underlying) + } + + /// Returns the file info of the given path. + /// + /// The method throws if the underlying stat call fails. + public func getFileInfo(_ path: AbsolutePath) throws -> FileInfo { + try self.getFileInfo(path.underlying) + } + + /// Copy a file or directory. + public func copy(from source: AbsolutePath, to destination: AbsolutePath) throws { + try self.copy(from: source.underlying, to: destination.underlying) + } + + /// Move a file or directory. + public func move(from source: AbsolutePath, to destination: AbsolutePath) throws { + try self.move(from: source.underlying, to: destination.underlying) + } + + /// Execute the given block while holding the lock. + public func withLock(on path: AbsolutePath, type: FileLock.LockType, _ body: () throws -> T) throws -> T { + try self.withLock(on: path.underlying, type: type, body) + } +} // MARK: - user level @@ -22,13 +205,14 @@ extension FileSystem { /// SwiftPM directory under user's home directory (~/.swiftpm) public var dotSwiftPM: AbsolutePath { get throws { - return try self.homeDirectory.appending(".swiftpm") + try self.homeDirectory.appending(".swiftpm") } } - fileprivate var idiomaticSwiftPMDirectory: AbsolutePath? { + private var idiomaticSwiftPMDirectory: AbsolutePath? { get throws { - return try FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first.flatMap { try AbsolutePath(validating: $0.path) }?.appending("org.swift.swiftpm") + try FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first + .flatMap { try AbsolutePath(validating: $0.path) }?.appending("org.swift.swiftpm") } } } @@ -52,9 +236,9 @@ extension FileSystem { } } - fileprivate var dotSwiftPMCachesDirectory: AbsolutePath { + private var dotSwiftPMCachesDirectory: AbsolutePath { get throws { - return try self.dotSwiftPM.appending("cache") + try self.dotSwiftPM.appending("cache") } } } @@ -74,7 +258,11 @@ extension FileSystem { // locking ~/.swiftpm to protect from concurrent access try self.withLock(on: self.dotSwiftPM, type: .exclusive) { if !self.exists(try self.dotSwiftPMCachesDirectory, followSymlink: false) { - try self.createSymbolicLink(dotSwiftPMCachesDirectory, pointingAt: idiomaticCacheDirectory, relative: false) + try self.createSymbolicLink( + dotSwiftPMCachesDirectory, + pointingAt: idiomaticCacheDirectory, + relative: false + ) } } return idiomaticCacheDirectory @@ -95,15 +283,17 @@ extension FileSystem { } } - fileprivate var dotSwiftPMConfigurationDirectory: AbsolutePath { + private var dotSwiftPMConfigurationDirectory: AbsolutePath { get throws { - return try self.dotSwiftPM.appending("configuration") + try self.dotSwiftPM.appending("configuration") } } } extension FileSystem { - public func getOrCreateSwiftPMConfigurationDirectory(warningHandler: @escaping (String) -> Void) throws -> AbsolutePath { + public func getOrCreateSwiftPMConfigurationDirectory(warningHandler: @escaping (String) -> Void) throws + -> AbsolutePath + { let idiomaticConfigurationDirectory = try self.swiftPMConfigurationDirectory // temporary 5.6, remove on next version: transition from previous configuration location @@ -121,7 +311,9 @@ extension FileSystem { let srcContents = try? self.readFileContents(file) let dstContents = try? self.readFileContents(destination) if srcContents != dstContents { - warningHandler("Usage of \(file) has been deprecated. Please delete it and use the new \(destination) instead.") + warningHandler( + "Usage of \(file) has been deprecated. Please delete it and use the new \(destination) instead." + ) } } } @@ -134,19 +326,25 @@ extension FileSystem { let oldConfigDirectory = idiomaticConfigurationDirectory.parentDirectory if self.exists(oldConfigDirectory, followSymlink: false) && self.isDirectory(oldConfigDirectory) { let configurationFiles = try self.getDirectoryContents(oldConfigDirectory) - .map{ oldConfigDirectory.appending(component: $0) } - .filter{ self.isFile($0) && !self.isSymlink($0) && $0.extension != "lock" && ((try? self.readFileContents($0)) ?? []).count > 0 } + .map { oldConfigDirectory.appending(component: $0) } + .filter { + self.isFile($0) && !self.isSymlink($0) && $0 + .extension != "lock" && ((try? self.readFileContents($0)) ?? []).count > 0 + } try handleExistingFiles(configurationFiles) } - // in the case where ~/.swiftpm/configuration is the idiomatic location (eg on Linux) + // in the case where ~/.swiftpm/configuration is the idiomatic location (eg on Linux) } else { // copy the configuration files from old location (~/.swiftpm/config) to new one (~/.swiftpm/configuration) // but leave them there for backwards compatibility (eg older toolchain) let oldConfigDirectory = try self.dotSwiftPM.appending("config") if self.exists(oldConfigDirectory, followSymlink: false) && self.isDirectory(oldConfigDirectory) { let configurationFiles = try self.getDirectoryContents(oldConfigDirectory) - .map{ oldConfigDirectory.appending(component: $0) } - .filter{ self.isFile($0) && !self.isSymlink($0) && $0.extension != "lock" && ((try? self.readFileContents($0)) ?? []).count > 0 } + .map { oldConfigDirectory.appending(component: $0) } + .filter { + self.isFile($0) && !self.isSymlink($0) && $0 + .extension != "lock" && ((try? self.readFileContents($0)) ?? []).count > 0 + } try handleExistingFiles(configurationFiles) } } @@ -164,7 +362,11 @@ extension FileSystem { // locking ~/.swiftpm to protect from concurrent access try self.withLock(on: self.dotSwiftPM, type: .exclusive) { if !self.exists(try self.dotSwiftPMConfigurationDirectory, followSymlink: false) { - try self.createSymbolicLink(dotSwiftPMConfigurationDirectory, pointingAt: idiomaticConfigurationDirectory, relative: false) + try self.createSymbolicLink( + dotSwiftPMConfigurationDirectory, + pointingAt: idiomaticConfigurationDirectory, + relative: false + ) } } @@ -186,9 +388,9 @@ extension FileSystem { } } - fileprivate var dotSwiftPMSecurityDirectory: AbsolutePath { + private var dotSwiftPMSecurityDirectory: AbsolutePath { get throws { - return try self.dotSwiftPM.appending("security") + try self.dotSwiftPM.appending("security") } } } @@ -200,7 +402,8 @@ extension FileSystem { // temporary 5.6, remove on next version: transition from ~/.swiftpm/security to idiomatic location + symbolic link if try idiomaticSecurityDirectory != self.dotSwiftPMSecurityDirectory && self.exists(try self.dotSwiftPMSecurityDirectory) && - self.isDirectory(try self.dotSwiftPMSecurityDirectory) { + self.isDirectory(try self.dotSwiftPMSecurityDirectory) + { try self.removeFileTree(self.dotSwiftPMSecurityDirectory) } // ~temporary 5.6 migration @@ -217,7 +420,11 @@ extension FileSystem { // locking ~/.swiftpm to protect from concurrent access try self.withLock(on: self.dotSwiftPM, type: .exclusive) { if !self.exists(try self.dotSwiftPMSecurityDirectory, followSymlink: false) { - try self.createSymbolicLink(dotSwiftPMSecurityDirectory, pointingAt: idiomaticSecurityDirectory, relative: false) + try self.createSymbolicLink( + dotSwiftPMSecurityDirectory, + pointingAt: idiomaticSecurityDirectory, + relative: false + ) } } return idiomaticSecurityDirectory @@ -240,9 +447,9 @@ extension FileSystem { } } - fileprivate var dotSwiftPMSwiftSDKsDirectory: AbsolutePath { + private var dotSwiftPMSwiftSDKsDirectory: AbsolutePath { get throws { - return try dotSwiftPM.appending(component: swiftSDKsDirectoryName) + try dotSwiftPM.appending(component: swiftSDKsDirectoryName) } } @@ -287,10 +494,12 @@ extension FileSystem { // MARK: - Utilities extension FileSystem { + @_disfavoredOverload public func readFileContents(_ path: AbsolutePath) throws -> Data { try Data(self.readFileContents(path).contents) } + @_disfavoredOverload public func readFileContents(_ path: AbsolutePath) throws -> String { try String(decoding: self.readFileContents(path), as: UTF8.self) } @@ -342,8 +551,8 @@ extension FileSystem { extension FileSystem { public func stripFirstLevel(of path: AbsolutePath) throws { let topLevelDirectories = try self.getDirectoryContents(path) - .map{ path.appending(component: $0) } - .filter{ self.isDirectory($0) } + .map { path.appending(component: $0) } + .filter { self.isDirectory($0) } guard topLevelDirectories.count == 1, let rootDirectory = topLevelDirectories.first else { throw StringError("stripFirstLevel requires single top level directory") diff --git a/Sources/Basics/FileSystem/Path+Extensions.swift b/Sources/Basics/FileSystem/Path+Extensions.swift deleted file mode 100644 index 98d802e325f..00000000000 --- a/Sources/Basics/FileSystem/Path+Extensions.swift +++ /dev/null @@ -1,59 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift open source project -// -// Copyright (c) 2023 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See http://swift.org/LICENSE.txt for license information -// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -import struct TSCBasic.AbsolutePath - -extension AbsolutePath { - public func appending(_ component: String) -> AbsolutePath { - self.appending(component: component) - } - - public func appending(_ components: String...) -> AbsolutePath { - self.appending(components: components) - } - - public func appending(extension: String) -> AbsolutePath { - guard !self.isRoot else { return self } - let `extension` = `extension`.spm_dropPrefix(".") - return self.parentDirectory.appending("\(basename).\(`extension`)") - } - - public func basenameWithoutAnyExtension() -> String { - var basename = self.basename - if let index = basename.firstIndex(of: ".") { - basename.removeSubrange(index ..< basename.endIndex) - } - return String(basename) - } - - public func escapedPathString() -> String { - return self.pathString.replacingOccurrences(of: "\\", with: "\\\\") - } - - /// Unlike ``AbsolutePath//extension``, this property returns all characters after the first `.` character in a - /// filename. If no dot character is present in the filename or first dot is the last character, `nil` is returned. - var allExtensions: [String]? { - guard let firstDot = basename.firstIndex(of: ".") else { - return nil - } - - var extensions = String(basename[firstDot ..< basename.endIndex]) - - guard extensions.count > 1 else { - return nil - } - - extensions.removeFirst() - - return extensions.split(separator: ".").map(String.init) - } -} diff --git a/Sources/Basics/FileSystem/RelativePath.swift b/Sources/Basics/FileSystem/RelativePath.swift new file mode 100644 index 00000000000..38af45df6cd --- /dev/null +++ b/Sources/Basics/FileSystem/RelativePath.swift @@ -0,0 +1,166 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift open source project +// +// Copyright (c) 2023 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See http://swift.org/LICENSE.txt for license information +// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +import struct TSCBasic.RelativePath + +// public for transition +public typealias TSCRelativePath = TSCBasic.RelativePath + +/// Represents a relative file system path. A relative path never starts with +/// a `/` character, and holds a normalized string representation. As with +/// AbsolutePath, the normalization is strictly syntactic, and does not access +/// the file system in any way. +/// +/// The relative path string is normalized by: +/// - Collapsing `..` path components that aren't at the beginning +/// - Removing extraneous `.` path components +/// - Removing any trailing path separator +/// - Removing any redundant path separators +/// - Replacing a completely empty path with a `.` +/// +/// This string manipulation may change the meaning of a path if any of the +/// path components are symbolic links on disk. However, the file system is +/// never accessed in any way when initializing a RelativePath. +public struct RelativePath: Hashable, Sendable { + let underlying: TSCBasic.RelativePath + + // public for transition + public init(_ underlying: TSCBasic.RelativePath) { + self.underlying = underlying + } + + /// Convenience initializer that verifies that the path is relative. + public init(validating pathString: String) throws { + self.underlying = try .init(validating: pathString) + } + + /// Directory component. For a relative path without any path separators, + /// this is the `.` string instead of the empty string. + public var dirname: String { + self.underlying.dirname + } + + /// Last path component (including the suffix, if any). It is never empty. + public var basename: String { + self.underlying.basename + } + + /// Returns the basename without the extension. + public var basenameWithoutExt: String { + self.underlying.basenameWithoutExt + } + + /// Suffix (including leading `.` character) if any. Note that a basename + /// that starts with a `.` character is not considered a suffix, nor is a + /// trailing `.` character. + public var suffix: String? { + self.underlying.suffix + } + + /// Extension of the give path's basename. This follow same rules as + /// suffix except that it doesn't include leading `.` character. + public var `extension`: String? { + self.underlying.extension + } + + /// Normalized string representation (the normalization rules are described + /// in the documentation of the initializer). This string is never empty. + public var pathString: String { + self.underlying.pathString + } +} + +extension RelativePath { + /// Returns an array of strings that make up the path components of the + /// relative path. This is the same sequence of strings as the basenames + /// of each successive path component. Therefore the returned array of + /// path components is never empty; even an empty path has a single path + /// component: the `.` string. + public var components: [String] { + self.underlying.components + } + + /// Returns the relative path with the given relative path applied. + public func appending(_ subpath: RelativePath) -> RelativePath { + Self(self.underlying.appending(subpath.underlying)) + } + + /// Returns the relative path with an additional literal component appended. + /// + /// This method accepts pseudo-path like '.' or '..', but should not contain "/". + public func appending(component: String) -> RelativePath { + Self(self.underlying.appending(component: component)) + } + + /// Returns the relative path with additional literal components appended. + /// + /// This method should only be used in cases where the input is guaranteed + /// to be a valid path component (i.e., it cannot be empty, contain a path + /// separator, or be a pseudo-path like '.' or '..'). + public func appending(components: [String]) -> RelativePath { + Self(self.underlying.appending(components: components)) + } + + /// Returns the relative path with additional literal components appended. + /// + /// This method should only be used in cases where the input is guaranteed + /// to be a valid path component (i.e., it cannot be empty, contain a path + /// separator, or be a pseudo-path like '.' or '..'). + public func appending(components: String...) -> RelativePath { + Self(self.underlying.appending(components: components)) + } + + /// Returns the relative path with additional literal components appended. + /// + /// This method should only be used in cases where the input is guaranteed + /// to be a valid path component (i.e., it cannot be empty, contain a path + /// separator, or be a pseudo-path like '.' or '..'). + public func appending(_ component: String) -> RelativePath { + self.appending(component: component) + } + + /// Returns the relative path with additional literal components appended. + /// + /// This method should only be used in cases where the input is guaranteed + /// to be a valid path component (i.e., it cannot be empty, contain a path + /// separator, or be a pseudo-path like '.' or '..'). + public func appending(_ components: String...) -> RelativePath { + self.appending(components: components) + } +} + +extension RelativePath: Codable { + public func encode(to encoder: Encoder) throws { + try self.underlying.encode(to: encoder) + } + + public init(from decoder: Decoder) throws { + self = try .init(TSCBasic.RelativePath(from: decoder)) + } +} + +/// Make relative paths CustomStringConvertible and CustomDebugStringConvertible. +extension RelativePath: CustomStringConvertible { + public var description: String { + self.underlying.description + } + + public var debugDescription: String { + self.underlying.debugDescription + } +} + +extension TSCRelativePath { + public init(_ path: RelativePath) { + self = path.underlying + } +} diff --git a/Sources/Basics/FileSystem/TSCAdapters.swift b/Sources/Basics/FileSystem/TSCAdapters.swift new file mode 100644 index 00000000000..8ef392570fb --- /dev/null +++ b/Sources/Basics/FileSystem/TSCAdapters.swift @@ -0,0 +1,164 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift open source project +// +// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See http://swift.org/LICENSE.txt for license information +// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +import func TSCBasic.getEnvSearchPaths +import func TSCBasic.lookupExecutablePath +import func TSCBasic.makeDirectories +import func TSCBasic.resolveSymlinks +import func TSCBasic.walk +import func TSCBasic.withTemporaryDirectory + +import struct TSCBasic.FileSystemError +import class TSCBasic.LocalFileOutputByteStream +import enum TSCBasic.ProcessEnv +import class TSCBasic.RecursibleDirectoryContentsGenerator + +public func resolveSymlinks(_ path: AbsolutePath) throws -> AbsolutePath { + try AbsolutePath(TSCBasic.resolveSymlinks(path.underlying)) +} + +public func withTemporaryDirectory( + dir: AbsolutePath? = nil, prefix: String = "TemporaryDirectory", + _ body: (AbsolutePath, @escaping (AbsolutePath) -> Void) throws -> Result +) throws -> Result { + try TSCBasic.withTemporaryDirectory(dir: dir?.underlying, prefix: prefix) { path, callback in + let callback2 = { (path: AbsolutePath) in + callback(path.underlying) + } + return try body(AbsolutePath(path), callback2) + } +} + +public func withTemporaryDirectory( + dir: AbsolutePath? = nil, prefix: String = "TemporaryDirectory", + _ body: (AbsolutePath, @escaping (AbsolutePath) async -> Void) async throws -> Result +) async throws -> Result { + try await TSCBasic.withTemporaryDirectory(dir: dir?.underlying, prefix: prefix) { path, callback in + let callback2: (AbsolutePath) async -> Void = { (path: AbsolutePath) in + await callback(path.underlying) + } + return try await body(AbsolutePath(path), callback2) + } +} + +public func withTemporaryDirectory( + dir: AbsolutePath? = nil, prefix: String = "TemporaryDirectory", removeTreeOnDeinit: Bool = false, + _ body: (AbsolutePath) throws -> Result +) throws -> Result { + try TSCBasic.withTemporaryDirectory(dir: dir?.underlying, prefix: prefix, removeTreeOnDeinit: removeTreeOnDeinit) { + try body(AbsolutePath($0)) + } +} + +@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) +public func withTemporaryDirectory( + dir: AbsolutePath? = nil, prefix: String = "TemporaryDirectory", removeTreeOnDeinit: Bool = false, + _ body: (AbsolutePath) async throws -> Result +) async throws -> Result { + try await TSCBasic.withTemporaryDirectory( + dir: dir?.underlying, + prefix: prefix, + removeTreeOnDeinit: removeTreeOnDeinit + ) { + try await body(AbsolutePath($0)) + } +} + +/// Lookup an executable path from an environment variable value, current working +/// directory or search paths. Only return a value that is both found and executable. +/// +/// This method searches in the following order: +/// * If env value is a valid absolute path, return it. +/// * If env value is relative path, first try to locate it in current working directory. +/// * Otherwise, in provided search paths. +/// +/// - Parameters: +/// - filename: The name of the file to find. +/// - currentWorkingDirectory: The current working directory to look in. +/// - searchPaths: The additional search paths to look in if not found in cwd. +/// - Returns: Valid path to executable if present, otherwise nil. +public func lookupExecutablePath( + filename: String?, + currentWorkingDirectory: AbsolutePath? = localFileSystem.currentWorkingDirectory, + searchPaths: [AbsolutePath] = [] +) -> AbsolutePath? { + TSCBasic.lookupExecutablePath( + filename: filename, + currentWorkingDirectory: currentWorkingDirectory?.underlying, + searchPaths: searchPaths.map(\.underlying) + ).flatMap { AbsolutePath($0) } +} + +/// Create a list of AbsolutePath search paths from a string, such as the PATH environment variable. +/// +/// - Parameters: +/// - pathString: The path string to parse. +/// - currentWorkingDirectory: The current working directory, the relative paths will be converted to absolute paths +/// based on this path. +/// - Returns: List of search paths. +public func getEnvSearchPaths( + pathString: String?, + currentWorkingDirectory: AbsolutePath? +) -> [AbsolutePath] { + TSCBasic.getEnvSearchPaths( + pathString: pathString, + currentWorkingDirectory: currentWorkingDirectory?.underlying + ).map { AbsolutePath($0) } +} + +public func walk( + _ path: AbsolutePath, + fileSystem: FileSystem = localFileSystem, + recursively: Bool = true +) throws -> WalkResult { + let result = try TSCBasic.walk( + path.underlying, + fileSystem: fileSystem, + recursively: recursively + ) + return WalkResult(result) +} + +public class WalkResult: IteratorProtocol, Sequence { + private let underlying: TSCBasic.RecursibleDirectoryContentsGenerator + + init(_ underlying: TSCBasic.RecursibleDirectoryContentsGenerator) { + self.underlying = underlying + } + + public func next() -> AbsolutePath? { + self.underlying.next().flatMap { AbsolutePath($0) } + } +} + +public func makeDirectories(_ path: AbsolutePath) throws { + try TSCBasic.makeDirectories(path.underlying) +} + +extension TSCBasic.LocalFileOutputByteStream { + public convenience init(_ path: AbsolutePath, closeOnDeinit: Bool = true, buffered: Bool = true) throws { + try self.init(path.underlying, closeOnDeinit: closeOnDeinit, buffered: buffered) + } +} + +extension TSCBasic.ProcessEnv { + public static func chdir(_ path: AbsolutePath) throws { + try self.chdir(path.underlying) + } +} + +extension TSCBasic.FileSystemError { + @_disfavoredOverload + public init(_ kind: Kind, _ path: AbsolutePath? = nil) { + self.init(kind, path?.underlying) + } +} diff --git a/Sources/Basics/FileSystem/TemporaryFile.swift b/Sources/Basics/FileSystem/TemporaryFile.swift index c801a3c514e..cb7ce4eaae8 100644 --- a/Sources/Basics/FileSystem/TemporaryFile.swift +++ b/Sources/Basics/FileSystem/TemporaryFile.swift @@ -12,7 +12,7 @@ import _Concurrency import Foundation -import TSCBasic +import enum TSCBasic.TempFileError /// Creates a temporary directory and evaluates a closure with the directory path as an argument. /// The temporary directory will live on disk while the closure is evaluated and will be deleted when @@ -37,7 +37,7 @@ public func withTemporaryDirectory( _ body: @Sendable @escaping (AbsolutePath, @escaping (AbsolutePath) -> Void) async throws -> Result ) throws -> Task { let temporaryDirectory = try createTemporaryDirectory(fileSystem: fileSystem, dir: dir, prefix: prefix) - + let task: Task = Task { try await withTaskCancellationHandler { try await body(temporaryDirectory) { path in @@ -46,9 +46,8 @@ public func withTemporaryDirectory( } onCancel: { try? fileSystem.removeFileTree(temporaryDirectory) } - } - + return task } @@ -80,13 +79,17 @@ public func withTemporaryDirectory( } } -private func createTemporaryDirectory(fileSystem: FileSystem, dir: AbsolutePath?, prefix: String) throws -> AbsolutePath { +private func createTemporaryDirectory( + fileSystem: FileSystem, + dir: AbsolutePath?, + prefix: String +) throws -> AbsolutePath { // This random generation is needed so that // it is more or less equal to generation using `mkdtemp` function let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" - - let randomSuffix = String((0..<6).map { _ in letters.randomElement()! }) - + + let randomSuffix = String((0 ..< 6).map { _ in letters.randomElement()! }) + let tempDirectory = try dir ?? fileSystem.tempDirectory guard fileSystem.isDirectory(tempDirectory) else { throw TempFileError.couldNotFindTmpDir(tempDirectory.pathString) @@ -94,7 +97,7 @@ private func createTemporaryDirectory(fileSystem: FileSystem, dir: AbsolutePath? // Construct path to the temporary directory. let templatePath = try AbsolutePath(validating: prefix + ".\(randomSuffix)", relativeTo: tempDirectory) - + try fileSystem.createDirectory(templatePath, recursive: true) return templatePath } diff --git a/Sources/Basics/FileSystem/VFSOverlay.swift b/Sources/Basics/FileSystem/VFSOverlay.swift index ac936fa767c..bbe902ec631 100644 --- a/Sources/Basics/FileSystem/VFSOverlay.swift +++ b/Sources/Basics/FileSystem/VFSOverlay.swift @@ -11,8 +11,6 @@ //===----------------------------------------------------------------------===// import class Foundation.JSONEncoder -import struct TSCBasic.AbsolutePath -import protocol TSCBasic.FileSystem public struct VFSOverlay: Encodable { public struct File: Encodable { diff --git a/Sources/Basics/FileSystem/VirtualFileSystem.swift b/Sources/Basics/FileSystem/VirtualFileSystem.swift index 376c76f1ff2..ca485b1be3c 100644 --- a/Sources/Basics/FileSystem/VirtualFileSystem.swift +++ b/Sources/Basics/FileSystem/VirtualFileSystem.swift @@ -11,9 +11,11 @@ //===----------------------------------------------------------------------===// import Foundation -import TSCBasic +import struct TSCBasic.ByteString +import struct TSCBasic.FileInfo +import enum TSCBasic.FileMode -fileprivate enum DirectoryNode: Codable { +private enum DirectoryNode: Codable { case directory(name: String, isSymlink: Bool, children: [DirectoryNode]) case file(name: String, isExecutable: Bool, isSymlink: Bool, contents: Data?) case root(children: [DirectoryNode]) @@ -21,7 +23,7 @@ fileprivate enum DirectoryNode: Codable { var children: [DirectoryNode] { switch self { case .directory(_, _, let children): return children - case .file(_, _, _, _): return [] + case .file: return [] case .root(let children): return children } } @@ -30,39 +32,39 @@ fileprivate enum DirectoryNode: Codable { switch self { case .directory(let name, _, _): return name case .file(let name, _, _, _): return name - case .root(_): return AbsolutePath.root.pathString + case .root: return AbsolutePath.root.pathString } } var fileAttributeType: FileAttributeType { switch self { - case .directory(_, _, _): return .typeDirectory + case .directory: return .typeDirectory case .file(_, _, let isSymlink, _): return isSymlink ? .typeSymbolicLink : .typeRegular - case .root(_): return .typeDirectory + case .root: return .typeDirectory } } var isDirectory: Bool { switch self { - case .directory(_, _, _): return true - case .file(_, _, _, _): return false - case .root(_): return true + case .directory: return true + case .file: return false + case .root: return true } } var isFile: Bool { switch self { - case .directory(_, _, _): return false - case .file(_, _, _, _): return true - case .root(_): return false + case .directory: return false + case .file: return true + case .root: return false } } var isRoot: Bool { switch self { - case .directory(_, _, _): return false - case .file(_, _, _, _): return false - case .root(_): return true + case .directory: return false + case .file: return false + case .root: return true } } @@ -70,7 +72,7 @@ fileprivate enum DirectoryNode: Codable { switch self { case .directory(_, let isSymlink, _): return isSymlink case .file(_, _, let isSymlink, _): return isSymlink - case .root(_): return false + case .root: return false } } } @@ -91,9 +93,12 @@ private enum Errors: Swift.Error, LocalizedError { } } -private extension FileSystem { - func getDirectoryNodes(_ path: AbsolutePath, includeContents: [AbsolutePath]) throws -> [DirectoryNode] { - return try getDirectoryContents(path).compactMap { +extension FileSystem { + fileprivate func getDirectoryNodes( + _ path: AbsolutePath, + includeContents: [AbsolutePath] + ) throws -> [DirectoryNode] { + try getDirectoryContents(path).compactMap { let current = path.appending(component: $0) let isSymlink = isSymlink(current) @@ -104,10 +109,19 @@ private extension FileSystem { } else { contents = nil } - return .file(name: $0, isExecutable: isExecutableFile(current), isSymlink: isSymlink, contents: contents) + return .file( + name: $0, + isExecutable: isExecutableFile(current), + isSymlink: isSymlink, + contents: contents + ) } else if isDirectory(current) { if $0.hasPrefix(".") { return nil } // we ignore hidden files - return .directory(name: $0, isSymlink: isSymlink, children: try getDirectoryNodes(current, includeContents: includeContents)) + return .directory( + name: $0, + isSymlink: isSymlink, + children: try getDirectoryNodes(current, includeContents: includeContents) + ) } else { throw Errors.unhandledDirectoryNode(path: current) } @@ -119,18 +133,31 @@ private extension FileSystem { public class VirtualFileSystem: FileSystem { private let root: DirectoryNode - public init(path: AbsolutePath, fs: FileSystem) throws { - self.root = try JSONDecoder.makeWithDefaults().decode(path: path, fileSystem: fs, as: DirectoryNode.self) + public init(path: TSCAbsolutePath, fs: FileSystem) throws { + self.root = try JSONDecoder.makeWithDefaults() + .decode(path: AbsolutePath(path), fileSystem: fs, as: DirectoryNode.self) assert(self.root.isRoot, "VFS needs to have a root node") } /// Write information about the directory tree at `directoryPath` into a JSON file at `vfsPath`. This can later be used to construct a `VirtualFileSystem` object. - public static func serializeDirectoryTree(_ directoryPath: AbsolutePath, into vfsPath: AbsolutePath, fs: FileSystem, includeContents: [AbsolutePath]) throws { - let data = try JSONEncoder.makeWithDefaults().encode(DirectoryNode.root(children: fs.getDirectoryNodes(directoryPath, includeContents: includeContents))) + public static func serializeDirectoryTree( + _ directoryPath: AbsolutePath, + into vfsPath: AbsolutePath, + fs: FileSystem, + includeContents: [AbsolutePath] + ) throws { + let data = try JSONEncoder.makeWithDefaults().encode( + DirectoryNode.root( + children: fs.getDirectoryNodes( + directoryPath, + includeContents: includeContents + ) + ) + ) try data.write(to: URL(fileURLWithPath: vfsPath.pathString)) } - private func findNode(_ path: AbsolutePath, followSymlink: Bool) -> DirectoryNode? { + private func findNode(_ path: TSCAbsolutePath, followSymlink: Bool) -> DirectoryNode? { var current: DirectoryNode? = self.root for component in path.components { if component == AbsolutePath.root.pathString { continue } @@ -140,100 +167,107 @@ public class VirtualFileSystem: FileSystem { return current } - public func exists(_ path: AbsolutePath, followSymlink: Bool) -> Bool { - return findNode(path, followSymlink: followSymlink) != nil + public func exists(_ path: TSCAbsolutePath, followSymlink: Bool) -> Bool { + findNode(path, followSymlink: followSymlink) != nil } - public func isDirectory(_ path: AbsolutePath) -> Bool { - return findNode(path, followSymlink: true)?.isDirectory == true + public func isDirectory(_ path: TSCAbsolutePath) -> Bool { + findNode(path, followSymlink: true)?.isDirectory == true } - public func isFile(_ path: AbsolutePath) -> Bool { - return findNode(path, followSymlink: true)?.isFile == true + public func isFile(_ path: TSCAbsolutePath) -> Bool { + findNode(path, followSymlink: true)?.isFile == true } - public func isExecutableFile(_ path: AbsolutePath) -> Bool { + public func isExecutableFile(_ path: TSCAbsolutePath) -> Bool { guard let node = findNode(path, followSymlink: true) else { return false } - if case let .file(_, isExecutable, _, _) = node { + if case .file(_, let isExecutable, _, _) = node { return isExecutable } else { return false } } - public func isSymlink(_ path: AbsolutePath) -> Bool { - return findNode(path, followSymlink: true)?.isSymlink == true + public func isSymlink(_ path: TSCAbsolutePath) -> Bool { + findNode(path, followSymlink: true)?.isSymlink == true } - public func isReadable(_ path: AbsolutePath) -> Bool { - return self.exists(path) + public func isReadable(_ path: TSCAbsolutePath) -> Bool { + self.exists(path) } - public func isWritable(_ path: AbsolutePath) -> Bool { - return false + public func isWritable(_: TSCAbsolutePath) -> Bool { + false } - public func getDirectoryContents(_ path: AbsolutePath) throws -> [String] { - guard let node = findNode(path, followSymlink: true) else { throw Errors.noSuchFileOrDirectory(path: path) } - return node.children.map { $0.name } + public func getDirectoryContents(_ path: TSCAbsolutePath) throws -> [String] { + guard let node = findNode(path, followSymlink: true) + else { throw Errors.noSuchFileOrDirectory(path: AbsolutePath(path)) } + return node.children.map(\.name) } - public let currentWorkingDirectory: AbsolutePath? = nil + public let currentWorkingDirectory: TSCAbsolutePath? = nil - public func changeCurrentWorkingDirectory(to path: AbsolutePath) throws { + public func changeCurrentWorkingDirectory(to path: TSCAbsolutePath) throws { throw Errors.readOnlyFileSystem } - public var homeDirectory = AbsolutePath.root + public var homeDirectory = TSCAbsolutePath.root - public var cachesDirectory: AbsolutePath? = nil + public var cachesDirectory: TSCAbsolutePath? = nil - public var tempDirectory = AbsolutePath.root + public var tempDirectory = TSCAbsolutePath.root - public func createSymbolicLink(_ path: AbsolutePath, pointingAt destination: AbsolutePath, relative: Bool) throws { + public func createSymbolicLink( + _ path: TSCAbsolutePath, + pointingAt destination: TSCAbsolutePath, + relative: Bool + ) throws { throw Errors.readOnlyFileSystem } - public func removeFileTree(_ path: AbsolutePath) throws { + public func removeFileTree(_: TSCAbsolutePath) throws { throw Errors.readOnlyFileSystem } - public func copy(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws { + public func copy(from sourcePath: TSCAbsolutePath, to destinationPath: TSCAbsolutePath) throws { throw Errors.readOnlyFileSystem } - public func move(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws { + public func move(from sourcePath: TSCAbsolutePath, to destinationPath: TSCAbsolutePath) throws { throw Errors.readOnlyFileSystem } - public func createDirectory(_ path: AbsolutePath, recursive: Bool) throws { + public func createDirectory(_ path: TSCAbsolutePath, recursive: Bool) throws { throw Errors.readOnlyFileSystem } - public func readFileContents(_ path: AbsolutePath) throws -> ByteString { - guard let node = findNode(path, followSymlink: true) else { throw Errors.noSuchFileOrDirectory(path: path) } + public func readFileContents(_ path: TSCAbsolutePath) throws -> ByteString { + guard let node = findNode(path, followSymlink: true) + else { throw Errors.noSuchFileOrDirectory(path: AbsolutePath(path)) } switch node { - case .directory(_, _, _): throw Errors.notAFile(path: path) + case .directory: throw Errors.notAFile(path: AbsolutePath(path)) case .file(_, _, _, let contents): if let contents { return ByteString(contents) } else { return "" } - case .root(_): throw Errors.notAFile(path: path) + case .root: throw Errors.notAFile(path: AbsolutePath(path)) } } - public func writeFileContents(_ path: AbsolutePath, bytes: ByteString) throws { + public func writeFileContents(_ path: TSCAbsolutePath, bytes: ByteString) throws { throw Errors.readOnlyFileSystem } - public func chmod(_ mode: FileMode, path: AbsolutePath, options: Set) throws { + public func chmod(_ mode: FileMode, path: TSCAbsolutePath, options: Set) throws { throw Errors.readOnlyFileSystem } - public func getFileInfo(_ path: AbsolutePath) throws -> FileInfo { - guard let node = findNode(path, followSymlink: true) else { throw Errors.noSuchFileOrDirectory(path: path) } + public func getFileInfo(_ path: TSCAbsolutePath) throws -> FileInfo { + guard let node = findNode(path, followSymlink: true) + else { throw Errors.noSuchFileOrDirectory(path: AbsolutePath(path)) } let attrs: [FileAttributeKey: Any] = [ .systemNumber: NSNumber(value: UInt64(0)), diff --git a/Sources/Basics/HTTPClient/HTTPClient.swift b/Sources/Basics/HTTPClient/HTTPClient.swift index 1943e1ac8ed..7fc28e12e97 100644 --- a/Sources/Basics/HTTPClient/HTTPClient.swift +++ b/Sources/Basics/HTTPClient/HTTPClient.swift @@ -11,8 +11,8 @@ //===----------------------------------------------------------------------===// import _Concurrency -import Foundation import DequeModule +import Foundation /// `async`-friendly wrapper for HTTP clients. It allows a specific client implementation (either Foundation or /// NIO-based) to be hidden from users of the wrapper. @@ -83,11 +83,13 @@ public actor HTTPClient { request.headers.add(name: "User-Agent", value: "SwiftPackageManager/\(SwiftVersion.current.displayString)") } - if let authorization = request.options.authorizationProvider?(request.url), !request.headers.contains("Authorization") { + if let authorization = request.options.authorizationProvider?(request.url), + !request.headers.contains("Authorization") + { request.headers.add(name: "Authorization", value: authorization) } - return try await executeWithStrategies(request: request, requestNumber: 0, observabilityScope, progress) + return try await self.executeWithStrategies(request: request, requestNumber: 0, observabilityScope, progress) } private func executeWithStrategies( @@ -135,7 +137,9 @@ public actor HTTPClient { ) } // check for valid response codes - if let validResponseCodes = request.options.validResponseCodes, !validResponseCodes.contains(response.statusCode) { + if let validResponseCodes = request.options.validResponseCodes, + !validResponseCodes.contains(response.statusCode) + { throw HTTPClientError.badResponseStatusCode(response.statusCode) } else { return response @@ -171,7 +175,7 @@ public actor HTTPClient { } // Avoid copy-on-write: remove entry from dictionary before mutating let hostErrors: HostErrors - if var errors = self.hostsErrors.removeValue(forKey: host) { + if var errors = self.hostsErrors.removeValue(forKey: host) { errors.numberOfErrors += 1 errors.lastError = Date() hostErrors = errors @@ -202,8 +206,8 @@ public actor HTTPClient { } } -public extension HTTPClient { - func head( +extension HTTPClient { + public func head( _ url: URL, headers: HTTPClientHeaders = .init(), options: Request.Options = .init() @@ -213,7 +217,7 @@ public extension HTTPClient { ) } - func get( + public func get( _ url: URL, headers: HTTPClientHeaders = .init(), options: Request.Options = .init() @@ -223,7 +227,7 @@ public extension HTTPClient { ) } - func put( + public func put( _ url: URL, body: Data?, headers: HTTPClientHeaders = .init(), @@ -234,7 +238,7 @@ public extension HTTPClient { ) } - func post( + public func post( _ url: URL, body: Data?, headers: HTTPClientHeaders = .init(), @@ -245,7 +249,7 @@ public extension HTTPClient { ) } - func delete( + public func delete( _ url: URL, headers: HTTPClientHeaders = .init(), options: Request.Options = .init() diff --git a/Sources/Basics/HTTPClient/HTTPClientConfiguration.swift b/Sources/Basics/HTTPClient/HTTPClientConfiguration.swift index e3e192a9d05..1c44c99fd67 100644 --- a/Sources/Basics/HTTPClient/HTTPClientConfiguration.swift +++ b/Sources/Basics/HTTPClient/HTTPClientConfiguration.swift @@ -14,7 +14,8 @@ import Foundation public struct HTTPClientConfiguration: Sendable { // FIXME: this should be unified with ``AuthorizationProvider`` protocol or renamed to avoid unintended shadowing. - public typealias AuthorizationProvider = @Sendable (URL) -> String? + public typealias AuthorizationProvider = @Sendable (URL) + -> String? public init( requestHeaders: HTTPClientHeaders? = nil, diff --git a/Sources/Basics/HTTPClient/HTTPClientRequest.swift b/Sources/Basics/HTTPClient/HTTPClientRequest.swift index 32ef28f61e2..2782bcd4141 100644 --- a/Sources/Basics/HTTPClient/HTTPClientRequest.swift +++ b/Sources/Basics/HTTPClient/HTTPClientRequest.swift @@ -12,9 +12,6 @@ import Foundation -import struct TSCBasic.AbsolutePath -import protocol TSCBasic.FileSystem - public struct HTTPClientRequest: Sendable { public let kind: Kind public let url: URL diff --git a/Sources/Basics/HTTPClient/HTTPClientResponse.swift b/Sources/Basics/HTTPClient/HTTPClientResponse.swift index 62316fa6576..7c7fd1b4c79 100644 --- a/Sources/Basics/HTTPClient/HTTPClientResponse.swift +++ b/Sources/Basics/HTTPClient/HTTPClientResponse.swift @@ -12,7 +12,7 @@ import Foundation -public struct HTTPClientResponse : Sendable { +public struct HTTPClientResponse: Sendable { public let statusCode: Int public let statusText: String? public let headers: HTTPClientHeaders @@ -35,20 +35,20 @@ public struct HTTPClientResponse : Sendable { } } -public extension HTTPClientResponse { - static func okay(body: String? = nil) -> HTTPClientResponse { +extension HTTPClientResponse { + public static func okay(body: String? = nil) -> HTTPClientResponse { .okay(body: body?.data(using: .utf8)) } - static func okay(body: Data?) -> HTTPClientResponse { + public static func okay(body: Data?) -> HTTPClientResponse { HTTPClientResponse(statusCode: 200, body: body) } - static func notFound(reason: String? = nil) -> HTTPClientResponse { + public static func notFound(reason: String? = nil) -> HTTPClientResponse { HTTPClientResponse(statusCode: 404, body: (reason ?? "Not Found").data(using: .utf8)) } - static func serverError(reason: String? = nil) -> HTTPClientResponse { + public static func serverError(reason: String? = nil) -> HTTPClientResponse { HTTPClientResponse(statusCode: 500, body: (reason ?? "Internal Server Error").data(using: .utf8)) } } diff --git a/Sources/Basics/HTTPClient/LegacyHTTPClient.swift b/Sources/Basics/HTTPClient/LegacyHTTPClient.swift index 41b07735591..9973e193900 100644 --- a/Sources/Basics/HTTPClient/LegacyHTTPClient.swift +++ b/Sources/Basics/HTTPClient/LegacyHTTPClient.swift @@ -11,15 +11,13 @@ //===----------------------------------------------------------------------===// import Dispatch +import struct Foundation.Data +import struct Foundation.Date import class Foundation.NSLock import class Foundation.OperationQueue import func Foundation.pow -import struct Foundation.Data -import struct Foundation.Date import struct Foundation.URL import struct Foundation.UUID -import TSCBasic - // MARK: - LegacyHTTPClient @@ -108,7 +106,9 @@ public final class LegacyHTTPClient: Cancellable { request.headers.add(name: "User-Agent", value: "SwiftPackageManager/\(SwiftVersion.current.displayString)") } - if let authorization = request.options.authorizationProvider?(request.url), !request.headers.contains("Authorization") { + if let authorization = request.options.authorizationProvider?(request.url), + !request.headers.contains("Authorization") + { request.headers.add(name: "Authorization", value: authorization) } // execute @@ -235,7 +235,9 @@ public final class LegacyHTTPClient: Cancellable { } } // check for valid response codes - if let validResponseCodes = request.options.validResponseCodes, !validResponseCodes.contains(response.statusCode) { + if let validResponseCodes = request.options.validResponseCodes, + !validResponseCodes.contains(response.statusCode) + { return completion(.failure(HTTPClientError.badResponseStatusCode(response.statusCode))) } completion(.success(response)) @@ -303,8 +305,8 @@ public final class LegacyHTTPClient: Cancellable { } } -public extension LegacyHTTPClient { - func head( +extension LegacyHTTPClient { + public func head( _ url: URL, headers: HTTPClientHeaders = .init(), options: Request.Options = .init(), @@ -318,7 +320,7 @@ public extension LegacyHTTPClient { ) } - func get( + public func get( _ url: URL, headers: HTTPClientHeaders = .init(), options: Request.Options = .init(), @@ -332,7 +334,7 @@ public extension LegacyHTTPClient { ) } - func put( + public func put( _ url: URL, body: Data?, headers: HTTPClientHeaders = .init(), @@ -347,7 +349,7 @@ public extension LegacyHTTPClient { ) } - func post( + public func post( _ url: URL, body: Data?, headers: HTTPClientHeaders = .init(), @@ -362,7 +364,7 @@ public extension LegacyHTTPClient { ) } - func delete( + public func delete( _ url: URL, headers: HTTPClientHeaders = .init(), options: Request.Options = .init(), diff --git a/Sources/Basics/HTTPClient/LegacyHTTPClientRequest.swift b/Sources/Basics/HTTPClient/LegacyHTTPClientRequest.swift index 78b2bf9a7ea..58ce1880c45 100644 --- a/Sources/Basics/HTTPClient/LegacyHTTPClientRequest.swift +++ b/Sources/Basics/HTTPClient/LegacyHTTPClientRequest.swift @@ -12,9 +12,6 @@ import Foundation -import struct TSCBasic.AbsolutePath -import protocol TSCBasic.FileSystem - public struct LegacyHTTPClientRequest { public let kind: Kind public let url: URL @@ -73,7 +70,8 @@ public struct LegacyHTTPClientRequest { } } - public typealias FileMoveCompletion = @Sendable (Error?) -> () + public typealias FileMoveCompletion = @Sendable (Error?) + -> Void public enum Kind { case generic(HTTPMethod) diff --git a/Sources/Basics/HTTPClient/URLSessionHTTPClient.swift b/Sources/Basics/HTTPClient/URLSessionHTTPClient.swift index e363486d140..d6302003d2a 100644 --- a/Sources/Basics/HTTPClient/URLSessionHTTPClient.swift +++ b/Sources/Basics/HTTPClient/URLSessionHTTPClient.swift @@ -12,7 +12,6 @@ import _Concurrency import Foundation -import TSCBasic import struct TSCUtility.Versioning #if canImport(FoundationNetworking) // FIXME: this brings OpenSSL dependency on Linux diff --git a/Sources/Basics/ImportScanning.swift b/Sources/Basics/ImportScanning.swift index f89e6df4a9f..9f931db3d50 100644 --- a/Sources/Basics/ImportScanning.swift +++ b/Sources/Basics/ImportScanning.swift @@ -13,7 +13,6 @@ import Dispatch import class Foundation.JSONDecoder -import struct TSCBasic.AbsolutePath import class TSCBasic.Process private let defaultImports = ["Swift", "SwiftOnoneSupport", "_Concurrency", @@ -24,7 +23,11 @@ private struct Imports: Decodable { } public protocol ImportScanner { - func scanImports(_ filePathToScan: AbsolutePath, callbackQueue: DispatchQueue, completion: @escaping (Result<[String], Error>) -> Void) + func scanImports( + _ filePathToScan: AbsolutePath, + callbackQueue: DispatchQueue, + completion: @escaping (Result<[String], Error>) -> Void + ) } public struct SwiftcImportScanner: ImportScanner { @@ -32,35 +35,42 @@ public struct SwiftcImportScanner: ImportScanner { private let swiftCompilerFlags: [String] private let swiftCompilerPath: AbsolutePath - public init(swiftCompilerEnvironment: EnvironmentVariables, swiftCompilerFlags: [String], swiftCompilerPath: AbsolutePath) { + public init( + swiftCompilerEnvironment: EnvironmentVariables, + swiftCompilerFlags: [String], + swiftCompilerPath: AbsolutePath + ) { self.swiftCompilerEnvironment = swiftCompilerEnvironment self.swiftCompilerFlags = swiftCompilerFlags self.swiftCompilerPath = swiftCompilerPath } - public func scanImports(_ filePathToScan: AbsolutePath, - callbackQueue: DispatchQueue, - completion: @escaping (Result<[String], Error>) -> Void) { + public func scanImports( + _ filePathToScan: AbsolutePath, + callbackQueue: DispatchQueue, + completion: @escaping (Result<[String], Error>) -> Void + ) { let cmd = [swiftCompilerPath.pathString, filePathToScan.pathString, "-scan-dependencies", "-Xfrontend", "-import-prescan"] + self.swiftCompilerFlags - TSCBasic.Process.popen(arguments: cmd, environment: self.swiftCompilerEnvironment, queue: callbackQueue) { result in - dispatchPrecondition(condition: .onQueue(callbackQueue)) - - do { - let stdout = try result.get().utf8Output() - let imports = try JSONDecoder.makeWithDefaults().decode(Imports.self, from: stdout).imports - .filter { !defaultImports.contains($0) } - - callbackQueue.async { - completion(.success(imports)) - } - } catch { - callbackQueue.async { - completion(.failure(error)) + TSCBasic.Process + .popen(arguments: cmd, environment: self.swiftCompilerEnvironment, queue: callbackQueue) { result in + dispatchPrecondition(condition: .onQueue(callbackQueue)) + + do { + let stdout = try result.get().utf8Output() + let imports = try JSONDecoder.makeWithDefaults().decode(Imports.self, from: stdout).imports + .filter { !defaultImports.contains($0) } + + callbackQueue.async { + completion(.success(imports)) + } + } catch { + callbackQueue.async { + completion(.failure(error)) + } } } - } } } diff --git a/Sources/Basics/JSON+Extensions.swift b/Sources/Basics/JSON+Extensions.swift index 7691cb3c1d4..de4c67d79ce 100644 --- a/Sources/Basics/JSON+Extensions.swift +++ b/Sources/Basics/JSON+Extensions.swift @@ -10,11 +10,10 @@ // //===----------------------------------------------------------------------===// -import class Foundation.DateFormatter import struct Foundation.Data +import class Foundation.DateFormatter import class Foundation.JSONDecoder import class Foundation.JSONEncoder -import TSCBasic #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) extension DateFormatter { @@ -81,11 +80,24 @@ extension JSONDecoder { } extension JSONEncoder { - public static func makeWithDefaults(prettified: Bool = true, dateEncodingStrategy: DateEncodingStrategy = .safeISO8601) -> JSONEncoder { - Self.makeWithDefaults(sortKeys: prettified, prettyPrint: prettified, escapeSlashes: !prettified, dateEncodingStrategy: dateEncodingStrategy) + public static func makeWithDefaults( + prettified: Bool = true, + dateEncodingStrategy: DateEncodingStrategy = .safeISO8601 + ) -> JSONEncoder { + Self.makeWithDefaults( + sortKeys: prettified, + prettyPrint: prettified, + escapeSlashes: !prettified, + dateEncodingStrategy: dateEncodingStrategy + ) } - public static func makeWithDefaults(sortKeys: Bool, prettyPrint: Bool, escapeSlashes: Bool, dateEncodingStrategy: DateEncodingStrategy = .safeISO8601) -> JSONEncoder { + public static func makeWithDefaults( + sortKeys: Bool, + prettyPrint: Bool, + escapeSlashes: Bool, + dateEncodingStrategy: DateEncodingStrategy = .safeISO8601 + ) -> JSONEncoder { let encoder = JSONEncoder() var outputFormatting: JSONEncoder.OutputFormatting = [] @@ -118,7 +130,7 @@ extension JSONEncoder { } extension JSONDecoder { - public func decode(path: AbsolutePath, fileSystem: FileSystem, `as` kind: T.Type) throws -> T { + public func decode(path: AbsolutePath, fileSystem: FileSystem, as kind: T.Type) throws -> T { let data: Data = try fileSystem.readFileContents(path) return try self.decode(kind, from: data) } diff --git a/Sources/Basics/JSONDecoder+Extensions.swift b/Sources/Basics/JSONDecoder+Extensions.swift index 0f49bebc26d..e3051857211 100644 --- a/Sources/Basics/JSONDecoder+Extensions.swift +++ b/Sources/Basics/JSONDecoder+Extensions.swift @@ -13,12 +13,12 @@ import Foundation extension JSONDecoder { - public func decode(_ type: T.Type, from string: String) throws -> T where T : Decodable { + public func decode(_ type: T.Type, from string: String) throws -> T where T: Decodable { guard let data = string.data(using: .utf8) else { let context = DecodingError.Context(codingPath: [], debugDescription: "invalid UTF-8 string") throw DecodingError.dataCorrupted(context) } - return try decode(type, from: data) + return try self.decode(type, from: data) } } diff --git a/Sources/Basics/Netrc.swift b/Sources/Basics/Netrc.swift index ace79718b58..4bbd211cd78 100644 --- a/Sources/Basics/Netrc.swift +++ b/Sources/Basics/Netrc.swift @@ -11,7 +11,6 @@ //===----------------------------------------------------------------------===// import Foundation -import TSCBasic /// Representation of Netrc configuration public struct Netrc { @@ -28,14 +27,15 @@ public struct Netrc { /// - Parameters: /// - url: The url to retrieve authorization information for. public func authorization(for url: URL) -> Authorization? { - guard let index = machines.firstIndex(where: { $0.name == url.host }) ?? machines.firstIndex(where: { $0.isDefault }) else { + guard let index = machines.firstIndex(where: { $0.name == url.host }) ?? machines + .firstIndex(where: { $0.isDefault }) + else { return .none } - let machine = machines[index] + let machine = self.machines[index] return Authorization(login: machine.login, password: machine.password) } - /// Representation of connection settings public struct Machine: Equatable { public let name: String @@ -43,7 +43,7 @@ public struct Netrc { public let password: String public var isDefault: Bool { - return name == "default" + self.name == "default" } public init(name: String, login: String, password: String) { @@ -53,11 +53,13 @@ public struct Netrc { } init?(for match: NSTextCheckingResult, string: String, variant: String = "") { - guard let name = RegexUtil.Token.machine.capture(in: match, string: string) ?? RegexUtil.Token.default.capture(in: match, string: string), - let login = RegexUtil.Token.login.capture(prefix: variant, in: match, string: string), - let password = RegexUtil.Token.password.capture(prefix: variant, in: match, string: string) else { - return nil - } + guard let name = RegexUtil.Token.machine.capture(in: match, string: string) ?? RegexUtil.Token.default + .capture(in: match, string: string), + let login = RegexUtil.Token.login.capture(prefix: variant, in: match, string: string), + let password = RegexUtil.Token.password.capture(prefix: variant, in: match, string: string) + else { + return nil + } self = Machine(name: name, login: login, password: password) } } @@ -96,12 +98,17 @@ public struct NetrcParser { /// - Parameters: /// - content: The content to parse public static func parse(_ content: String) throws -> Netrc { - let content = trimComments(from: content) + let content = self.trimComments(from: content) let regex = try! NSRegularExpression(pattern: RegexUtil.netrcPattern, options: []) - let matches = regex.matches(in: content, options: [], range: NSRange(content.startIndex.. String? { @@ -152,15 +160,18 @@ fileprivate enum RegexUtil { static let comments: String = "\\#[\\s\\S]*?.*$" static let `default`: String = #"(?:\s*(?default))"# static let accountOptional: String = #"(?:\s*account\s+\S++)?"# - static let loginPassword: String = #"\#(namedTrailingCapture("login", prefix: "lp"))\#(accountOptional)\#(namedTrailingCapture("password", prefix: "lp"))"# - static let passwordLogin: String = #"\#(namedTrailingCapture("password", prefix: "pl"))\#(accountOptional)\#(namedTrailingCapture("login", prefix: "pl"))"# - static let netrcPattern = #"(?:(?:(\#(namedTrailingCapture("machine"))|\#(namedMatch("default"))))(?:\#(loginPassword)|\#(passwordLogin)))"# + static let loginPassword: String = + #"\#(namedTrailingCapture("login", prefix: "lp"))\#(accountOptional)\#(namedTrailingCapture("password", prefix: "lp"))"# + static let passwordLogin: String = + #"\#(namedTrailingCapture("password", prefix: "pl"))\#(accountOptional)\#(namedTrailingCapture("login", prefix: "pl"))"# + static let netrcPattern = + #"(?:(?:(\#(namedTrailingCapture("machine"))|\#(namedMatch("default"))))(?:\#(loginPassword)|\#(passwordLogin)))"# static func namedMatch(_ string: String) -> String { - return #"(?:\s*(?<\#(string)>\#(string)))"# + #"(?:\s*(?<\#(string)>\#(string)))"# } static func namedTrailingCapture(_ string: String, prefix: String = "") -> String { - return #"\s*\#(string)\s+(?<\#(prefix + string)>\S++)"# + #"\s*\#(string)\s+(?<\#(prefix + string)>\S++)"# } } diff --git a/Sources/Basics/SQLite.swift b/Sources/Basics/SQLite.swift index f547c35f3fe..785d180ae34 100644 --- a/Sources/Basics/SQLite.swift +++ b/Sources/Basics/SQLite.swift @@ -12,8 +12,6 @@ import Foundation -import TSCBasic - @_implementationOnly import SPMSQLite3 /// A minimal SQLite wrapper. diff --git a/Sources/Basics/SQLiteBackedCache.swift b/Sources/Basics/SQLiteBackedCache.swift index e5138abb792..73554819747 100644 --- a/Sources/Basics/SQLiteBackedCache.swift +++ b/Sources/Basics/SQLiteBackedCache.swift @@ -12,14 +12,16 @@ import Foundation -import TSCBasic +import protocol TSCBasic.Closable +import class TSCBasic.InMemoryFileSystem +import var TSCBasic.localFileSystem /// SQLite backed persistent cache. public final class SQLiteBackedCache: Closable { public typealias Key = String public let tableName: String - public let fileSystem: TSCBasic.FileSystem + public let fileSystem: FileSystem public let location: SQLite.Location public let configuration: SQLiteBackedCacheConfiguration @@ -55,7 +57,11 @@ public final class SQLiteBackedCache: Closable { /// - tableName: The SQLite table name. Must follow SQLite naming rules (e.g., no spaces). /// - path: The path of the SQLite database. /// - configuration: Optional. Configuration for the cache. - public convenience init(tableName: String, path: AbsolutePath, configuration: SQLiteBackedCacheConfiguration = .init()) { + public convenience init( + tableName: String, + path: AbsolutePath, + configuration: SQLiteBackedCacheConfiguration = .init() + ) { self.init(tableName: tableName, location: .path(path), configuration: configuration) } @@ -78,10 +84,15 @@ public final class SQLiteBackedCache: Closable { } } - public func put(key: Key, value: Value, replace: Bool = false, observabilityScope: ObservabilityScope? = nil) throws { + public func put( + key: Key, + value: Value, + replace: Bool = false, + observabilityScope: ObservabilityScope? = nil + ) throws { do { let query = "INSERT OR \(replace ? "REPLACE" : "IGNORE") INTO \(self.tableName) VALUES (?, ?);" - try self.executeStatement(query) { statement -> Void in + try self.executeStatement(query) { statement in let data = try self.jsonEncoder.encode(value) let bindings: [SQLite.SQLiteValue] = [ .string(key), @@ -94,8 +105,11 @@ public final class SQLiteBackedCache: Closable { if !self.configuration.truncateWhenFull { throw error } - observabilityScope?.emit(warning: "truncating \(self.tableName) cache database since it reached max size of \(self.configuration.maxSizeInBytes ?? 0) bytes") - try self.executeStatement("DELETE FROM \(self.tableName);") { statement -> Void in + observabilityScope? + .emit( + warning: "truncating \(self.tableName) cache database since it reached max size of \(self.configuration.maxSizeInBytes ?? 0) bytes" + ) + try self.executeStatement("DELETE FROM \(self.tableName);") { statement in try statement.step() } try self.put(key: key, value: value, replace: replace, observabilityScope: observabilityScope) @@ -123,6 +137,7 @@ public final class SQLiteBackedCache: Closable { } } + @discardableResult private func executeStatement(_ query: String, _ body: (SQLite.PreparedStatement) throws -> T) throws -> T { try self.withDB { db in let result: Result diff --git a/Sources/Basics/Sandbox.swift b/Sources/Basics/Sandbox.swift index d3369ee0213..d155c0244dc 100644 --- a/Sources/Basics/Sandbox.swift +++ b/Sources/Basics/Sandbox.swift @@ -11,7 +11,7 @@ //===----------------------------------------------------------------------===// import Foundation -import TSCBasic +import func TSCBasic.determineTempDirectory public enum SandboxNetworkPermission: Equatable { case none @@ -55,7 +55,12 @@ public enum Sandbox { allowNetworkConnections: [SandboxNetworkPermission] = [] ) throws -> [String] { #if os(macOS) - let profile = try macOSSandboxProfile(strictness: strictness, writableDirectories: writableDirectories, readOnlyDirectories: readOnlyDirectories, allowNetworkConnections: allowNetworkConnections) + let profile = try macOSSandboxProfile( + strictness: strictness, + writableDirectories: writableDirectories, + readOnlyDirectories: readOnlyDirectories, + allowNetworkConnections: allowNetworkConnections + ) return ["/usr/bin/sandbox-exec", "-p", profile] + command #else // rdar://40235432, rdar://75636874 tracks implementing sandboxes for other platforms. @@ -86,7 +91,7 @@ fileprivate let threadSafeDarwinCacheDirectories: [AbsolutePath] = { guard confstr(name, buffer.baseAddress, length) == length else { return nil } - let value: String = String(cString: buffer.baseAddress!) + let value = String(cString: buffer.baseAddress!) guard value.hasSuffix("/") else { return nil } return try? resolveSymlinks(AbsolutePath(validating: value)) @@ -94,7 +99,7 @@ fileprivate let threadSafeDarwinCacheDirectories: [AbsolutePath] = { var directories: [AbsolutePath] = [] try? directories.append(AbsolutePath(validating: "/private/var/tmp")) - (try? TSCBasic.determineTempDirectory()).map { directories.append($0) } + (try? TSCBasic.determineTempDirectory()).map { directories.append(AbsolutePath($0)) } GetConfStr(_CS_DARWIN_USER_TEMP_DIR).map { directories.append($0) } GetConfStr(_CS_DARWIN_USER_CACHE_DIR).map { directories.append($0) } return directories @@ -178,7 +183,9 @@ fileprivate func macOSSandboxProfile( else if strictness == .writableTemporaryDirectory { // Add `subpath` expressions for the regular and the Foundation temporary directories. for tmpDir in ["/tmp", NSTemporaryDirectory()] { - writableDirectoriesExpression += try ["(subpath \(resolveSymlinks(AbsolutePath(validating: tmpDir)).quotedAsSubpathForSandboxProfile))"] + writableDirectoriesExpression += try [ + "(subpath \(resolveSymlinks(AbsolutePath(validating: tmpDir)).quotedAsSubpathForSandboxProfile))", + ] } } @@ -212,10 +219,10 @@ fileprivate func macOSSandboxProfile( return contents } -fileprivate extension AbsolutePath { +extension AbsolutePath { /// Private computed property that returns a version of the path as a string quoted for use as a subpath in a .sb sandbox profile. - var quotedAsSubpathForSandboxProfile: String { - return "\"" + self.pathString + fileprivate var quotedAsSubpathForSandboxProfile: String { + "\"" + self.pathString .replacingOccurrences(of: "\\", with: "\\\\") .replacingOccurrences(of: "\"", with: "\\\"") + "\"" diff --git a/Sources/Basics/String+Extensions.swift b/Sources/Basics/String+Extensions.swift index a24567bebab..4ce38d0c55b 100644 --- a/Sources/Basics/String+Extensions.swift +++ b/Sources/Basics/String+Extensions.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import TSCBasic +import struct TSCBasic.SHA256 extension String { /// generated for the byte string's contents. @@ -19,7 +19,7 @@ extension String { /// Secure Hashing Algorithm 2 (SHA-2) hashing with a 256-bit digest, when available, /// falling back on a native implementation in Swift provided by TSCBasic. public var sha256Checksum: String { - return SHA256().hash(self).hexadecimalRepresentation + SHA256().hash(self).hexadecimalRepresentation } /// Drops the given suffix from the string, if present. diff --git a/Sources/Basics/SwiftVersion.swift b/Sources/Basics/SwiftVersion.swift index b92fa0c3250..10be26ef8ba 100644 --- a/Sources/Basics/SwiftVersion.swift +++ b/Sources/Basics/SwiftVersion.swift @@ -23,11 +23,11 @@ public struct SwiftVersion { public var buildIdentifier: String? /// The major component of the version number. - public var major: Int { return self.version.major } + public var major: Int { self.version.major } /// The minor component of the version number. - public var minor: Int { return self.version.minor } + public var minor: Int { self.version.minor } /// The patch component of the version number. - public var patch: Int { return self.version.patch } + public var patch: Int { self.version.patch } /// The version as a readable string. public var displayString: String { diff --git a/Sources/Basics/Triple.swift b/Sources/Basics/Triple.swift index 62b9f9368d8..2eb4ed3f64b 100644 --- a/Sources/Basics/Triple.swift +++ b/Sources/Basics/Triple.swift @@ -12,7 +12,9 @@ import protocol Foundation.CustomNSError import var Foundation.NSLocalizedDescriptionKey -import TSCBasic + +import enum TSCBasic.JSON +import class TSCBasic.Process /// Triple - Helper class for working with Destination.target values /// diff --git a/Sources/Basics/WritableByteStream+Extensions.swift b/Sources/Basics/WritableByteStream+Extensions.swift index e616eeb61e8..ace54ecab15 100644 --- a/Sources/Basics/WritableByteStream+Extensions.swift +++ b/Sources/Basics/WritableByteStream+Extensions.swift @@ -10,7 +10,10 @@ // //===----------------------------------------------------------------------===// -import TSCBasic +import class TSCBasic.LocalFileOutputByteStream +import class TSCBasic.TerminalController +import class TSCBasic.ThreadSafeOutputByteStream +import protocol TSCBasic.WritableByteStream extension WritableByteStream { /// Returns true if an only if the output byte stream is attached to a TTY. diff --git a/Sources/Build/BuildDescription/ClangTargetBuildDescription.swift b/Sources/Build/BuildDescription/ClangTargetBuildDescription.swift index 59583705bd9..fbe1183b011 100644 --- a/Sources/Build/BuildDescription/ClangTargetBuildDescription.swift +++ b/Sources/Build/BuildDescription/ClangTargetBuildDescription.swift @@ -10,14 +10,14 @@ // //===----------------------------------------------------------------------===// +import Basics import PackageLoading import PackageModel -import TSCBasic - -import struct Basics.InternalError import class PackageGraph.ResolvedTarget import struct SPMBuildCore.BuildParameters +import enum TSCBasic.ProcessEnv + /// Target description for a Clang target i.e. C language family target. public final class ClangTargetBuildDescription { /// The target described by this target. diff --git a/Sources/Build/BuildDescription/PluginDescription.swift b/Sources/Build/BuildDescription/PluginDescription.swift index f47d8d07e4e..82abf9a3b3e 100644 --- a/Sources/Build/BuildDescription/PluginDescription.swift +++ b/Sources/Build/BuildDescription/PluginDescription.swift @@ -14,7 +14,7 @@ import PackageGraph import PackageModel import struct Basics.InternalError -import protocol TSCBasic.FileSystem +import protocol Basics.FileSystem /// Description for a plugin target. This is treated a bit differently from the /// regular kinds of targets, and is not included in the LLBuild description. diff --git a/Sources/Build/BuildDescription/ProductBuildDescription.swift b/Sources/Build/BuildDescription/ProductBuildDescription.swift index 8392a7a85d7..bbabcfedd52 100644 --- a/Sources/Build/BuildDescription/ProductBuildDescription.swift +++ b/Sources/Build/BuildDescription/ProductBuildDescription.swift @@ -11,11 +11,13 @@ //===----------------------------------------------------------------------===// import Basics +@_implementationOnly import DriverSupport import PackageGraph import PackageModel +import OrderedCollections import SPMBuildCore -import TSCBasic -@_implementationOnly import DriverSupport + +import struct TSCBasic.SortedArray /// The build description for a product. public final class ProductBuildDescription: SPMBuildCore.ProductBuildDescription { @@ -373,3 +375,9 @@ public final class ProductBuildDescription: SPMBuildCore.ProductBuildDescription return flags } } + +extension SortedArray where Element == AbsolutePath { + public static func +=(lhs: inout SortedArray, rhs: S) where S.Iterator.Element == AbsolutePath { + lhs.insert(contentsOf: rhs) + } +} diff --git a/Sources/Build/BuildDescription/SwiftTargetBuildDescription.swift b/Sources/Build/BuildDescription/SwiftTargetBuildDescription.swift index 99401d6d101..e4bbda3ada7 100644 --- a/Sources/Build/BuildDescription/SwiftTargetBuildDescription.swift +++ b/Sources/Build/BuildDescription/SwiftTargetBuildDescription.swift @@ -16,9 +16,10 @@ import PackageGraph import PackageLoading import PackageModel import SPMBuildCore -import TSCBasic @_implementationOnly import DriverSupport +import struct TSCBasic.ByteString + /// Target description for a Swift target. public final class SwiftTargetBuildDescription { /// The package this target belongs to. diff --git a/Sources/Build/BuildDescription/TargetBuildDescription.swift b/Sources/Build/BuildDescription/TargetBuildDescription.swift index 3bdbcd241ad..612524488dd 100644 --- a/Sources/Build/BuildDescription/TargetBuildDescription.swift +++ b/Sources/Build/BuildDescription/TargetBuildDescription.swift @@ -10,9 +10,9 @@ // //===----------------------------------------------------------------------===// +import Basics import class PackageGraph.ResolvedTarget import struct PackageModel.Resource -import struct TSCBasic.AbsolutePath /// A target description which can either be for a Swift or Clang target. public enum TargetBuildDescription { diff --git a/Sources/Build/BuildOperation.swift b/Sources/Build/BuildOperation.swift index 8301efc5d6f..79122bcd313 100644 --- a/Sources/Build/BuildOperation.swift +++ b/Sources/Build/BuildOperation.swift @@ -18,9 +18,14 @@ import PackageLoading import PackageModel import SPMBuildCore import SPMLLBuild -import TSCBasic import Foundation +import class TSCBasic.DiagnosticsEngine +import protocol TSCBasic.OutputByteStream +import class TSCBasic.Process +import enum TSCBasic.ProcessEnv +import struct TSCBasic.RegEx + import enum TSCUtility.Diagnostics import class TSCUtility.MultiLineNinjaProgressAnimation import class TSCUtility.NinjaProgressAnimation @@ -76,7 +81,7 @@ public final class BuildOperation: PackageStructureDelegate, SPMBuildCore.BuildS private let logLevel: Basics.Diagnostic.Severity /// File system to operate on. - private let fileSystem: TSCBasic.FileSystem + private let fileSystem: Basics.FileSystem /// ObservabilityScope with which to emit diagnostics. private let observabilityScope: ObservabilityScope @@ -102,7 +107,7 @@ public final class BuildOperation: PackageStructureDelegate, SPMBuildCore.BuildS pkgConfigDirectories: [AbsolutePath], outputStream: OutputByteStream, logLevel: Basics.Diagnostic.Severity, - fileSystem: TSCBasic.FileSystem, + fileSystem: Basics.FileSystem, observabilityScope: ObservabilityScope ) { /// Checks if stdout stream is tty. @@ -371,7 +376,7 @@ public final class BuildOperation: PackageStructureDelegate, SPMBuildCore.BuildS } } let delegate = Delegate(preparationStepName: "Compiling plugin \(plugin.targetName)", buildSystemDelegate: self.buildSystemDelegate) - let result = try tsc_await { + let result = try temp_await { pluginConfiguration.scriptRunner.compilePluginScript( sourceFiles: plugin.sources.paths, pluginName: plugin.targetName, @@ -604,7 +609,7 @@ public final class BuildOperation: PackageStructureDelegate, SPMBuildCore.BuildS if !pluginConfiguration.disableSandbox { commandLine = try Sandbox.apply(command: commandLine, strictness: .writableTemporaryDirectory, writableDirectories: [pluginResult.pluginOutputDirectory]) } - let processResult = try TSCBasic.Process.popen(arguments: commandLine, environment: command.configuration.environment) + let processResult = try Process.popen(arguments: commandLine, environment: command.configuration.environment) let output = try processResult.utf8Output() + processResult.utf8stderrOutput() if processResult.exitStatus != .terminated(code: 0) { throw StringError("failed: \(command)\n\n\(output)") @@ -684,7 +689,7 @@ extension BuildOperation { } extension BuildDescription { - static func create(with plan: BuildPlan, disableSandboxForPluginCommands: Bool, fileSystem: TSCBasic.FileSystem, observabilityScope: ObservabilityScope) throws -> (BuildDescription, LLBuildManifest.BuildManifest) { + static func create(with plan: BuildPlan, disableSandboxForPluginCommands: Bool, fileSystem: Basics.FileSystem, observabilityScope: ObservabilityScope) throws -> (BuildDescription, LLBuildManifest.BuildManifest) { // Generate the llbuild manifest. let llbuild = LLBuildManifestBuilder(plan, disableSandboxForPluginCommands: disableSandboxForPluginCommands, fileSystem: fileSystem, observabilityScope: observabilityScope) let buildManifest = try llbuild.generateManifest(at: plan.buildParameters.llbuildManifest) diff --git a/Sources/Build/BuildOperationBuildSystemDelegateHandler.swift b/Sources/Build/BuildOperationBuildSystemDelegateHandler.swift index 855ab52c330..1443e153e78 100644 --- a/Sources/Build/BuildOperationBuildSystemDelegateHandler.swift +++ b/Sources/Build/BuildOperationBuildSystemDelegateHandler.swift @@ -17,7 +17,15 @@ import LLBuildManifest import PackageModel import SPMBuildCore import SPMLLBuild -import TSCBasic + +import struct TSCBasic.ByteString +import protocol TSCBasic.ByteStreamable +import struct TSCBasic.Format +import class TSCBasic.LocalFileOutputByteStream +import protocol TSCBasic.OutputByteStream +import enum TSCBasic.ProcessEnv +import struct TSCBasic.RegEx +import class TSCBasic.ThreadSafeOutputByteStream import class TSCUtility.IndexStore import class TSCUtility.IndexStoreAPI @@ -29,7 +37,6 @@ typealias LLBuildBuildSystemDelegate = llbuildSwift.BuildSystemDelegate typealias LLBuildBuildSystemDelegate = llbuild.BuildSystemDelegate #endif -typealias Diagnostic = TSCBasic.Diagnostic class CustomLLBuildCommand: SPMLLBuild.ExternalCommand { let context: BuildExecutionContext @@ -62,7 +69,7 @@ final class TestDiscoveryCommand: CustomLLBuildCommand, TestBuildCommand { private func write( tests: [IndexStore.TestCaseClass], forModule module: String, - fileSystem: TSCBasic.FileSystem, + fileSystem: Basics.FileSystem, path: AbsolutePath ) throws { @@ -102,13 +109,13 @@ final class TestDiscoveryCommand: CustomLLBuildCommand, TestBuildCommand { try fileSystem.writeFileContents(path, string: content) } - private func execute(fileSystem: TSCBasic.FileSystem, tool: LLBuildManifest.TestDiscoveryTool) throws { + private func execute(fileSystem: Basics.FileSystem, tool: LLBuildManifest.TestDiscoveryTool) throws { let index = self.context.buildParameters.indexStore let api = try self.context.indexStoreAPI.get() - let store = try IndexStore.open(store: index, api: api) + let store = try IndexStore.open(store: TSCAbsolutePath(index), api: api) // FIXME: We can speed this up by having one llbuild command per object file. - let tests = try store.listTests(in: tool.inputs.map { try AbsolutePath(validating: $0.name) }) + let tests = try store.listTests(in: tool.inputs.map { try TSCAbsolutePath(AbsolutePath(validating: $0.name)) }) let outputs = tool.outputs.compactMap { try? AbsolutePath(validating: $0.name) } let testsByModule = Dictionary(grouping: tests, by: { $0.module.spm_mangledToC99ExtendedIdentifier() }) @@ -194,7 +201,7 @@ final class TestDiscoveryCommand: CustomLLBuildCommand, TestBuildCommand { } final class TestEntryPointCommand: CustomLLBuildCommand, TestBuildCommand { - private func execute(fileSystem: TSCBasic.FileSystem, tool: LLBuildManifest.TestEntryPointTool) throws { + private func execute(fileSystem: Basics.FileSystem, tool: LLBuildManifest.TestEntryPointTool) throws { // Find the inputs, which are the names of the test discovery module(s) let inputs = tool.inputs.compactMap { try? AbsolutePath(validating: $0.name) } let discoveryModuleNames = inputs.map(\.basenameWithoutExt) @@ -365,13 +372,13 @@ public struct BuildDescription: Codable { self.pluginDescriptions = pluginDescriptions } - public func write(fileSystem: TSCBasic.FileSystem, path: AbsolutePath) throws { + public func write(fileSystem: Basics.FileSystem, path: AbsolutePath) throws { let encoder = JSONEncoder.makeWithDefaults() let data = try encoder.encode(self) try fileSystem.writeFileContents(path, bytes: ByteString(data)) } - public static func load(fileSystem: TSCBasic.FileSystem, path: AbsolutePath) throws -> BuildDescription { + public static func load(fileSystem: Basics.FileSystem, path: AbsolutePath) throws -> BuildDescription { let contents: Data = try fileSystem.readFileContents(path) let decoder = JSONDecoder.makeWithDefaults() return try decoder.decode(BuildDescription.self, from: contents) @@ -402,14 +409,14 @@ public final class BuildExecutionContext { /// Optional provider of build error resolution advice. let buildErrorAdviceProvider: BuildErrorAdviceProvider? - let fileSystem: TSCBasic.FileSystem + let fileSystem: Basics.FileSystem let observabilityScope: ObservabilityScope public init( _ buildParameters: BuildParameters, buildDescription: BuildDescription? = nil, - fileSystem: TSCBasic.FileSystem, + fileSystem: Basics.FileSystem, observabilityScope: ObservabilityScope, packageStructureDelegate: PackageStructureDelegate, buildErrorAdviceProvider: BuildErrorAdviceProvider? = nil @@ -450,7 +457,7 @@ public final class BuildExecutionContext { let indexStoreLib = try buildParameters.toolchain.toolchainLibDir .appending("libIndexStore" + ext) #endif - return try .success(IndexStoreAPI(dylib: indexStoreLib)) + return try .success(IndexStoreAPI(dylib: TSCAbsolutePath(indexStoreLib))) } catch { return .failure(error) } diff --git a/Sources/Build/BuildPlan.swift b/Sources/Build/BuildPlan.swift index 3166bf6e67b..786a506fe11 100644 --- a/Sources/Build/BuildPlan.swift +++ b/Sources/Build/BuildPlan.swift @@ -19,7 +19,9 @@ import PackageLoading import PackageModel import SPMBuildCore @_implementationOnly import SwiftDriver -import TSCBasic + +import enum TSCBasic.ProcessEnv +import func TSCBasic.topologicalSort import enum TSCUtility.Diagnostics import var TSCUtility.verbosity @@ -1041,7 +1043,7 @@ extension Basics.Diagnostic { """) } - static func binaryTargetsNotSupported() -> Diagnostic.Message { + static func binaryTargetsNotSupported() -> Self { .error("binary targets are not supported on this platform") } } @@ -1114,3 +1116,4 @@ extension ResolvedProduct { return !isAutomaticLibrary && !isBinaryOnly && !isPlugin } } + diff --git a/Sources/Build/LLBuildManifestBuilder.swift b/Sources/Build/LLBuildManifestBuilder.swift index 85d87eb05e8..b4df96fb4c3 100644 --- a/Sources/Build/LLBuildManifestBuilder.swift +++ b/Sources/Build/LLBuildManifestBuilder.swift @@ -17,7 +17,10 @@ import PackageGraph import PackageModel import SPMBuildCore @_implementationOnly import SwiftDriver -import TSCBasic + +import struct TSCBasic.ByteString +import enum TSCBasic.ProcessEnv +import func TSCBasic.topologicalSort public class LLBuildManifestBuilder { public enum TargetKind { @@ -533,7 +536,7 @@ extension LLBuildManifestBuilder { } dependencyModuleDetailsMap[ModuleDependencyId.swiftPlaceholder(target.c99name)] = SwiftDriver.ExternalTargetModuleDetails( - path: dependencySwiftTargetDescription.moduleOutputPath, + path: TSCAbsolutePath(dependencySwiftTargetDescription.moduleOutputPath), isFramework: false ) try self.collectTargetDependencyModuleDetails( @@ -1084,10 +1087,10 @@ extension TypedVirtualPath { /// Resolve a typed virtual path provided by the Swift driver to /// a node in the build graph. func resolveToNode(fileSystem: FileSystem) throws -> Node { - if let absolutePath = file.absolutePath { + if let absolutePath = (file.absolutePath.flatMap{ AbsolutePath($0) }) { return Node.file(absolutePath) - } else if let relativePath = file.relativePath { - guard let workingDirectory = fileSystem.currentWorkingDirectory else { + } else if let relativePath = (file.relativePath.flatMap{ RelativePath($0) }) { + guard let workingDirectory: AbsolutePath = fileSystem.currentWorkingDirectory else { throw InternalError("unknown working directory") } return Node.file(workingDirectory.appending(relativePath)) diff --git a/Sources/Build/SwiftCompilerOutputParser.swift b/Sources/Build/SwiftCompilerOutputParser.swift index 25fd712d41d..86b118b2be0 100644 --- a/Sources/Build/SwiftCompilerOutputParser.swift +++ b/Sources/Build/SwiftCompilerOutputParser.swift @@ -11,7 +11,6 @@ //===----------------------------------------------------------------------===// import Foundation -import TSCBasic import class TSCUtility.JSONMessageStreamingParser import protocol TSCUtility.JSONMessageStreamingParserDelegate diff --git a/Sources/Commands/PackageTools/APIDiff.swift b/Sources/Commands/PackageTools/APIDiff.swift index 56135990bea..4ce1d92606d 100644 --- a/Sources/Commands/PackageTools/APIDiff.swift +++ b/Sources/Commands/PackageTools/APIDiff.swift @@ -17,7 +17,6 @@ import Dispatch import PackageGraph import PackageModel import SourceControl -import TSCBasic struct DeprecatedAPIDiff: ParsableCommand { static let configuration = CommandConfiguration(commandName: "experimental-api-diff", diff --git a/Sources/Commands/PackageTools/ArchiveSource.swift b/Sources/Commands/PackageTools/ArchiveSource.swift index ff4b74f61a7..c51ee8159d9 100644 --- a/Sources/Commands/PackageTools/ArchiveSource.swift +++ b/Sources/Commands/PackageTools/ArchiveSource.swift @@ -14,7 +14,6 @@ import ArgumentParser import Basics import CoreCommands import SourceControl -import TSCBasic extension SwiftPackageTool { struct ArchiveSource: SwiftCommand { @@ -72,7 +71,7 @@ extension SwiftPackageTool { try repository.archive(to: archivePath) } else { let zipArchiver = ZipArchiver(fileSystem: fileSystem, cancellator: cancellator) - try tsc_await { + try temp_await { zipArchiver.compress(directory: packageDirectory, to: archivePath, completion: $0) } } diff --git a/Sources/Commands/PackageTools/CompletionTool.swift b/Sources/Commands/PackageTools/CompletionTool.swift index 3c6ac029aff..b7423bd29f6 100644 --- a/Sources/Commands/PackageTools/CompletionTool.swift +++ b/Sources/Commands/PackageTools/CompletionTool.swift @@ -12,7 +12,8 @@ import ArgumentParser import CoreCommands -import TSCBasic + +import var TSCBasic.stdoutStream extension SwiftPackageTool { struct CompletionTool: SwiftCommand { diff --git a/Sources/Commands/PackageTools/ComputeChecksum.swift b/Sources/Commands/PackageTools/ComputeChecksum.swift index c7d70229511..192cbaf1bf1 100644 --- a/Sources/Commands/PackageTools/ComputeChecksum.swift +++ b/Sources/Commands/PackageTools/ComputeChecksum.swift @@ -11,10 +11,12 @@ //===----------------------------------------------------------------------===// import ArgumentParser +import Basics import CoreCommands -import TSCBasic import Workspace +import struct TSCBasic.SHA256 + struct ComputeChecksum: SwiftCommand { static let configuration = CommandConfiguration( abstract: "Compute the checksum for a binary artifact.") diff --git a/Sources/Commands/PackageTools/Config.swift b/Sources/Commands/PackageTools/Config.swift index aa7b024318a..f9ebed2174b 100644 --- a/Sources/Commands/PackageTools/Config.swift +++ b/Sources/Commands/PackageTools/Config.swift @@ -13,9 +13,10 @@ import ArgumentParser import Basics import CoreCommands -import TSCBasic import Workspace +import var TSCBasic.stderrStream + extension SwiftPackageTool { struct Config: ParsableCommand { static let configuration = CommandConfiguration( diff --git a/Sources/Commands/PackageTools/Describe.swift b/Sources/Commands/PackageTools/Describe.swift index 8d5c364f98b..8b3b20f6e60 100644 --- a/Sources/Commands/PackageTools/Describe.swift +++ b/Sources/Commands/PackageTools/Describe.swift @@ -11,10 +11,12 @@ //===----------------------------------------------------------------------===// import ArgumentParser +import Basics import CoreCommands import Foundation import PackageModel -import TSCBasic + +import struct TSCBasic.StringError extension SwiftPackageTool { struct Describe: SwiftCommand { @@ -34,7 +36,7 @@ extension SwiftPackageTool { throw StringError("unknown package") } - let package = try tsc_await { + let package = try temp_await { workspace.loadRootPackage( at: packagePath, observabilityScope: swiftTool.observabilityScope, diff --git a/Sources/Commands/PackageTools/EditCommands.swift b/Sources/Commands/PackageTools/EditCommands.swift index db186a49699..044368ce5c3 100644 --- a/Sources/Commands/PackageTools/EditCommands.swift +++ b/Sources/Commands/PackageTools/EditCommands.swift @@ -11,9 +11,9 @@ //===----------------------------------------------------------------------===// import ArgumentParser +import Basics import CoreCommands import SourceControl -import TSCBasic extension SwiftPackageTool { struct Edit: SwiftCommand { diff --git a/Sources/Commands/PackageTools/Format.swift b/Sources/Commands/PackageTools/Format.swift index 7d9d6437e49..46b5ba962b2 100644 --- a/Sources/Commands/PackageTools/Format.swift +++ b/Sources/Commands/PackageTools/Format.swift @@ -11,10 +11,14 @@ //===----------------------------------------------------------------------===// import ArgumentParser +import Basics import CoreCommands import PackageModel -import TSCBasic -import TSCUtility + +import class TSCBasic.Process +import enum TSCBasic.ProcessEnv + +import enum TSCUtility.Diagnostics extension SwiftPackageTool { struct Format: SwiftCommand { @@ -32,7 +36,7 @@ extension SwiftPackageTool { // Look for swift-format binary. // FIXME: This should be moved to user toolchain. let swiftFormatInEnv = lookupExecutablePath(filename: ProcessEnv.vars["SWIFT_FORMAT"]) - guard let swiftFormat = swiftFormatInEnv ?? Process.findExecutable("swift-format") else { + guard let swiftFormat = swiftFormatInEnv ?? Process.findExecutable("swift-format").flatMap(AbsolutePath.init) else { swiftTool.observabilityScope.emit(error: "Could not find swift-format in PATH or SWIFT_FORMAT") throw TSCUtility.Diagnostics.fatalError } @@ -44,7 +48,7 @@ extension SwiftPackageTool { throw StringError("unknown package") } - let package = try tsc_await { + let package = try temp_await { workspace.loadRootPackage( at: packagePath, observabilityScope: swiftTool.observabilityScope, diff --git a/Sources/Commands/PackageTools/Learn.swift b/Sources/Commands/PackageTools/Learn.swift index 2ecf75eeee3..ecdab48a608 100644 --- a/Sources/Commands/PackageTools/Learn.swift +++ b/Sources/Commands/PackageTools/Learn.swift @@ -11,10 +11,10 @@ //===----------------------------------------------------------------------===// import ArgumentParser +import Basics import CoreCommands import PackageGraph import PackageModel -import TSCBasic extension SwiftPackageTool { struct Learn: SwiftCommand { diff --git a/Sources/Commands/PackageTools/PluginCommand.swift b/Sources/Commands/PackageTools/PluginCommand.swift index d31f475e4f9..5dd33c5e339 100644 --- a/Sources/Commands/PackageTools/PluginCommand.swift +++ b/Sources/Commands/PackageTools/PluginCommand.swift @@ -16,7 +16,8 @@ import CoreCommands import Dispatch import PackageGraph import PackageModel -import TSCBasic + +import enum TSCBasic.ProcessEnv struct PluginCommand: SwiftCommand { static let configuration = CommandConfiguration( @@ -271,7 +272,7 @@ struct PluginCommand: SwiftCommand { // Run the command plugin. let buildEnvironment = try swiftTool.buildParameters().buildEnvironment - let _ = try tsc_await { plugin.invoke( + let _ = try temp_await { plugin.invoke( action: .performCommand(package: package, arguments: arguments), buildEnvironment: buildEnvironment, scriptRunner: pluginScriptRunner, diff --git a/Sources/Commands/PackageTools/ShowDependencies.swift b/Sources/Commands/PackageTools/ShowDependencies.swift index b71490c8b8c..7d0610cad8c 100644 --- a/Sources/Commands/PackageTools/ShowDependencies.swift +++ b/Sources/Commands/PackageTools/ShowDependencies.swift @@ -12,9 +12,13 @@ import ArgumentParser +import Basics import CoreCommands import PackageGraph -import TSCBasic + +import class TSCBasic.LocalFileOutputByteStream +import protocol TSCBasic.OutputByteStream +import var TSCBasic.stdoutStream extension SwiftPackageTool { struct ShowDependencies: SwiftCommand { diff --git a/Sources/Commands/PackageTools/SwiftPackageTool.swift b/Sources/Commands/PackageTools/SwiftPackageTool.swift index d250f663e4d..41cdb7dfdb9 100644 --- a/Sources/Commands/PackageTools/SwiftPackageTool.swift +++ b/Sources/Commands/PackageTools/SwiftPackageTool.swift @@ -19,7 +19,6 @@ import PackageLoading import PackageModel import SourceControl import SPMBuildCore -import TSCBasic import Workspace import XCBuildSupport diff --git a/Sources/Commands/Snippets/CardStack.swift b/Sources/Commands/Snippets/CardStack.swift index 538c9b32ec0..7d2f3cb52d7 100644 --- a/Sources/Commands/Snippets/CardStack.swift +++ b/Sources/Commands/Snippets/CardStack.swift @@ -14,7 +14,9 @@ import Basics import CoreCommands import PackageGraph import PackageModel -import TSCBasic + +import var TSCBasic.stdoutStream +import class TSCBasic.TerminalController fileprivate extension TerminalController { func clearScreen() { diff --git a/Sources/Commands/Snippets/Cards/SnippetCard.swift b/Sources/Commands/Snippets/Cards/SnippetCard.swift index 378b542ff16..a1ef7b53666 100644 --- a/Sources/Commands/Snippets/Cards/SnippetCard.swift +++ b/Sources/Commands/Snippets/Cards/SnippetCard.swift @@ -10,9 +10,12 @@ // //===----------------------------------------------------------------------===// +import Basics import CoreCommands import PackageModel -import TSCBasic + +import enum TSCBasic.ProcessEnv +import func TSCBasic.exec /// A card displaying a ``Snippet`` at the terminal. struct SnippetCard: Card { diff --git a/Sources/Commands/SwiftBuildTool.swift b/Sources/Commands/SwiftBuildTool.swift index 7560bca9cbb..abf5468aef3 100644 --- a/Sources/Commands/SwiftBuildTool.swift +++ b/Sources/Commands/SwiftBuildTool.swift @@ -16,9 +16,11 @@ import Build import CoreCommands import PackageGraph import SPMBuildCore -import TSCBasic import XCBuildSupport +import class TSCBasic.Process +import var TSCBasic.stdoutStream + import enum TSCUtility.Diagnostics import func TSCUtility.getClangVersion import struct TSCUtility.Version diff --git a/Sources/Commands/SwiftRunTool.swift b/Sources/Commands/SwiftRunTool.swift index 345e0482aa1..642d56b6f9a 100644 --- a/Sources/Commands/SwiftRunTool.swift +++ b/Sources/Commands/SwiftRunTool.swift @@ -16,7 +16,9 @@ import CoreCommands import Foundation import PackageGraph import PackageModel -import TSCBasic + +import enum TSCBasic.ProcessEnv +import func TSCBasic.exec import enum TSCUtility.Diagnostics diff --git a/Sources/Commands/SwiftTestTool.swift b/Sources/Commands/SwiftTestTool.swift index 04c9872f707..e350840faa6 100644 --- a/Sources/Commands/SwiftTestTool.swift +++ b/Sources/Commands/SwiftTestTool.swift @@ -19,10 +19,17 @@ import class Foundation.ProcessInfo import PackageGraph import PackageModel import SPMBuildCore -import TSCBasic import func TSCLibc.exit import Workspace +import struct TSCBasic.ByteString +import enum TSCBasic.JSON +import class TSCBasic.Process +import enum TSCBasic.ProcessEnv +import var TSCBasic.stdoutStream +import class TSCBasic.SynchronizedQueue +import class TSCBasic.Thread + import class TSCUtility.NinjaProgressAnimation import class TSCUtility.PercentProgressAnimation import protocol TSCUtility.ProgressAnimationProtocol diff --git a/Sources/Commands/ToolWorkspaceDelegate.swift b/Sources/Commands/ToolWorkspaceDelegate.swift index adcf56eb44c..43404b76d92 100644 --- a/Sources/Commands/ToolWorkspaceDelegate.swift +++ b/Sources/Commands/ToolWorkspaceDelegate.swift @@ -21,7 +21,6 @@ import PackageModel import SPMBuildCore import Workspace -import struct TSCBasic.AbsolutePath import protocol TSCBasic.OutputByteStream import struct TSCUtility.Version diff --git a/Sources/Commands/Utilities/APIDigester.swift b/Sources/Commands/Utilities/APIDigester.swift index 2ca82a63c13..6b67692418f 100644 --- a/Sources/Commands/Utilities/APIDigester.swift +++ b/Sources/Commands/Utilities/APIDigester.swift @@ -13,8 +13,6 @@ import Dispatch import Foundation -import TSCBasic - import SPMBuildCore import Basics import CoreCommands @@ -23,6 +21,11 @@ import PackageModel import SourceControl import Workspace +import protocol TSCBasic.DiagnosticLocation +import class TSCBasic.Process +import struct TSCBasic.ProcessResult +import func TSCBasic.withTemporaryFile + import enum TSCUtility.Diagnostics import struct TSCUtility.SerializedDiagnostics import var TSCUtility.verbosity diff --git a/Sources/Commands/Utilities/DOTManifestSerializer.swift b/Sources/Commands/Utilities/DOTManifestSerializer.swift index 144a5234e2b..dc35f75e8c6 100644 --- a/Sources/Commands/Utilities/DOTManifestSerializer.swift +++ b/Sources/Commands/Utilities/DOTManifestSerializer.swift @@ -11,7 +11,8 @@ //===----------------------------------------------------------------------===// import LLBuildManifest -import TSCBasic + +import protocol TSCBasic.OutputByteStream /// Serializes an LLBuildManifest graph to a .dot file public struct DOTManifestSerializer { diff --git a/Sources/Commands/Utilities/DependenciesSerializer.swift b/Sources/Commands/Utilities/DependenciesSerializer.swift index 00ffabe8d4b..3a036bec15f 100644 --- a/Sources/Commands/Utilities/DependenciesSerializer.swift +++ b/Sources/Commands/Utilities/DependenciesSerializer.swift @@ -10,10 +10,12 @@ // //===----------------------------------------------------------------------===// -import TSCBasic import PackageModel import PackageGraph +import enum TSCBasic.JSON +import protocol TSCBasic.OutputByteStream + protocol DependenciesDumper { func dump(dependenciesOf: ResolvedPackage, on: OutputByteStream) } diff --git a/Sources/Commands/Utilities/DescribedPackage.swift b/Sources/Commands/Utilities/DescribedPackage.swift index b1e62c1cb85..3c7609f732a 100644 --- a/Sources/Commands/Utilities/DescribedPackage.swift +++ b/Sources/Commands/Utilities/DescribedPackage.swift @@ -10,10 +10,14 @@ // //===----------------------------------------------------------------------===// -import TSCBasic +import Basics import PackageModel import Foundation +import class TSCBasic.BufferedOutputByteStream +import protocol TSCBasic.OutputByteStream +import func TSCBasic.transitiveClosure + /// Represents a package for the sole purpose of generating a description. struct DescribedPackage: Encodable { let name: String // for backwards compatibility diff --git a/Sources/Commands/Utilities/MultiRootSupport.swift b/Sources/Commands/Utilities/MultiRootSupport.swift index fe9fc1f9934..7ee468a81f5 100644 --- a/Sources/Commands/Utilities/MultiRootSupport.swift +++ b/Sources/Commands/Utilities/MultiRootSupport.swift @@ -17,7 +17,6 @@ import Foundation import FoundationXML #endif import class PackageModel.Manifest -import TSCBasic /// A bare minimum loader for Xcode workspaces. /// diff --git a/Sources/Commands/Utilities/PluginDelegate.swift b/Sources/Commands/Utilities/PluginDelegate.swift index 1042a12b12f..35422835db3 100644 --- a/Sources/Commands/Utilities/PluginDelegate.swift +++ b/Sources/Commands/Utilities/PluginDelegate.swift @@ -15,7 +15,9 @@ import CoreCommands import Foundation import PackageModel import SPMBuildCore -import TSCBasic + +import class TSCBasic.BufferedOutputByteStream +import class TSCBasic.Process final class PluginDelegate: PluginInvocationDelegate { let swiftTool: SwiftTool diff --git a/Sources/Commands/Utilities/SymbolGraphExtract.swift b/Sources/Commands/Utilities/SymbolGraphExtract.swift index 2aecdc3bbfe..3d501d8bb54 100644 --- a/Sources/Commands/Utilities/SymbolGraphExtract.swift +++ b/Sources/Commands/Utilities/SymbolGraphExtract.swift @@ -12,11 +12,12 @@ import ArgumentParser import Basics +@_implementationOnly import DriverSupport import PackageGraph import PackageModel import SPMBuildCore -import TSCBasic -@_implementationOnly import DriverSupport + +import class TSCBasic.Process /// A wrapper for swift-symbolgraph-extract tool. public struct SymbolGraphExtract { diff --git a/Sources/Commands/Utilities/TestingSupport.swift b/Sources/Commands/Utilities/TestingSupport.swift index 75bff1ddc94..7a662750c47 100644 --- a/Sources/Commands/Utilities/TestingSupport.swift +++ b/Sources/Commands/Utilities/TestingSupport.swift @@ -14,9 +14,12 @@ import Basics import CoreCommands import PackageModel import SPMBuildCore -import TSCBasic import Workspace +import class TSCBasic.Process +import var TSCBasic.stderrStream +import var TSCBasic.stdoutStream +import func TSCBasic.withTemporaryFile /// Internal helper functionality for the SwiftTestTool command and for the /// plugin support. @@ -91,7 +94,7 @@ enum TestingSupport { try TSCBasic.Process.checkNonZeroExit(arguments: args, environment: env) // Read the temporary file's content. - return try swiftTool.fileSystem.readFileContents(tempFile.path) + return try swiftTool.fileSystem.readFileContents(AbsolutePath(tempFile.path)) } #else let env = try Self.constructTestEnvironment( diff --git a/Sources/CoreCommands/Options.swift b/Sources/CoreCommands/Options.swift index c07585008c9..814a2b07e30 100644 --- a/Sources/CoreCommands/Options.swift +++ b/Sources/CoreCommands/Options.swift @@ -12,6 +12,8 @@ import ArgumentParser +import var Basics.localFileSystem +import struct Basics.AbsolutePath import struct Basics.Triple import struct Foundation.URL @@ -24,8 +26,6 @@ import enum PackageModel.Sanitizer import struct SPMBuildCore.BuildSystemProvider -import struct TSCBasic.AbsolutePath -import var TSCBasic.localFileSystem import struct TSCBasic.StringError import struct TSCUtility.Version diff --git a/Sources/CoreCommands/SwiftTool.swift b/Sources/CoreCommands/SwiftTool.swift index ab833655fa3..8edb55ed785 100644 --- a/Sources/CoreCommands/SwiftTool.swift +++ b/Sources/CoreCommands/SwiftTool.swift @@ -30,10 +30,7 @@ import Darwin import Glibc #endif -import struct TSCBasic.AbsolutePath import func TSCBasic.exec -import protocol TSCBasic.FileSystem -import var TSCBasic.localFileSystem import protocol TSCBasic.OutputByteStream import class TSCBasic.Process import enum TSCBasic.ProcessEnv diff --git a/Sources/CoreCommands/SwiftToolObservabilityHandler.swift b/Sources/CoreCommands/SwiftToolObservabilityHandler.swift index a40786fb1a3..2c82fe21912 100644 --- a/Sources/CoreCommands/SwiftToolObservabilityHandler.swift +++ b/Sources/CoreCommands/SwiftToolObservabilityHandler.swift @@ -13,8 +13,14 @@ import Basics import Dispatch -import TSCBasic -import TSCUtility + +import protocol TSCBasic.OutputByteStream +import class TSCBasic.TerminalController +import class TSCBasic.ThreadSafeOutputByteStream + +import class TSCUtility.MultiLineNinjaProgressAnimation +import class TSCUtility.NinjaProgressAnimation +import protocol TSCUtility.ProgressAnimationProtocol public struct SwiftToolObservabilityHandler: ObservabilityHandlerProvider { private let outputHandler: OutputHandler diff --git a/Sources/DriverSupport/DriverSupportUtils.swift b/Sources/DriverSupport/DriverSupportUtils.swift index c9f0344be18..238c703d8bf 100644 --- a/Sources/DriverSupport/DriverSupportUtils.swift +++ b/Sources/DriverSupport/DriverSupportUtils.swift @@ -13,7 +13,6 @@ import Basics import PackageModel import SwiftDriver -import protocol TSCBasic.FileSystem import class TSCBasic.Process import enum TSCBasic.ProcessEnv import struct TSCBasic.ProcessResult @@ -43,7 +42,7 @@ public class DriverSupport { let driver = try Driver( args: ["swiftc"], executor: executor, - compilerExecutableDir: toolchain.swiftCompilerPath.parentDirectory + compilerExecutableDir: TSCAbsolutePath(toolchain.swiftCompilerPath.parentDirectory) ) let supportedFlagSet = Set(driver.supportedFrontendFlags.map { $0.trimmingCharacters(in: ["-"]) }) flagsMap.put([swiftcPathString + "-frontend": supportedFlagSet]) diff --git a/Sources/DriverSupport/SPMSwiftDriverExecutor.swift b/Sources/DriverSupport/SPMSwiftDriverExecutor.swift index 6e9f334d1aa..c611c6eec8e 100644 --- a/Sources/DriverSupport/SPMSwiftDriverExecutor.swift +++ b/Sources/DriverSupport/SPMSwiftDriverExecutor.swift @@ -13,7 +13,6 @@ import Basics import SwiftDriver -import protocol TSCBasic.FileSystem import class TSCBasic.Process import struct TSCBasic.ProcessResult diff --git a/Sources/LLBuildManifest/BuildManifest.swift b/Sources/LLBuildManifest/BuildManifest.swift index 635c3371887..c2a2826db08 100644 --- a/Sources/LLBuildManifest/BuildManifest.swift +++ b/Sources/LLBuildManifest/BuildManifest.swift @@ -11,7 +11,6 @@ //===----------------------------------------------------------------------===// import Basics -import struct TSCBasic.AbsolutePath public struct BuildManifest { public typealias TargetName = String diff --git a/Sources/LLBuildManifest/ManifestWriter.swift b/Sources/LLBuildManifest/ManifestWriter.swift index 17a91cff611..ab824d59395 100644 --- a/Sources/LLBuildManifest/ManifestWriter.swift +++ b/Sources/LLBuildManifest/ManifestWriter.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// -import TSCBasic +import Basics +import protocol TSCBasic.ByteStreamable +import struct TSCBasic.Format +import protocol TSCBasic.OutputByteStream +import class TSCBasic.BufferedOutputByteStream public struct ManifestWriter { let fileSystem: FileSystem diff --git a/Sources/LLBuildManifest/Node.swift b/Sources/LLBuildManifest/Node.swift index 11b607e7a18..9800cb34e64 100644 --- a/Sources/LLBuildManifest/Node.swift +++ b/Sources/LLBuildManifest/Node.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import TSCBasic +import Basics public struct Node: Hashable, Codable { public enum Kind: String, Hashable, Codable { diff --git a/Sources/LLBuildManifest/Tools.swift b/Sources/LLBuildManifest/Tools.swift index f3e3b4a904d..fa73b001c7d 100644 --- a/Sources/LLBuildManifest/Tools.swift +++ b/Sources/LLBuildManifest/Tools.swift @@ -12,7 +12,6 @@ import Basics import class Foundation.ProcessInfo -import TSCBasic public protocol ToolProtocol: Codable { /// The name of the tool. diff --git a/Sources/PackageCollections/Model/Collection.swift b/Sources/PackageCollections/Model/Collection.swift index 4455678181e..7d335ce6924 100644 --- a/Sources/PackageCollections/Model/Collection.swift +++ b/Sources/PackageCollections/Model/Collection.swift @@ -10,12 +10,11 @@ // //===----------------------------------------------------------------------===// +import Basics import struct Foundation.Date import struct Foundation.URL - import PackageModel import SourceControl -import TSCBasic public enum PackageCollectionsModel {} diff --git a/Sources/PackageCollections/PackageCollections+CertificatePolicy.swift b/Sources/PackageCollections/PackageCollections+CertificatePolicy.swift index 799f4a14688..e92fda539d5 100644 --- a/Sources/PackageCollections/PackageCollections+CertificatePolicy.swift +++ b/Sources/PackageCollections/PackageCollections+CertificatePolicy.swift @@ -13,7 +13,6 @@ import struct Foundation.URL import PackageCollectionsSigning -import TSCBasic /// Configuration in this file is intended for package collection sources to define certificate policies /// that are more restrictive. For example, a source may want to require that all their package diff --git a/Sources/PackageCollections/PackageCollections+Configuration.swift b/Sources/PackageCollections/PackageCollections+Configuration.swift index fde46c34264..17deee1f5d1 100644 --- a/Sources/PackageCollections/PackageCollections+Configuration.swift +++ b/Sources/PackageCollections/PackageCollections+Configuration.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import TSCBasic +import Basics // TODO: how do we read default config values? ENV variables? user settings? extension PackageCollections { diff --git a/Sources/PackageCollections/PackageCollections+Storage.swift b/Sources/PackageCollections/PackageCollections+Storage.swift index 958ca09c3ea..b238c2c8dd3 100644 --- a/Sources/PackageCollections/PackageCollections+Storage.swift +++ b/Sources/PackageCollections/PackageCollections+Storage.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import TSCBasic +import protocol TSCBasic.Closable extension PackageCollections { struct Storage: Closable { diff --git a/Sources/PackageCollections/PackageCollections+Validation.swift b/Sources/PackageCollections/PackageCollections+Validation.swift index bfd48e75984..fb088a480b4 100644 --- a/Sources/PackageCollections/PackageCollections+Validation.swift +++ b/Sources/PackageCollections/PackageCollections+Validation.swift @@ -10,8 +10,6 @@ // //===----------------------------------------------------------------------===// -import TSCBasic - import Basics import PackageCollectionsModel import PackageModel diff --git a/Sources/PackageCollections/PackageCollections.swift b/Sources/PackageCollections/PackageCollections.swift index 4caa8810c13..f8e9fd90fad 100644 --- a/Sources/PackageCollections/PackageCollections.swift +++ b/Sources/PackageCollections/PackageCollections.swift @@ -12,7 +12,8 @@ import Basics import PackageModel -import TSCBasic + +import protocol TSCBasic.Closable // TODO: is there a better name? this conflicts with the module name which is okay in this case but not ideal in Swift public struct PackageCollections: PackageCollectionsProtocol, Closable { diff --git a/Sources/PackageCollections/PackageIndex+Configuration.swift b/Sources/PackageCollections/PackageIndex+Configuration.swift index a9fd236e02e..80083ff9fc5 100644 --- a/Sources/PackageCollections/PackageIndex+Configuration.swift +++ b/Sources/PackageCollections/PackageIndex+Configuration.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// +import Basics import Foundation -import TSCBasic public struct PackageIndexConfiguration: Equatable { public var url: URL? diff --git a/Sources/PackageCollections/PackageIndex.swift b/Sources/PackageCollections/PackageIndex.swift index 294a5164d1f..77e801a05ee 100644 --- a/Sources/PackageCollections/PackageIndex.swift +++ b/Sources/PackageCollections/PackageIndex.swift @@ -14,7 +14,8 @@ import Basics import Dispatch import Foundation import PackageModel -import TSCBasic + +import protocol TSCBasic.Closable struct PackageIndex: PackageIndexProtocol, Closable { private let configuration: PackageIndexConfiguration diff --git a/Sources/PackageCollections/PackageIndexAndCollections.swift b/Sources/PackageCollections/PackageIndexAndCollections.swift index 6b7a4691920..a8e1789eded 100644 --- a/Sources/PackageCollections/PackageIndexAndCollections.swift +++ b/Sources/PackageCollections/PackageIndexAndCollections.swift @@ -14,7 +14,8 @@ import Basics import Dispatch import struct Foundation.URL import PackageModel -import TSCBasic + +import protocol TSCBasic.Closable public struct PackageIndexAndCollections: Closable { private let index: PackageIndexProtocol diff --git a/Sources/PackageCollections/Providers/GitHubPackageMetadataProvider.swift b/Sources/PackageCollections/Providers/GitHubPackageMetadataProvider.swift index 592f2f1b493..c7219d8aa9a 100644 --- a/Sources/PackageCollections/Providers/GitHubPackageMetadataProvider.swift +++ b/Sources/PackageCollections/Providers/GitHubPackageMetadataProvider.swift @@ -18,7 +18,8 @@ import struct Foundation.NSRange import class Foundation.NSRegularExpression import struct Foundation.URL import PackageModel -import TSCBasic + +import protocol TSCBasic.Closable import struct TSCUtility.Version diff --git a/Sources/PackageCollections/Providers/JSONPackageCollectionProvider.swift b/Sources/PackageCollections/Providers/JSONPackageCollectionProvider.swift index b2aafbce3b3..6d8f4f3d803 100644 --- a/Sources/PackageCollections/Providers/JSONPackageCollectionProvider.swift +++ b/Sources/PackageCollections/Providers/JSONPackageCollectionProvider.swift @@ -22,7 +22,6 @@ import PackageCollectionsModel import PackageCollectionsSigning import PackageModel import SourceControl -import TSCBasic import struct TSCUtility.Version diff --git a/Sources/PackageCollections/Providers/PackageMetadataProvider.swift b/Sources/PackageCollections/Providers/PackageMetadataProvider.swift index 19706e160ff..f4d04a2ce5b 100644 --- a/Sources/PackageCollections/Providers/PackageMetadataProvider.swift +++ b/Sources/PackageCollections/Providers/PackageMetadataProvider.swift @@ -14,7 +14,6 @@ import struct Foundation.Date import struct Foundation.URL import PackageModel -import TSCBasic import struct TSCUtility.Version diff --git a/Sources/PackageCollections/Storage/FilePackageCollectionsSourcesStorage.swift b/Sources/PackageCollections/Storage/FilePackageCollectionsSourcesStorage.swift index 1f045c9295c..7c940a17201 100644 --- a/Sources/PackageCollections/Storage/FilePackageCollectionsSourcesStorage.swift +++ b/Sources/PackageCollections/Storage/FilePackageCollectionsSourcesStorage.swift @@ -16,7 +16,6 @@ import struct Foundation.Data import class Foundation.JSONDecoder import class Foundation.JSONEncoder import struct Foundation.URL -import TSCBasic struct FilePackageCollectionsSourcesStorage: PackageCollectionsSourcesStorage { let fileSystem: FileSystem diff --git a/Sources/PackageCollections/Storage/SQLitePackageCollectionsStorage.swift b/Sources/PackageCollections/Storage/SQLitePackageCollectionsStorage.swift index 252d86d5cfe..4a921700908 100644 --- a/Sources/PackageCollections/Storage/SQLitePackageCollectionsStorage.swift +++ b/Sources/PackageCollections/Storage/SQLitePackageCollectionsStorage.swift @@ -18,7 +18,9 @@ import class Foundation.JSONEncoder import class Foundation.NSLock import struct Foundation.URL import PackageModel -import TSCBasic + +import protocol TSCBasic.Closable +import class TSCBasic.InMemoryFileSystem final class SQLitePackageCollectionsStorage: PackageCollectionsStorage, Closable { private static let packageCollectionsTableName = "package_collections" diff --git a/Sources/PackageCollectionsSigning/PackageCollectionSigning.swift b/Sources/PackageCollectionsSigning/PackageCollectionSigning.swift index 1a061a3e0e2..f20e901a819 100644 --- a/Sources/PackageCollectionsSigning/PackageCollectionSigning.swift +++ b/Sources/PackageCollectionsSigning/PackageCollectionSigning.swift @@ -10,12 +10,11 @@ // //===----------------------------------------------------------------------===// -import Dispatch -import Foundation - @_implementationOnly import _CryptoExtras import Basics @_implementationOnly import Crypto +import Dispatch +import Foundation import PackageCollectionsModel @_implementationOnly import X509 diff --git a/Sources/PackageCollectionsTool/SwiftPackageCollectionsTool.swift b/Sources/PackageCollectionsTool/SwiftPackageCollectionsTool.swift index 3312fadcb43..2be6a168a05 100644 --- a/Sources/PackageCollectionsTool/SwiftPackageCollectionsTool.swift +++ b/Sources/PackageCollectionsTool/SwiftPackageCollectionsTool.swift @@ -17,7 +17,6 @@ import CoreCommands import Foundation import PackageCollections import PackageModel -import TSCBasic import struct TSCUtility.Version @@ -88,7 +87,7 @@ public struct SwiftPackageCollectionsTool: ParsableCommand { func run(_ swiftTool: SwiftTool) throws { let collections = try with(swiftTool) { collections in - try tsc_await { collections.listCollections(identifiers: nil, callback: $0) } + try temp_await { collections.listCollections(identifiers: nil, callback: $0) } } if self.jsonOptions.json { @@ -109,7 +108,7 @@ public struct SwiftPackageCollectionsTool: ParsableCommand { func run(_ swiftTool: SwiftTool) throws { let collections = try with(swiftTool) { collections in - try tsc_await { collections.refreshCollections(callback: $0) } + try temp_await { collections.refreshCollections(callback: $0) } } print("Refreshed \(collections.count) configured package collection\(collections.count == 1 ? "" : "s").") } @@ -140,7 +139,7 @@ public struct SwiftPackageCollectionsTool: ParsableCommand { let collection: PackageCollectionsModel.Collection = try with(swiftTool) { collections in do { let userTrusted = self.trustUnsigned - return try tsc_await { + return try temp_await { collections.addCollection( source, order: order, @@ -177,8 +176,8 @@ public struct SwiftPackageCollectionsTool: ParsableCommand { let source = PackageCollectionsModel.CollectionSource(type: .json, url: collectionURL) try with(swiftTool) { collections in - let collection = try tsc_await { collections.getCollection(source, callback: $0) } - _ = try tsc_await { collections.removeCollection(source, callback: $0) } + let collection = try temp_await { collections.getCollection(source, callback: $0) } + _ = try temp_await { collections.removeCollection(source, callback: $0) } print("Removed \"\(collection.name)\" from your package collections.") } } @@ -210,7 +209,7 @@ public struct SwiftPackageCollectionsTool: ParsableCommand { try with(swiftTool) { collections in switch searchMethod { case .keywords: - let results = try tsc_await { collections.findPackages(searchQuery, collections: nil, callback: $0) } + let results = try temp_await { collections.findPackages(searchQuery, collections: nil, callback: $0) } if jsonOptions.json { try JSONEncoder.makeWithDefaults().print(results.items) @@ -221,7 +220,7 @@ public struct SwiftPackageCollectionsTool: ParsableCommand { } case .module: - let results = try tsc_await { collections.findTargets(searchQuery, searchType: .exactMatch, collections: nil, callback: $0) } + let results = try temp_await { collections.findTargets(searchQuery, searchType: .exactMatch, collections: nil, callback: $0) } let packages = Set(results.items.flatMap { $0.packages }) if jsonOptions.json { @@ -293,7 +292,7 @@ public struct SwiftPackageCollectionsTool: ParsableCommand { let identity = PackageIdentity(urlString: self.packageURL) do { // assume URL is for a package in an imported collection - let result = try tsc_await { collections.getPackageMetadata(identity: identity, location: self.packageURL, callback: $0) } + let result = try temp_await { collections.getPackageMetadata(identity: identity, location: self.packageURL, callback: $0) } if let versionString = version { guard let version = TSCUtility.Version(versionString), let result = result.package.versions.first(where: { $0.version == version }), let printedResult = printVersion(result) else { @@ -334,7 +333,7 @@ public struct SwiftPackageCollectionsTool: ParsableCommand { do { let source = PackageCollectionsModel.CollectionSource(type: .json, url: collectionURL, skipSignatureCheck: self.skipSignatureCheck) - let collection = try tsc_await { collections.getCollection(source, callback: $0) } + let collection = try temp_await { collections.getCollection(source, callback: $0) } let description = optionalRow("Description", collection.overview) let keywords = optionalRow("Keywords", collection.keywords?.joined(separator: ", ")) diff --git a/Sources/PackageFingerprint/FilePackageFingerprintStorage.swift b/Sources/PackageFingerprint/FilePackageFingerprintStorage.swift index be7364b0887..918a6594b66 100644 --- a/Sources/PackageFingerprint/FilePackageFingerprintStorage.swift +++ b/Sources/PackageFingerprint/FilePackageFingerprintStorage.swift @@ -14,7 +14,6 @@ import Basics import Dispatch import Foundation import PackageModel -import TSCBasic import struct TSCUtility.Version diff --git a/Sources/PackageGraph/DependencyMirrors.swift b/Sources/PackageGraph/DependencyMirrors.swift index 1f7fa08c5d2..51780e3a015 100644 --- a/Sources/PackageGraph/DependencyMirrors.swift +++ b/Sources/PackageGraph/DependencyMirrors.swift @@ -10,10 +10,12 @@ // //===----------------------------------------------------------------------===// +import Basics import Foundation import OrderedCollections import PackageModel -import TSCBasic + +import struct TSCBasic.StringError /// A collection of dependency mirrors. public final class DependencyMirrors: Equatable { diff --git a/Sources/PackageGraph/DependencyResolutionNode.swift b/Sources/PackageGraph/DependencyResolutionNode.swift index ff7ec20c638..9b643ef915f 100644 --- a/Sources/PackageGraph/DependencyResolutionNode.swift +++ b/Sources/PackageGraph/DependencyResolutionNode.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// -import TSCBasic import PackageModel + import struct TSCUtility.Version /// A node in the dependency resolution graph. diff --git a/Sources/PackageGraph/DependencyResolver.swift b/Sources/PackageGraph/DependencyResolver.swift index 45795551123..e44693b345b 100644 --- a/Sources/PackageGraph/DependencyResolver.swift +++ b/Sources/PackageGraph/DependencyResolver.swift @@ -13,7 +13,6 @@ import Basics import Dispatch import PackageModel -import TSCBasic import struct TSCUtility.Version diff --git a/Sources/PackageGraph/GraphLoadingNode.swift b/Sources/PackageGraph/GraphLoadingNode.swift index ddd2eeecbea..453f1d8080e 100644 --- a/Sources/PackageGraph/GraphLoadingNode.swift +++ b/Sources/PackageGraph/GraphLoadingNode.swift @@ -10,9 +10,9 @@ // //===----------------------------------------------------------------------===// +import Basics import PackageLoading import PackageModel -import TSCBasic /// A node used while loading the packages in a resolved graph. /// diff --git a/Sources/PackageGraph/PackageContainer.swift b/Sources/PackageGraph/PackageContainer.swift index be23a97601d..39b81309a61 100644 --- a/Sources/PackageGraph/PackageContainer.swift +++ b/Sources/PackageGraph/PackageContainer.swift @@ -13,8 +13,7 @@ import Basics import Dispatch import PackageModel -import struct TSCBasic.AbsolutePath -import protocol TSCBasic.FileSystem + import struct TSCUtility.Version /// A container of packages. diff --git a/Sources/PackageGraph/PackageGraph+Loading.swift b/Sources/PackageGraph/PackageGraph+Loading.swift index 0a35030a417..c3cb849a173 100644 --- a/Sources/PackageGraph/PackageGraph+Loading.swift +++ b/Sources/PackageGraph/PackageGraph+Loading.swift @@ -14,7 +14,8 @@ import Basics import OrderedCollections import PackageLoading import PackageModel -import TSCBasic + +import func TSCBasic.topologicalSort extension PackageGraph { diff --git a/Sources/PackageGraph/PackageGraph.swift b/Sources/PackageGraph/PackageGraph.swift index e571e1c3f16..066f53206c7 100644 --- a/Sources/PackageGraph/PackageGraph.swift +++ b/Sources/PackageGraph/PackageGraph.swift @@ -12,7 +12,8 @@ import PackageLoading import PackageModel -import TSCBasic + +import func TSCBasic.topologicalSort enum PackageGraphError: Swift.Error { /// Indicates a non-root package with no targets. diff --git a/Sources/PackageGraph/PackageGraphRoot.swift b/Sources/PackageGraph/PackageGraphRoot.swift index 78a32b2dda8..ad14f6ace55 100644 --- a/Sources/PackageGraph/PackageGraphRoot.swift +++ b/Sources/PackageGraph/PackageGraphRoot.swift @@ -12,7 +12,7 @@ import Basics import PackageModel -import TSCBasic + import enum TSCUtility.Git /// Represents the input to the package graph root. diff --git a/Sources/PackageGraph/PinsStore.swift b/Sources/PackageGraph/PinsStore.swift index b96f1540794..f476ed229e3 100644 --- a/Sources/PackageGraph/PinsStore.swift +++ b/Sources/PackageGraph/PinsStore.swift @@ -13,7 +13,8 @@ import Basics import Foundation import PackageModel -import TSCBasic + +import enum TSCBasic.JSON import struct TSCUtility.Version diff --git a/Sources/PackageGraph/PubGrub/DiagnosticReportBuilder.swift b/Sources/PackageGraph/PubGrub/DiagnosticReportBuilder.swift index 1b3eb3a75a1..0a5289587e2 100644 --- a/Sources/PackageGraph/PubGrub/DiagnosticReportBuilder.swift +++ b/Sources/PackageGraph/PubGrub/DiagnosticReportBuilder.swift @@ -10,8 +10,6 @@ // //===----------------------------------------------------------------------===// -import TSCBasic - struct DiagnosticReportBuilder { let rootNode: DependencyResolutionNode let incompatibilities: [DependencyResolutionNode: [Incompatibility]] diff --git a/Sources/PackageGraph/PubGrub/Incompatibility.swift b/Sources/PackageGraph/PubGrub/Incompatibility.swift index 3ad39d80d96..c2646deb806 100644 --- a/Sources/PackageGraph/PubGrub/Incompatibility.swift +++ b/Sources/PackageGraph/PubGrub/Incompatibility.swift @@ -13,7 +13,6 @@ import Basics import OrderedCollections import PackageModel -import TSCBasic /// A set of terms that are incompatible with each other and can therefore not /// all be true at the same time. In dependency resolution, these are derived diff --git a/Sources/PackageGraph/PubGrub/PartialSolution.swift b/Sources/PackageGraph/PubGrub/PartialSolution.swift index b0858e7ca8c..c59b209216c 100644 --- a/Sources/PackageGraph/PubGrub/PartialSolution.swift +++ b/Sources/PackageGraph/PubGrub/PartialSolution.swift @@ -12,7 +12,7 @@ import Basics import OrderedCollections -import TSCBasic + import struct TSCUtility.Version /// The partial solution is a constantly updated solution used throughout the diff --git a/Sources/PackageGraph/PubGrub/PubGrubDependencyResolver.swift b/Sources/PackageGraph/PubGrub/PubGrubDependencyResolver.swift index 4162523e593..7acfa00a1a5 100644 --- a/Sources/PackageGraph/PubGrub/PubGrubDependencyResolver.swift +++ b/Sources/PackageGraph/PubGrub/PubGrubDependencyResolver.swift @@ -15,7 +15,6 @@ import Dispatch import class Foundation.NSLock import OrderedCollections import PackageModel -import TSCBasic import struct TSCUtility.Version diff --git a/Sources/PackageGraph/ResolvedPackage.swift b/Sources/PackageGraph/ResolvedPackage.swift index 41d1f19d401..fe7939c499f 100644 --- a/Sources/PackageGraph/ResolvedPackage.swift +++ b/Sources/PackageGraph/ResolvedPackage.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import TSCBasic +import Basics import PackageModel /// A fully resolved package. Contains resolved targets, products and dependencies of the package. diff --git a/Sources/PackageGraph/ResolvedProduct.swift b/Sources/PackageGraph/ResolvedProduct.swift index 5a8628ad057..48c2c9b2da2 100644 --- a/Sources/PackageGraph/ResolvedProduct.swift +++ b/Sources/PackageGraph/ResolvedProduct.swift @@ -11,7 +11,6 @@ //===----------------------------------------------------------------------===// import Basics -import TSCBasic import PackageModel public final class ResolvedProduct { diff --git a/Sources/PackageGraph/ResolvedTarget.swift b/Sources/PackageGraph/ResolvedTarget.swift index 41bcc7b29b2..67824c73d97 100644 --- a/Sources/PackageGraph/ResolvedTarget.swift +++ b/Sources/PackageGraph/ResolvedTarget.swift @@ -10,9 +10,10 @@ // //===----------------------------------------------------------------------===// -import TSCBasic import PackageModel +import func TSCBasic.topologicalSort + /// Represents a fully resolved target. All the dependencies for the target are resolved. public final class ResolvedTarget { /// Represents dependency of a resolved target. diff --git a/Sources/PackageLoading/Diagnostics.swift b/Sources/PackageLoading/Diagnostics.swift index 7f2985f755a..57c3ca003f4 100644 --- a/Sources/PackageLoading/Diagnostics.swift +++ b/Sources/PackageLoading/Diagnostics.swift @@ -12,7 +12,6 @@ import Basics import PackageModel -import TSCBasic extension Basics.Diagnostic { static func targetHasNoSources(name: String, type: TargetDescription.TargetType, shouldSuggestRelaxedSourceDir: Bool) -> Self { diff --git a/Sources/PackageLoading/ManifestJSONParser.swift b/Sources/PackageLoading/ManifestJSONParser.swift index 396c417b486..72b1d5895d4 100644 --- a/Sources/PackageLoading/ManifestJSONParser.swift +++ b/Sources/PackageLoading/ManifestJSONParser.swift @@ -13,13 +13,15 @@ @_implementationOnly import Foundation import PackageModel +import struct Basics.AbsolutePath +import protocol Basics.FileSystem import struct Basics.InternalError -import struct TSCBasic.AbsolutePath -import protocol TSCBasic.FileSystem +import struct Basics.RelativePath + import enum TSCBasic.PathValidationError import struct TSCBasic.RegEx -import struct TSCBasic.RelativePath import struct TSCBasic.StringError + import struct TSCUtility.Version enum ManifestJSONParser { @@ -145,7 +147,7 @@ enum ManifestJSONParser { toolsVersion: ToolsVersion, packageKind: PackageReference.Kind, identityResolver: IdentityResolver, - fileSystem: TSCBasic.FileSystem + fileSystem: FileSystem ) throws -> PackageDependency { switch dependency.kind { case .registry(let identity, let requirement): @@ -179,7 +181,7 @@ enum ManifestJSONParser { at location: String, name: String?, identityResolver: IdentityResolver, - fileSystem: TSCBasic.FileSystem + fileSystem: FileSystem ) throws -> PackageDependency { let location = try sanitizeDependencyLocation(fileSystem: fileSystem, packageKind: packageKind, dependencyLocation: location) let path: AbsolutePath @@ -201,7 +203,7 @@ enum ManifestJSONParser { name: String?, requirement: PackageDependency.SourceControl.Requirement, identityResolver: IdentityResolver, - fileSystem: TSCBasic.FileSystem + fileSystem: FileSystem ) throws -> PackageDependency { // cleans up variants of path based location var location = try sanitizeDependencyLocation(fileSystem: fileSystem, packageKind: packageKind, dependencyLocation: location) @@ -287,7 +289,7 @@ enum ManifestJSONParser { } } - private static func sanitizeDependencyLocation(fileSystem: TSCBasic.FileSystem, packageKind: PackageReference.Kind, dependencyLocation: String) throws -> String { + private static func sanitizeDependencyLocation(fileSystem: FileSystem, packageKind: PackageReference.Kind, dependencyLocation: String) throws -> String { if dependencyLocation.hasPrefix("~/") { // If the dependency URL starts with '~/', try to expand it. return try AbsolutePath(validating: String(dependencyLocation.dropFirst(2)), relativeTo: fileSystem.homeDirectory).pathString diff --git a/Sources/PackageLoading/ManifestLoader+Validation.swift b/Sources/PackageLoading/ManifestLoader+Validation.swift index a841b649aaa..90763852082 100644 --- a/Sources/PackageLoading/ManifestLoader+Validation.swift +++ b/Sources/PackageLoading/ManifestLoader+Validation.swift @@ -13,7 +13,6 @@ import Basics @_implementationOnly import Foundation import PackageModel -import TSCBasic public struct ManifestValidator { static var supportedLocalBinaryDependencyExtensions: [String] { diff --git a/Sources/PackageLoading/ManifestLoader.swift b/Sources/PackageLoading/ManifestLoader.swift index ec2790eb82f..179460722ca 100644 --- a/Sources/PackageLoading/ManifestLoader.swift +++ b/Sources/PackageLoading/ManifestLoader.swift @@ -14,7 +14,13 @@ import Basics import Dispatch @_implementationOnly import Foundation import PackageModel -import TSCBasic + +import class TSCBasic.BufferedOutputByteStream +import struct TSCBasic.ByteString +import class TSCBasic.Process +import enum TSCBasic.ProcessEnv +import struct TSCBasic.ProcessResult + import enum TSCUtility.Diagnostics import struct TSCUtility.Version diff --git a/Sources/PackageLoading/ManifestSignatureParser.swift b/Sources/PackageLoading/ManifestSignatureParser.swift index a2c3dbc6ad9..27e82cfe1d5 100644 --- a/Sources/PackageLoading/ManifestSignatureParser.swift +++ b/Sources/PackageLoading/ManifestSignatureParser.swift @@ -10,10 +10,9 @@ // //===----------------------------------------------------------------------===// +import Basics @_implementationOnly import struct Foundation.Data -import TSCBasic - public enum ManifestSignatureParser { public static func parse(manifestPath: AbsolutePath, fileSystem: FileSystem) throws -> ManifestSignature? { let manifestContents: String diff --git a/Sources/PackageLoading/ModuleMapGenerator.swift b/Sources/PackageLoading/ModuleMapGenerator.swift index 3ecb7343002..4b15d1c3883 100644 --- a/Sources/PackageLoading/ModuleMapGenerator.swift +++ b/Sources/PackageLoading/ModuleMapGenerator.swift @@ -13,7 +13,6 @@ import Basics @_implementationOnly import Foundation import PackageModel -import TSCBasic /// Name of the module map file recognized by the Clang and Swift compilers. public let moduleMapFilename = "module.modulemap" diff --git a/Sources/PackageLoading/PackageBuilder.swift b/Sources/PackageLoading/PackageBuilder.swift index 61e245b7192..b8859fbbe1d 100644 --- a/Sources/PackageLoading/PackageBuilder.swift +++ b/Sources/PackageLoading/PackageBuilder.swift @@ -14,7 +14,10 @@ import Basics import Dispatch import OrderedCollections import PackageModel -import TSCBasic + +import func TSCBasic.findCycle +import func TSCBasic.topologicalSort +import struct TSCBasic.KeyedPair /// An error in the structure or layout of a package. public enum ModuleError: Swift.Error { diff --git a/Sources/PackageLoading/PkgConfig.swift b/Sources/PackageLoading/PkgConfig.swift index 579b90cf4ff..93adcc49b7c 100644 --- a/Sources/PackageLoading/PkgConfig.swift +++ b/Sources/PackageLoading/PkgConfig.swift @@ -12,7 +12,10 @@ import Basics @_implementationOnly import Foundation -import TSCBasic +import OrderedCollections + +import class TSCBasic.Process +import enum TSCBasic.ProcessEnv /// Information on an individual `pkg-config` supported package. public struct PkgConfig { diff --git a/Sources/PackageLoading/Platform.swift b/Sources/PackageLoading/Platform.swift index f1f3e6cf520..862ea340253 100644 --- a/Sources/PackageLoading/Platform.swift +++ b/Sources/PackageLoading/Platform.swift @@ -10,12 +10,9 @@ // //===----------------------------------------------------------------------===// -@_implementationOnly -import Foundation +import Basics +@_implementationOnly import Foundation -import struct TSCBasic.AbsolutePath -import protocol TSCBasic.FileSystem -import var TSCBasic.localFileSystem import class TSCBasic.Process private func isAndroid() -> Bool { diff --git a/Sources/PackageLoading/RegistryReleaseMetadataSerialization.swift b/Sources/PackageLoading/RegistryReleaseMetadataSerialization.swift index 6b74835a5a1..f892019b626 100644 --- a/Sources/PackageLoading/RegistryReleaseMetadataSerialization.swift +++ b/Sources/PackageLoading/RegistryReleaseMetadataSerialization.swift @@ -13,7 +13,6 @@ import Basics @_implementationOnly import Foundation import PackageModel -import TSCBasic public enum RegistryReleaseMetadataStorage { public static let fileName = ".registry-metadata" diff --git a/Sources/PackageLoading/Target+PkgConfig.swift b/Sources/PackageLoading/Target+PkgConfig.swift index 5c011c1e9c3..935c6b0f269 100644 --- a/Sources/PackageLoading/Target+PkgConfig.swift +++ b/Sources/PackageLoading/Target+PkgConfig.swift @@ -12,7 +12,9 @@ import Basics import PackageModel -import TSCBasic + +import class TSCBasic.Process + import enum TSCUtility.Platform /// Wrapper struct containing result of a pkgConfig query. diff --git a/Sources/PackageLoading/TargetSourcesBuilder.swift b/Sources/PackageLoading/TargetSourcesBuilder.swift index 6f9ec15a990..129d9e141d9 100644 --- a/Sources/PackageLoading/TargetSourcesBuilder.swift +++ b/Sources/PackageLoading/TargetSourcesBuilder.swift @@ -13,7 +13,6 @@ import Basics @_implementationOnly import Foundation import PackageModel -import TSCBasic /// A utility to compute the source/resource files of a target. public struct TargetSourcesBuilder { diff --git a/Sources/PackageLoading/ToolsVersionParser.swift b/Sources/PackageLoading/ToolsVersionParser.swift index c71a0c8968a..6c3cade990f 100644 --- a/Sources/PackageLoading/ToolsVersionParser.swift +++ b/Sources/PackageLoading/ToolsVersionParser.swift @@ -13,7 +13,9 @@ import Basics @_implementationOnly import Foundation import PackageModel -import TSCBasic + +import struct TSCBasic.ByteString +import struct TSCBasic.RegEx import struct TSCUtility.Version diff --git a/Sources/PackageMetadata/PackageMetadata.swift b/Sources/PackageMetadata/PackageMetadata.swift index 140d9d5d3bf..02c5cd2e778 100644 --- a/Sources/PackageMetadata/PackageMetadata.swift +++ b/Sources/PackageMetadata/PackageMetadata.swift @@ -20,9 +20,7 @@ import SourceControl import struct Foundation.Date import struct Foundation.URL -import struct TSCBasic.AbsolutePath -import protocol TSCBasic.FileSystem -import func TSCBasic.withTemporaryDirectory + import struct TSCUtility.Version public struct Package { diff --git a/Sources/PackageModel/ArtifactsArchiveMetadata.swift b/Sources/PackageModel/ArtifactsArchiveMetadata.swift index 94fc20e4850..4c08b01fb55 100644 --- a/Sources/PackageModel/ArtifactsArchiveMetadata.swift +++ b/Sources/PackageModel/ArtifactsArchiveMetadata.swift @@ -12,7 +12,6 @@ import Basics import Foundation -import TSCBasic import struct TSCUtility.Version diff --git a/Sources/PackageModel/BuildSettings.swift b/Sources/PackageModel/BuildSettings.swift index 26465e53ce0..36418200910 100644 --- a/Sources/PackageModel/BuildSettings.swift +++ b/Sources/PackageModel/BuildSettings.swift @@ -10,8 +10,6 @@ // //===----------------------------------------------------------------------===// -import TSCBasic - /// Namespace for build settings. public enum BuildSettings { diff --git a/Sources/PackageModel/Destination.swift b/Sources/PackageModel/Destination.swift index a73c4bf7269..0ec8e64626e 100644 --- a/Sources/PackageModel/Destination.swift +++ b/Sources/PackageModel/Destination.swift @@ -12,7 +12,9 @@ import Basics import Foundation -import TSCBasic + +import class TSCBasic.Process +import enum TSCBasic.ProcessEnv import struct TSCUtility.Version diff --git a/Sources/PackageModel/Diagnostics.swift b/Sources/PackageModel/Diagnostics.swift index c5c656fb7f4..f03652e3c0a 100644 --- a/Sources/PackageModel/Diagnostics.swift +++ b/Sources/PackageModel/Diagnostics.swift @@ -10,8 +10,6 @@ // //===----------------------------------------------------------------------===// -import TSCBasic - import Foundation /// The diagnostic triggered when the package has a newer tools version than the installed tools. diff --git a/Sources/PackageModel/IdentityResolver.swift b/Sources/PackageModel/IdentityResolver.swift index f6c8b50f934..a03d0a04828 100644 --- a/Sources/PackageModel/IdentityResolver.swift +++ b/Sources/PackageModel/IdentityResolver.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// +import Basics import Foundation -import TSCBasic // TODO: refactor this when adding registry support public protocol IdentityResolver { diff --git a/Sources/PackageModel/Manifest/Manifest.swift b/Sources/PackageModel/Manifest/Manifest.swift index b2269aaa1ae..62f8896ce88 100644 --- a/Sources/PackageModel/Manifest/Manifest.swift +++ b/Sources/PackageModel/Manifest/Manifest.swift @@ -12,7 +12,8 @@ import Basics import Foundation -import TSCBasic + +import func TSCBasic.transitiveClosure import struct TSCUtility.Version diff --git a/Sources/PackageModel/Manifest/PackageDependencyDescription.swift b/Sources/PackageModel/Manifest/PackageDependencyDescription.swift index 53c8481bcd5..ef17ec8fb83 100644 --- a/Sources/PackageModel/Manifest/PackageDependencyDescription.swift +++ b/Sources/PackageModel/Manifest/PackageDependencyDescription.swift @@ -12,7 +12,8 @@ import Foundation import Basics -import TSCBasic + +import struct TSCBasic.CodableRange import struct TSCUtility.Version diff --git a/Sources/PackageModel/ManifestSourceGeneration.swift b/Sources/PackageModel/ManifestSourceGeneration.swift index efa383d877a..d79f93cd6c3 100644 --- a/Sources/PackageModel/ManifestSourceGeneration.swift +++ b/Sources/PackageModel/ManifestSourceGeneration.swift @@ -10,9 +10,8 @@ // //===----------------------------------------------------------------------===// +import Basics import Foundation -import TSCBasic - /// Extensions on Manifest for generating source code expressing its contents /// in canonical declarative form. Note that this bakes in the results of any diff --git a/Sources/PackageModel/MinimumDeploymentTarget.swift b/Sources/PackageModel/MinimumDeploymentTarget.swift index 6b990578f9c..e4963694489 100644 --- a/Sources/PackageModel/MinimumDeploymentTarget.swift +++ b/Sources/PackageModel/MinimumDeploymentTarget.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// -import TSCBasic +import Basics + +import class TSCBasic.Process +import struct TSCBasic.ProcessResult + public struct MinimumDeploymentTarget { public let xcTestMinimumDeploymentTargets: [PackageModel.Platform:PlatformVersion] diff --git a/Sources/PackageModel/ModuleMapType.swift b/Sources/PackageModel/ModuleMapType.swift index c84711dfa4b..d4f1a241bee 100644 --- a/Sources/PackageModel/ModuleMapType.swift +++ b/Sources/PackageModel/ModuleMapType.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import TSCBasic +import Basics /// A type of module map layout. Contains all the information needed to generate or use a module map for a target that can have C-style headers. public enum ModuleMapType: Equatable { diff --git a/Sources/PackageModel/PackageIdentity.swift b/Sources/PackageModel/PackageIdentity.swift index b744804c62c..3066fdf56d9 100644 --- a/Sources/PackageModel/PackageIdentity.swift +++ b/Sources/PackageModel/PackageIdentity.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// +import Basics import Foundation -import TSCBasic /// The canonical identifier for a package, based on its source location. public struct PackageIdentity: CustomStringConvertible, Sendable { diff --git a/Sources/PackageModel/PackageModel.swift b/Sources/PackageModel/PackageModel.swift index 690a458ff2b..33dd6ed7a4b 100644 --- a/Sources/PackageModel/PackageModel.swift +++ b/Sources/PackageModel/PackageModel.swift @@ -12,11 +12,10 @@ import Basics import struct Foundation.URL -import TSCBasic -import struct TSCUtility.Version import enum TSCUtility.PackageLocation import struct TSCUtility.PolymorphicCodableArray +import struct TSCUtility.Version /// The basic package representation. /// diff --git a/Sources/PackageModel/PackageReference.swift b/Sources/PackageModel/PackageReference.swift index a82dca1e34d..6238eae42ae 100644 --- a/Sources/PackageModel/PackageReference.swift +++ b/Sources/PackageModel/PackageReference.swift @@ -12,7 +12,6 @@ import Basics import Foundation -import TSCBasic /// A package reference. /// diff --git a/Sources/PackageModel/Product.swift b/Sources/PackageModel/Product.swift index 13b65869a5f..eea25a3c56c 100644 --- a/Sources/PackageModel/Product.swift +++ b/Sources/PackageModel/Product.swift @@ -11,7 +11,6 @@ //===----------------------------------------------------------------------===// import Basics -import TSCBasic import struct TSCUtility.PolymorphicCodableArray diff --git a/Sources/PackageModel/Resource.swift b/Sources/PackageModel/Resource.swift index b2f19446dfd..7e2b6c15e76 100644 --- a/Sources/PackageModel/Resource.swift +++ b/Sources/PackageModel/Resource.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import TSCBasic +import Basics /// An individual resource file and its corresponding rule. public struct Resource: Codable, Equatable { diff --git a/Sources/PackageModel/Sanitizers.swift b/Sources/PackageModel/Sanitizers.swift index d9677cd7666..92f2fe994ca 100644 --- a/Sources/PackageModel/Sanitizers.swift +++ b/Sources/PackageModel/Sanitizers.swift @@ -10,8 +10,6 @@ // //===----------------------------------------------------------------------===// -import TSCBasic - /// Available runtime sanitizers. public enum Sanitizer: String, Encodable, CaseIterable { case address diff --git a/Sources/PackageModel/Snippets/Model/Snippet.swift b/Sources/PackageModel/Snippets/Model/Snippet.swift index 45a2fde48e6..d44e8753d31 100644 --- a/Sources/PackageModel/Snippets/Model/Snippet.swift +++ b/Sources/PackageModel/Snippets/Model/Snippet.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import TSCBasic +import Basics public struct Snippet { public var path: AbsolutePath diff --git a/Sources/PackageModel/Snippets/Model/SnippetGroup.swift b/Sources/PackageModel/Snippets/Model/SnippetGroup.swift index 377126ff4b9..de3b080c496 100644 --- a/Sources/PackageModel/Snippets/Model/SnippetGroup.swift +++ b/Sources/PackageModel/Snippets/Model/SnippetGroup.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import TSCBasic +import Basics public struct SnippetGroup { public var name: String diff --git a/Sources/PackageModel/Sources.swift b/Sources/PackageModel/Sources.swift index 333c354c36b..efe55605920 100644 --- a/Sources/PackageModel/Sources.swift +++ b/Sources/PackageModel/Sources.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import TSCBasic +import Basics /// A grouping of related source files. public struct Sources: Codable { diff --git a/Sources/PackageModel/SwiftLanguageVersion.swift b/Sources/PackageModel/SwiftLanguageVersion.swift index 61eb2414686..03408c8cba1 100644 --- a/Sources/PackageModel/SwiftLanguageVersion.swift +++ b/Sources/PackageModel/SwiftLanguageVersion.swift @@ -10,10 +10,10 @@ // //===----------------------------------------------------------------------===// -import TSCBasic - import Foundation +import struct TSCBasic.RegEx + import struct TSCUtility.Version /// Represents a Swift language version. diff --git a/Sources/PackageModel/SwiftSDKBundle.swift b/Sources/PackageModel/SwiftSDKBundle.swift index cc8bc9b6532..6ddbc644a36 100644 --- a/Sources/PackageModel/SwiftSDKBundle.swift +++ b/Sources/PackageModel/SwiftSDKBundle.swift @@ -10,14 +10,9 @@ // //===----------------------------------------------------------------------===// - import Basics -import func TSCBasic.tsc_await -import func TSCBasic.withTemporaryDirectory -import protocol TSCBasic.FileSystem import struct Foundation.URL -import struct TSCBasic.AbsolutePath import struct TSCBasic.RegEx /// Represents an `.artifactbundle` on the filesystem that contains a Swift SDK. @@ -160,7 +155,7 @@ public struct SwiftSDKBundle { destination: downloadedBundlePath ) request.options.validResponseCodes = [200] - _ = try tsc_await { + _ = try temp_await { client.execute( request, observabilityScope: observabilityScope, @@ -173,7 +168,7 @@ public struct SwiftSDKBundle { print("Destination artifact bundle successfully downloaded from `\(bundleURL)`.") } else if - let cwd = fileSystem.currentWorkingDirectory, + let cwd: AbsolutePath = fileSystem.currentWorkingDirectory, let originalBundlePath = try? AbsolutePath(validating: bundlePathOrURL, relativeTo: cwd) { bundlePath = originalBundlePath @@ -231,7 +226,7 @@ public struct SwiftSDKBundle { print("\(bundleName) is assumed to be an archive, unpacking...") - try tsc_await { archiver.extract(from: bundlePath, to: temporaryDirectory, completion: $0) } + try temp_await { archiver.extract(from: bundlePath, to: temporaryDirectory, completion: $0) } return temporaryDirectory.appending(component: unpackedBundleName) } diff --git a/Sources/PackageModel/SwiftSDKConfigurationStore.swift b/Sources/PackageModel/SwiftSDKConfigurationStore.swift index 53ec3b8b42e..38a444dfab5 100644 --- a/Sources/PackageModel/SwiftSDKConfigurationStore.swift +++ b/Sources/PackageModel/SwiftSDKConfigurationStore.swift @@ -11,7 +11,6 @@ //===----------------------------------------------------------------------===// import Basics -import TSCBasic import class Foundation.JSONDecoder import class Foundation.JSONEncoder diff --git a/Sources/PackageModel/Target.swift b/Sources/PackageModel/Target.swift index b8914a0d973..a5eab7cb6b2 100644 --- a/Sources/PackageModel/Target.swift +++ b/Sources/PackageModel/Target.swift @@ -10,11 +10,10 @@ // //===----------------------------------------------------------------------===// -import TSCBasic +import Basics import Dispatch import protocol TSCUtility.PolymorphicCodableProtocol -import Basics public class Target: PolymorphicCodableProtocol { public static var implementations: [PolymorphicCodableProtocol.Type] = [ diff --git a/Sources/PackageModel/Toolchain.swift b/Sources/PackageModel/Toolchain.swift index b2173fd48d7..f8353927ea2 100644 --- a/Sources/PackageModel/Toolchain.swift +++ b/Sources/PackageModel/Toolchain.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import TSCBasic +import Basics public protocol Toolchain { /// Path of the librarian. diff --git a/Sources/PackageModel/ToolchainConfiguration.swift b/Sources/PackageModel/ToolchainConfiguration.swift index fd1a90eef90..761871a0682 100644 --- a/Sources/PackageModel/ToolchainConfiguration.swift +++ b/Sources/PackageModel/ToolchainConfiguration.swift @@ -11,7 +11,6 @@ //===----------------------------------------------------------------------===// import Basics -import TSCBasic /// Toolchain configuration required for evaluation of swift code such as the manifests or plugins /// diff --git a/Sources/PackageModel/ToolsVersion.swift b/Sources/PackageModel/ToolsVersion.swift index 64ffc99a5f1..258243e22ab 100644 --- a/Sources/PackageModel/ToolsVersion.swift +++ b/Sources/PackageModel/ToolsVersion.swift @@ -12,7 +12,6 @@ import Basics import Foundation -import TSCBasic import struct TSCUtility.Version diff --git a/Sources/PackageModel/Toolset.swift b/Sources/PackageModel/Toolset.swift index c9a9b8c5c70..8853e00c480 100644 --- a/Sources/PackageModel/Toolset.swift +++ b/Sources/PackageModel/Toolset.swift @@ -10,12 +10,9 @@ // //===----------------------------------------------------------------------===// +import Basics import Foundation -import class Basics.ObservabilityScope -import struct TSCBasic.AbsolutePath -import protocol TSCBasic.FileSystem -import struct TSCBasic.RelativePath import struct TSCBasic.StringError import struct TSCUtility.Version diff --git a/Sources/PackageModel/UserToolchain.swift b/Sources/PackageModel/UserToolchain.swift index 07314975343..bd642670ac9 100644 --- a/Sources/PackageModel/UserToolchain.swift +++ b/Sources/PackageModel/UserToolchain.swift @@ -12,7 +12,8 @@ import Basics import Foundation -import TSCBasic + +import class TSCBasic.Process #if os(Windows) private let hostExecutableSuffix = ".exe" @@ -161,7 +162,7 @@ public final class UserToolchain: Toolchain { return triple.isAndroid() ? "llvm-ar" : "ar" }() - if let librarian: AbsolutePath = UserToolchain.lookup( + if let librarian = UserToolchain.lookup( variable: variable, searchPaths: searchPaths, environment: environment diff --git a/Sources/PackageModel/WindowsToolchainInfo.swift b/Sources/PackageModel/WindowsToolchainInfo.swift index ba1a85d9c94..794ae3b4cab 100644 --- a/Sources/PackageModel/WindowsToolchainInfo.swift +++ b/Sources/PackageModel/WindowsToolchainInfo.swift @@ -12,7 +12,6 @@ import Basics import Foundation -import TSCBasic public struct WindowsSDKSettings { public struct DefaultProperties { diff --git a/Sources/PackageRegistry/RegistryClient.swift b/Sources/PackageRegistry/RegistryClient.swift index 62fdabb3ecd..feb71b7ff80 100644 --- a/Sources/PackageRegistry/RegistryClient.swift +++ b/Sources/PackageRegistry/RegistryClient.swift @@ -17,7 +17,8 @@ import PackageFingerprint import PackageLoading import PackageModel import PackageSigning -import TSCBasic + +import protocol TSCBasic.HashAlgorithm import struct TSCUtility.Version @@ -355,7 +356,7 @@ public final class RegistryClient: Cancellable { return nil } let configuration = self.configuration.signing(for: package, registry: registry) - return try? tsc_await { completion in + return try? temp_await { completion in let wrappedCompletion: @Sendable (Result) -> Void = { completion($0) } diff --git a/Sources/PackageRegistry/RegistryDownloadsManager.swift b/Sources/PackageRegistry/RegistryDownloadsManager.swift index 15922b0c4c1..dcddf1c3a7f 100644 --- a/Sources/PackageRegistry/RegistryDownloadsManager.swift +++ b/Sources/PackageRegistry/RegistryDownloadsManager.swift @@ -15,7 +15,6 @@ import Dispatch import Foundation import PackageLoading import PackageModel -import TSCBasic import struct TSCUtility.Version diff --git a/Sources/PackageRegistry/SignatureValidation.swift b/Sources/PackageRegistry/SignatureValidation.swift index 785f94b2ed5..87d46367d8c 100644 --- a/Sources/PackageRegistry/SignatureValidation.swift +++ b/Sources/PackageRegistry/SignatureValidation.swift @@ -19,7 +19,6 @@ import PackageLoading import PackageModel import PackageSigning -import TSCBasic import struct TSCUtility.Version protocol SignatureValidationDelegate { diff --git a/Sources/PackageRegistryTool/PackageRegistryTool+Auth.swift b/Sources/PackageRegistryTool/PackageRegistryTool+Auth.swift index 18eeae3e4a6..c15b948c54a 100644 --- a/Sources/PackageRegistryTool/PackageRegistryTool+Auth.swift +++ b/Sources/PackageRegistryTool/PackageRegistryTool+Auth.swift @@ -17,7 +17,8 @@ import CoreCommands import Foundation import PackageModel import PackageRegistry -import TSCBasic + +import struct TSCBasic.SHA256 #if os(Windows) import WinSDK @@ -162,7 +163,7 @@ extension SwiftPackageRegistryTool { } // Save in cache so we can try the credentials and persist to storage only if login succeeds - try tsc_await { callback in + try temp_await { callback in authorizationWriter?.addOrUpdate( for: registryURL, user: storeUsername, @@ -203,7 +204,7 @@ extension SwiftPackageRegistryTool { ) // Try logging in - try tsc_await { callback in + try temp_await { callback in registryClient.login( loginURL: loginURL, timeout: .seconds(5), @@ -241,7 +242,7 @@ extension SwiftPackageRegistryTool { } if saveChanges { - try tsc_await { callback in + try temp_await { callback in authorizationWriter?.addOrUpdate( for: registryURL, user: storeUsername, @@ -307,7 +308,7 @@ extension SwiftPackageRegistryTool { // Only OS credential store supports deletion if osStore { - try tsc_await { callback in authorizationWriter?.remove(for: registryURL, callback: callback) } + try temp_await { callback in authorizationWriter?.remove(for: registryURL, callback: callback) } print("Credentials have been removed from operating system's secure credential store.") } else { print("netrc file not updated. Please remove credentials from the file manually.") diff --git a/Sources/PackageRegistryTool/PackageRegistryTool+Publish.swift b/Sources/PackageRegistryTool/PackageRegistryTool+Publish.swift index 34b172066ae..9ef8f02dfcf 100644 --- a/Sources/PackageRegistryTool/PackageRegistryTool+Publish.swift +++ b/Sources/PackageRegistryTool/PackageRegistryTool+Publish.swift @@ -18,12 +18,15 @@ import Foundation import PackageModel import PackageRegistry import PackageSigning -import TSCBasic -import struct TSCUtility.Version import Workspace - @_implementationOnly import X509 // FIXME: need this import or else SwiftSigningIdentity initializer fails +import struct TSCBasic.ByteString +import struct TSCBasic.SHA256 +import struct TSCBasic.RegEx + +import struct TSCUtility.Version + extension SwiftPackageRegistryTool { struct Publish: SwiftCommand { static let metadataFilename = "package-metadata.json" @@ -198,7 +201,7 @@ extension SwiftPackageRegistryTool { swiftTool.observabilityScope .emit(info: "publishing \(self.packageIdentity) archive at '\(archivePath)' to \(registryURL)") - let result = try tsc_await { + let result = try temp_await { registryClient.publish( registryURL: registryURL, packageIdentity: self.packageIdentity, diff --git a/Sources/PackageRegistryTool/PackageRegistryTool.swift b/Sources/PackageRegistryTool/PackageRegistryTool.swift index 30f11a06469..cb4b01263f0 100644 --- a/Sources/PackageRegistryTool/PackageRegistryTool.swift +++ b/Sources/PackageRegistryTool/PackageRegistryTool.swift @@ -16,7 +16,6 @@ import CoreCommands import Foundation import PackageModel import PackageRegistry -import TSCBasic import Workspace @available(macOS 10.15, macCatalyst 13, iOS 13, tvOS 13, watchOS 6, *) diff --git a/Sources/PackageSigning/SigningEntity/FilePackageSigningEntityStorage.swift b/Sources/PackageSigning/SigningEntity/FilePackageSigningEntityStorage.swift index ecd0209e305..8e70493e67d 100644 --- a/Sources/PackageSigning/SigningEntity/FilePackageSigningEntityStorage.swift +++ b/Sources/PackageSigning/SigningEntity/FilePackageSigningEntityStorage.swift @@ -14,7 +14,6 @@ import Basics import Dispatch import Foundation import PackageModel -import TSCBasic import struct TSCUtility.Version diff --git a/Sources/SPMBuildCore/BinaryTarget+Extensions.swift b/Sources/SPMBuildCore/BinaryTarget+Extensions.swift index 5c643202b31..06d77f1356b 100644 --- a/Sources/SPMBuildCore/BinaryTarget+Extensions.swift +++ b/Sources/SPMBuildCore/BinaryTarget+Extensions.swift @@ -14,7 +14,6 @@ import Basics import Foundation import PackageGraph import PackageModel -import TSCBasic /// Information about a library from a binary dependency. public struct LibraryInfo: Equatable { diff --git a/Sources/SPMBuildCore/BuildParameters.swift b/Sources/SPMBuildCore/BuildParameters.swift index 86ccd2c1109..a130ada4ddd 100644 --- a/Sources/SPMBuildCore/BuildParameters.swift +++ b/Sources/SPMBuildCore/BuildParameters.swift @@ -10,14 +10,11 @@ // //===----------------------------------------------------------------------===// +import Basics import class Foundation.ProcessInfo - -import TSCBasic import PackageModel import PackageGraph -import struct Basics.Triple - public struct BuildParameters: Encodable { /// Mode for the indexing-while-building feature. public enum IndexStoreMode: String, Encodable { diff --git a/Sources/SPMBuildCore/BuildSystem.swift b/Sources/SPMBuildCore/BuildSystem.swift index f601242a648..0d0278d5f2f 100644 --- a/Sources/SPMBuildCore/BuildSystem.swift +++ b/Sources/SPMBuildCore/BuildSystem.swift @@ -13,7 +13,6 @@ import Basics import PackageGraph -import struct TSCBasic.AbsolutePath import protocol TSCBasic.OutputByteStream import enum TSCBasic.ProcessEnv diff --git a/Sources/SPMBuildCore/BuiltTestProduct.swift b/Sources/SPMBuildCore/BuiltTestProduct.swift index d2a23e145fd..bdea7300b55 100644 --- a/Sources/SPMBuildCore/BuiltTestProduct.swift +++ b/Sources/SPMBuildCore/BuiltTestProduct.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import TSCBasic +import Basics /// Represents a test product which is built and is present on disk. public struct BuiltTestProduct: Codable { diff --git a/Sources/SPMBuildCore/PluginContextSerializer.swift b/Sources/SPMBuildCore/PluginContextSerializer.swift index aeaf2bb58c4..7af829e9f93 100644 --- a/Sources/SPMBuildCore/PluginContextSerializer.swift +++ b/Sources/SPMBuildCore/PluginContextSerializer.swift @@ -15,7 +15,6 @@ import Foundation import PackageGraph import PackageLoading import PackageModel -import TSCBasic typealias WireInput = HostToPluginMessage.InputContext diff --git a/Sources/SPMBuildCore/PluginInvocation.swift b/Sources/SPMBuildCore/PluginInvocation.swift index adef6c54ea7..370ea9cd2ad 100644 --- a/Sources/SPMBuildCore/PluginInvocation.swift +++ b/Sources/SPMBuildCore/PluginInvocation.swift @@ -15,7 +15,8 @@ import Foundation import PackageModel import PackageLoading import PackageGraph -import TSCBasic + +import protocol TSCBasic.DiagnosticLocation public enum PluginAction { case createBuildToolCommands(package: ResolvedPackage, target: ResolvedTarget) @@ -466,7 +467,7 @@ extension PackageGraph { // Invoke the build tool plugin with the input parameters and the delegate that will collect outputs. let startTime = DispatchTime.now() - let success = try tsc_await { pluginTarget.invoke( + let success = try temp_await { pluginTarget.invoke( action: .createBuildToolCommands(package: package, target: target), buildEnvironment: buildEnvironment, scriptRunner: pluginScriptRunner, diff --git a/Sources/SPMBuildCore/PluginScriptRunner.swift b/Sources/SPMBuildCore/PluginScriptRunner.swift index 8f1721fb1c8..e0a74a2a07c 100644 --- a/Sources/SPMBuildCore/PluginScriptRunner.swift +++ b/Sources/SPMBuildCore/PluginScriptRunner.swift @@ -15,7 +15,6 @@ import Foundation import PackageModel import PackageLoading import PackageGraph -import TSCBasic /// Implements the mechanics of running and communicating with a plugin (implemented as a set of Swift source files). In most environments this is done by compiling the code to an executable, invoking it as a sandboxed subprocess, and communicating with it using pipes. Specific implementations are free to implement things differently, however. public protocol PluginScriptRunner { diff --git a/Sources/SPMBuildCore/PrebuildCommandResult.swift b/Sources/SPMBuildCore/PrebuildCommandResult.swift index 7a2c9890c80..bdc3e7b567e 100644 --- a/Sources/SPMBuildCore/PrebuildCommandResult.swift +++ b/Sources/SPMBuildCore/PrebuildCommandResult.swift @@ -11,8 +11,6 @@ //===----------------------------------------------------------------------===// import Basics -import TSCBasic - /// Represents the result of running prebuild commands for a single plugin invocation for a target. public struct PrebuildCommandResult { diff --git a/Sources/SPMBuildCore/XCFrameworkMetadata.swift b/Sources/SPMBuildCore/XCFrameworkMetadata.swift index 4bb3417f462..1b90a46bf29 100644 --- a/Sources/SPMBuildCore/XCFrameworkMetadata.swift +++ b/Sources/SPMBuildCore/XCFrameworkMetadata.swift @@ -10,11 +10,13 @@ // //===----------------------------------------------------------------------===// +import struct Basics.AbsolutePath +import protocol Basics.FileSystem +import struct Basics.Triple import Foundation import PackageModel -import TSCBasic -import struct Basics.Triple +import struct TSCBasic.StringError public struct XCFrameworkMetadata: Equatable { public struct Library: Equatable { diff --git a/Sources/SPMTestSupport/GitRepositoryExtensions.swift b/Sources/SPMTestSupport/GitRepositoryExtensions.swift index 72a843c5020..58b5050952d 100644 --- a/Sources/SPMTestSupport/GitRepositoryExtensions.swift +++ b/Sources/SPMTestSupport/GitRepositoryExtensions.swift @@ -10,9 +10,10 @@ // //===----------------------------------------------------------------------===// -import TSCBasic import SourceControl +import class TSCBasic.Process + import enum TSCUtility.Git /// Extensions useful for unit testing purposes. diff --git a/Sources/SPMTestSupport/InMemoryGitRepository.swift b/Sources/SPMTestSupport/InMemoryGitRepository.swift index 0f4b90e8255..f688907b64c 100644 --- a/Sources/SPMTestSupport/InMemoryGitRepository.swift +++ b/Sources/SPMTestSupport/InMemoryGitRepository.swift @@ -14,7 +14,11 @@ import Basics import Dispatch import Foundation import SourceControl -import TSCBasic + +import struct TSCBasic.ByteString +import enum TSCBasic.FileMode +import struct TSCBasic.FileSystemError +import class TSCBasic.InMemoryFileSystem /// The error encountered during in memory git repository operations. public enum InMemoryGitRepositoryError: Swift.Error { @@ -208,112 +212,112 @@ public final class InMemoryGitRepository { } extension InMemoryGitRepository: FileSystem { - public func exists(_ path: AbsolutePath, followSymlink: Bool) -> Bool { + public func exists(_ path: TSCAbsolutePath, followSymlink: Bool) -> Bool { self.lock.withLock { self.head.fileSystem.exists(path, followSymlink: followSymlink) } } - public func isDirectory(_ path: AbsolutePath) -> Bool { + public func isDirectory(_ path: TSCAbsolutePath) -> Bool { self.lock.withLock { self.head.fileSystem.isDirectory(path) } } - public func isFile(_ path: AbsolutePath) -> Bool { + public func isFile(_ path: TSCAbsolutePath) -> Bool { self.lock.withLock { self.head.fileSystem.isFile(path) } } - public func isSymlink(_ path: AbsolutePath) -> Bool { + public func isSymlink(_ path: TSCAbsolutePath) -> Bool { self.lock.withLock { self.head.fileSystem.isSymlink(path) } } - public func isExecutableFile(_ path: AbsolutePath) -> Bool { + public func isExecutableFile(_ path: TSCAbsolutePath) -> Bool { self.lock.withLock { self.head.fileSystem.isExecutableFile(path) } } - public func isReadable(_ path: AbsolutePath) -> Bool { + public func isReadable(_ path: TSCAbsolutePath) -> Bool { return self.exists(path) } - public func isWritable(_ path: AbsolutePath) -> Bool { + public func isWritable(_ path: TSCAbsolutePath) -> Bool { return false } - public var currentWorkingDirectory: AbsolutePath? { - return AbsolutePath("/") + public var currentWorkingDirectory: TSCAbsolutePath? { + return .root } - public func changeCurrentWorkingDirectory(to path: AbsolutePath) throws { + public func changeCurrentWorkingDirectory(to path: TSCAbsolutePath) throws { throw FileSystemError(.unsupported, path) } - public var homeDirectory: AbsolutePath { + public var homeDirectory: TSCAbsolutePath { fatalError("Unsupported") } - public var cachesDirectory: AbsolutePath? { + public var cachesDirectory: TSCAbsolutePath? { fatalError("Unsupported") } - public var tempDirectory: AbsolutePath { + public var tempDirectory: TSCAbsolutePath { fatalError("Unsupported") } - public func getDirectoryContents(_ path: AbsolutePath) throws -> [String] { + public func getDirectoryContents(_ path: TSCAbsolutePath) throws -> [String] { try self.lock.withLock { try self.head.fileSystem.getDirectoryContents(path) } } - public func createDirectory(_ path: AbsolutePath, recursive: Bool) throws { + public func createDirectory(_ path: TSCAbsolutePath, recursive: Bool) throws { try self.lock.withLock { try self.head.fileSystem.createDirectory(path, recursive: recursive) } } - public func createSymbolicLink(_ path: AbsolutePath, pointingAt destination: AbsolutePath, relative: Bool) throws { + public func createSymbolicLink(_ path: TSCAbsolutePath, pointingAt destination: TSCAbsolutePath, relative: Bool) throws { throw FileSystemError(.unsupported, path) } - public func readFileContents(_ path: AbsolutePath) throws -> ByteString { + public func readFileContents(_ path: TSCAbsolutePath) throws -> ByteString { try self.lock.withLock { return try head.fileSystem.readFileContents(path) } } - public func writeFileContents(_ path: AbsolutePath, bytes: ByteString) throws { + public func writeFileContents(_ path: TSCAbsolutePath, bytes: ByteString) throws { try self.lock.withLock { try self.head.fileSystem.writeFileContents(path, bytes: bytes) self.isDirty = true } } - public func removeFileTree(_ path: AbsolutePath) throws { + public func removeFileTree(_ path: TSCAbsolutePath) throws { try self.lock.withLock { try self.head.fileSystem.removeFileTree(path) } } - public func chmod(_ mode: FileMode, path: AbsolutePath, options: Set) throws { + public func chmod(_ mode: FileMode, path: TSCAbsolutePath, options: Set) throws { try self.lock.withLock { try self.head.fileSystem.chmod(mode, path: path, options: options) } } - public func copy(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws { + public func copy(from sourcePath: TSCAbsolutePath, to destinationPath: TSCAbsolutePath) throws { try self.lock.withLock { try self.head.fileSystem.copy(from: sourcePath, to: destinationPath) } } - public func move(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws { + public func move(from sourcePath: TSCAbsolutePath, to destinationPath: TSCAbsolutePath) throws { try self.lock.withLock { try self.head.fileSystem.move(from: sourcePath, to: destinationPath) } diff --git a/Sources/SPMTestSupport/ManifestExtensions.swift b/Sources/SPMTestSupport/ManifestExtensions.swift index 9779b20c7eb..bd3315ad3ac 100644 --- a/Sources/SPMTestSupport/ManifestExtensions.swift +++ b/Sources/SPMTestSupport/ManifestExtensions.swift @@ -10,9 +10,10 @@ // //===----------------------------------------------------------------------===// +import Basics import Foundation import PackageModel -import TSCBasic + import struct TSCUtility.Version extension Manifest { diff --git a/Sources/SPMTestSupport/MockArchiver.swift b/Sources/SPMTestSupport/MockArchiver.swift index 94a15f3888a..2bfc63546a3 100644 --- a/Sources/SPMTestSupport/MockArchiver.swift +++ b/Sources/SPMTestSupport/MockArchiver.swift @@ -11,7 +11,6 @@ //===----------------------------------------------------------------------===// import Basics -import TSCBasic public class MockArchiver: Archiver { public typealias ExtractionHandler = ( diff --git a/Sources/SPMTestSupport/MockDependency.swift b/Sources/SPMTestSupport/MockDependency.swift index 9d16196214b..809deb0abcf 100644 --- a/Sources/SPMTestSupport/MockDependency.swift +++ b/Sources/SPMTestSupport/MockDependency.swift @@ -10,10 +10,10 @@ // //===----------------------------------------------------------------------===// +import Basics import Foundation import PackageLoading import PackageModel -import TSCBasic public typealias SourceControlRequirement = PackageDependency.SourceControl.Requirement public typealias RegistryRequirement = PackageDependency.Registry.Requirement diff --git a/Sources/SPMTestSupport/MockDependencyGraph.swift b/Sources/SPMTestSupport/MockDependencyGraph.swift index 50e8c58fc58..6a17968ab0b 100644 --- a/Sources/SPMTestSupport/MockDependencyGraph.swift +++ b/Sources/SPMTestSupport/MockDependencyGraph.swift @@ -13,7 +13,7 @@ import XCTest import PackageGraph import PackageModel -import TSCBasic + import struct TSCUtility.Version public struct MockDependencyGraph { diff --git a/Sources/SPMTestSupport/MockHTTPClient.swift b/Sources/SPMTestSupport/MockHTTPClient.swift index f80bcd3e1fe..c680bcc2612 100644 --- a/Sources/SPMTestSupport/MockHTTPClient.swift +++ b/Sources/SPMTestSupport/MockHTTPClient.swift @@ -11,7 +11,6 @@ //===----------------------------------------------------------------------===// import Basics -import TSCBasic extension LegacyHTTPClient { public static func mock(fileSystem: FileSystem) -> LegacyHTTPClient { diff --git a/Sources/SPMTestSupport/MockHashAlgorithm.swift b/Sources/SPMTestSupport/MockHashAlgorithm.swift index aae15d90348..4d8c88e4e81 100644 --- a/Sources/SPMTestSupport/MockHashAlgorithm.swift +++ b/Sources/SPMTestSupport/MockHashAlgorithm.swift @@ -11,7 +11,9 @@ //===----------------------------------------------------------------------===// import Basics -import TSCBasic + +import struct TSCBasic.ByteString +import protocol TSCBasic.HashAlgorithm public final class MockHashAlgorithm { public typealias Handler = @Sendable (ByteString) -> ByteString diff --git a/Sources/SPMTestSupport/MockManifestLoader.swift b/Sources/SPMTestSupport/MockManifestLoader.swift index 9c100bda654..6cb5881eef4 100644 --- a/Sources/SPMTestSupport/MockManifestLoader.swift +++ b/Sources/SPMTestSupport/MockManifestLoader.swift @@ -15,7 +15,7 @@ import Dispatch import PackageModel import PackageLoading import PackageGraph -import TSCBasic + import func XCTest.XCTFail import struct TSCUtility.Version @@ -107,7 +107,7 @@ extension ManifestLoader { // FIXME: placeholder packageLocation = identity.description } - return try tsc_await { + return try temp_await { self.load( manifestPath: manifestPath, manifestToolsVersion: manifestToolsVersion, @@ -156,7 +156,7 @@ extension ManifestLoader { // FIXME: placeholder packageLocation = identity.description } - return try tsc_await { + return try temp_await { self.load( packagePath: packagePath, packageIdentity: packageIdentity, diff --git a/Sources/SPMTestSupport/MockPackage.swift b/Sources/SPMTestSupport/MockPackage.swift index 28c538d9d3d..87919a4c688 100644 --- a/Sources/SPMTestSupport/MockPackage.swift +++ b/Sources/SPMTestSupport/MockPackage.swift @@ -10,9 +10,9 @@ // //===----------------------------------------------------------------------===// +import Basics import Foundation import PackageModel -import TSCBasic public struct MockPackage { public let name: String diff --git a/Sources/SPMTestSupport/MockPackageContainer.swift b/Sources/SPMTestSupport/MockPackageContainer.swift index 79aeaecece8..fa93289358f 100644 --- a/Sources/SPMTestSupport/MockPackageContainer.swift +++ b/Sources/SPMTestSupport/MockPackageContainer.swift @@ -15,7 +15,6 @@ import Dispatch import PackageGraph import PackageModel import SourceControl -import TSCBasic import XCTest import struct TSCUtility.Version diff --git a/Sources/SPMTestSupport/MockRegistry.swift b/Sources/SPMTestSupport/MockRegistry.swift index 393c3d77364..9d70cc5e375 100644 --- a/Sources/SPMTestSupport/MockRegistry.swift +++ b/Sources/SPMTestSupport/MockRegistry.swift @@ -18,7 +18,8 @@ import PackageLoading import PackageModel import PackageRegistry import PackageSigning -import TSCBasic + +import protocol TSCBasic.HashAlgorithm import struct TSCUtility.Version diff --git a/Sources/SPMTestSupport/MockWorkspace.swift b/Sources/SPMTestSupport/MockWorkspace.swift index 07742210021..5489dcd57a0 100644 --- a/Sources/SPMTestSupport/MockWorkspace.swift +++ b/Sources/SPMTestSupport/MockWorkspace.swift @@ -16,13 +16,12 @@ import PackageLoading import PackageModel import PackageRegistry import SourceControl -import TSCBasic import Workspace import XCTest -import struct TSCUtility.Version +import class TSCBasic.InMemoryFileSystem -public typealias Diagnostic = TSCBasic.Diagnostic +import struct TSCUtility.Version public final class MockWorkspace { let sandbox: AbsolutePath @@ -727,7 +726,7 @@ public final class MockWorkspace { let rootInput = PackageGraphRootInput( packages: try rootPaths(for: roots), dependencies: dependencies ) - let rootManifests = try tsc_await { workspace.loadRootManifests(packages: rootInput.packages, observabilityScope: observability.topScope, completion: $0) } + let rootManifests = try temp_await { workspace.loadRootManifests(packages: rootInput.packages, observabilityScope: observability.topScope, completion: $0) } let graphRoot = PackageGraphRoot(input: rootInput, manifests: rootManifests) let manifests = try workspace.loadDependencyManifests(root: graphRoot, observabilityScope: observability.topScope) result(manifests, observability.diagnostics) diff --git a/Sources/SPMTestSupport/Observability.swift b/Sources/SPMTestSupport/Observability.swift index 0b4ba93eaf5..f5526179c62 100644 --- a/Sources/SPMTestSupport/Observability.swift +++ b/Sources/SPMTestSupport/Observability.swift @@ -11,10 +11,13 @@ //===----------------------------------------------------------------------===// import Basics -import struct TSCBasic.StringError import func XCTest.XCTAssertEqual import func XCTest.XCTFail +import struct TSCBasic.StringError + +import TSCTestSupport + extension ObservabilitySystem { public static func makeForTesting(verbose: Bool = true) -> TestingObservability { let collector = TestingObservability.Collector(verbose: verbose) diff --git a/Sources/SPMTestSupport/PIFTester.swift b/Sources/SPMTestSupport/PIFTester.swift index 068953df61e..4e4641fa016 100644 --- a/Sources/SPMTestSupport/PIFTester.swift +++ b/Sources/SPMTestSupport/PIFTester.swift @@ -10,9 +10,9 @@ // //===----------------------------------------------------------------------===// -import TSCBasic -import XCTest +import Basics import XCBuildSupport +import XCTest public func PIFTester(_ pif: PIF.TopLevelObject, _ body: (PIFWorkspaceTester) throws -> Void) throws { try body(PIFWorkspaceTester(workspace: pif.workspace)) diff --git a/Sources/SPMTestSupport/PackageDependencyDescriptionExtensions.swift b/Sources/SPMTestSupport/PackageDependencyDescriptionExtensions.swift index 182794d1ef1..04233baf846 100644 --- a/Sources/SPMTestSupport/PackageDependencyDescriptionExtensions.swift +++ b/Sources/SPMTestSupport/PackageDependencyDescriptionExtensions.swift @@ -10,9 +10,9 @@ // //===----------------------------------------------------------------------===// +import Basics import Foundation import PackageModel -import TSCBasic import struct TSCUtility.Version diff --git a/Sources/SPMTestSupport/SwiftPMProduct.swift b/Sources/SPMTestSupport/SwiftPMProduct.swift index ae4946d12ba..96dc1af9860 100644 --- a/Sources/SPMTestSupport/SwiftPMProduct.swift +++ b/Sources/SPMTestSupport/SwiftPMProduct.swift @@ -10,13 +10,11 @@ // //===----------------------------------------------------------------------===// -import struct TSCBasic.AbsolutePath -import var TSCBasic.localFileSystem +import Basics +import Foundation + import class TSCBasic.Process import struct TSCBasic.ProcessResult -import struct TSCBasic.RelativePath - -import Foundation /// Defines the executables used by SwiftPM. /// Contains path to the currently built executable and @@ -151,3 +149,8 @@ public enum SwiftPMError: Error { case packagePathNotFound case executionFailure(underlying: Error, stdout: String, stderr: String) } + +public enum SwiftPMProductError: Swift.Error { + case packagePathNotFound + case executionFailure(error: Swift.Error, output: String, stderr: String) +} diff --git a/Sources/SPMTestSupport/Toolchain.swift b/Sources/SPMTestSupport/Toolchain.swift index 97bf04eb1e9..3861f5c5c36 100644 --- a/Sources/SPMTestSupport/Toolchain.swift +++ b/Sources/SPMTestSupport/Toolchain.swift @@ -10,10 +10,14 @@ // //===----------------------------------------------------------------------===// +import Basics import Foundation import PackageModel import Workspace -import TSCBasic + +import struct TSCBasic.ByteString +import class TSCBasic.Process +import struct TSCBasic.StringError import struct TSCUtility.SerializedDiagnostics #if os(macOS) diff --git a/Sources/SPMTestSupport/XCTAssertHelpers.swift b/Sources/SPMTestSupport/XCTAssertHelpers.swift index 849a5af4f4b..5459b1c912e 100644 --- a/Sources/SPMTestSupport/XCTAssertHelpers.swift +++ b/Sources/SPMTestSupport/XCTAssertHelpers.swift @@ -14,12 +14,35 @@ import Basics #if os(macOS) import class Foundation.Bundle #endif -import TSCBasic -@_exported import TSCTestSupport +import TSCTestSupport import XCTest +import struct TSCBasic.ProcessResult + import struct TSCUtility.Version +@_exported import func TSCTestSupport.XCTAssertMatch +@_exported import func TSCTestSupport.XCTAssertNoMatch +@_exported import func TSCTestSupport.XCTAssertResultSuccess +@_exported import func TSCTestSupport.XCTAssertThrows + +public func XCTAssertFileExists(_ path: AbsolutePath, file: StaticString = #file, line: UInt = #line) { + TSCTestSupport.XCTAssertFileExists(TSCAbsolutePath(path), file: file, line: line) +} + +public func XCTAssertDirectoryExists(_ path: AbsolutePath, file: StaticString = #file, line: UInt = #line) { + TSCTestSupport.XCTAssertDirectoryExists(TSCAbsolutePath(path), file: file, line: line) +} + +public func XCTAssertNoSuchPath(_ path: AbsolutePath, file: StaticString = #file, line: UInt = #line) { + TSCTestSupport.XCTAssertNoSuchPath(TSCAbsolutePath(path), file: file, line: line) +} + + +public func XCTAssertEqual (_ lhs:(T,U), _ rhs:(T,U), file: StaticString = #file, line: UInt = #line) { + TSCTestSupport.XCTAssertEqual(lhs, rhs, file: file, line: line) +} + public func XCTSkipIfCI(file: StaticString = #filePath, line: UInt = #line) throws { if let ci = ProcessInfo.processInfo.environment["CI"] as? NSString, ci.boolValue { throw XCTSkip("Skipping because the test is being run on CI", file: file, line: line) diff --git a/Sources/SPMTestSupport/misc.swift b/Sources/SPMTestSupport/misc.swift index d661aec2bc0..a01197a7899 100644 --- a/Sources/SPMTestSupport/misc.swift +++ b/Sources/SPMTestSupport/misc.swift @@ -20,13 +20,30 @@ import PackageGraph import PackageLoading import PackageModel import SourceControl -import TSCBasic +import TSCTestSupport import Workspace import func XCTest.XCTFail +import struct TSCBasic.ByteString +import struct TSCBasic.ProcessResult + import enum TSCUtility.Git -@_exported import TSCTestSupport +@_exported import func TSCTestSupport.systemQuietly +@_exported import enum TSCTestSupport.StringPattern + +public func testWithTemporaryDirectory( + function: StaticString = #function, + body: (AbsolutePath) throws -> Void +) throws { + let body2 = { (path: TSCAbsolutePath) in + try body(AbsolutePath(path)) + } + try TSCTestSupport.testWithTemporaryDirectory( + function: function, + body: body2 + ) +} /// Test-helper function that runs a block of code on a copy of a test fixture /// package. The copy is made into a temporary directory, and the block is @@ -270,6 +287,18 @@ public func loadPackageGraph( public let emptyZipFile = ByteString([0x80, 0x75, 0x05, 0x06] + [UInt8](repeating: 0x00, count: 18)) +extension FileSystem { + @_disfavoredOverload + public func createEmptyFiles(at root: AbsolutePath, files: String...) { + self.createEmptyFiles(at: TSCAbsolutePath(root), files: files) + } + + @_disfavoredOverload + public func createEmptyFiles(at root: AbsolutePath, files: [String]) { + self.createEmptyFiles(at: TSCAbsolutePath(root), files: files) + } +} + extension URL: ExpressibleByStringLiteral { public init(_ value: StringLiteralType) { self.init(string: value)! @@ -295,3 +324,43 @@ extension PackageIdentity { Self.plain(value).registry! } } + +extension AbsolutePath: ExpressibleByStringLiteral { + public init(_ value: StringLiteralType) { + try! self.init(validating: value) + } +} + +extension AbsolutePath: ExpressibleByStringInterpolation { + public init(stringLiteral value: String) { + try! self.init(validating: value) + } +} + +extension AbsolutePath { + public init(_ path: StringLiteralType, relativeTo basePath: AbsolutePath) { + try! self.init(validating: path, relativeTo: basePath) + } +} + +extension RelativePath { + @available(*, deprecated, message: "use direct string instead") + public init(static path: StaticString) { + let pathString = path.withUTF8Buffer { + String(decoding: $0, as: UTF8.self) + } + try! self.init(validating: pathString) + } +} + +extension RelativePath: ExpressibleByStringLiteral { + public init(_ value: StringLiteralType) { + try! self.init(validating: value) + } +} + +extension RelativePath: ExpressibleByStringInterpolation { + public init(stringLiteral value: String) { + try! self.init(validating: value) + } +} diff --git a/Sources/SourceControl/GitRepository.swift b/Sources/SourceControl/GitRepository.swift index 669a2167512..4848474a16a 100644 --- a/Sources/SourceControl/GitRepository.swift +++ b/Sources/SourceControl/GitRepository.swift @@ -13,7 +13,16 @@ import Basics import Dispatch import class Foundation.NSLock -import TSCBasic + +import class TSCBasic.Process +import struct TSCBasic.ByteString +import enum TSCBasic.FileMode +import struct TSCBasic.FileInfo +import struct TSCBasic.ProcessResult +import protocol TSCBasic.DiagnosticLocation +import struct TSCBasic.RegEx +import enum TSCBasic.ProcessEnv +import struct TSCBasic.FileSystemError import enum TSCUtility.Git import protocol TSCUtility.DiagnosticLocationProviding @@ -103,7 +112,7 @@ public struct GitRepositoryProvider: RepositoryProvider, Cancellable { } } - public func fetch(repository: RepositorySpecifier, to path: AbsolutePath, progressHandler: FetchProgress.Handler? = nil) throws { + public func fetch(repository: RepositorySpecifier, to path: Basics.AbsolutePath, progressHandler: FetchProgress.Handler? = nil) throws { // Perform a bare clone. // // NOTE: We intentionally do not create a shallow clone here; the @@ -126,14 +135,14 @@ public struct GitRepositoryProvider: RepositoryProvider, Cancellable { progress: progressHandler) } - public func repositoryExists(at directory: AbsolutePath) -> Bool { + public func repositoryExists(at directory: Basics.AbsolutePath) -> Bool { if !localFileSystem.isDirectory(directory) { return false } return self.isValidDirectory(directory) } - public func isValidDirectory(_ directory: AbsolutePath) -> Bool { + public func isValidDirectory(_ directory: Basics.AbsolutePath) -> Bool { do { let result = try self.git.run(["-C", directory.pathString, "rev-parse", "--git-dir"]) return result == ".git" || result == "." || result == directory.pathString @@ -152,18 +161,18 @@ public struct GitRepositoryProvider: RepositoryProvider, Cancellable { } } - public func copy(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws { + public func copy(from sourcePath: Basics.AbsolutePath, to destinationPath: Basics.AbsolutePath) throws { try localFileSystem.copy(from: sourcePath, to: destinationPath) } - public func open(repository: RepositorySpecifier, at path: AbsolutePath) -> Repository { + public func open(repository: RepositorySpecifier, at path: Basics.AbsolutePath) -> Repository { return GitRepository(git: self.git, path: path, isWorkingRepo: false) } public func createWorkingCopy( repository: RepositorySpecifier, - sourcePath: AbsolutePath, - at destinationPath: AbsolutePath, + sourcePath: Basics.AbsolutePath, + at destinationPath: Basics.AbsolutePath, editable: Bool ) throws -> WorkingCheckout { if editable { @@ -201,7 +210,7 @@ public struct GitRepositoryProvider: RepositoryProvider, Cancellable { return try self.openWorkingCopy(at: destinationPath) } - public func workingCopyExists(at path: AbsolutePath) throws -> Bool { + public func workingCopyExists(at path: Basics.AbsolutePath) throws -> Bool { guard localFileSystem.exists(path) else { throw InternalError("\(path) does not exist") } @@ -210,7 +219,7 @@ public struct GitRepositoryProvider: RepositoryProvider, Cancellable { return try repo.checkoutExists() } - public func openWorkingCopy(at path: AbsolutePath) throws -> WorkingCheckout { + public func openWorkingCopy(at path: Basics.AbsolutePath) throws -> WorkingCheckout { return GitRepository(git: self.git, path: path) } @@ -610,7 +619,7 @@ public final class GitRepository: Repository, WorkingCheckout { } /// Returns true if the file at `path` is ignored by `git` - public func areIgnored(_ paths: [AbsolutePath]) throws -> [Bool] { + public func areIgnored(_ paths: [Basics.AbsolutePath]) throws -> [Bool] { return try self.lock.withLock { let stringPaths = paths.map { $0.pathString } @@ -794,7 +803,7 @@ private class GitFileSystemView: FileSystem { // MARK: FileSystem Implementations - private func getEntry(_ path: AbsolutePath) throws -> Tree.Entry? { + private func getEntry(_ path: TSCAbsolutePath) throws -> Tree.Entry? { // Walk the components resolving the tree (starting with a synthetic // root entry). var current: Tree.Entry = Tree.Entry(location: self.root, type: .tree, name: AbsolutePath.root.pathString) @@ -806,7 +815,7 @@ private class GitFileSystemView: FileSystem { currentPath = currentPath.appending(component: component) // We have a component to resolve, so the current entry must be a tree. guard current.type == .tree else { - throw FileSystemError(.notDirectory, currentPath) + throw FileSystemError(.notDirectory, .init(currentPath)) } // Fetch the tree. @@ -837,7 +846,7 @@ private class GitFileSystemView: FileSystem { return tree } - func exists(_ path: AbsolutePath, followSymlink: Bool) -> Bool { + func exists(_ path: TSCAbsolutePath, followSymlink: Bool) -> Bool { do { return try self.getEntry(path) != nil } catch { @@ -845,7 +854,7 @@ private class GitFileSystemView: FileSystem { } } - func isFile(_ path: AbsolutePath) -> Bool { + func isFile(_ path: TSCAbsolutePath) -> Bool { do { if let entry = try getEntry(path), entry.type != .tree { return true @@ -856,7 +865,7 @@ private class GitFileSystemView: FileSystem { } } - func isDirectory(_ path: AbsolutePath) -> Bool { + func isDirectory(_ path: TSCAbsolutePath) -> Bool { do { if let entry = try getEntry(path), entry.type == .tree { return true @@ -867,7 +876,7 @@ private class GitFileSystemView: FileSystem { } } - func isSymlink(_ path: AbsolutePath) -> Bool { + func isSymlink(_ path: TSCAbsolutePath) -> Bool { do { if let entry = try getEntry(path), entry.type == .symlink { return true @@ -878,30 +887,30 @@ private class GitFileSystemView: FileSystem { } } - func isExecutableFile(_ path: AbsolutePath) -> Bool { + func isExecutableFile(_ path: TSCAbsolutePath) -> Bool { if let entry = try? getEntry(path), entry.type == .executableBlob { return true } return false } - func isReadable(_ path: AbsolutePath) -> Bool { + func isReadable(_ path: TSCAbsolutePath) -> Bool { return self.exists(path) } - func isWritable(_ path: AbsolutePath) -> Bool { + func isWritable(_ path: TSCAbsolutePath) -> Bool { return false } - public var currentWorkingDirectory: AbsolutePath? { - return AbsolutePath.root + public var currentWorkingDirectory: TSCAbsolutePath? { + return TSCAbsolutePath.root } - func changeCurrentWorkingDirectory(to path: AbsolutePath) throws { + func changeCurrentWorkingDirectory(to path: TSCAbsolutePath) throws { throw InternalError("changeCurrentWorkingDirectory not supported") } - func getDirectoryContents(_ path: AbsolutePath) throws -> [String] { + func getDirectoryContents(_ path: TSCAbsolutePath) throws -> [String] { guard let entry = try getEntry(path) else { throw FileSystemError(.noEntry, path) } @@ -911,7 +920,7 @@ private class GitFileSystemView: FileSystem { return try self.getTree(entry.location).contents.map { $0.name } } - func readFileContents(_ path: AbsolutePath) throws -> ByteString { + func readFileContents(_ path: TSCAbsolutePath) throws -> ByteString { guard let entry = try getEntry(path) else { throw FileSystemError(.noEntry, path) } @@ -929,47 +938,47 @@ private class GitFileSystemView: FileSystem { // MARK: Unsupported methods. - public var homeDirectory: AbsolutePath { + public var homeDirectory: TSCAbsolutePath { fatalError("unsupported") } - public var cachesDirectory: AbsolutePath? { + public var cachesDirectory: TSCAbsolutePath? { fatalError("unsupported") } - public var tempDirectory: AbsolutePath { + public var tempDirectory: TSCAbsolutePath { fatalError("unsupported") } - func createDirectory(_ path: AbsolutePath) throws { + func createDirectory(_ path: TSCAbsolutePath) throws { throw FileSystemError(.unsupported, path) } - func createDirectory(_ path: AbsolutePath, recursive: Bool) throws { + func createDirectory(_ path: TSCAbsolutePath, recursive: Bool) throws { throw FileSystemError(.unsupported, path) } - func createSymbolicLink(_ path: AbsolutePath, pointingAt destination: AbsolutePath, relative: Bool) throws { + func createSymbolicLink(_ path: TSCAbsolutePath, pointingAt destination: TSCAbsolutePath, relative: Bool) throws { throw FileSystemError(.unsupported, path) } - func writeFileContents(_ path: AbsolutePath, bytes: ByteString) throws { + func writeFileContents(_ path: TSCAbsolutePath, bytes: ByteString) throws { throw FileSystemError(.unsupported, path) } - func removeFileTree(_ path: AbsolutePath) throws { + func removeFileTree(_ path: TSCAbsolutePath) throws { throw FileSystemError(.unsupported, path) } - func chmod(_ mode: FileMode, path: AbsolutePath, options: Set) throws { + func chmod(_ mode: FileMode, path: TSCAbsolutePath, options: Set) throws { throw FileSystemError(.unsupported, path) } - func copy(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws { + func copy(from sourcePath: TSCAbsolutePath, to destinationPath: TSCAbsolutePath) throws { fatalError("will never be supported") } - func move(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws { + func move(from sourcePath: TSCAbsolutePath, to destinationPath: TSCAbsolutePath) throws { fatalError("will never be supported") } } diff --git a/Sources/SourceControl/Repository.swift b/Sources/SourceControl/Repository.swift index f03001cf20c..e41a7f1635a 100644 --- a/Sources/SourceControl/Repository.swift +++ b/Sources/SourceControl/Repository.swift @@ -10,9 +10,8 @@ // //===----------------------------------------------------------------------===// -import Foundation -import TSCBasic import Basics +import Foundation /// Specifies a repository address. public struct RepositorySpecifier: Hashable, Sendable { diff --git a/Sources/SourceControl/RepositoryManager.swift b/Sources/SourceControl/RepositoryManager.swift index 87a233adb80..050ca1e300b 100644 --- a/Sources/SourceControl/RepositoryManager.swift +++ b/Sources/SourceControl/RepositoryManager.swift @@ -13,9 +13,10 @@ import Basics import Dispatch import Foundation -import TSCBasic import PackageModel +import enum TSCBasic.ProcessEnv + /// Manages a collection of bare repositories. public class RepositoryManager: Cancellable { public typealias Delegate = RepositoryManagerDelegate diff --git a/Sources/SwiftSDKTool/Configuration/ConfigurationSubcommand.swift b/Sources/SwiftSDKTool/Configuration/ConfigurationSubcommand.swift index 71af64df1a9..635c46d1f61 100644 --- a/Sources/SwiftSDKTool/Configuration/ConfigurationSubcommand.swift +++ b/Sources/SwiftSDKTool/Configuration/ConfigurationSubcommand.swift @@ -14,8 +14,6 @@ import ArgumentParser import Basics import PackageModel -import struct TSCBasic.AbsolutePath - protocol ConfigurationSubcommand: SwiftSDKSubcommand { /// An identifier of an already installed destination. var destinationID: String { get } diff --git a/Sources/SwiftSDKTool/Configuration/ResetConfiguration.swift b/Sources/SwiftSDKTool/Configuration/ResetConfiguration.swift index 1e719b59eed..d57e8c3103b 100644 --- a/Sources/SwiftSDKTool/Configuration/ResetConfiguration.swift +++ b/Sources/SwiftSDKTool/Configuration/ResetConfiguration.swift @@ -15,8 +15,6 @@ import Basics import CoreCommands import PackageModel -import struct TSCBasic.AbsolutePath - struct ResetConfiguration: ConfigurationSubcommand { static let configuration = CommandConfiguration( commandName: "reset", diff --git a/Sources/SwiftSDKTool/Configuration/SetConfiguration.swift b/Sources/SwiftSDKTool/Configuration/SetConfiguration.swift index 2b8f67f9caf..6b08fec6760 100644 --- a/Sources/SwiftSDKTool/Configuration/SetConfiguration.swift +++ b/Sources/SwiftSDKTool/Configuration/SetConfiguration.swift @@ -15,8 +15,6 @@ import Basics import CoreCommands import PackageModel -import struct TSCBasic.AbsolutePath - struct SetConfiguration: ConfigurationSubcommand { static let configuration = CommandConfiguration( commandName: "set", @@ -85,7 +83,7 @@ struct SetConfiguration: ConfigurationSubcommand { var configuration = destination.pathsConfiguration var updatedProperties = [String]() - let currentWorkingDirectory = fileSystem.currentWorkingDirectory + let currentWorkingDirectory: AbsolutePath? = fileSystem.currentWorkingDirectory if let sdkRootPath { configuration.sdkRootPath = try AbsolutePath(validating: sdkRootPath, relativeTo: currentWorkingDirectory) diff --git a/Sources/SwiftSDKTool/Configuration/ShowConfiguration.swift b/Sources/SwiftSDKTool/Configuration/ShowConfiguration.swift index fd7851ae6a9..c166f147838 100644 --- a/Sources/SwiftSDKTool/Configuration/ShowConfiguration.swift +++ b/Sources/SwiftSDKTool/Configuration/ShowConfiguration.swift @@ -15,8 +15,6 @@ import Basics import CoreCommands import PackageModel -import struct TSCBasic.AbsolutePath - struct ShowConfiguration: ConfigurationSubcommand { static let configuration = CommandConfiguration( commandName: "show", diff --git a/Sources/SwiftSDKTool/InstallSwiftSDK.swift b/Sources/SwiftSDKTool/InstallSwiftSDK.swift index e4fe5ca9fa1..a77eaf8dc16 100644 --- a/Sources/SwiftSDKTool/InstallSwiftSDK.swift +++ b/Sources/SwiftSDKTool/InstallSwiftSDK.swift @@ -16,10 +16,7 @@ import CoreCommands import Foundation import PackageModel -import struct TSCBasic.AbsolutePath -import var TSCBasic.localFileSystem import var TSCBasic.stdoutStream -import func TSCBasic.tsc_await public struct InstallSwiftSDK: SwiftSDKSubcommand { public static let configuration = CommandConfiguration( diff --git a/Sources/SwiftSDKTool/ListSwiftSDKs.swift b/Sources/SwiftSDKTool/ListSwiftSDKs.swift index 71ff1119d1f..b70162b100f 100644 --- a/Sources/SwiftSDKTool/ListSwiftSDKs.swift +++ b/Sources/SwiftSDKTool/ListSwiftSDKs.swift @@ -16,8 +16,6 @@ import CoreCommands import PackageModel import SPMBuildCore -import struct TSCBasic.AbsolutePath - public struct ListSwiftSDKs: SwiftSDKSubcommand { public static let configuration = CommandConfiguration( commandName: "list", diff --git a/Sources/SwiftSDKTool/RemoveSwiftSDK.swift b/Sources/SwiftSDKTool/RemoveSwiftSDK.swift index 909e0e1920d..b081ef98cca 100644 --- a/Sources/SwiftSDKTool/RemoveSwiftSDK.swift +++ b/Sources/SwiftSDKTool/RemoveSwiftSDK.swift @@ -15,8 +15,6 @@ import Basics import CoreCommands import PackageModel -import struct TSCBasic.AbsolutePath - public struct RemoveSwiftSDK: SwiftSDKSubcommand { public static let configuration = CommandConfiguration( commandName: "remove", diff --git a/Sources/SwiftSDKTool/SwiftSDKSubcommand.swift b/Sources/SwiftSDKTool/SwiftSDKSubcommand.swift index 06a7e6caadf..751488012dd 100644 --- a/Sources/SwiftSDKTool/SwiftSDKSubcommand.swift +++ b/Sources/SwiftSDKTool/SwiftSDKSubcommand.swift @@ -16,9 +16,6 @@ import CoreCommands import Dispatch import PackageModel -import struct TSCBasic.AbsolutePath -import protocol TSCBasic.FileSystem -import var TSCBasic.localFileSystem import var TSCBasic.stdoutStream /// A protocol for functions and properties common to all destination subcommands. diff --git a/Sources/Workspace/DefaultPluginScriptRunner.swift b/Sources/Workspace/DefaultPluginScriptRunner.swift index 71f3be2792a..1932e775e01 100644 --- a/Sources/Workspace/DefaultPluginScriptRunner.swift +++ b/Sources/Workspace/DefaultPluginScriptRunner.swift @@ -15,25 +15,29 @@ import Foundation import PackageGraph import PackageModel import SPMBuildCore -import TSCBasic + +import struct TSCBasic.ByteString +import struct TSCBasic.ProcessResult +import enum TSCBasic.ProcessEnv +import class TSCBasic.Process import struct TSCUtility.SerializedDiagnostics /// A plugin script runner that compiles the plugin source files as an executable binary for the host platform, and invokes it as a subprocess. public struct DefaultPluginScriptRunner: PluginScriptRunner, Cancellable { private let fileSystem: FileSystem - private let cacheDir: AbsolutePath + private let cacheDir: Basics.AbsolutePath private let toolchain: UserToolchain private let extraPluginSwiftCFlags: [String] private let enableSandbox: Bool private let cancellator: Cancellator private let verboseOutput: Bool - private let sdkRootCache = ThreadSafeBox() + private let sdkRootCache = ThreadSafeBox() public init( - fileSystem: FileSystem, - cacheDir: AbsolutePath, + fileSystem: Basics.FileSystem, + cacheDir: Basics.AbsolutePath, toolchain: UserToolchain, extraPluginSwiftCFlags: [String] = [], enableSandbox: Bool = true, @@ -50,13 +54,13 @@ public struct DefaultPluginScriptRunner: PluginScriptRunner, Cancellable { /// Starts evaluating a plugin by compiling it and running it as a subprocess. The name is used as the basename for the executable and auxiliary files. The tools version controls the availability of APIs in PackagePlugin, and should be set to the tools version of the package that defines the plugin (not the package containing the target to which it is being applied). This function returns immediately and then repeated calls the output handler on the given callback queue as plain-text output is received from the plugin, and then eventually calls the completion handler on the given callback queue once the plugin is done. public func runPluginScript( - sourceFiles: [AbsolutePath], + sourceFiles: [Basics.AbsolutePath], pluginName: String, initialMessage: Data, toolsVersion: ToolsVersion, - workingDirectory: AbsolutePath, - writableDirectories: [AbsolutePath], - readOnlyDirectories: [AbsolutePath], + workingDirectory: Basics.AbsolutePath, + writableDirectories: [Basics.AbsolutePath], + readOnlyDirectories: [Basics.AbsolutePath], allowNetworkConnections: [SandboxNetworkPermission], fileSystem: FileSystem, observabilityScope: ObservabilityScope, @@ -108,7 +112,7 @@ public struct DefaultPluginScriptRunner: PluginScriptRunner, Cancellable { /// Starts compiling a plugin script asynchronously and when done, calls the completion handler on the callback queue with the results (including the path of the compiled plugin executable and with any emitted diagnostics, etc). Existing compilation results that are still valid are reused, if possible. This function itself returns immediately after starting the compile. Note that the completion handler only receives a `.failure` result if the compiler couldn't be invoked at all; a non-zero exit code from the compiler still returns `.success` with a full compilation result that notes the error in the diagnostics (in other words, a `.failure` result only means "failure to invoke the compiler"). public func compilePluginScript( - sourceFiles: [AbsolutePath], + sourceFiles: [Basics.AbsolutePath], pluginName: String, toolsVersion: ToolsVersion, observabilityScope: ObservabilityScope, @@ -248,7 +252,8 @@ public struct DefaultPluginScriptRunner: PluginScriptRunner, Cancellable { stringToHash.append("\(key)=\(value)\n") } for sourceFile in sourceFiles { - stringToHash.append(try fileSystem.readFileContents(sourceFile).description) + let source: String = try fileSystem.readFileContents(sourceFile) + stringToHash.append(source) } compilerInputHash = ByteString(encodingAsUTF8: stringToHash).sha256Checksum observabilityScope.emit(debug: "Computed hash of plugin compilation inputs: \(compilerInputHash!)") @@ -388,12 +393,12 @@ public struct DefaultPluginScriptRunner: PluginScriptRunner, Cancellable { /// Returns path to the sdk, if possible. // FIXME: This is copied from ManifestLoader. This should be consolidated when ManifestLoader is cleaned up. - private func sdkRoot() -> AbsolutePath? { + private func sdkRoot() -> Basics.AbsolutePath? { if let sdkRoot = self.sdkRootCache.get() { return sdkRoot } - var sdkRootPath: AbsolutePath? + var sdkRootPath: Basics.AbsolutePath? // Find SDKROOT on macOS using xcrun. #if os(macOS) let foundPath = try? TSCBasic.Process.checkNonZeroExit( @@ -402,7 +407,7 @@ public struct DefaultPluginScriptRunner: PluginScriptRunner, Cancellable { guard let sdkRoot = foundPath?.spm_chomp(), !sdkRoot.isEmpty else { return nil } - if let path = try? AbsolutePath(validating: sdkRoot) { + if let path = try? Basics.AbsolutePath(validating: sdkRoot) { sdkRootPath = path self.sdkRootCache.put(path) } @@ -413,10 +418,10 @@ public struct DefaultPluginScriptRunner: PluginScriptRunner, Cancellable { /// Private function that invokes a compiled plugin executable and communicates with it until it finishes. fileprivate func invoke( - compiledExec: AbsolutePath, - workingDirectory: AbsolutePath, - writableDirectories: [AbsolutePath], - readOnlyDirectories: [AbsolutePath], + compiledExec: Basics.AbsolutePath, + workingDirectory: Basics.AbsolutePath, + writableDirectories: [Basics.AbsolutePath], + readOnlyDirectories: [Basics.AbsolutePath], allowNetworkConnections: [SandboxNetworkPermission], initialMessage: Data, observabilityScope: ObservabilityScope, @@ -450,7 +455,7 @@ public struct DefaultPluginScriptRunner: PluginScriptRunner, Cancellable { } // Create and configure a Process. We set the working directory to the cache directory, so that relative paths end up there. - let process = Process() + let process = Foundation.Process() process.executableURL = URL(fileURLWithPath: command[0]) process.arguments = Array(command.dropFirst()) process.environment = ProcessInfo.processInfo.environment diff --git a/Sources/Workspace/Diagnostics.swift b/Sources/Workspace/Diagnostics.swift index ef65b7119e1..4165aed82f2 100644 --- a/Sources/Workspace/Diagnostics.swift +++ b/Sources/Workspace/Diagnostics.swift @@ -15,7 +15,8 @@ import Foundation import PackageGraph import PackageLoading import PackageModel -import TSCBasic + +import struct TSCBasic.FileSystemError public struct ManifestParseDiagnostic: CustomStringConvertible { public let errors: [String] diff --git a/Sources/Workspace/FileSystemPackageContainer.swift b/Sources/Workspace/FileSystemPackageContainer.swift index 8835dd32f58..8033394f268 100644 --- a/Sources/Workspace/FileSystemPackageContainer.swift +++ b/Sources/Workspace/FileSystemPackageContainer.swift @@ -15,7 +15,6 @@ import Dispatch import PackageGraph import PackageLoading import PackageModel -import TSCBasic import struct TSCUtility.Version diff --git a/Sources/Workspace/InitPackage.swift b/Sources/Workspace/InitPackage.swift index 36fe0d9f294..d0d0e5e3bf9 100644 --- a/Sources/Workspace/InitPackage.swift +++ b/Sources/Workspace/InitPackage.swift @@ -11,9 +11,10 @@ //===----------------------------------------------------------------------===// import Basics -import TSCBasic import PackageModel +import protocol TSCBasic.OutputByteStream + /// Create an initial template package. public final class InitPackage { /// The tool version to be used for new packages. diff --git a/Sources/Workspace/ManagedArtifact.swift b/Sources/Workspace/ManagedArtifact.swift index 9b2e15862f4..53bf899f226 100644 --- a/Sources/Workspace/ManagedArtifact.swift +++ b/Sources/Workspace/ManagedArtifact.swift @@ -10,10 +10,10 @@ // //===----------------------------------------------------------------------===// +import Basics import PackageGraph import PackageModel import SourceControl -import TSCBasic extension Workspace { /// A downloaded artifact managed by the workspace. diff --git a/Sources/Workspace/ManagedDependency.swift b/Sources/Workspace/ManagedDependency.swift index 4953760c944..0fbf78c85a8 100644 --- a/Sources/Workspace/ManagedDependency.swift +++ b/Sources/Workspace/ManagedDependency.swift @@ -14,7 +14,6 @@ import Basics import PackageGraph import PackageModel import SourceControl -import TSCBasic import struct TSCUtility.Version diff --git a/Sources/Workspace/RegistryPackageContainer.swift b/Sources/Workspace/RegistryPackageContainer.swift index e6093401f3d..82c5bb756fc 100644 --- a/Sources/Workspace/RegistryPackageContainer.swift +++ b/Sources/Workspace/RegistryPackageContainer.swift @@ -16,7 +16,8 @@ import PackageGraph import PackageLoading import PackageModel import PackageRegistry -import TSCBasic + +import class TSCBasic.InMemoryFileSystem import struct TSCUtility.Version diff --git a/Sources/Workspace/ResolvedFileWatcher.swift b/Sources/Workspace/ResolvedFileWatcher.swift index 2c9a790c2b5..d8b5764d88d 100644 --- a/Sources/Workspace/ResolvedFileWatcher.swift +++ b/Sources/Workspace/ResolvedFileWatcher.swift @@ -10,10 +10,12 @@ // //===----------------------------------------------------------------------===// +import Basics import class Foundation.NSLock import PackageModel import PackageGraph -import TSCBasic + +import struct TSCBasic.ByteString import class TSCUtility.FSWatch @@ -24,7 +26,7 @@ final class ResolvedFileWatcher { private var fswatch: FSWatch! private var existingValue: ByteString? private let valueLock = NSLock() - private let resolvedFile: AbsolutePath + private let resolvedFile: TSCAbsolutePath public func updateValue() { valueLock.withLock { @@ -33,9 +35,10 @@ final class ResolvedFileWatcher { } init(resolvedFile: AbsolutePath, onChange: @escaping () -> ()) throws { + let resolvedFile = TSCAbsolutePath(resolvedFile) self.resolvedFile = resolvedFile - let block = { [weak self] (paths: [AbsolutePath]) in + let block = { [weak self] (paths: [TSCAbsolutePath]) in guard let self else { return } // Check if resolved file is part of the received paths. @@ -45,7 +48,7 @@ final class ResolvedFileWatcher { self.valueLock.withLock { // Compute the contents of the resolved file and fire the onChange block // if its value is different than existing value. - let newValue = try? localFileSystem.readFileContents(resolvedFile) + let newValue: ByteString? = try? localFileSystem.readFileContents(resolvedFile) if self.existingValue != newValue { self.existingValue = newValue onChange() diff --git a/Sources/Workspace/ResolverPrecomputationProvider.swift b/Sources/Workspace/ResolverPrecomputationProvider.swift index 7fffebb6f6e..eb2d02bce14 100644 --- a/Sources/Workspace/ResolverPrecomputationProvider.swift +++ b/Sources/Workspace/ResolverPrecomputationProvider.swift @@ -15,7 +15,6 @@ import Dispatch import PackageGraph import PackageModel import SourceControl -import TSCBasic import struct TSCUtility.Version diff --git a/Sources/Workspace/SourceControlPackageContainer.swift b/Sources/Workspace/SourceControlPackageContainer.swift index 1e5572ed4dc..06b73a7970d 100644 --- a/Sources/Workspace/SourceControlPackageContainer.swift +++ b/Sources/Workspace/SourceControlPackageContainer.swift @@ -18,7 +18,8 @@ import PackageGraph import PackageLoading import PackageModel import SourceControl -import TSCBasic + +import struct TSCBasic.RegEx import enum TSCUtility.Git import struct TSCUtility.Version diff --git a/Sources/Workspace/ToolsVersionSpecificationRewriter.swift b/Sources/Workspace/ToolsVersionSpecificationRewriter.swift index 29af86f43d7..aefe97cb0a3 100644 --- a/Sources/Workspace/ToolsVersionSpecificationRewriter.swift +++ b/Sources/Workspace/ToolsVersionSpecificationRewriter.swift @@ -16,10 +16,13 @@ /// // ----------------------------------------------------------------------------- -import TSCBasic +import Basics import PackageModel import PackageLoading +import struct TSCBasic.ByteString +import class TSCBasic.BufferedOutputByteStream + public struct ToolsVersionSpecificationWriter { // designed to be used as a static utility private init() {} diff --git a/Sources/Workspace/Workspace+BinaryArtifacts.swift b/Sources/Workspace/Workspace+BinaryArtifacts.swift index 579024f0caf..13c5be1198f 100644 --- a/Sources/Workspace/Workspace+BinaryArtifacts.swift +++ b/Sources/Workspace/Workspace+BinaryArtifacts.swift @@ -14,9 +14,11 @@ import Basics import Foundation import PackageModel import SPMBuildCore -import TSCBasic - import PackageLoading + +import struct TSCBasic.ByteString +import protocol TSCBasic.HashAlgorithm + import enum TSCUtility.Diagnostics extension Workspace { diff --git a/Sources/Workspace/Workspace+Configuration.swift b/Sources/Workspace/Workspace+Configuration.swift index 20249dd6322..f443420a7a2 100644 --- a/Sources/Workspace/Workspace+Configuration.swift +++ b/Sources/Workspace/Workspace+Configuration.swift @@ -17,7 +17,9 @@ import PackageGraph import PackageLoading import PackageModel import PackageRegistry -import TSCBasic + +import struct TSCBasic.ByteString +import enum TSCBasic.ProcessEnv import protocol TSCUtility.SimplePersistanceProtocol import class TSCUtility.SimplePersistence diff --git a/Sources/Workspace/Workspace+State.swift b/Sources/Workspace/Workspace+State.swift index a9dd0a87431..b54ab25cb71 100644 --- a/Sources/Workspace/Workspace+State.swift +++ b/Sources/Workspace/Workspace+State.swift @@ -15,7 +15,6 @@ import Foundation import PackageGraph import PackageModel import SourceControl -import TSCBasic import struct TSCUtility.Version diff --git a/Sources/Workspace/Workspace.swift b/Sources/Workspace/Workspace.swift index d5b82c8fdc3..b266b944c52 100644 --- a/Sources/Workspace/Workspace.swift +++ b/Sources/Workspace/Workspace.swift @@ -21,14 +21,20 @@ import PackageGraph import PackageRegistry import PackageSigning import SourceControl -import TSCBasic + +import protocol TSCBasic.HashAlgorithm +import class TSCBasic.InMemoryFileSystem +import struct TSCBasic.KeyedPair +import var TSCBasic.stderrStream +import struct TSCBasic.SHA256 +import func TSCBasic.topologicalSort +import func TSCBasic.transitiveClosure +import func TSCBasic.os_signpost import enum TSCUtility.Diagnostics import enum TSCUtility.SignpostName import struct TSCUtility.Version -public typealias Diagnostic = TSCBasic.Diagnostic - /// Enumeration of the different reasons for which the resolver needs to be run. public enum WorkspaceResolveReason: Equatable { /// Resolution was forced. @@ -65,7 +71,7 @@ public protocol WorkspaceDelegate: AnyObject { func willLoadManifest(packageIdentity: PackageIdentity, packagePath: AbsolutePath, url: String, version: Version?, packageKind: PackageReference.Kind) /// The workspace has loaded a package manifest, either successfully or not. The manifest is nil if an error occurs, in which case there will also be at least one error in the list of diagnostics (there may be warnings even if a manifest is loaded successfully). - func didLoadManifest(packageIdentity: PackageIdentity, packagePath: AbsolutePath, url: String, version: Version?, packageKind: PackageReference.Kind, manifest: Manifest?, diagnostics: [Basics.Diagnostic], duration: DispatchTimeInterval) + func didLoadManifest(packageIdentity: PackageIdentity, packagePath: AbsolutePath, url: String, version: Version?, packageKind: PackageReference.Kind, manifest: Manifest?, diagnostics: [Diagnostic], duration: DispatchTimeInterval) /// The workspace has started fetching this package. func willFetchPackage(package: PackageIdentity, packageLocation: String?, fetchDetails: PackageFetchDetails) @@ -1360,7 +1366,7 @@ extension Workspace { for path in paths { do { - let result = try tsc_await { + let result = try temp_await { scanner.scanImports(path, callbackQueue: DispatchQueue.sharedConcurrent, completion: $0) } importList[pkgId]?[pluginTarget.name]?.append(contentsOf: result) @@ -2178,7 +2184,7 @@ extension Workspace { .packageMetadata(identity: packageIdentity, kind: packageKind) } - var manifestLoadingDiagnostics = [Basics.Diagnostic]() + var manifestLoadingDiagnostics = [Diagnostic]() let start = DispatchTime.now() self.manifestLoader.load( diff --git a/Sources/XCBuildSupport/PIF.swift b/Sources/XCBuildSupport/PIF.swift index 6fcb64094e7..8fa68a21266 100644 --- a/Sources/XCBuildSupport/PIF.swift +++ b/Sources/XCBuildSupport/PIF.swift @@ -12,9 +12,10 @@ import Basics import Foundation -import TSCBasic import PackageModel +import struct TSCBasic.ByteString + /// The Project Interchange Format (PIF) is a structured representation of the /// project model created by clients (Xcode/SwiftPM) to send to XCBuild. /// diff --git a/Sources/XCBuildSupport/PIFBuilder.swift b/Sources/XCBuildSupport/PIFBuilder.swift index c5a7751bd2b..961564bbf12 100644 --- a/Sources/XCBuildSupport/PIFBuilder.swift +++ b/Sources/XCBuildSupport/PIFBuilder.swift @@ -11,15 +11,15 @@ //===----------------------------------------------------------------------===// import Foundation - -import TSCBasic - import Basics import PackageModel import PackageLoading import PackageGraph import SPMBuildCore +import func TSCBasic.topologicalSort +import func TSCBasic.memoize + /// The parameters required by `PIFBuilder`. struct PIFBuilderParameters { diff --git a/Sources/XCBuildSupport/XCBuildDelegate.swift b/Sources/XCBuildSupport/XCBuildDelegate.swift index 279137e0608..46393936a2a 100644 --- a/Sources/XCBuildSupport/XCBuildDelegate.swift +++ b/Sources/XCBuildSupport/XCBuildDelegate.swift @@ -13,7 +13,9 @@ import Basics import Foundation import SPMBuildCore -import TSCBasic + +import class TSCBasic.ThreadSafeOutputByteStream +import protocol TSCBasic.OutputByteStream import enum TSCUtility.Diagnostics import protocol TSCUtility.ProgressAnimationProtocol diff --git a/Sources/XCBuildSupport/XCBuildMessage.swift b/Sources/XCBuildSupport/XCBuildMessage.swift index 36fe447b8ac..b68c9bb9abd 100644 --- a/Sources/XCBuildSupport/XCBuildMessage.swift +++ b/Sources/XCBuildSupport/XCBuildMessage.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// +import Basics import Foundation -import TSCBasic /// Represents a message output by xcbuild. public enum XCBuildMessage { diff --git a/Sources/XCBuildSupport/XCBuildOutputParser.swift b/Sources/XCBuildSupport/XCBuildOutputParser.swift index 259ef59dbe8..5feee48d755 100644 --- a/Sources/XCBuildSupport/XCBuildOutputParser.swift +++ b/Sources/XCBuildSupport/XCBuildOutputParser.swift @@ -11,7 +11,6 @@ //===----------------------------------------------------------------------===// import Foundation -import TSCBasic import class TSCUtility.JSONMessageStreamingParser import protocol TSCUtility.JSONMessageStreamingParserDelegate diff --git a/Sources/XCBuildSupport/XcodeBuildSystem.swift b/Sources/XCBuildSupport/XcodeBuildSystem.swift index 7a07043f219..58457b7f420 100644 --- a/Sources/XCBuildSupport/XcodeBuildSystem.swift +++ b/Sources/XCBuildSupport/XcodeBuildSystem.swift @@ -16,7 +16,12 @@ import class Foundation.JSONEncoder import PackageGraph import PackageModel import SPMBuildCore -import TSCBasic + +import protocol TSCBasic.OutputByteStream +import class TSCBasic.Process +import enum TSCBasic.ProcessEnv +import func TSCBasic.withTemporaryFile +import func TSCBasic.memoize import class TSCUtility.MultiLinePercentProgressAnimation import enum TSCUtility.Diagnostics @@ -227,7 +232,7 @@ public final class XcodeBuildSystem: SPMBuildCore.BuildSystem { // Write out the parameters as a JSON file, and return the path. let encoder = JSONEncoder.makeWithDefaults() let data = try encoder.encode(params) - let file = try withTemporaryFile(deleteOnClose: false) { $0.path } + let file = try withTemporaryFile(deleteOnClose: false) { AbsolutePath($0.path) } try self.fileSystem.writeFileContents(file, data: data) return file } diff --git a/Sources/swift-bootstrap/main.swift b/Sources/swift-bootstrap/main.swift index db78b04846d..a7cdb1e3da3 100644 --- a/Sources/swift-bootstrap/main.swift +++ b/Sources/swift-bootstrap/main.swift @@ -20,9 +20,12 @@ import PackageGraph import PackageLoading import PackageModel import SPMBuildCore -import TSCBasic import XCBuildSupport +import struct TSCBasic.KeyedPair +import func TSCBasic.topologicalSort +import var TSCBasic.stdoutStream + import enum TSCUtility.Diagnostics import struct TSCUtility.Version @@ -147,7 +150,7 @@ struct SwiftBootstrapBuildTool: ParsableCommand { } }.topScope - guard let cwd = fileSystem.currentWorkingDirectory else { + guard let cwd: AbsolutePath = fileSystem.currentWorkingDirectory else { observabilityScope.emit(error: "couldn't determine the current working directory") throw ExitCode.failure } @@ -195,7 +198,7 @@ struct SwiftBootstrapBuildTool: ParsableCommand { ] init(fileSystem: FileSystem, observabilityScope: ObservabilityScope, logLevel: Basics.Diagnostic.Severity) throws { - guard let cwd = fileSystem.currentWorkingDirectory else { + guard let cwd: AbsolutePath = fileSystem.currentWorkingDirectory else { throw ExitCode.failure } @@ -310,7 +313,7 @@ struct SwiftBootstrapBuildTool: ParsableCommand { func loadPackageGraph(packagePath: AbsolutePath, manifestLoader: ManifestLoader) throws -> PackageGraph { let rootPackageRef = PackageReference(identity: .init(path: packagePath), kind: .root(packagePath)) - let rootPackageManifest = try tsc_await { self.loadManifest(manifestLoader: manifestLoader, package: rootPackageRef, completion: $0) } + let rootPackageManifest = try temp_await { self.loadManifest(manifestLoader: manifestLoader, package: rootPackageRef, completion: $0) } var loadedManifests = [PackageIdentity: Manifest]() loadedManifests[rootPackageRef.identity] = rootPackageManifest @@ -407,7 +410,7 @@ struct SwiftBootstrapBuildTool: ParsableCommand { // TODO: move to shared area extension AbsolutePath: ExpressibleByArgument { public init?(argument: String) { - if let cwd = localFileSystem.currentWorkingDirectory { + if let cwd: AbsolutePath = localFileSystem.currentWorkingDirectory { guard let path = try? AbsolutePath(validating: argument, relativeTo: cwd) else { return nil } diff --git a/Sources/swift-package-manager/SwiftPM.swift b/Sources/swift-package-manager/SwiftPM.swift index 180f0914ac8..8502bb621ca 100644 --- a/Sources/swift-package-manager/SwiftPM.swift +++ b/Sources/swift-package-manager/SwiftPM.swift @@ -10,11 +10,11 @@ // //===----------------------------------------------------------------------===// +import Basics import Commands import SwiftSDKTool import PackageCollectionsTool import PackageRegistryTool -import TSCBasic let firstArg = CommandLine.arguments[0] let execName = (try? AbsolutePath(validating: firstArg).basenameWithoutExt) ?? diff --git a/Tests/BasicsTests/Archiver/TarArchiverTests.swift b/Tests/BasicsTests/Archiver/TarArchiverTests.swift index 8e8aed8ad62..2efb0848171 100644 --- a/Tests/BasicsTests/Archiver/TarArchiverTests.swift +++ b/Tests/BasicsTests/Archiver/TarArchiverTests.swift @@ -11,11 +11,13 @@ //===----------------------------------------------------------------------===// import Basics -import TSCBasic import TSCclibc // for SPM_posix_spawn_file_actions_addchdir_np_supported -import TSCTestSupport +import SPMTestSupport import XCTest +import class TSCBasic.InMemoryFileSystem +import struct TSCBasic.FileSystemError + final class TarArchiverTests: XCTestCase { func testSuccess() throws { try testWithTemporaryDirectory { tmpdir in diff --git a/Tests/BasicsTests/Archiver/UniversalArchiverTests.swift b/Tests/BasicsTests/Archiver/UniversalArchiverTests.swift index c3783e37216..685d6e954ee 100644 --- a/Tests/BasicsTests/Archiver/UniversalArchiverTests.swift +++ b/Tests/BasicsTests/Archiver/UniversalArchiverTests.swift @@ -11,11 +11,13 @@ //===----------------------------------------------------------------------===// import Basics -import TSCBasic import TSCclibc // for SPM_posix_spawn_file_actions_addchdir_np_supported -import TSCTestSupport +import SPMTestSupport import XCTest +import class TSCBasic.InMemoryFileSystem +import struct TSCBasic.FileSystemError + final class UniversalArchiverTests: XCTestCase { func testSuccess() throws { try testWithTemporaryDirectory { tmpdir in diff --git a/Tests/BasicsTests/Archiver/ZipArchiverTests.swift b/Tests/BasicsTests/Archiver/ZipArchiverTests.swift index 02a40c36d69..5883e7c42d6 100644 --- a/Tests/BasicsTests/Archiver/ZipArchiverTests.swift +++ b/Tests/BasicsTests/Archiver/ZipArchiverTests.swift @@ -11,11 +11,13 @@ //===----------------------------------------------------------------------===// import Basics -import TSCBasic -import TSCTestSupport +import SPMTestSupport import XCTest import TSCclibc // for SPM_posix_spawn_file_actions_addchdir_np_supported +import class TSCBasic.InMemoryFileSystem +import struct TSCBasic.FileSystemError + class ZipArchiverTests: XCTestCase { func testZipArchiverSuccess() throws { try testWithTemporaryDirectory { tmpdir in @@ -255,17 +257,17 @@ class ArchiverTests: XCTestCase { extension Archiver { func extract(from: AbsolutePath, to: AbsolutePath) throws { - try tsc_await { + try temp_await { self.extract(from: from, to: to, completion: $0) } } func compress(directory: AbsolutePath, to: AbsolutePath) throws { - try tsc_await { + try temp_await { self.compress(directory: directory, to: to, completion: $0) } } func validate(path: AbsolutePath) throws -> Bool { - try tsc_await { + try temp_await { self.validate(path: path, completion: $0) } } diff --git a/Tests/BasicsTests/AuthorizationProviderTests.swift b/Tests/BasicsTests/AuthorizationProviderTests.swift index 410465a17dd..e6066f315d2 100644 --- a/Tests/BasicsTests/AuthorizationProviderTests.swift +++ b/Tests/BasicsTests/AuthorizationProviderTests.swift @@ -10,11 +10,9 @@ // //===----------------------------------------------------------------------===// -import XCTest - @testable import Basics -import TSCBasic -import TSCTestSupport +import SPMTestSupport +import XCTest final class AuthorizationProviderTests: XCTestCase { func testBasicAPIs() { @@ -41,14 +39,14 @@ final class AuthorizationProviderTests: XCTestCase { let otherPassword = UUID().uuidString // Add - XCTAssertNoThrow(try tsc_await { callback in provider.addOrUpdate(for: url, user: user, password: password, callback: callback) }) - XCTAssertNoThrow(try tsc_await { callback in provider.addOrUpdate(for: otherURL, user: user, password: otherPassword, callback: callback) }) + XCTAssertNoThrow(try temp_await { callback in provider.addOrUpdate(for: url, user: user, password: password, callback: callback) }) + XCTAssertNoThrow(try temp_await { callback in provider.addOrUpdate(for: otherURL, user: user, password: otherPassword, callback: callback) }) self.assertAuthentication(provider, for: url, expected: (user, password)) // Update - the new password is appended to the end of file let newPassword = UUID().uuidString - XCTAssertNoThrow(try tsc_await { callback in provider.addOrUpdate(for: url, user: user, password: newPassword, callback: callback) }) + XCTAssertNoThrow(try temp_await { callback in provider.addOrUpdate(for: url, user: user, password: newPassword, callback: callback) }) // .netrc file now contains two entries for `url`: one with `password` and the other with `newPassword`. // `NetrcAuthorizationProvider` returns the first entry it finds. @@ -76,21 +74,21 @@ final class AuthorizationProviderTests: XCTestCase { let otherPassword = UUID().uuidString // Add - XCTAssertNoThrow(try tsc_await { callback in provider.addOrUpdate(for: url, user: user, password: password, callback: callback) }) - XCTAssertNoThrow(try tsc_await { callback in provider.addOrUpdate(for: otherURL, user: user, password: otherPassword, callback: callback) }) + XCTAssertNoThrow(try temp_await { callback in provider.addOrUpdate(for: url, user: user, password: password, callback: callback) }) + XCTAssertNoThrow(try temp_await { callback in provider.addOrUpdate(for: otherURL, user: user, password: otherPassword, callback: callback) }) self.assertAuthentication(provider, for: url, expected: (user, password)) // Update let newPassword = UUID().uuidString - XCTAssertNoThrow(try tsc_await { callback in provider.addOrUpdate(for: url, user: user, password: newPassword, callback: callback) }) + XCTAssertNoThrow(try temp_await { callback in provider.addOrUpdate(for: url, user: user, password: newPassword, callback: callback) }) // Existing password is updated self.assertAuthentication(provider, for: url, expected: (user, newPassword)) self.assertAuthentication(provider, for: otherURL, expected: (user, otherPassword)) // Delete - XCTAssertNoThrow(try tsc_await { callback in provider.remove(for: url, callback: callback) }) + XCTAssertNoThrow(try temp_await { callback in provider.remove(for: url, callback: callback) }) XCTAssertNil(provider.authentication(for: url)) self.assertAuthentication(provider, for: otherURL, expected: (user, otherPassword)) #endif diff --git a/Tests/BasicsTests/ByteStringExtensionsTests.swift b/Tests/BasicsTests/ByteStringExtensionsTests.swift index 0e89d480381..7659695c0e5 100644 --- a/Tests/BasicsTests/ByteStringExtensionsTests.swift +++ b/Tests/BasicsTests/ByteStringExtensionsTests.swift @@ -11,9 +11,10 @@ //===----------------------------------------------------------------------===// import Basics -import TSCBasic import XCTest +import struct TSCBasic.ByteString + final class ByteStringExtensionsTests: XCTestCase { func testSHA256Checksum() { let byteString = ByteString(encodingAsUTF8: "abc") diff --git a/Tests/BasicsTests/CancellatorTests.swift b/Tests/BasicsTests/CancellatorTests.swift index a71d15667ce..5dae72dc02f 100644 --- a/Tests/BasicsTests/CancellatorTests.swift +++ b/Tests/BasicsTests/CancellatorTests.swift @@ -11,9 +11,10 @@ //===----------------------------------------------------------------------===// @testable import Basics -import TSCBasic -import XCTest import SPMTestSupport +import XCTest + +import class TSCBasic.Process final class CancellatorTests: XCTestCase { func testHappyCase() throws { diff --git a/Tests/BasicsTests/DictionaryTest.swift b/Tests/BasicsTests/DictionaryTest.swift index aac571120fa..88e4cbbd913 100644 --- a/Tests/BasicsTests/DictionaryTest.swift +++ b/Tests/BasicsTests/DictionaryTest.swift @@ -11,7 +11,6 @@ //===----------------------------------------------------------------------===// @testable import Basics -import TSCBasic import XCTest final class DictionaryTests: XCTestCase { diff --git a/Tests/BasicsTests/EnvironmentVariablesTests.swift b/Tests/BasicsTests/EnvironmentVariablesTests.swift index 24e05a5ff98..173613bc43d 100644 --- a/Tests/BasicsTests/EnvironmentVariablesTests.swift +++ b/Tests/BasicsTests/EnvironmentVariablesTests.swift @@ -11,9 +11,10 @@ //===----------------------------------------------------------------------===// @testable import Basics -import TSCBasic import XCTest +import enum TSCBasic.ProcessEnv + final class EnvironmentVariablesTests: XCTestCase { #if os(Windows) let pathDelimiter = ";" diff --git a/Tests/BasicsTests/FileSystem/FileSystemTests.swift b/Tests/BasicsTests/FileSystem/FileSystemTests.swift index c0fdfab34d7..8f32cbf92f5 100644 --- a/Tests/BasicsTests/FileSystem/FileSystemTests.swift +++ b/Tests/BasicsTests/FileSystem/FileSystemTests.swift @@ -12,9 +12,10 @@ @testable import Basics -import TSCBasic -import XCTest import TSCTestSupport +import XCTest + +import class TSCBasic.InMemoryFileSystem final class FileSystemTests: XCTestCase { func testStripFirstLevelComponent() throws { diff --git a/Tests/BasicsTests/FileSystem/PathShimTests.swift b/Tests/BasicsTests/FileSystem/PathShimTests.swift new file mode 100644 index 00000000000..2699b01fa79 --- /dev/null +++ b/Tests/BasicsTests/FileSystem/PathShimTests.swift @@ -0,0 +1,76 @@ +/* + This source file is part of the Swift.org open source project + + Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors + Licensed under Apache License v2.0 with Runtime Library Exception + + See http://swift.org/LICENSE.txt for license information + See http://swift.org/CONTRIBUTORS.txt for Swift project authors +*/ + +import Basics +import Foundation +import XCTest + +class PathShimTests : XCTestCase { + func testRescursiveDirectoryCreation() { + // For the tests we'll need a temporary directory. + try! withTemporaryDirectory(removeTreeOnDeinit: true) { path in + // Create a directory under several ancestor directories. + let dirPath = path.appending(components: "abc", "def", "ghi", "mno", "pqr") + try! makeDirectories(dirPath) + + // Check that we were able to actually create the directory. + XCTAssertTrue(localFileSystem.isDirectory(dirPath)) + + // Check that there's no error if we try to create the directory again. + try! makeDirectories(dirPath) + } + } +} + +class WalkTests : XCTestCase { + func testNonRecursive() throws { + #if os(Android) + let root = "/system" + var expected: [AbsolutePath] = [ + "\(root)/usr", + "\(root)/bin", + "\(root)/xbin" + ] + #else + let root = "" + var expected: [AbsolutePath] = [ + "/usr", + "/bin", + "/sbin" + ] + #endif + for x in try walk(AbsolutePath(validating: "\(root)/"), recursively: false) { + if let i = expected.firstIndex(of: x) { + expected.remove(at: i) + } + #if os(Android) + XCTAssertEqual(3, x.components.count) + #else + XCTAssertEqual(2, x.components.count) + #endif + } + XCTAssertEqual(expected.count, 0) + } + + func testRecursive() { + let root = AbsolutePath(#file).parentDirectory.parentDirectory.parentDirectory.parentDirectory.appending(component: "Sources") + var expected = [ + root.appending(component: "Basics"), + root.appending(component: "Build"), + root.appending(component: "Commands") + ] + for x in try! walk(root) { + if let i = expected.firstIndex(of: x) { + expected.remove(at: i) + } + } + XCTAssertEqual(expected, []) + } +} diff --git a/Tests/BasicsTests/FileSystem/PathTests.swift b/Tests/BasicsTests/FileSystem/PathTests.swift new file mode 100644 index 00000000000..bfa1012c04d --- /dev/null +++ b/Tests/BasicsTests/FileSystem/PathTests.swift @@ -0,0 +1,405 @@ +/* + This source file is part of the Swift.org open source project + + Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors + Licensed under Apache License v2.0 with Runtime Library Exception + + See http://swift.org/LICENSE.txt for license information + See http://swift.org/CONTRIBUTORS.txt for Swift project authors +*/ + +import Basics +import Foundation +import XCTest + +class PathTests: XCTestCase { + func testBasics() { + XCTAssertEqual(AbsolutePath("/").pathString, "/") + XCTAssertEqual(AbsolutePath("/a").pathString, "/a") + XCTAssertEqual(AbsolutePath("/a/b/c").pathString, "/a/b/c") + XCTAssertEqual(RelativePath(".").pathString, ".") + XCTAssertEqual(RelativePath("a").pathString, "a") + XCTAssertEqual(RelativePath("a/b/c").pathString, "a/b/c") + XCTAssertEqual(RelativePath("~").pathString, "~") // `~` is not special + } + + func testStringInitialization() throws { + let abs1 = AbsolutePath("/") + let abs2 = AbsolutePath(abs1, ".") + XCTAssertEqual(abs1, abs2) + let rel3 = "." + let abs3 = try AbsolutePath(abs2, validating: rel3) + XCTAssertEqual(abs2, abs3) + let base = AbsolutePath("/base/path") + let abs4 = AbsolutePath("/a/b/c", relativeTo: base) + XCTAssertEqual(abs4, AbsolutePath("/a/b/c")) + let abs5 = AbsolutePath("./a/b/c", relativeTo: base) + XCTAssertEqual(abs5, AbsolutePath("/base/path/a/b/c")) + let abs6 = AbsolutePath("~/bla", relativeTo: base) // `~` isn't special + XCTAssertEqual(abs6, AbsolutePath("/base/path/~/bla")) + } + + func testStringLiteralInitialization() { + let abs = AbsolutePath("/") + XCTAssertEqual(abs.pathString, "/") + let rel1 = RelativePath(".") + XCTAssertEqual(rel1.pathString, ".") + let rel2 = RelativePath("~") + XCTAssertEqual(rel2.pathString, "~") // `~` is not special + } + + func testRepeatedPathSeparators() { + XCTAssertEqual(AbsolutePath("/ab//cd//ef").pathString, "/ab/cd/ef") + XCTAssertEqual(AbsolutePath("/ab///cd//ef").pathString, "/ab/cd/ef") + XCTAssertEqual(RelativePath("ab//cd//ef").pathString, "ab/cd/ef") + XCTAssertEqual(RelativePath("ab//cd///ef").pathString, "ab/cd/ef") + } + + func testTrailingPathSeparators() { + XCTAssertEqual(AbsolutePath("/ab/cd/ef/").pathString, "/ab/cd/ef") + XCTAssertEqual(AbsolutePath("/ab/cd/ef//").pathString, "/ab/cd/ef") + XCTAssertEqual(RelativePath("ab/cd/ef/").pathString, "ab/cd/ef") + XCTAssertEqual(RelativePath("ab/cd/ef//").pathString, "ab/cd/ef") + } + + func testDotPathComponents() { + XCTAssertEqual(AbsolutePath("/ab/././cd//ef").pathString, "/ab/cd/ef") + XCTAssertEqual(AbsolutePath("/ab/./cd//ef/.").pathString, "/ab/cd/ef") + XCTAssertEqual(RelativePath("ab/./cd/././ef").pathString, "ab/cd/ef") + XCTAssertEqual(RelativePath("ab/./cd/ef/.").pathString, "ab/cd/ef") + } + + func testDotDotPathComponents() { + XCTAssertEqual(AbsolutePath("/..").pathString, "/") + XCTAssertEqual(AbsolutePath("/../../../../..").pathString, "/") + XCTAssertEqual(AbsolutePath("/abc/..").pathString, "/") + XCTAssertEqual(AbsolutePath("/abc/../..").pathString, "/") + XCTAssertEqual(AbsolutePath("/../abc").pathString, "/abc") + XCTAssertEqual(AbsolutePath("/../abc/..").pathString, "/") + XCTAssertEqual(AbsolutePath("/../abc/../def").pathString, "/def") + XCTAssertEqual(RelativePath("..").pathString, "..") + XCTAssertEqual(RelativePath("../..").pathString, "../..") + XCTAssertEqual(RelativePath(".././..").pathString, "../..") + XCTAssertEqual(RelativePath("../abc/..").pathString, "..") + XCTAssertEqual(RelativePath("../abc/.././").pathString, "..") + XCTAssertEqual(RelativePath("abc/..").pathString, ".") + } + + func testCombinationsAndEdgeCases() { + XCTAssertEqual(AbsolutePath("///").pathString, "/") + XCTAssertEqual(AbsolutePath("/./").pathString, "/") + XCTAssertEqual(RelativePath("").pathString, ".") + XCTAssertEqual(RelativePath(".").pathString, ".") + XCTAssertEqual(RelativePath("./abc").pathString, "abc") + XCTAssertEqual(RelativePath("./abc/").pathString, "abc") + XCTAssertEqual(RelativePath("./abc/../bar").pathString, "bar") + XCTAssertEqual(RelativePath("foo/../bar").pathString, "bar") + XCTAssertEqual(RelativePath("foo///..///bar///baz").pathString, "bar/baz") + XCTAssertEqual(RelativePath("foo/../bar/./").pathString, "bar") + XCTAssertEqual(RelativePath("../abc/def/").pathString, "../abc/def") + XCTAssertEqual(RelativePath("././././.").pathString, ".") + XCTAssertEqual(RelativePath("./././../.").pathString, "..") + XCTAssertEqual(RelativePath("./").pathString, ".") + XCTAssertEqual(RelativePath(".//").pathString, ".") + XCTAssertEqual(RelativePath("./.").pathString, ".") + XCTAssertEqual(RelativePath("././").pathString, ".") + XCTAssertEqual(RelativePath("../").pathString, "..") + XCTAssertEqual(RelativePath("../.").pathString, "..") + XCTAssertEqual(RelativePath("./..").pathString, "..") + XCTAssertEqual(RelativePath("./../.").pathString, "..") + XCTAssertEqual(RelativePath("./////../////./////").pathString, "..") + XCTAssertEqual(RelativePath("../a").pathString, "../a") + XCTAssertEqual(RelativePath("../a/..").pathString, "..") + XCTAssertEqual(RelativePath("a/..").pathString, ".") + XCTAssertEqual(RelativePath("a/../////../////./////").pathString, "..") + } + + func testDirectoryNameExtraction() { + XCTAssertEqual(AbsolutePath("/").dirname, "/") + XCTAssertEqual(AbsolutePath("/a").dirname, "/") + XCTAssertEqual(AbsolutePath("/./a").dirname, "/") + XCTAssertEqual(AbsolutePath("/../..").dirname, "/") + XCTAssertEqual(AbsolutePath("/ab/c//d/").dirname, "/ab/c") + XCTAssertEqual(RelativePath("ab/c//d/").dirname, "ab/c") + XCTAssertEqual(RelativePath("../a").dirname, "..") + XCTAssertEqual(RelativePath("../a/..").dirname, ".") + XCTAssertEqual(RelativePath("a/..").dirname, ".") + XCTAssertEqual(RelativePath("./..").dirname, ".") + XCTAssertEqual(RelativePath("a/../////../////./////").dirname, ".") + XCTAssertEqual(RelativePath("abc").dirname, ".") + XCTAssertEqual(RelativePath("").dirname, ".") + XCTAssertEqual(RelativePath(".").dirname, ".") + } + + func testBaseNameExtraction() { + XCTAssertEqual(AbsolutePath("/").basename, "/") + XCTAssertEqual(AbsolutePath("/a").basename, "a") + XCTAssertEqual(AbsolutePath("/./a").basename, "a") + XCTAssertEqual(AbsolutePath("/../..").basename, "/") + XCTAssertEqual(RelativePath("../..").basename, "..") + XCTAssertEqual(RelativePath("../a").basename, "a") + XCTAssertEqual(RelativePath("../a/..").basename, "..") + XCTAssertEqual(RelativePath("a/..").basename, ".") + XCTAssertEqual(RelativePath("./..").basename, "..") + XCTAssertEqual(RelativePath("a/../////../////./////").basename, "..") + XCTAssertEqual(RelativePath("abc").basename, "abc") + XCTAssertEqual(RelativePath("").basename, ".") + XCTAssertEqual(RelativePath(".").basename, ".") + } + + func testBaseNameWithoutExt() { + XCTAssertEqual(AbsolutePath("/").basenameWithoutExt, "/") + XCTAssertEqual(AbsolutePath("/a").basenameWithoutExt, "a") + XCTAssertEqual(AbsolutePath("/./a").basenameWithoutExt, "a") + XCTAssertEqual(AbsolutePath("/../..").basenameWithoutExt, "/") + XCTAssertEqual(RelativePath("../..").basenameWithoutExt, "..") + XCTAssertEqual(RelativePath("../a").basenameWithoutExt, "a") + XCTAssertEqual(RelativePath("../a/..").basenameWithoutExt, "..") + XCTAssertEqual(RelativePath("a/..").basenameWithoutExt, ".") + XCTAssertEqual(RelativePath("./..").basenameWithoutExt, "..") + XCTAssertEqual(RelativePath("a/../////../////./////").basenameWithoutExt, "..") + XCTAssertEqual(RelativePath("abc").basenameWithoutExt, "abc") + XCTAssertEqual(RelativePath("").basenameWithoutExt, ".") + XCTAssertEqual(RelativePath(".").basenameWithoutExt, ".") + + XCTAssertEqual(AbsolutePath("/a.txt").basenameWithoutExt, "a") + XCTAssertEqual(AbsolutePath("/./a.txt").basenameWithoutExt, "a") + XCTAssertEqual(RelativePath("../a.bc").basenameWithoutExt, "a") + XCTAssertEqual(RelativePath("abc.swift").basenameWithoutExt, "abc") + XCTAssertEqual(RelativePath("../a.b.c").basenameWithoutExt, "a.b") + XCTAssertEqual(RelativePath("abc.xyz.123").basenameWithoutExt, "abc.xyz") + } + + func testSuffixExtraction() { + XCTAssertEqual(RelativePath("a").suffix, nil) + XCTAssertEqual(RelativePath("a").extension, nil) + XCTAssertEqual(RelativePath("a.").suffix, nil) + XCTAssertEqual(RelativePath("a.").extension, nil) + XCTAssertEqual(RelativePath(".a").suffix, nil) + XCTAssertEqual(RelativePath(".a").extension, nil) + XCTAssertEqual(RelativePath("").suffix, nil) + XCTAssertEqual(RelativePath("").extension, nil) + XCTAssertEqual(RelativePath(".").suffix, nil) + XCTAssertEqual(RelativePath(".").extension, nil) + XCTAssertEqual(RelativePath("..").suffix, nil) + XCTAssertEqual(RelativePath("..").extension, nil) + XCTAssertEqual(RelativePath("a.foo").suffix, ".foo") + XCTAssertEqual(RelativePath("a.foo").extension, "foo") + XCTAssertEqual(RelativePath(".a.foo").suffix, ".foo") + XCTAssertEqual(RelativePath(".a.foo").extension, "foo") + XCTAssertEqual(RelativePath(".a.foo.bar").suffix, ".bar") + XCTAssertEqual(RelativePath(".a.foo.bar").extension, "bar") + XCTAssertEqual(RelativePath("a.foo.bar").suffix, ".bar") + XCTAssertEqual(RelativePath("a.foo.bar").extension, "bar") + XCTAssertEqual(RelativePath(".a.foo.bar.baz").suffix, ".baz") + XCTAssertEqual(RelativePath(".a.foo.bar.baz").extension, "baz") + } + + func testParentDirectory() { + XCTAssertEqual(AbsolutePath("/").parentDirectory, AbsolutePath("/")) + XCTAssertEqual(AbsolutePath("/").parentDirectory.parentDirectory, AbsolutePath("/")) + XCTAssertEqual(AbsolutePath("/bar").parentDirectory, AbsolutePath("/")) + XCTAssertEqual(AbsolutePath("/bar/../foo/..//").parentDirectory.parentDirectory, AbsolutePath("/")) + XCTAssertEqual(AbsolutePath("/bar/../foo/..//yabba/a/b").parentDirectory.parentDirectory, AbsolutePath("/yabba")) + } + + @available(*, deprecated) + func testConcatenation() { + XCTAssertEqual(AbsolutePath(AbsolutePath("/"), RelativePath("")).pathString, "/") + XCTAssertEqual(AbsolutePath(AbsolutePath("/"), RelativePath(".")).pathString, "/") + XCTAssertEqual(AbsolutePath(AbsolutePath("/"), RelativePath("..")).pathString, "/") + XCTAssertEqual(AbsolutePath(AbsolutePath("/"), RelativePath("bar")).pathString, "/bar") + XCTAssertEqual(AbsolutePath(AbsolutePath("/foo/bar"), RelativePath("..")).pathString, "/foo") + XCTAssertEqual(AbsolutePath(AbsolutePath("/bar"), RelativePath("../foo")).pathString, "/foo") + XCTAssertEqual(AbsolutePath(AbsolutePath("/bar"), RelativePath("../foo/..//")).pathString, "/") + XCTAssertEqual(AbsolutePath(AbsolutePath("/bar/../foo/..//yabba/"), RelativePath("a/b")).pathString, "/yabba/a/b") + + XCTAssertEqual(AbsolutePath("/").appending(RelativePath("")).pathString, "/") + XCTAssertEqual(AbsolutePath("/").appending(RelativePath(".")).pathString, "/") + XCTAssertEqual(AbsolutePath("/").appending(RelativePath("..")).pathString, "/") + XCTAssertEqual(AbsolutePath("/").appending(RelativePath("bar")).pathString, "/bar") + XCTAssertEqual(AbsolutePath("/foo/bar").appending(RelativePath("..")).pathString, "/foo") + XCTAssertEqual(AbsolutePath("/bar").appending(RelativePath("../foo")).pathString, "/foo") + XCTAssertEqual(AbsolutePath("/bar").appending(RelativePath("../foo/..//")).pathString, "/") + XCTAssertEqual(AbsolutePath("/bar/../foo/..//yabba/").appending(RelativePath("a/b")).pathString, "/yabba/a/b") + + XCTAssertEqual(AbsolutePath("/").appending(component: "a").pathString, "/a") + XCTAssertEqual(AbsolutePath("/a").appending(component: "b").pathString, "/a/b") + XCTAssertEqual(AbsolutePath("/").appending(components: "a", "b").pathString, "/a/b") + XCTAssertEqual(AbsolutePath("/a").appending(components: "b", "c").pathString, "/a/b/c") + + XCTAssertEqual(AbsolutePath("/a/b/c").appending(components: "", "c").pathString, "/a/b/c/c") + XCTAssertEqual(AbsolutePath("/a/b/c").appending(components: "").pathString, "/a/b/c") + XCTAssertEqual(AbsolutePath("/a/b/c").appending(components: ".").pathString, "/a/b/c") + XCTAssertEqual(AbsolutePath("/a/b/c").appending(components: "..").pathString, "/a/b") + XCTAssertEqual(AbsolutePath("/a/b/c").appending(components: "..", "d").pathString, "/a/b/d") + XCTAssertEqual(AbsolutePath("/").appending(components: "..").pathString, "/") + XCTAssertEqual(AbsolutePath("/").appending(components: ".").pathString, "/") + XCTAssertEqual(AbsolutePath("/").appending(components: "..", "a").pathString, "/a") + + XCTAssertEqual(RelativePath("hello").appending(components: "a", "b", "c", "..").pathString, "hello/a/b") + XCTAssertEqual(RelativePath("hello").appending(RelativePath("a/b/../c/d")).pathString, "hello/a/c/d") + } + + func testPathComponents() { + XCTAssertEqual(AbsolutePath("/").components, ["/"]) + XCTAssertEqual(AbsolutePath("/.").components, ["/"]) + XCTAssertEqual(AbsolutePath("/..").components, ["/"]) + XCTAssertEqual(AbsolutePath("/bar").components, ["/", "bar"]) + XCTAssertEqual(AbsolutePath("/foo/bar/..").components, ["/", "foo"]) + XCTAssertEqual(AbsolutePath("/bar/../foo").components, ["/", "foo"]) + XCTAssertEqual(AbsolutePath("/bar/../foo/..//").components, ["/"]) + XCTAssertEqual(AbsolutePath("/bar/../foo/..//yabba/a/b/").components, ["/", "yabba", "a", "b"]) + + XCTAssertEqual(RelativePath("").components, ["."]) + XCTAssertEqual(RelativePath(".").components, ["."]) + XCTAssertEqual(RelativePath("..").components, [".."]) + XCTAssertEqual(RelativePath("bar").components, ["bar"]) + XCTAssertEqual(RelativePath("foo/bar/..").components, ["foo"]) + XCTAssertEqual(RelativePath("bar/../foo").components, ["foo"]) + XCTAssertEqual(RelativePath("bar/../foo/..//").components, ["."]) + XCTAssertEqual(RelativePath("bar/../foo/..//yabba/a/b/").components, ["yabba", "a", "b"]) + XCTAssertEqual(RelativePath("../..").components, ["..", ".."]) + XCTAssertEqual(RelativePath(".././/..").components, ["..", ".."]) + XCTAssertEqual(RelativePath("../a").components, ["..", "a"]) + XCTAssertEqual(RelativePath("../a/..").components, [".."]) + XCTAssertEqual(RelativePath("a/..").components, ["."]) + XCTAssertEqual(RelativePath("./..").components, [".."]) + XCTAssertEqual(RelativePath("a/../////../////./////").components, [".."]) + XCTAssertEqual(RelativePath("abc").components, ["abc"]) + } + + func testRelativePathFromAbsolutePaths() { + XCTAssertEqual(AbsolutePath("/").relative(to: AbsolutePath("/")), RelativePath(".")); + XCTAssertEqual(AbsolutePath("/a/b/c/d").relative(to: AbsolutePath("/")), RelativePath("a/b/c/d")); + XCTAssertEqual(AbsolutePath("/").relative(to: AbsolutePath("/a/b/c")), RelativePath("../../..")); + XCTAssertEqual(AbsolutePath("/a/b/c/d").relative(to: AbsolutePath("/a/b")), RelativePath("c/d")); + XCTAssertEqual(AbsolutePath("/a/b/c/d").relative(to: AbsolutePath("/a/b/c")), RelativePath("d")); + XCTAssertEqual(AbsolutePath("/a/b/c/d").relative(to: AbsolutePath("/a/c/d")), RelativePath("../../b/c/d")); + XCTAssertEqual(AbsolutePath("/a/b/c/d").relative(to: AbsolutePath("/b/c/d")), RelativePath("../../../a/b/c/d")); + } + + func testComparison() { + XCTAssertTrue(AbsolutePath("/") <= AbsolutePath("/")); + XCTAssertTrue(AbsolutePath("/abc") < AbsolutePath("/def")); + XCTAssertTrue(AbsolutePath("/2") <= AbsolutePath("/2.1")); + XCTAssertTrue(AbsolutePath("/3.1") > AbsolutePath("/2")); + XCTAssertTrue(AbsolutePath("/2") >= AbsolutePath("/2")); + XCTAssertTrue(AbsolutePath("/2.1") >= AbsolutePath("/2")); + } + + func testAncestry() { + XCTAssertTrue(AbsolutePath("/a/b/c/d/e/f").isDescendantOfOrEqual(to: AbsolutePath("/a/b/c/d"))) + XCTAssertTrue(AbsolutePath("/a/b/c/d/e/f.swift").isDescendantOfOrEqual(to: AbsolutePath("/a/b/c"))) + XCTAssertTrue(AbsolutePath("/").isDescendantOfOrEqual(to: AbsolutePath("/"))) + XCTAssertTrue(AbsolutePath("/foo/bar").isDescendantOfOrEqual(to: AbsolutePath("/"))) + XCTAssertFalse(AbsolutePath("/foo/bar").isDescendantOfOrEqual(to: AbsolutePath("/foo/bar/baz"))) + XCTAssertFalse(AbsolutePath("/foo/bar").isDescendantOfOrEqual(to: AbsolutePath("/bar"))) + + XCTAssertFalse(AbsolutePath("/foo/bar").isDescendant(of: AbsolutePath("/foo/bar"))) + XCTAssertTrue(AbsolutePath("/foo/bar").isDescendant(of: AbsolutePath("/foo"))) + + XCTAssertTrue(AbsolutePath("/a/b/c/d").isAncestorOfOrEqual(to: AbsolutePath("/a/b/c/d/e/f"))) + XCTAssertTrue(AbsolutePath("/a/b/c").isAncestorOfOrEqual(to: AbsolutePath("/a/b/c/d/e/f.swift"))) + XCTAssertTrue(AbsolutePath("/").isAncestorOfOrEqual(to: AbsolutePath("/"))) + XCTAssertTrue(AbsolutePath("/").isAncestorOfOrEqual(to: AbsolutePath("/foo/bar"))) + XCTAssertFalse(AbsolutePath("/foo/bar/baz").isAncestorOfOrEqual(to: AbsolutePath("/foo/bar"))) + XCTAssertFalse(AbsolutePath("/bar").isAncestorOfOrEqual(to: AbsolutePath("/foo/bar"))) + + XCTAssertFalse(AbsolutePath("/foo/bar").isAncestor(of: AbsolutePath("/foo/bar"))) + XCTAssertTrue(AbsolutePath("/foo").isAncestor(of: AbsolutePath("/foo/bar"))) + } + + func testAbsolutePathValidation() { + XCTAssertNoThrow(try AbsolutePath(validating: "/a/b/c/d")) + + XCTAssertThrowsError(try AbsolutePath(validating: "~/a/b/d")) { error in + XCTAssertEqual("\(error)", "invalid absolute path '~/a/b/d'; absolute path must begin with '/'") + } + + XCTAssertThrowsError(try AbsolutePath(validating: "a/b/d")) { error in + XCTAssertEqual("\(error)", "invalid absolute path 'a/b/d'") + } + } + + func testRelativePathValidation() { + XCTAssertNoThrow(try RelativePath(validating: "a/b/c/d")) + + XCTAssertThrowsError(try RelativePath(validating: "/a/b/d")) { error in + XCTAssertEqual("\(error)", "invalid relative path '/a/b/d'; relative path should not begin with '/'") + //XCTAssertEqual("\(error)", "invalid relative path '/a/b/d'; relative path should not begin with '/' or '~'") + } + + /*XCTAssertThrowsError(try RelativePath(validating: "~/a/b/d")) { error in + XCTAssertEqual("\(error)", "invalid relative path '~/a/b/d'; relative path should not begin with '/' or '~'") + }*/ + } + + func testCodable() throws { + struct Foo: Codable, Equatable { + var path: AbsolutePath + } + + struct Bar: Codable, Equatable { + var path: RelativePath + } + + struct Baz: Codable, Equatable { + var path: String + } + + do { + let foo = Foo(path: "/path/to/foo") + let data = try JSONEncoder().encode(foo) + let decodedFoo = try JSONDecoder().decode(Foo.self, from: data) + XCTAssertEqual(foo, decodedFoo) + } + + do { + let foo = Foo(path: "/path/to/../to/foo") + let data = try JSONEncoder().encode(foo) + let decodedFoo = try JSONDecoder().decode(Foo.self, from: data) + XCTAssertEqual(foo, decodedFoo) + XCTAssertEqual(foo.path.pathString, "/path/to/foo") + XCTAssertEqual(decodedFoo.path.pathString, "/path/to/foo") + } + + do { + let bar = Bar(path: "path/to/bar") + let data = try JSONEncoder().encode(bar) + let decodedBar = try JSONDecoder().decode(Bar.self, from: data) + XCTAssertEqual(bar, decodedBar) + } + + do { + let bar = Bar(path: "path/to/../to/bar") + let data = try JSONEncoder().encode(bar) + let decodedBar = try JSONDecoder().decode(Bar.self, from: data) + XCTAssertEqual(bar, decodedBar) + XCTAssertEqual(bar.path.pathString, "path/to/bar") + XCTAssertEqual(decodedBar.path.pathString, "path/to/bar") + } + + do { + let data = try JSONEncoder().encode(Baz(path: "")) + XCTAssertThrowsError(try JSONDecoder().decode(Foo.self, from: data)) + XCTAssertNoThrow(try JSONDecoder().decode(Bar.self, from: data)) // empty string is a valid relative path + } + + do { + let data = try JSONEncoder().encode(Baz(path: "foo")) + XCTAssertThrowsError(try JSONDecoder().decode(Foo.self, from: data)) + } + + do { + let data = try JSONEncoder().encode(Baz(path: "/foo")) + XCTAssertThrowsError(try JSONDecoder().decode(Bar.self, from: data)) + } + } + + // FIXME: We also need tests for join() operations. + + // FIXME: We also need tests for dirname, basename, suffix, etc. + + // FIXME: We also need test for stat() operations. +} diff --git a/Tests/BasicsTests/FileSystem/TemporaryFileTests.swift b/Tests/BasicsTests/FileSystem/TemporaryFileTests.swift index 09cfe35d47c..5460faf901d 100644 --- a/Tests/BasicsTests/FileSystem/TemporaryFileTests.swift +++ b/Tests/BasicsTests/FileSystem/TemporaryFileTests.swift @@ -11,7 +11,6 @@ //===----------------------------------------------------------------------===// import XCTest -import TSCBasic import Basics diff --git a/Tests/BasicsTests/FileSystem/VFSTests.swift b/Tests/BasicsTests/FileSystem/VFSTests.swift index 6cb39a8cd38..83b8513fa69 100644 --- a/Tests/BasicsTests/FileSystem/VFSTests.swift +++ b/Tests/BasicsTests/FileSystem/VFSTests.swift @@ -11,9 +11,11 @@ //===----------------------------------------------------------------------===// import Basics -import TSCBasic +import func TSCBasic.withTemporaryFile import XCTest +import struct TSCBasic.ByteString + func testWithTemporaryDirectory( function: StaticString = #function, body: @escaping (AbsolutePath) async throws -> Void @@ -47,7 +49,7 @@ class VFSTests: XCTestCase { 0x02 ] - let fs = TSCBasic.localFileSystem + let fs = localFileSystem try withTemporaryFile { [contents] vfsPath in try withTemporaryDirectory(removeTreeOnDeinit: true) { [contents] tempDirPath in let file = tempDirPath.appending("best") @@ -68,7 +70,7 @@ class VFSTests: XCTestCase { try fs.createDirectory(tempDirPath.appending("dir")) try fs.writeFileContents(tempDirPath.appending(components: ["dir", "file"]), bytes: []) - try VirtualFileSystem.serializeDirectoryTree(tempDirPath, into: vfsPath.path, fs: fs, includeContents: [executable]) + try VirtualFileSystem.serializeDirectoryTree(tempDirPath, into: AbsolutePath(vfsPath.path), fs: fs, includeContents: [executable]) } let vfs = try VirtualFileSystem(path: vfsPath.path, fs: fs) diff --git a/Tests/BasicsTests/ObservabilitySystemTests.swift b/Tests/BasicsTests/ObservabilitySystemTests.swift index 1dd145d33a9..564fe13630a 100644 --- a/Tests/BasicsTests/ObservabilitySystemTests.swift +++ b/Tests/BasicsTests/ObservabilitySystemTests.swift @@ -12,7 +12,6 @@ @testable import Basics import SPMTestSupport -import TSCBasic import XCTest // TODO: remove when transition to new diagnostics system is complete diff --git a/Tests/BasicsTests/SQLiteBackedCacheTests.swift b/Tests/BasicsTests/SQLiteBackedCacheTests.swift index df8383f297a..8678adf61a9 100644 --- a/Tests/BasicsTests/SQLiteBackedCacheTests.swift +++ b/Tests/BasicsTests/SQLiteBackedCacheTests.swift @@ -11,8 +11,7 @@ //===----------------------------------------------------------------------===// @testable import Basics -import TSCBasic -import TSCTestSupport +import SPMTestSupport import tsan_utils import XCTest diff --git a/Tests/BasicsTests/SandboxTests.swift b/Tests/BasicsTests/SandboxTests.swift index 753e0020f1b..83e4d4e25ea 100644 --- a/Tests/BasicsTests/SandboxTests.swift +++ b/Tests/BasicsTests/SandboxTests.swift @@ -12,9 +12,11 @@ @testable import Basics import SPMTestSupport -import TSCBasic import XCTest +import class TSCBasic.Process +import struct TSCBasic.ProcessResult + final class SandboxTest: XCTestCase { func testSandboxOnAllPlatforms() throws { try withTemporaryDirectory { path in diff --git a/Tests/BasicsTests/StringExtensionsTests.swift b/Tests/BasicsTests/StringExtensionsTests.swift index 2cb1a715e25..aa4e1aaeada 100644 --- a/Tests/BasicsTests/StringExtensionsTests.swift +++ b/Tests/BasicsTests/StringExtensionsTests.swift @@ -11,7 +11,6 @@ //===----------------------------------------------------------------------===// import Basics -import TSCBasic import XCTest final class StringExtensionsTests: XCTestCase { diff --git a/Tests/BasicsTests/URLSessionHTTPClientTests.swift b/Tests/BasicsTests/URLSessionHTTPClientTests.swift index 6d8de5c4953..195e513bf5a 100644 --- a/Tests/BasicsTests/URLSessionHTTPClientTests.swift +++ b/Tests/BasicsTests/URLSessionHTTPClientTests.swift @@ -17,10 +17,13 @@ import Foundation // need to decide how to best deal with that import FoundationNetworking #endif -import TSCBasic -import TSCTestSupport +import SPMTestSupport import XCTest +import struct TSCBasic.ByteString +import enum TSCBasic.FileMode +import struct TSCBasic.FileSystemError + final class URLSessionHTTPClientTest: XCTestCase { func testHead() { let configuration = URLSessionConfiguration.ephemeral @@ -1116,87 +1119,87 @@ private class MockURLProtocol: URLProtocol { } final class FailingFileSystem: FileSystem { - var currentWorkingDirectory: AbsolutePath? { + var currentWorkingDirectory: TSCAbsolutePath? { fatalError("unexpected call") } - var homeDirectory: AbsolutePath { + var homeDirectory: TSCAbsolutePath { fatalError("unexpected call") } - var cachesDirectory: AbsolutePath? { + var cachesDirectory: TSCAbsolutePath? { fatalError("unexpected call") } - var tempDirectory: AbsolutePath { + var tempDirectory: TSCAbsolutePath { fatalError("unexpected call") } - func changeCurrentWorkingDirectory(to path: AbsolutePath) throws { + func changeCurrentWorkingDirectory(to path: TSCAbsolutePath) throws { fatalError("unexpected call") } - func exists(_ path: AbsolutePath, followSymlink: Bool) -> Bool { + func exists(_ path: TSCAbsolutePath, followSymlink: Bool) -> Bool { fatalError("unexpected call") } - func isDirectory(_: AbsolutePath) -> Bool { + func isDirectory(_: TSCAbsolutePath) -> Bool { fatalError("unexpected call") } - func isFile(_: AbsolutePath) -> Bool { + func isFile(_: TSCAbsolutePath) -> Bool { fatalError("unexpected call") } - func isExecutableFile(_: AbsolutePath) -> Bool { + func isExecutableFile(_: TSCAbsolutePath) -> Bool { fatalError("unexpected call") } - func isSymlink(_: AbsolutePath) -> Bool { + func isSymlink(_: TSCAbsolutePath) -> Bool { fatalError("unexpected call") } - func isReadable(_ path: AbsolutePath) -> Bool { + func isReadable(_ path: TSCAbsolutePath) -> Bool { fatalError("unexpected call") } - func isWritable(_ path: AbsolutePath) -> Bool { + func isWritable(_ path: TSCAbsolutePath) -> Bool { fatalError("unexpected call") } - func getDirectoryContents(_: AbsolutePath) throws -> [String] { + func getDirectoryContents(_: TSCAbsolutePath) throws -> [String] { fatalError("unexpected call") } - func readFileContents(_: AbsolutePath) throws -> ByteString { + func readFileContents(_: TSCAbsolutePath) throws -> ByteString { fatalError("unexpected call") } - func removeFileTree(_: AbsolutePath) throws { + func removeFileTree(_: TSCAbsolutePath) throws { fatalError("unexpected call") } - func chmod(_ mode: FileMode, path: AbsolutePath, options: Set) throws { + func chmod(_ mode: FileMode, path: TSCAbsolutePath, options: Set) throws { fatalError("unexpected call") } - func writeFileContents(_ path: AbsolutePath, bytes: ByteString) throws { + func writeFileContents(_ path: TSCAbsolutePath, bytes: ByteString) throws { fatalError("unexpected call") } - func createDirectory(_ path: AbsolutePath, recursive: Bool) throws { + func createDirectory(_ path: TSCAbsolutePath, recursive: Bool) throws { fatalError("unexpected call") } - func createSymbolicLink(_ path: AbsolutePath, pointingAt destination: AbsolutePath, relative: Bool) throws { + func createSymbolicLink(_ path: TSCAbsolutePath, pointingAt destination: TSCAbsolutePath, relative: Bool) throws { fatalError("unexpected call") } - func copy(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws { + func copy(from sourcePath: TSCAbsolutePath, to destinationPath: TSCAbsolutePath) throws { fatalError("unexpected call") } - func move(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws { + func move(from sourcePath: TSCAbsolutePath, to destinationPath: TSCAbsolutePath) throws { throw FileSystemError(.unsupported) } } diff --git a/Tests/BuildTests/BuildPlanTests.swift b/Tests/BuildTests/BuildPlanTests.swift index 38e96e71676..cb085085f49 100644 --- a/Tests/BuildTests/BuildPlanTests.swift +++ b/Tests/BuildTests/BuildPlanTests.swift @@ -12,17 +12,20 @@ import Basics @testable import Build +@_implementationOnly import DriverSupport import PackageLoading @testable import PackageGraph @testable import PackageModel import SPMBuildCore import SPMTestSupport import SwiftDriver -import TSCBasic import Workspace import XCTest + +import struct TSCBasic.ByteString +import class TSCBasic.InMemoryFileSystem + import enum TSCUtility.Diagnostics -@_implementationOnly import DriverSupport final class BuildPlanTests: XCTestCase { let inputsDir = AbsolutePath(#file).parentDirectory.appending(components: "Inputs") @@ -635,7 +638,7 @@ final class BuildPlanTests: XCTestCase { result.checkProductsCount(1) result.checkTargetsCount(2) - let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") + let buildPath = result.plan.buildParameters.dataPath.appending(components: "debug") let exe = try result.target(for: "exe").swiftTarget().compileArguments() XCTAssertMatch(exe, ["-swift-version", "4", "-enable-batch-mode", "-Onone", "-enable-testing", "-g", .equal(j), "-DSWIFT_PACKAGE", "-DDEBUG", "-module-cache-path", "\(buildPath.appending(components: "ModuleCache"))", .anySequence]) @@ -784,9 +787,9 @@ final class BuildPlanTests: XCTestCase { } func testSwiftConditionalDependency() throws { - let Pkg: AbsolutePath = AbsolutePath("/Pkg") + let Pkg: AbsolutePath = "/Pkg" - let fs = InMemoryFileSystem(emptyFiles: + let fs: FileSystem = InMemoryFileSystem(emptyFiles: Pkg.appending(components: "Sources", "exe", "main.swift").pathString, Pkg.appending(components: "Sources", "PkgLib", "lib.swift").pathString, "/ExtPkg/Sources/ExtLib/lib.swift", @@ -991,7 +994,7 @@ final class BuildPlanTests: XCTestCase { result.checkProductsCount(1) result.checkTargetsCount(1) - let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "release") + let buildPath = result.plan.buildParameters.dataPath.appending(components: "release") let exe = try result.target(for: "exe").swiftTarget().compileArguments() XCTAssertMatch(exe, ["-swift-version", "4", "-O", "-g", .equal(j), "-DSWIFT_PACKAGE", "-module-cache-path", "\(buildPath.appending(components: "ModuleCache"))", .anySequence]) @@ -1067,7 +1070,7 @@ final class BuildPlanTests: XCTestCase { result.checkProductsCount(1) result.checkTargetsCount(1) - let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "release") + let buildPath = result.plan.buildParameters.dataPath.appending(components: "release") let exe = try result.target(for: "exe").swiftTarget().compileArguments() XCTAssertMatch(exe, ["-swift-version", "4", "-O", "-g", .equal(j), "-DSWIFT_PACKAGE", "-module-cache-path", "\(buildPath.appending(components: "ModuleCache"))", .anySequence]) @@ -1112,10 +1115,10 @@ final class BuildPlanTests: XCTestCase { } func testBasicClangPackage() throws { - let Pkg: AbsolutePath = AbsolutePath("/Pkg") - let ExtPkg: AbsolutePath = AbsolutePath("/ExtPkg") + let Pkg: AbsolutePath = "/Pkg" + let ExtPkg: AbsolutePath = "/ExtPkg" - let fs = InMemoryFileSystem(emptyFiles: + let fs: FileSystem = InMemoryFileSystem(emptyFiles: Pkg.appending(components: "Sources", "exe", "main.c").pathString, Pkg.appending(components: "Sources", "lib", "lib.c").pathString, Pkg.appending(components: "Sources", "lib", "lib.S").pathString, @@ -1162,7 +1165,7 @@ final class BuildPlanTests: XCTestCase { result.checkProductsCount(1) result.checkTargetsCount(3) - let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") + let buildPath = result.plan.buildParameters.dataPath.appending(components: "debug") let ext = try result.target(for: "extlib").clangTarget() var args: [String] = [] @@ -1354,9 +1357,9 @@ final class BuildPlanTests: XCTestCase { } func testCLanguageStandard() throws { - let Pkg: AbsolutePath = AbsolutePath("/Pkg") + let Pkg: AbsolutePath = "/Pkg" - let fs = InMemoryFileSystem(emptyFiles: + let fs: FileSystem = InMemoryFileSystem(emptyFiles: Pkg.appending(components: "Sources", "exe", "main.cpp").pathString, Pkg.appending(components: "Sources", "lib", "lib.c").pathString, Pkg.appending(components: "Sources", "lib", "libx.cpp").pathString, @@ -1392,7 +1395,7 @@ final class BuildPlanTests: XCTestCase { result.checkProductsCount(1) result.checkTargetsCount(2) - let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") + let buildPath = result.plan.buildParameters.dataPath.appending(components: "debug") #if os(macOS) XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [ @@ -1443,7 +1446,7 @@ final class BuildPlanTests: XCTestCase { } func testSwiftCMixed() throws { - let Pkg: AbsolutePath = AbsolutePath("/Pkg") + let Pkg: AbsolutePath = "/Pkg" let fs = InMemoryFileSystem(emptyFiles: Pkg.appending(components: "Sources", "exe", "main.swift").pathString, @@ -1476,7 +1479,7 @@ final class BuildPlanTests: XCTestCase { result.checkProductsCount(1) result.checkTargetsCount(2) - let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") + let buildPath = result.plan.buildParameters.dataPath.appending(components: "debug") let lib = try result.target(for: "lib").clangTarget() var args: [String] = [] @@ -1636,7 +1639,7 @@ final class BuildPlanTests: XCTestCase { observabilityScope: observability.topScope ) - let buildPath: AbsolutePath = plan.buildParameters.dataPath.appending(components: "debug") + let buildPath = plan.buildParameters.dataPath.appending(components: "debug") XCTAssertEqual(try plan.createREPLArguments().sorted(), ["-I\(Dep.appending(components: "Sources", "CDep", "include"))", "-I\(buildPath)", "-I\(buildPath.appending(components: "lib.build"))", "-L\(buildPath)", "-lpkg__REPL", "repl"]) @@ -1684,7 +1687,7 @@ final class BuildPlanTests: XCTestCase { result.checkTargetsCount(3) #endif - let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") + let buildPath = result.plan.buildParameters.dataPath.appending(components: "debug") let foo = try result.target(for: "Foo").swiftTarget().compileArguments() XCTAssertMatch(foo, [.anySequence, "-swift-version", "4", "-enable-batch-mode", "-Onone", "-enable-testing", "-g", .equal(j), "-DSWIFT_PACKAGE", "-DDEBUG", "-module-cache-path", "\(buildPath.appending(components: "ModuleCache"))", .anySequence]) @@ -1764,7 +1767,7 @@ final class BuildPlanTests: XCTestCase { result.checkProductsCount(1) result.checkTargetsCount(1) - let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "release") + let buildPath = result.plan.buildParameters.dataPath.appending(components: "release") let exe = try result.target(for: "exe").swiftTarget().compileArguments() @@ -2107,7 +2110,7 @@ final class BuildPlanTests: XCTestCase { result.checkProductsCount(1) result.checkTargetsCount(1) - let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") + let buildPath = result.plan.buildParameters.dataPath.appending(components: "debug") XCTAssertMatch(try result.target(for: "exe").swiftTarget().compileArguments(), ["-swift-version", "4", "-enable-batch-mode", "-Onone", "-enable-testing", "-g", .equal(j), "-DSWIFT_PACKAGE", "-DDEBUG", "-Xcc", "-fmodule-map-file=\(Clibgit.appending(components: "module.modulemap"))", "-module-cache-path", "\(buildPath.appending(components: "ModuleCache"))", .anySequence]) @@ -2230,7 +2233,7 @@ final class BuildPlanTests: XCTestCase { result.checkProductsCount(2) result.checkTargetsCount(2) - let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") + let buildPath = result.plan.buildParameters.dataPath.appending(components: "debug") let fooLinkArgs = try result.buildProduct(for: "Foo").linkArguments() let barLinkArgs = try result.buildProduct(for: "Bar-Baz").linkArguments() @@ -2355,7 +2358,7 @@ final class BuildPlanTests: XCTestCase { result.checkProductsCount(2) result.checkTargetsCount(2) - let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") + let buildPath = result.plan.buildParameters.dataPath.appending(components: "debug") let exe = try result.target(for: "exe").swiftTarget().compileArguments() XCTAssertMatch(exe, ["-swift-version", "4", "-enable-batch-mode", "-Onone", "-enable-testing", "-g", .equal(j), "-DSWIFT_PACKAGE", "-DDEBUG", "-module-cache-path", "\(buildPath.appending(components: "ModuleCache"))", .anySequence]) @@ -2404,7 +2407,7 @@ final class BuildPlanTests: XCTestCase { } func testClangTargets() throws { - let Pkg: AbsolutePath = AbsolutePath("/Pkg") + let Pkg: AbsolutePath = "/Pkg" let fs = InMemoryFileSystem(emptyFiles: Pkg.appending(components: "Sources", "exe", "main.c").pathString, @@ -2442,7 +2445,7 @@ final class BuildPlanTests: XCTestCase { result.checkTargetsCount(2) let triple = result.plan.buildParameters.triple - let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") + let buildPath = result.plan.buildParameters.dataPath.appending(components: "debug") let exe = try result.target(for: "exe").clangTarget() @@ -2876,7 +2879,7 @@ final class BuildPlanTests: XCTestCase { } func testWindowsTarget() throws { - let Pkg: AbsolutePath = AbsolutePath("/Pkg") + let Pkg: AbsolutePath = "/Pkg" let fs = InMemoryFileSystem(emptyFiles: Pkg.appending(components: "Sources", "exe", "main.swift").pathString, Pkg.appending(components: "Sources", "lib", "lib.c").pathString, @@ -2908,7 +2911,7 @@ final class BuildPlanTests: XCTestCase { result.checkProductsCount(1) result.checkTargetsCount(2) - let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") + let buildPath = result.plan.buildParameters.dataPath.appending(components: "debug") let lib = try result.target(for: "lib").clangTarget() let args = [ @@ -2936,7 +2939,7 @@ final class BuildPlanTests: XCTestCase { } func testWASITarget() throws { - let Pkg: AbsolutePath = AbsolutePath("/Pkg") + let Pkg: AbsolutePath = "/Pkg" let fs = InMemoryFileSystem(emptyFiles: Pkg.appending(components: "Sources", "app", "main.swift").pathString, @@ -2974,7 +2977,7 @@ final class BuildPlanTests: XCTestCase { result.checkProductsCount(2) result.checkTargetsCount(5) // There are two additional targets on non-Apple platforms, for test discovery and test entry point - let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") + let buildPath = result.plan.buildParameters.dataPath.appending(components: "debug") let lib = try result.target(for: "lib").clangTarget() let args = [ @@ -3653,7 +3656,7 @@ final class BuildPlanTests: XCTestCase { func testExecBuildTimeDependency() throws { let PkgA = AbsolutePath("/PkgA") - let fs = InMemoryFileSystem(emptyFiles: + let fs: FileSystem = InMemoryFileSystem(emptyFiles: PkgA.appending(components: "Sources", "exe", "main.swift").pathString, PkgA.appending(components: "Sources", "swiftlib", "lib.swift").pathString, "/PkgB/Sources/PkgB/PkgB.swift" @@ -3696,7 +3699,7 @@ final class BuildPlanTests: XCTestCase { observabilityScope: observability.topScope ) - let buildPath: AbsolutePath = plan.buildParameters.dataPath.appending(components: "debug") + let buildPath = plan.buildParameters.dataPath.appending(components: "debug") let yaml = try fs.tempDirectory.appending(components: UUID().uuidString, "debug.yaml") try fs.createDirectory(yaml.parentDirectory, recursive: true) @@ -3720,7 +3723,7 @@ final class BuildPlanTests: XCTestCase { let PkgA = AbsolutePath("/PkgA") // This has a Swift and ObjC target in the same package. - let fs = InMemoryFileSystem(emptyFiles: + let fs: FileSystem = InMemoryFileSystem(emptyFiles: PkgA.appending(components: "Sources", "Bar", "main.m").pathString, PkgA.appending(components: "Sources", "Foo", "Foo.swift").pathString ) @@ -3749,7 +3752,7 @@ final class BuildPlanTests: XCTestCase { ) let result = try BuildPlanResult(plan: plan) - let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") + let buildPath = result.plan.buildParameters.dataPath.appending(components: "debug") let fooTarget = try result.target(for: "Foo").swiftTarget().compileArguments() #if os(macOS) @@ -3783,7 +3786,7 @@ final class BuildPlanTests: XCTestCase { let PkgA = AbsolutePath("/PkgA") // This has a Swift and ObjC target in different packages with automatic product type. - let fs = InMemoryFileSystem(emptyFiles: + let fs: FileSystem = InMemoryFileSystem(emptyFiles: PkgA.appending(components: "Sources", "Bar", "main.m").pathString, "/PkgB/Sources/Foo/Foo.swift" ) @@ -3823,7 +3826,7 @@ final class BuildPlanTests: XCTestCase { ) let result = try BuildPlanResult(plan: plan) - let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") + let buildPath = result.plan.buildParameters.dataPath.appending(components: "debug") let fooTarget = try result.target(for: "Foo").swiftTarget().compileArguments() #if os(macOS) @@ -3857,7 +3860,7 @@ final class BuildPlanTests: XCTestCase { let PkgA = AbsolutePath("/PkgA") // This has a Swift and ObjC target in different packages with dynamic product type. - let fs = InMemoryFileSystem(emptyFiles: + let fs: FileSystem = InMemoryFileSystem(emptyFiles: PkgA.appending(components: "Sources", "Bar", "main.m").pathString, "/PkgB/Sources/Foo/Foo.swift" ) @@ -3917,7 +3920,7 @@ final class BuildPlanTests: XCTestCase { XCTAssertNoMatch(barTarget, [.anySequence, "-fmodule-map-file=/path/to/build/debug/Foo.build/module.modulemap", .anySequence]) #endif - let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") + let buildPath = result.plan.buildParameters.dataPath.appending(components: "debug") let yaml = try fs.tempDirectory.appending(components: UUID().uuidString, "debug.yaml") try fs.createDirectory(yaml.parentDirectory, recursive: true) @@ -3934,7 +3937,7 @@ final class BuildPlanTests: XCTestCase { } func testModulewrap() throws { - let fs = InMemoryFileSystem(emptyFiles: + let fs: FileSystem = InMemoryFileSystem(emptyFiles: "/Pkg/Sources/exe/main.swift", "/Pkg/Sources/lib/lib.swift" ) @@ -3963,7 +3966,7 @@ final class BuildPlanTests: XCTestCase { observabilityScope: observability.topScope )) - let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") + let buildPath = result.plan.buildParameters.dataPath.appending(components: "debug") let objects = try result.buildProduct(for: "exe").objects XCTAssertTrue(objects.contains(buildPath.appending(components: "exe.build", "exe.swiftmodule.o")), objects.description) @@ -3993,7 +3996,7 @@ final class BuildPlanTests: XCTestCase { } func testArchiving() throws { - let fs = InMemoryFileSystem(emptyFiles: + let fs: FileSystem = InMemoryFileSystem(emptyFiles: "/Package/Sources/rary/rary.swift" ) @@ -4023,7 +4026,7 @@ final class BuildPlanTests: XCTestCase { observabilityScope: observability.topScope )) - let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") + let buildPath = result.plan.buildParameters.dataPath.appending(components: "debug") let yaml = try fs.tempDirectory.appending(components: UUID().uuidString, "debug.yaml") try fs.createDirectory(yaml.parentDirectory, recursive: true) @@ -4108,7 +4111,7 @@ final class BuildPlanTests: XCTestCase { ) let result = try BuildPlanResult(plan: plan) - let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") + let buildPath = result.plan.buildParameters.dataPath.appending(components: "debug") let fooTarget = try result.target(for: "Foo").swiftTarget() XCTAssertEqual(try fooTarget.objects.map{ $0.pathString }, [ @@ -4174,7 +4177,7 @@ final class BuildPlanTests: XCTestCase { ) let result = try BuildPlanResult(plan: plan) - let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") + let buildPath = result.plan.buildParameters.dataPath.appending(components: "debug") let fooTarget = try result.target(for: "Foo").swiftTarget() XCTAssertEqual(try fooTarget.objects.map{ $0.pathString }, [ @@ -4239,7 +4242,7 @@ final class BuildPlanTests: XCTestCase { ) let result = try BuildPlanResult(plan: plan) - let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending("debug") + let buildPath = result.plan.buildParameters.dataPath.appending("debug") let fooTarget = try result.target(for: "Foo").clangTarget() XCTAssertEqual(try fooTarget.objects.map(\.pathString).sorted(), [ @@ -4311,7 +4314,7 @@ final class BuildPlanTests: XCTestCase { } func testXCFrameworkBinaryTargets(platform: String, arch: String, destinationTriple: Basics.Triple) throws { - let Pkg: AbsolutePath = AbsolutePath("/Pkg") + let Pkg: AbsolutePath = "/Pkg" let fs = InMemoryFileSystem(emptyFiles: Pkg.appending(components: "Sources", "exe", "main.swift").pathString, @@ -4429,7 +4432,7 @@ final class BuildPlanTests: XCTestCase { result.checkProductsCount(3) result.checkTargetsCount(3) - let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") + let buildPath = result.plan.buildParameters.dataPath.appending(components: "debug") let libraryBasicArguments = try result.target(for: "Library").swiftTarget().compileArguments() XCTAssertMatch(libraryBasicArguments, [.anySequence, "-F", "\(buildPath)", .anySequence]) @@ -4573,7 +4576,7 @@ final class BuildPlanTests: XCTestCase { } func testSnippets() throws { - let fs = InMemoryFileSystem(emptyFiles: + let fs: FileSystem = InMemoryFileSystem(emptyFiles: "/Pkg/Sources/Lib/Lib.swift", "/Pkg/Snippets/ASnippet.swift", "/Pkg/.build/release.yaml" diff --git a/Tests/BuildTests/IncrementalBuildTests.swift b/Tests/BuildTests/IncrementalBuildTests.swift index ecf8a897853..3f20d6280c4 100644 --- a/Tests/BuildTests/IncrementalBuildTests.swift +++ b/Tests/BuildTests/IncrementalBuildTests.swift @@ -10,11 +10,9 @@ // //===----------------------------------------------------------------------===// -import XCTest - +import Basics import SPMTestSupport -import TSCBasic - +import XCTest /// Functional tests of incremental builds. These are fairly ad hoc at this /// point, and because of the time they take, they need to be kept minimal. diff --git a/Tests/BuildTests/LLBuildManifestTests.swift b/Tests/BuildTests/LLBuildManifestTests.swift index 73d9413223d..becb6aacbb5 100644 --- a/Tests/BuildTests/LLBuildManifestTests.swift +++ b/Tests/BuildTests/LLBuildManifestTests.swift @@ -10,17 +10,18 @@ // //===----------------------------------------------------------------------===// +import Basics +import LLBuildManifest import XCTest -import TSCBasic -import LLBuildManifest +import class TSCBasic.InMemoryFileSystem // FIXME: This should be in its own test target. final class LLBuildManifestTests: XCTestCase { func testBasics() throws { var manifest = BuildManifest() - let root: AbsolutePath = AbsolutePath("/some") + let root: AbsolutePath = "/some" manifest.defaultTarget = "main" manifest.addPhonyCmd( @@ -66,7 +67,7 @@ final class LLBuildManifestTests: XCTestCase { func testShellCommands() throws { var manifest = BuildManifest() - let root: AbsolutePath = AbsolutePath.root + let root: AbsolutePath = .root manifest.defaultTarget = "main" manifest.addShellCmd( diff --git a/Tests/BuildTests/MockBuildTestHelper.swift b/Tests/BuildTests/MockBuildTestHelper.swift index f1fd0a35868..a18da1e6cf4 100644 --- a/Tests/BuildTests/MockBuildTestHelper.swift +++ b/Tests/BuildTests/MockBuildTestHelper.swift @@ -15,7 +15,6 @@ @testable import Build import Basics import SPMBuildCore -import TSCBasic import XCTest struct MockToolchain: PackageModel.Toolchain { @@ -61,7 +60,7 @@ let hostTriple = try! UserToolchain.default.triple #endif func mockBuildParameters( - buildPath: AbsolutePath = AbsolutePath("/path/to/build"), + buildPath: AbsolutePath = "/path/to/build", config: BuildConfiguration = .debug, toolchain: PackageModel.Toolchain = MockToolchain(), flags: PackageModel.BuildFlags = PackageModel.BuildFlags(), diff --git a/Tests/BuildTests/ModuleAliasingBuildTests.swift b/Tests/BuildTests/ModuleAliasingBuildTests.swift index a6bf1be0b1e..ecf4b6c95e8 100644 --- a/Tests/BuildTests/ModuleAliasingBuildTests.swift +++ b/Tests/BuildTests/ModuleAliasingBuildTests.swift @@ -18,10 +18,11 @@ import PackageLoading import SPMBuildCore import SPMTestSupport import SwiftDriver -import TSCBasic import Workspace import XCTest +import class TSCBasic.InMemoryFileSystem + final class ModuleAliasingBuildTests: XCTestCase { func testModuleAliasingEmptyAlias() throws { let fs = InMemoryFileSystem( diff --git a/Tests/CommandsTests/APIDiffTests.swift b/Tests/CommandsTests/APIDiffTests.swift index eea3e39e18b..4ee9728cfce 100644 --- a/Tests/CommandsTests/APIDiffTests.swift +++ b/Tests/CommandsTests/APIDiffTests.swift @@ -18,10 +18,11 @@ import Foundation import PackageModel import SourceControl import SPMTestSupport -import TSCBasic import Workspace import XCTest +import enum TSCBasic.ProcessEnv + final class APIDiffTests: CommandsTestCase { private let driverSupport = DriverSupport() diff --git a/Tests/CommandsTests/BuildToolTests.swift b/Tests/CommandsTests/BuildToolTests.swift index d524b0b3d01..3fd5922a081 100644 --- a/Tests/CommandsTests/BuildToolTests.swift +++ b/Tests/CommandsTests/BuildToolTests.swift @@ -10,13 +10,13 @@ // //===----------------------------------------------------------------------===// +import Basics @testable import Commands import PackageGraph import PackageLoading import PackageModel import SPMBuildCore import SPMTestSupport -import TSCBasic import Workspace import XCTest diff --git a/Tests/CommandsTests/CommandsTestCase.swift b/Tests/CommandsTests/CommandsTestCase.swift index 730e6ea9a38..b49fe7561a8 100644 --- a/Tests/CommandsTests/CommandsTestCase.swift +++ b/Tests/CommandsTests/CommandsTestCase.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import TSCBasic +import Basics import XCTest class CommandsTestCase: XCTestCase { diff --git a/Tests/CommandsTests/MultiRootSupportTests.swift b/Tests/CommandsTests/MultiRootSupportTests.swift index efbf5494b43..024bac2015c 100644 --- a/Tests/CommandsTests/MultiRootSupportTests.swift +++ b/Tests/CommandsTests/MultiRootSupportTests.swift @@ -13,10 +13,11 @@ import Basics import Commands import SPMTestSupport -import TSCBasic import Workspace import XCTest +import class TSCBasic.InMemoryFileSystem + final class MultiRootSupportTests: CommandsTestCase { func testWorkspaceLoader() throws { diff --git a/Tests/CommandsTests/PackageRegistryToolTests.swift b/Tests/CommandsTests/PackageRegistryToolTests.swift index 0e04ec21841..97261c79d0c 100644 --- a/Tests/CommandsTests/PackageRegistryToolTests.swift +++ b/Tests/CommandsTests/PackageRegistryToolTests.swift @@ -18,11 +18,13 @@ import PackageModel @testable import PackageRegistryTool import PackageSigning import SPMTestSupport -import TSCBasic import TSCclibc // for SPM_posix_spawn_file_actions_addchdir_np_supported import Workspace import XCTest +import enum TSCBasic.JSON +import struct TSCBasic.ProcessResult + let defaultRegistryBaseURL = URL("https://packages.example.com") let customRegistryBaseURL = URL("https://custom.packages.example.com") @@ -393,7 +395,7 @@ final class PackageRegistryToolTests: CommandsTestCase { let archiver = ZipArchiver(fileSystem: localFileSystem) let extractPath = archivePath.parentDirectory.appending(component: UUID().uuidString) try localFileSystem.createDirectory(extractPath) - try tsc_await { archiver.extract(from: archivePath, to: extractPath, completion: $0) } + try temp_await { archiver.extract(from: archivePath, to: extractPath, completion: $0) } try localFileSystem.stripFirstLevel(of: extractPath) XCTAssertFileExists(extractPath.appending("Package.swift")) return extractPath @@ -548,7 +550,7 @@ final class PackageRegistryToolTests: CommandsTestCase { let archiver = ZipArchiver(fileSystem: localFileSystem) let extractPath = archivePath.parentDirectory.appending(component: UUID().uuidString) try localFileSystem.createDirectory(extractPath) - try tsc_await { archiver.extract(from: archivePath, to: extractPath, completion: $0) } + try temp_await { archiver.extract(from: archivePath, to: extractPath, completion: $0) } try localFileSystem.stripFirstLevel(of: extractPath) let manifestInArchive = try localFileSystem.readFileContents(extractPath.appending(manifestFile)).contents @@ -641,7 +643,7 @@ final class PackageRegistryToolTests: CommandsTestCase { // Validate signatures var verifierConfiguration = VerifierConfiguration() - verifierConfiguration.trustedRoots = try tsc_await { self.testRoots(callback: $0) } + verifierConfiguration.trustedRoots = try temp_await { self.testRoots(callback: $0) } // archive signature let archivePath = workingDirectory.appending("\(packageIdentity)-\(version).zip") @@ -751,7 +753,7 @@ final class PackageRegistryToolTests: CommandsTestCase { // Validate signatures var verifierConfiguration = VerifierConfiguration() - verifierConfiguration.trustedRoots = try tsc_await { self.testRoots(callback: $0) } + verifierConfiguration.trustedRoots = try temp_await { self.testRoots(callback: $0) } // archive signature let archivePath = workingDirectory.appending("\(packageIdentity)-\(version).zip") @@ -858,7 +860,7 @@ final class PackageRegistryToolTests: CommandsTestCase { // Validate signatures var verifierConfiguration = VerifierConfiguration() - verifierConfiguration.trustedRoots = try tsc_await { self.testRoots(callback: $0) } + verifierConfiguration.trustedRoots = try temp_await { self.testRoots(callback: $0) } // archive signature let archivePath = workingDirectory.appending("\(packageIdentity)-\(version).zip") @@ -944,7 +946,7 @@ final class PackageRegistryToolTests: CommandsTestCase { let archiver = ZipArchiver(fileSystem: localFileSystem) let extractPath = archivePath.parentDirectory.appending(component: UUID().uuidString) try localFileSystem.createDirectory(extractPath) - try tsc_await { archiver.extract(from: archivePath, to: extractPath, completion: $0) } + try temp_await { archiver.extract(from: archivePath, to: extractPath, completion: $0) } try localFileSystem.stripFirstLevel(of: extractPath) let manifestSignature = try ManifestSignatureParser.parse( diff --git a/Tests/CommandsTests/PackageToolTests.swift b/Tests/CommandsTests/PackageToolTests.swift index 50276496310..a96973e09e1 100644 --- a/Tests/CommandsTests/PackageToolTests.swift +++ b/Tests/CommandsTests/PackageToolTests.swift @@ -19,10 +19,15 @@ import PackageLoading import PackageModel import SourceControl import SPMTestSupport -import TSCBasic import Workspace import XCTest +import struct TSCBasic.ByteString +import class TSCBasic.BufferedOutputByteStream +import class TSCBasic.InMemoryFileSystem +import enum TSCBasic.JSON +import class TSCBasic.Process + final class PackageToolTests: CommandsTestCase { @discardableResult private func execute( @@ -2902,7 +2907,7 @@ final class PackageToolTests: CommandsTestCase { // Load the root manifest. let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: []) - let rootManifests = try tsc_await { + let rootManifests = try temp_await { workspace.loadRootManifests( packages: rootInput.packages, observabilityScope: observability.topScope, diff --git a/Tests/CommandsTests/RunToolTests.swift b/Tests/CommandsTests/RunToolTests.swift index 3bf52df82e7..44f91cffa73 100644 --- a/Tests/CommandsTests/RunToolTests.swift +++ b/Tests/CommandsTests/RunToolTests.swift @@ -10,11 +10,12 @@ // //===----------------------------------------------------------------------===// +import Basics +import Commands +import SPMTestSupport import XCTest -import SPMTestSupport -import Commands -import TSCBasic +import class TSCBasic.Process final class RunToolTests: CommandsTestCase { diff --git a/Tests/CommandsTests/SwiftToolTests.swift b/Tests/CommandsTests/SwiftToolTests.swift index ae783644adf..62b2dde2955 100644 --- a/Tests/CommandsTests/SwiftToolTests.swift +++ b/Tests/CommandsTests/SwiftToolTests.swift @@ -14,9 +14,12 @@ @testable import CoreCommands @testable import Commands import SPMTestSupport -import TSCBasic import XCTest +import class TSCBasic.BufferedOutputByteStream +import protocol TSCBasic.OutputByteStream +import var TSCBasic.stderrStream + final class SwiftToolTests: CommandsTestCase { func testVerbosityLogLevel() throws { try fixture(name: "Miscellaneous/Simple") { fixturePath in diff --git a/Tests/CommandsTests/TestToolTests.swift b/Tests/CommandsTests/TestToolTests.swift index eb76b177ca1..741f61a2e31 100644 --- a/Tests/CommandsTests/TestToolTests.swift +++ b/Tests/CommandsTests/TestToolTests.swift @@ -10,10 +10,10 @@ // //===----------------------------------------------------------------------===// +import Basics import Commands import PackageModel import SPMTestSupport -import TSCBasic import XCTest final class TestToolTests: CommandsTestCase { diff --git a/Tests/FunctionalPerformanceTests/BuildPerfTests.swift b/Tests/FunctionalPerformanceTests/BuildPerfTests.swift index ca83606d0b5..e0b4aaf3398 100644 --- a/Tests/FunctionalPerformanceTests/BuildPerfTests.swift +++ b/Tests/FunctionalPerformanceTests/BuildPerfTests.swift @@ -10,13 +10,15 @@ // //===----------------------------------------------------------------------===// +import Basics import Commands import PackageModel import SPMTestSupport -import TSCBasic import Workspace import XCTest +import class TSCTestSupport.XCTestCasePerf + class BuildPerfTests: XCTestCasePerf { @discardableResult diff --git a/Tests/FunctionalTests/CFamilyTargetTests.swift b/Tests/FunctionalTests/CFamilyTargetTests.swift index 3be104775c9..d443a4f89d3 100644 --- a/Tests/FunctionalTests/CFamilyTargetTests.swift +++ b/Tests/FunctionalTests/CFamilyTargetTests.swift @@ -10,16 +10,18 @@ // //===----------------------------------------------------------------------===// +import Basics import Commands import PackageGraph import PackageLoading import PackageModel import SourceControl import SPMTestSupport -import TSCBasic import Workspace import XCTest +import class TSCBasic.Process + typealias Process = TSCBasic.Process /// Asserts if a directory (recursively) contains a file. diff --git a/Tests/FunctionalTests/DependencyResolutionTests.swift b/Tests/FunctionalTests/DependencyResolutionTests.swift index 2a84526dca0..0a312de947e 100644 --- a/Tests/FunctionalTests/DependencyResolutionTests.swift +++ b/Tests/FunctionalTests/DependencyResolutionTests.swift @@ -10,11 +10,11 @@ // //===----------------------------------------------------------------------===// +import Basics import Commands import PackageModel import SourceControl import SPMTestSupport -import TSCBasic import Workspace import XCTest diff --git a/Tests/FunctionalTests/MacroTests.swift b/Tests/FunctionalTests/MacroTests.swift index 9821e8a9816..bf058b5a25f 100644 --- a/Tests/FunctionalTests/MacroTests.swift +++ b/Tests/FunctionalTests/MacroTests.swift @@ -13,7 +13,6 @@ import DriverSupport import SPMTestSupport import PackageModel -import TSCBasic import XCTest class MacroTests: XCTestCase { diff --git a/Tests/FunctionalTests/MiscellaneousTests.swift b/Tests/FunctionalTests/MiscellaneousTests.swift index 4b13cf6952e..ce5dc05b10b 100644 --- a/Tests/FunctionalTests/MiscellaneousTests.swift +++ b/Tests/FunctionalTests/MiscellaneousTests.swift @@ -14,10 +14,12 @@ import Basics import PackageModel import SourceControl import SPMTestSupport -import TSCBasic import Workspace import XCTest +import class TSCBasic.Process +import enum TSCBasic.ProcessEnv + typealias ProcessID = TSCBasic.Process.ProcessID class MiscellaneousTestCase: XCTestCase { diff --git a/Tests/FunctionalTests/ModuleAliasingFixtureTests.swift b/Tests/FunctionalTests/ModuleAliasingFixtureTests.swift index 6655802828b..1173b5c291a 100644 --- a/Tests/FunctionalTests/ModuleAliasingFixtureTests.swift +++ b/Tests/FunctionalTests/ModuleAliasingFixtureTests.swift @@ -14,7 +14,6 @@ import Commands import PackageModel import SourceControl import SPMTestSupport -import TSCBasic import Workspace import XCTest diff --git a/Tests/FunctionalTests/ModuleMapTests.swift b/Tests/FunctionalTests/ModuleMapTests.swift index 2bf0d486e48..d646c8be2b9 100644 --- a/Tests/FunctionalTests/ModuleMapTests.swift +++ b/Tests/FunctionalTests/ModuleMapTests.swift @@ -10,10 +10,10 @@ // //===----------------------------------------------------------------------===// +import Basics import Commands import PackageModel import SPMTestSupport -import TSCBasic import Workspace import XCTest diff --git a/Tests/FunctionalTests/PluginTests.swift b/Tests/FunctionalTests/PluginTests.swift index 23d63c9d041..243f38d4ab6 100644 --- a/Tests/FunctionalTests/PluginTests.swift +++ b/Tests/FunctionalTests/PluginTests.swift @@ -16,7 +16,6 @@ import PackageLoading import PackageModel @testable import SPMBuildCore import SPMTestSupport -import TSCBasic import Workspace import XCTest @@ -365,7 +364,7 @@ class PluginTests: XCTestCase { // Load the root manifest. let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: []) - let rootManifests = try tsc_await { + let rootManifests = try temp_await { workspace.loadRootManifests( packages: rootInput.packages, observabilityScope: observability.topScope, @@ -461,7 +460,7 @@ class PluginTests: XCTestCase { ) let toolSearchDirectories = [try UserToolchain.default.swiftCompilerPath.parentDirectory] - let success = try tsc_await { plugin.invoke( + let success = try temp_await { plugin.invoke( action: .performCommand(package: package, arguments: arguments), buildEnvironment: BuildEnvironment(platform: .macOS, configuration: .debug), scriptRunner: scriptRunner, @@ -547,7 +546,7 @@ class PluginTests: XCTestCase { // Load the root manifest. let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: []) - let rootManifests = try tsc_await { + let rootManifests = try temp_await { workspace.loadRootManifests( packages: rootInput.packages, observabilityScope: observability.topScope, @@ -644,7 +643,7 @@ class PluginTests: XCTestCase { // Load the root manifest. let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: []) - let rootManifests = try tsc_await { + let rootManifests = try temp_await { workspace.loadRootManifests( packages: rootInput.packages, observabilityScope: observability.topScope, @@ -939,7 +938,7 @@ class PluginTests: XCTestCase { // Load the root manifest. let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: []) - let rootManifests = try tsc_await { + let rootManifests = try temp_await { workspace.loadRootManifests( packages: rootInput.packages, observabilityScope: observability.topScope, diff --git a/Tests/FunctionalTests/ResourcesTests.swift b/Tests/FunctionalTests/ResourcesTests.swift index 94d4956e668..60857fb8877 100644 --- a/Tests/FunctionalTests/ResourcesTests.swift +++ b/Tests/FunctionalTests/ResourcesTests.swift @@ -10,12 +10,9 @@ // //===----------------------------------------------------------------------===// -import XCTest +import Basics import SPMTestSupport - -import struct TSCBasic.AbsolutePath -import var TSCBasic.localFileSystem -import func TSCBasic.withTemporaryDirectory +import XCTest class ResourcesTests: XCTestCase { func testSimpleResources() throws { diff --git a/Tests/FunctionalTests/SwiftPMXCTestHelperTests.swift b/Tests/FunctionalTests/SwiftPMXCTestHelperTests.swift index d3d2744a26b..86fa9cb62a3 100644 --- a/Tests/FunctionalTests/SwiftPMXCTestHelperTests.swift +++ b/Tests/FunctionalTests/SwiftPMXCTestHelperTests.swift @@ -10,10 +10,10 @@ // //===----------------------------------------------------------------------===// +import Basics import Commands import PackageModel import SPMTestSupport -import TSCBasic import Workspace import XCTest diff --git a/Tests/FunctionalTests/TestDiscoveryTests.swift b/Tests/FunctionalTests/TestDiscoveryTests.swift index 7cb3e07d9b7..05d14fe5edd 100644 --- a/Tests/FunctionalTests/TestDiscoveryTests.swift +++ b/Tests/FunctionalTests/TestDiscoveryTests.swift @@ -10,9 +10,9 @@ // //===----------------------------------------------------------------------===// +import Basics import PackageModel import SPMTestSupport -import TSCBasic import XCTest class TestDiscoveryTests: XCTestCase { diff --git a/Tests/FunctionalTests/ToolsVersionTests.swift b/Tests/FunctionalTests/ToolsVersionTests.swift index c1076687dea..cda47969570 100644 --- a/Tests/FunctionalTests/ToolsVersionTests.swift +++ b/Tests/FunctionalTests/ToolsVersionTests.swift @@ -10,14 +10,13 @@ // //===----------------------------------------------------------------------===// -import XCTest - -import TSCBasic -import SPMTestSupport +import Basics import Commands import PackageModel import SourceControl +import SPMTestSupport import Workspace +import XCTest class ToolsVersionTests: XCTestCase { diff --git a/Tests/FunctionalTests/VersionSpecificTests.swift b/Tests/FunctionalTests/VersionSpecificTests.swift index 30fb5ac4392..ad264e078fe 100644 --- a/Tests/FunctionalTests/VersionSpecificTests.swift +++ b/Tests/FunctionalTests/VersionSpecificTests.swift @@ -13,7 +13,6 @@ import Basics import SourceControl import SPMTestSupport -import TSCBasic import XCTest class VersionSpecificTests: XCTestCase { diff --git a/Tests/PackageCollectionsSigningTests/CertificatePolicyTests.swift b/Tests/PackageCollectionsSigningTests/CertificatePolicyTests.swift index 69211953b51..9c1cf293527 100644 --- a/Tests/PackageCollectionsSigningTests/CertificatePolicyTests.swift +++ b/Tests/PackageCollectionsSigningTests/CertificatePolicyTests.swift @@ -13,15 +13,14 @@ import Basics @testable import PackageCollectionsSigning import SPMTestSupport -import TSCBasic import X509 import XCTest class CertificatePolicyTests: XCTestCase { func test_RSA_validate_happyCase() throws { - let certChain = try tsc_await { callback in self.readTestRSACertChain(callback: callback) } + let certChain = try temp_await { callback in self.readTestRSACertChain(callback: callback) } let policy = TestCertificatePolicy(trustedRoots: certChain.suffix(1)) - XCTAssertNoThrow(try tsc_await { callback in policy.validate( + XCTAssertNoThrow(try temp_await { callback in policy.validate( certChain: certChain, validationTime: TestCertificatePolicy.testCertValidDate, callback: callback @@ -29,9 +28,9 @@ class CertificatePolicyTests: XCTestCase { } func test_EC_validate_happyCase() throws { - let certChain = try tsc_await { callback in self.readTestECCertChain(callback: callback) } + let certChain = try temp_await { callback in self.readTestECCertChain(callback: callback) } let policy = TestCertificatePolicy(trustedRoots: certChain.suffix(1)) - XCTAssertNoThrow(try tsc_await { callback in policy.validate( + XCTAssertNoThrow(try temp_await { callback in policy.validate( certChain: certChain, validationTime: TestCertificatePolicy.testCertValidDate, callback: callback @@ -39,10 +38,10 @@ class CertificatePolicyTests: XCTestCase { } func test_validate_untrustedRoot() throws { - let certChain = try tsc_await { callback in self.readTestRSACertChain(callback: callback) } + let certChain = try temp_await { callback in self.readTestRSACertChain(callback: callback) } // Test root is not trusted let policy = TestCertificatePolicy(trustedRoots: nil) - XCTAssertThrowsError(try tsc_await { callback in policy.validate( + XCTAssertThrowsError(try temp_await { callback in policy.validate( certChain: certChain, validationTime: TestCertificatePolicy.testCertValidDate, callback: callback @@ -54,12 +53,12 @@ class CertificatePolicyTests: XCTestCase { } func test_validate_expiredCert() throws { - let certChain = try tsc_await { callback in self.readTestRSACertChain(callback: callback) } + let certChain = try temp_await { callback in self.readTestRSACertChain(callback: callback) } // Test root is not trusted let policy = TestCertificatePolicy(trustedRoots: certChain.suffix(1)) // Use verify date outside of cert's validity period - XCTAssertThrowsError(try tsc_await { callback in policy.validate( + XCTAssertThrowsError(try temp_await { callback in policy.validate( certChain: certChain, validationTime: TestCertificatePolicy.testCertInvalidDate, callback: callback @@ -98,7 +97,7 @@ class CertificatePolicyTests: XCTestCase { callbackQueue: callbackQueue ) - XCTAssertThrowsError(try tsc_await { callback in + XCTAssertThrowsError(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) { error in guard CertificatePolicyError.invalidCertChain == error as? CertificatePolicyError else { @@ -136,7 +135,7 @@ class CertificatePolicyTests: XCTestCase { observabilityScope: ObservabilitySystem.NOOP, callbackQueue: callbackQueue ) - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) } @@ -149,7 +148,7 @@ class CertificatePolicyTests: XCTestCase { observabilityScope: ObservabilitySystem.NOOP, callbackQueue: callbackQueue ) - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) } @@ -165,7 +164,7 @@ class CertificatePolicyTests: XCTestCase { observabilityScope: ObservabilitySystem.NOOP, callbackQueue: callbackQueue ) - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) } @@ -201,7 +200,7 @@ class CertificatePolicyTests: XCTestCase { observabilityScope: ObservabilitySystem.NOOP, callbackQueue: callbackQueue ) - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) } @@ -214,7 +213,7 @@ class CertificatePolicyTests: XCTestCase { observabilityScope: ObservabilitySystem.NOOP, callbackQueue: callbackQueue ) - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) } @@ -230,7 +229,7 @@ class CertificatePolicyTests: XCTestCase { observabilityScope: ObservabilitySystem.NOOP, callbackQueue: callbackQueue ) - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) } @@ -266,7 +265,7 @@ class CertificatePolicyTests: XCTestCase { observabilityScope: ObservabilitySystem.NOOP, callbackQueue: callbackQueue ) - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) } @@ -279,7 +278,7 @@ class CertificatePolicyTests: XCTestCase { observabilityScope: ObservabilitySystem.NOOP, callbackQueue: callbackQueue ) - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) } @@ -295,7 +294,7 @@ class CertificatePolicyTests: XCTestCase { observabilityScope: ObservabilitySystem.NOOP, callbackQueue: callbackQueue ) - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) } @@ -331,7 +330,7 @@ class CertificatePolicyTests: XCTestCase { observabilityScope: ObservabilitySystem.NOOP, callbackQueue: callbackQueue ) - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) } @@ -344,7 +343,7 @@ class CertificatePolicyTests: XCTestCase { observabilityScope: ObservabilitySystem.NOOP, callbackQueue: callbackQueue ) - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) } @@ -360,7 +359,7 @@ class CertificatePolicyTests: XCTestCase { observabilityScope: ObservabilitySystem.NOOP, callbackQueue: callbackQueue ) - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) } @@ -400,7 +399,7 @@ class CertificatePolicyTests: XCTestCase { callbackQueue: callbackQueue ) - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) } @@ -417,7 +416,7 @@ class CertificatePolicyTests: XCTestCase { callbackQueue: callbackQueue ) - XCTAssertThrowsError(try tsc_await { callback in + XCTAssertThrowsError(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) { error in guard CertificatePolicyError.invalidCertChain == error as? CertificatePolicyError else { @@ -438,7 +437,7 @@ class CertificatePolicyTests: XCTestCase { callbackQueue: callbackQueue ) - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) } @@ -455,7 +454,7 @@ class CertificatePolicyTests: XCTestCase { callbackQueue: callbackQueue ) - XCTAssertThrowsError(try tsc_await { callback in + XCTAssertThrowsError(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) { error in guard CertificatePolicyError.invalidCertChain == error as? CertificatePolicyError else { @@ -498,7 +497,7 @@ class CertificatePolicyTests: XCTestCase { callbackQueue: callbackQueue ) - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) } @@ -515,7 +514,7 @@ class CertificatePolicyTests: XCTestCase { callbackQueue: callbackQueue ) - XCTAssertThrowsError(try tsc_await { callback in + XCTAssertThrowsError(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) { error in guard CertificatePolicyError.invalidCertChain == error as? CertificatePolicyError else { @@ -536,7 +535,7 @@ class CertificatePolicyTests: XCTestCase { callbackQueue: callbackQueue ) - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) } @@ -553,7 +552,7 @@ class CertificatePolicyTests: XCTestCase { callbackQueue: callbackQueue ) - XCTAssertThrowsError(try tsc_await { callback in + XCTAssertThrowsError(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) { error in guard CertificatePolicyError.invalidCertChain == error as? CertificatePolicyError else { @@ -596,7 +595,7 @@ class CertificatePolicyTests: XCTestCase { callbackQueue: callbackQueue ) - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) } @@ -613,7 +612,7 @@ class CertificatePolicyTests: XCTestCase { callbackQueue: callbackQueue ) - XCTAssertThrowsError(try tsc_await { callback in + XCTAssertThrowsError(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) { error in guard CertificatePolicyError.invalidCertChain == error as? CertificatePolicyError else { @@ -634,7 +633,7 @@ class CertificatePolicyTests: XCTestCase { callbackQueue: callbackQueue ) - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) } @@ -651,7 +650,7 @@ class CertificatePolicyTests: XCTestCase { callbackQueue: callbackQueue ) - XCTAssertThrowsError(try tsc_await { callback in + XCTAssertThrowsError(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) { error in guard CertificatePolicyError.invalidCertChain == error as? CertificatePolicyError else { @@ -694,7 +693,7 @@ class CertificatePolicyTests: XCTestCase { callbackQueue: callbackQueue ) - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) } @@ -711,7 +710,7 @@ class CertificatePolicyTests: XCTestCase { callbackQueue: callbackQueue ) - XCTAssertThrowsError(try tsc_await { callback in + XCTAssertThrowsError(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) { error in guard CertificatePolicyError.invalidCertChain == error as? CertificatePolicyError else { @@ -732,7 +731,7 @@ class CertificatePolicyTests: XCTestCase { callbackQueue: callbackQueue ) - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) } @@ -749,7 +748,7 @@ class CertificatePolicyTests: XCTestCase { callbackQueue: callbackQueue ) - XCTAssertThrowsError(try tsc_await { callback in + XCTAssertThrowsError(try temp_await { callback in policy.validate(certChain: certChain, callback: callback) }) { error in guard CertificatePolicyError.invalidCertChain == error as? CertificatePolicyError else { diff --git a/Tests/PackageCollectionsSigningTests/PackageCollectionSigningTests.swift b/Tests/PackageCollectionsSigningTests/PackageCollectionSigningTests.swift index ffc0c1775de..fdf733af771 100644 --- a/Tests/PackageCollectionsSigningTests/PackageCollectionSigningTests.swift +++ b/Tests/PackageCollectionsSigningTests/PackageCollectionSigningTests.swift @@ -15,14 +15,13 @@ import Foundation import PackageCollectionsModel @testable import PackageCollectionsSigning import SPMTestSupport -import TSCBasic import X509 import XCTest class PackageCollectionSigningTests: XCTestCase { func test_RSA_signAndValidate_happyCase() throws { try fixture(name: "Signing", createGitRepo: false) { fixturePath in - let collection = try tsc_await { callback in self.testPackageCollection(callback: callback) } + let collection = try temp_await { callback in self.testPackageCollection(callback: callback) } let certPath = fixturePath.appending(components: "Certificates", "Test_rsa.cer") let intermediateCAPath = fixturePath.appending(components: "Certificates", "TestIntermediateCA.cer") @@ -40,7 +39,7 @@ class PackageCollectionSigningTests: XCTestCase { ) // Sign the collection - let signedCollection = try tsc_await { callback in + let signedCollection = try temp_await { callback in signing.sign( collection: collection, certChainPaths: certChainPaths, @@ -51,7 +50,7 @@ class PackageCollectionSigningTests: XCTestCase { } // Then validate that signature is valid - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in signing.validate(signedCollection: signedCollection, certPolicyKey: .custom, callback: callback) }) } @@ -96,7 +95,7 @@ class PackageCollectionSigningTests: XCTestCase { ) // Sign collection1 - let signedCollection = try tsc_await { callback in + let signedCollection = try temp_await { callback in signing.sign( collection: collection1, certChainPaths: certChainPaths, @@ -113,7 +112,7 @@ class PackageCollectionSigningTests: XCTestCase { // The signature should be invalid XCTAssertThrowsError( - try tsc_await { callback in + try temp_await { callback in signing.validate(signedCollection: badSignedCollection, certPolicyKey: .custom, callback: callback) } ) { error in @@ -126,7 +125,7 @@ class PackageCollectionSigningTests: XCTestCase { func test_EC_signAndValidate_happyCase() throws { try fixture(name: "Signing", createGitRepo: false) { fixturePath in - let collection = try tsc_await { callback in self.testPackageCollection(callback: callback) } + let collection = try temp_await { callback in self.testPackageCollection(callback: callback) } let certPath = fixturePath.appending(components: "Certificates", "Test_ec.cer") let intermediateCAPath = fixturePath.appending(components: "Certificates", "TestIntermediateCA.cer") @@ -144,7 +143,7 @@ class PackageCollectionSigningTests: XCTestCase { ) // Sign the collection - let signedCollection = try tsc_await { callback in + let signedCollection = try temp_await { callback in signing.sign( collection: collection, certChainPaths: certChainPaths, @@ -155,7 +154,7 @@ class PackageCollectionSigningTests: XCTestCase { } // Then validate that signature is valid - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in signing.validate(signedCollection: signedCollection, certPolicyKey: .custom, callback: callback) }) } @@ -200,7 +199,7 @@ class PackageCollectionSigningTests: XCTestCase { ) // Sign collection1 - let signedCollection = try tsc_await { callback in + let signedCollection = try temp_await { callback in signing.sign( collection: collection1, certChainPaths: certChainPaths, @@ -217,7 +216,7 @@ class PackageCollectionSigningTests: XCTestCase { // The signature should be invalid XCTAssertThrowsError( - try tsc_await { callback in + try temp_await { callback in signing.validate(signedCollection: badSignedCollection, certPolicyKey: .custom, callback: callback) } ) { error in @@ -235,7 +234,7 @@ class PackageCollectionSigningTests: XCTestCase { #endif try fixture(name: "Signing", createGitRepo: false) { fixturePath in - let collection = try tsc_await { callback in self.testPackageCollection(callback: callback) } + let collection = try temp_await { callback in self.testPackageCollection(callback: callback) } let certPath = fixturePath.appending(components: "Certificates", "development.cer") let intermediateCAPath = fixturePath.appending(components: "Certificates", "AppleWWDRCAG3.cer") @@ -255,7 +254,7 @@ class PackageCollectionSigningTests: XCTestCase { ) // Sign the collection - let signedCollection = try tsc_await { callback in + let signedCollection = try temp_await { callback in signing.sign( collection: collection, certChainPaths: certChainPaths, @@ -266,7 +265,7 @@ class PackageCollectionSigningTests: XCTestCase { } // Then validate that signature is valid - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in signing.validate( signedCollection: signedCollection, certPolicyKey: certPolicyKey, @@ -285,7 +284,7 @@ class PackageCollectionSigningTests: XCTestCase { ) // Sign the collection - let signedCollection = try tsc_await { callback in + let signedCollection = try temp_await { callback in signing.sign( collection: collection, certChainPaths: certChainPaths, @@ -296,7 +295,7 @@ class PackageCollectionSigningTests: XCTestCase { } // Then validate that signature is valid - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in signing.validate( signedCollection: signedCollection, certPolicyKey: certPolicyKey, @@ -316,7 +315,7 @@ class PackageCollectionSigningTests: XCTestCase { ) // Sign the collection - let signedCollection = try tsc_await { callback in + let signedCollection = try temp_await { callback in signing.sign( collection: collection, certChainPaths: certChainPaths, @@ -327,7 +326,7 @@ class PackageCollectionSigningTests: XCTestCase { } // Then validate that signature is valid - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in signing.validate( signedCollection: signedCollection, certPolicyKey: certPolicyKey, @@ -345,7 +344,7 @@ class PackageCollectionSigningTests: XCTestCase { #endif try fixture(name: "Signing", createGitRepo: false) { fixturePath in - let collection = try tsc_await { callback in self.testPackageCollection(callback: callback) } + let collection = try temp_await { callback in self.testPackageCollection(callback: callback) } let certPath = fixturePath.appending(components: "Certificates", "swift_package_collection.cer") let intermediateCAPath = fixturePath.appending(components: "Certificates", "AppleWWDRCAG3.cer") @@ -363,7 +362,7 @@ class PackageCollectionSigningTests: XCTestCase { ) // Sign the collection - let signedCollection = try tsc_await { callback in + let signedCollection = try temp_await { callback in signing.sign( collection: collection, certChainPaths: certChainPaths, @@ -374,7 +373,7 @@ class PackageCollectionSigningTests: XCTestCase { } // Then validate that signature is valid - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in signing.validate( signedCollection: signedCollection, certPolicyKey: certPolicyKey, @@ -394,7 +393,7 @@ class PackageCollectionSigningTests: XCTestCase { ) // Sign the collection - let signedCollection = try tsc_await { callback in + let signedCollection = try temp_await { callback in signing.sign( collection: collection, certChainPaths: certChainPaths, @@ -405,7 +404,7 @@ class PackageCollectionSigningTests: XCTestCase { } // Then validate that signature is valid - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in signing.validate( signedCollection: signedCollection, certPolicyKey: certPolicyKey, @@ -423,7 +422,7 @@ class PackageCollectionSigningTests: XCTestCase { #endif try fixture(name: "Signing", createGitRepo: false) { fixturePath in - let collection = try tsc_await { callback in self.testPackageCollection(callback: callback) } + let collection = try temp_await { callback in self.testPackageCollection(callback: callback) } let certPath = fixturePath.appending(components: "Certificates", "swift_package.cer") let intermediateCAPath = fixturePath.appending(components: "Certificates", "AppleWWDRCAG6.cer") @@ -443,7 +442,7 @@ class PackageCollectionSigningTests: XCTestCase { ) // Sign the collection - let signedCollection = try tsc_await { callback in + let signedCollection = try temp_await { callback in signing.sign( collection: collection, certChainPaths: certChainPaths, @@ -454,7 +453,7 @@ class PackageCollectionSigningTests: XCTestCase { } // Then validate that signature is valid - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in signing.validate( signedCollection: signedCollection, certPolicyKey: certPolicyKey, @@ -473,7 +472,7 @@ class PackageCollectionSigningTests: XCTestCase { ) // Sign the collection - let signedCollection = try tsc_await { callback in + let signedCollection = try temp_await { callback in signing.sign( collection: collection, certChainPaths: certChainPaths, @@ -484,7 +483,7 @@ class PackageCollectionSigningTests: XCTestCase { } // Then validate that signature is valid - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in signing.validate( signedCollection: signedCollection, certPolicyKey: certPolicyKey, @@ -504,7 +503,7 @@ class PackageCollectionSigningTests: XCTestCase { ) // Sign the collection - let signedCollection = try tsc_await { callback in + let signedCollection = try temp_await { callback in signing.sign( collection: collection, certChainPaths: certChainPaths, @@ -515,7 +514,7 @@ class PackageCollectionSigningTests: XCTestCase { } // Then validate that signature is valid - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in signing.validate( signedCollection: signedCollection, certPolicyKey: certPolicyKey, @@ -533,7 +532,7 @@ class PackageCollectionSigningTests: XCTestCase { #endif try fixture(name: "Signing", createGitRepo: false) { fixturePath in - let collection = try tsc_await { callback in self.testPackageCollection(callback: callback) } + let collection = try temp_await { callback in self.testPackageCollection(callback: callback) } let certPath = fixturePath.appending(components: "Certificates", "development.cer") let intermediateCAPath = fixturePath.appending(components: "Certificates", "AppleWWDRCAG3.cer") @@ -553,7 +552,7 @@ class PackageCollectionSigningTests: XCTestCase { ) // Sign the collection - let signedCollection = try tsc_await { callback in + let signedCollection = try temp_await { callback in signing.sign( collection: collection, certChainPaths: certChainPaths, @@ -564,7 +563,7 @@ class PackageCollectionSigningTests: XCTestCase { } // Then validate that signature is valid - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in signing.validate( signedCollection: signedCollection, certPolicyKey: certPolicyKey, @@ -583,7 +582,7 @@ class PackageCollectionSigningTests: XCTestCase { ) // Sign the collection - let signedCollection = try tsc_await { callback in + let signedCollection = try temp_await { callback in signing.sign( collection: collection, certChainPaths: certChainPaths, @@ -594,7 +593,7 @@ class PackageCollectionSigningTests: XCTestCase { } // Then validate that signature is valid - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in signing.validate( signedCollection: signedCollection, certPolicyKey: certPolicyKey, @@ -612,7 +611,7 @@ class PackageCollectionSigningTests: XCTestCase { #endif try fixture(name: "Signing", createGitRepo: false) { fixturePath in - let collection = try tsc_await { callback in self.testPackageCollection(callback: callback) } + let collection = try temp_await { callback in self.testPackageCollection(callback: callback) } let certPath = fixturePath.appending(components: "Certificates", "swift_package_collection.cer") let intermediateCAPath = fixturePath.appending(components: "Certificates", "AppleWWDRCAG3.cer") @@ -633,7 +632,7 @@ class PackageCollectionSigningTests: XCTestCase { ) // Sign the collection - let signedCollection = try tsc_await { callback in + let signedCollection = try temp_await { callback in signing.sign( collection: collection, certChainPaths: certChainPaths, @@ -644,7 +643,7 @@ class PackageCollectionSigningTests: XCTestCase { } // Then validate that signature is valid - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in signing.validate( signedCollection: signedCollection, certPolicyKey: certPolicyKey, @@ -664,7 +663,7 @@ class PackageCollectionSigningTests: XCTestCase { ) // Sign the collection - let signedCollection = try tsc_await { callback in + let signedCollection = try temp_await { callback in signing.sign( collection: collection, certChainPaths: certChainPaths, @@ -675,7 +674,7 @@ class PackageCollectionSigningTests: XCTestCase { } // Then validate that signature is valid - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in signing.validate( signedCollection: signedCollection, certPolicyKey: certPolicyKey, @@ -693,7 +692,7 @@ class PackageCollectionSigningTests: XCTestCase { #endif try fixture(name: "Signing", createGitRepo: false) { fixturePath in - let collection = try tsc_await { callback in self.testPackageCollection(callback: callback) } + let collection = try temp_await { callback in self.testPackageCollection(callback: callback) } let certPath = fixturePath.appending(components: "Certificates", "swift_package.cer") let intermediateCAPath = fixturePath.appending(components: "Certificates", "AppleWWDRCAG6.cer") @@ -714,7 +713,7 @@ class PackageCollectionSigningTests: XCTestCase { ) // Sign the collection - let signedCollection = try tsc_await { callback in + let signedCollection = try temp_await { callback in signing.sign( collection: collection, certChainPaths: certChainPaths, @@ -725,7 +724,7 @@ class PackageCollectionSigningTests: XCTestCase { } // Then validate that signature is valid - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in signing.validate( signedCollection: signedCollection, certPolicyKey: certPolicyKey, @@ -745,7 +744,7 @@ class PackageCollectionSigningTests: XCTestCase { ) // Sign the collection - let signedCollection = try tsc_await { callback in + let signedCollection = try temp_await { callback in signing.sign( collection: collection, certChainPaths: certChainPaths, @@ -756,7 +755,7 @@ class PackageCollectionSigningTests: XCTestCase { } // Then validate that signature is valid - XCTAssertNoThrow(try tsc_await { callback in + XCTAssertNoThrow(try temp_await { callback in signing.validate( signedCollection: signedCollection, certPolicyKey: certPolicyKey, diff --git a/Tests/PackageCollectionsSigningTests/SignatureTests.swift b/Tests/PackageCollectionsSigningTests/SignatureTests.swift index feee965df5b..1ad7455f67f 100644 --- a/Tests/PackageCollectionsSigningTests/SignatureTests.swift +++ b/Tests/PackageCollectionsSigningTests/SignatureTests.swift @@ -10,15 +10,14 @@ // //===----------------------------------------------------------------------===// -import Foundation -import XCTest - import _CryptoExtras +import Basics import Crypto +import Foundation @testable import PackageCollectionsSigning import SPMTestSupport -import TSCBasic import X509 +import XCTest class SignatureTests: XCTestCase { func test_RS256_generateAndValidate_happyCase() throws { @@ -43,7 +42,7 @@ class SignatureTests: XCTestCase { try privateKey.signature(for: SHA256.hash(data: $0), padding: Signature.rsaSigningPadding).rawRepresentation } - let parsedSignature = try tsc_await { callback in + let parsedSignature = try temp_await { callback in Signature.parse( signature, certChainValidate: { _, cb in cb(.success([certificate])) }, @@ -79,7 +78,7 @@ class SignatureTests: XCTestCase { try privateKey.signature(for: SHA256.hash(data: $0), padding: Signature.rsaSigningPadding).rawRepresentation } - XCTAssertThrowsError(try tsc_await { callback in + XCTAssertThrowsError(try temp_await { callback in Signature.parse( signature, certChainValidate: { _, cb in cb(.success([certificate])) }, @@ -116,7 +115,7 @@ class SignatureTests: XCTestCase { try privateKey.signature(for: SHA256.hash(data: $0)).rawRepresentation } - let parsedSignature = try tsc_await { callback in + let parsedSignature = try temp_await { callback in Signature.parse( signature, certChainValidate: { _, cb in cb(.success([certificate])) }, @@ -152,7 +151,7 @@ class SignatureTests: XCTestCase { try privateKey.signature(for: SHA256.hash(data: $0)).rawRepresentation } - XCTAssertThrowsError(try tsc_await { callback in + XCTAssertThrowsError(try temp_await { callback in Signature.parse( signature, certChainValidate: { _, cb in cb(.success([certificate])) }, diff --git a/Tests/PackageCollectionsTests/GitHubPackageMetadataProviderTests.swift b/Tests/PackageCollectionsTests/GitHubPackageMetadataProviderTests.swift index 899fd4eeea1..7269b73c678 100644 --- a/Tests/PackageCollectionsTests/GitHubPackageMetadataProviderTests.swift +++ b/Tests/PackageCollectionsTests/GitHubPackageMetadataProviderTests.swift @@ -18,7 +18,8 @@ import Basics import PackageModel import SourceControl import SPMTestSupport -import TSCBasic + +import enum TSCBasic.ProcessEnv import struct TSCUtility.Version @@ -368,7 +369,7 @@ internal extension GitHubPackageMetadataProvider { private extension GitHubPackageMetadataProvider { func syncGet(identity: PackageIdentity, location: String) throws -> Model.PackageBasicMetadata { - try tsc_await { callback in + try temp_await { callback in self.get(identity: identity, location: location) { result, _ in callback(result) } } } diff --git a/Tests/PackageCollectionsTests/JSONPackageCollectionProviderTests.swift b/Tests/PackageCollectionsTests/JSONPackageCollectionProviderTests.swift index aeb6501608c..7d70a8ce672 100644 --- a/Tests/PackageCollectionsTests/JSONPackageCollectionProviderTests.swift +++ b/Tests/PackageCollectionsTests/JSONPackageCollectionProviderTests.swift @@ -19,7 +19,6 @@ import PackageCollectionsSigning import PackageModel import SourceControl import SPMTestSupport -import TSCBasic class JSONPackageCollectionProviderTests: XCTestCase { func testGood() throws { @@ -48,7 +47,7 @@ class JSONPackageCollectionProviderTests: XCTestCase { httpClient.configuration.retryStrategy = .none let provider = JSONPackageCollectionProvider(httpClient: httpClient) let source = PackageCollectionsModel.CollectionSource(type: .json, url: url) - let collection = try tsc_await { callback in provider.get(source, callback: callback) } + let collection = try temp_await { callback in provider.get(source, callback: callback) } XCTAssertEqual(collection.name, "Sample Package Collection") XCTAssertEqual(collection.overview, "This is a sample package collection listing made-up packages.") @@ -97,7 +96,7 @@ class JSONPackageCollectionProviderTests: XCTestCase { httpClient.configuration.retryStrategy = .none let provider = JSONPackageCollectionProvider(httpClient: httpClient) let source = PackageCollectionsModel.CollectionSource(type: .json, url: path.asURL) - let collection = try tsc_await { callback in provider.get(source, callback: callback) } + let collection = try temp_await { callback in provider.get(source, callback: callback) } XCTAssertEqual(collection.name, "Sample Package Collection") XCTAssertEqual(collection.overview, "This is a sample package collection listing made-up packages.") @@ -143,7 +142,7 @@ class JSONPackageCollectionProviderTests: XCTestCase { httpClient.configuration.circuitBreakerStrategy = .none httpClient.configuration.retryStrategy = .none let provider = JSONPackageCollectionProvider(httpClient: httpClient) - XCTAssertThrowsError(try tsc_await { callback in provider.get(source, callback: callback) }, "expected error", { error in + XCTAssertThrowsError(try temp_await { callback in provider.get(source, callback: callback) }, "expected error", { error in guard case .invalidSource(let errorMessage) = error as? JSONPackageCollectionProviderError else { return XCTFail("invalid error \(error)") } @@ -168,7 +167,7 @@ class JSONPackageCollectionProviderTests: XCTestCase { httpClient.configuration.retryStrategy = .none let configuration = JSONPackageCollectionProvider.Configuration(maximumSizeInBytes: 10) let provider = JSONPackageCollectionProvider(configuration: configuration, httpClient: httpClient) - XCTAssertThrowsError(try tsc_await { callback in provider.get(source, callback: callback) }, "expected error", { error in + XCTAssertThrowsError(try temp_await { callback in provider.get(source, callback: callback) }, "expected error", { error in XCTAssertEqual(error as? JSONPackageCollectionProviderError, .responseTooLarge(url, maxSize * 2)) }) } @@ -197,7 +196,7 @@ class JSONPackageCollectionProviderTests: XCTestCase { httpClient.configuration.retryStrategy = .none let configuration = JSONPackageCollectionProvider.Configuration(maximumSizeInBytes: 10) let provider = JSONPackageCollectionProvider(configuration: configuration, httpClient: httpClient) - XCTAssertThrowsError(try tsc_await { callback in provider.get(source, callback: callback) }, "expected error", { error in + XCTAssertThrowsError(try temp_await { callback in provider.get(source, callback: callback) }, "expected error", { error in XCTAssertEqual(error as? JSONPackageCollectionProviderError, .responseTooLarge(url, maxSize * 2)) }) } @@ -217,7 +216,7 @@ class JSONPackageCollectionProviderTests: XCTestCase { httpClient.configuration.retryStrategy = .none let configuration = JSONPackageCollectionProvider.Configuration(maximumSizeInBytes: 10) let provider = JSONPackageCollectionProvider(configuration: configuration, httpClient: httpClient) - XCTAssertThrowsError(try tsc_await { callback in provider.get(source, callback: callback) }, "expected error", { error in + XCTAssertThrowsError(try temp_await { callback in provider.get(source, callback: callback) }, "expected error", { error in XCTAssertEqual(error as? JSONPackageCollectionProviderError, .invalidResponse(url, "Missing Content-Length header")) }) } @@ -249,7 +248,7 @@ class JSONPackageCollectionProviderTests: XCTestCase { httpClient.configuration.retryStrategy = .none let configuration = JSONPackageCollectionProvider.Configuration(maximumSizeInBytes: 10) let provider = JSONPackageCollectionProvider(configuration: configuration, httpClient: httpClient) - XCTAssertThrowsError(try tsc_await { callback in provider.get(source, callback: callback) }, "expected error", { error in + XCTAssertThrowsError(try temp_await { callback in provider.get(source, callback: callback) }, "expected error", { error in XCTAssertEqual(error as? HTTPClientError, .responseTooLarge(maxSize * 2)) }) } @@ -269,7 +268,7 @@ class JSONPackageCollectionProviderTests: XCTestCase { httpClient.configuration.circuitBreakerStrategy = .none httpClient.configuration.retryStrategy = .none let provider = JSONPackageCollectionProvider(httpClient: httpClient) - XCTAssertThrowsError(try tsc_await { callback in provider.get(source, callback: callback) }, "expected error", { error in + XCTAssertThrowsError(try temp_await { callback in provider.get(source, callback: callback) }, "expected error", { error in XCTAssertEqual(error as? JSONPackageCollectionProviderError, .collectionUnavailable(url, statusCode)) }) } @@ -295,7 +294,7 @@ class JSONPackageCollectionProviderTests: XCTestCase { httpClient.configuration.circuitBreakerStrategy = .none httpClient.configuration.retryStrategy = .none let provider = JSONPackageCollectionProvider(httpClient: httpClient) - XCTAssertThrowsError(try tsc_await { callback in provider.get(source, callback: callback) }, "expected error", { error in + XCTAssertThrowsError(try temp_await { callback in provider.get(source, callback: callback) }, "expected error", { error in XCTAssertEqual(error as? JSONPackageCollectionProviderError, .collectionUnavailable(url, statusCode)) }) } @@ -314,7 +313,7 @@ class JSONPackageCollectionProviderTests: XCTestCase { httpClient.configuration.circuitBreakerStrategy = .none httpClient.configuration.retryStrategy = .none let provider = JSONPackageCollectionProvider(httpClient: httpClient) - XCTAssertThrowsError(try tsc_await { callback in provider.get(source, callback: callback) }, "expected error", { error in + XCTAssertThrowsError(try temp_await { callback in provider.get(source, callback: callback) }, "expected error", { error in XCTAssertEqual(error as? JSONPackageCollectionProviderError, .collectionNotFound(url)) }) } @@ -339,7 +338,7 @@ class JSONPackageCollectionProviderTests: XCTestCase { httpClient.configuration.circuitBreakerStrategy = .none httpClient.configuration.retryStrategy = .none let provider = JSONPackageCollectionProvider(httpClient: httpClient) - XCTAssertThrowsError(try tsc_await { callback in provider.get(source, callback: callback) }, "expected error", { error in + XCTAssertThrowsError(try temp_await { callback in provider.get(source, callback: callback) }, "expected error", { error in XCTAssertEqual(error as? JSONPackageCollectionProviderError, .collectionNotFound(url)) }) } @@ -367,7 +366,7 @@ class JSONPackageCollectionProviderTests: XCTestCase { httpClient.configuration.retryStrategy = .none let provider = JSONPackageCollectionProvider(httpClient: httpClient) let source = PackageCollectionsModel.CollectionSource(type: .json, url: url) - XCTAssertThrowsError(try tsc_await { callback in provider.get(source, callback: callback) }, "expected error", { error in + XCTAssertThrowsError(try temp_await { callback in provider.get(source, callback: callback) }, "expected error", { error in XCTAssertEqual(error as? JSONPackageCollectionProviderError, .invalidJSON(url)) }) } @@ -403,7 +402,7 @@ class JSONPackageCollectionProviderTests: XCTestCase { let signatureValidator = MockCollectionSignatureValidator(["Sample Package Collection"]) let provider = JSONPackageCollectionProvider(httpClient: httpClient, signatureValidator: signatureValidator) let source = PackageCollectionsModel.CollectionSource(type: .json, url: url) - let collection = try tsc_await { callback in provider.get(source, callback: callback) } + let collection = try temp_await { callback in provider.get(source, callback: callback) } XCTAssertEqual(collection.name, "Sample Package Collection") XCTAssertEqual(collection.overview, "This is a sample package collection listing made-up packages.") @@ -476,7 +475,7 @@ class JSONPackageCollectionProviderTests: XCTestCase { let provider = JSONPackageCollectionProvider(httpClient: httpClient, signatureValidator: signatureValidator) // Skip signature check let source = PackageCollectionsModel.CollectionSource(type: .json, url: url, skipSignatureCheck: true) - let collection = try tsc_await { callback in provider.get(source, callback: callback) } + let collection = try temp_await { callback in provider.get(source, callback: callback) } XCTAssertEqual(collection.name, "Sample Package Collection") XCTAssertEqual(collection.overview, "This is a sample package collection listing made-up packages.") @@ -547,7 +546,7 @@ class JSONPackageCollectionProviderTests: XCTestCase { let provider = JSONPackageCollectionProvider(httpClient: httpClient, signatureValidator: signatureValidator) let source = PackageCollectionsModel.CollectionSource(type: .json, url: url) - XCTAssertThrowsError(try tsc_await { callback in provider.get(source, callback: callback) }, "expected error", { error in + XCTAssertThrowsError(try temp_await { callback in provider.get(source, callback: callback) }, "expected error", { error in switch error { case PackageCollectionError.cannotVerifySignature: break @@ -590,7 +589,7 @@ class JSONPackageCollectionProviderTests: XCTestCase { let provider = JSONPackageCollectionProvider(httpClient: httpClient, signatureValidator: signatureValidator) let source = PackageCollectionsModel.CollectionSource(type: .json, url: url) - XCTAssertThrowsError(try tsc_await { callback in provider.get(source, callback: callback) }, "expected error", { error in + XCTAssertThrowsError(try temp_await { callback in provider.get(source, callback: callback) }, "expected error", { error in switch error { case PackageCollectionError.invalidSignature: break @@ -616,7 +615,7 @@ class JSONPackageCollectionProviderTests: XCTestCase { let provider = JSONPackageCollectionProvider(httpClient: httpClient, signatureValidator: signatureValidator) let source = PackageCollectionsModel.CollectionSource(type: .json, url: path.asURL) - let collection = try tsc_await { callback in provider.get(source, callback: callback) } + let collection = try temp_await { callback in provider.get(source, callback: callback) } XCTAssertEqual(collection.name, "Sample Package Collection") XCTAssertEqual(collection.overview, "This is a sample package collection listing made-up packages.") @@ -689,7 +688,7 @@ class JSONPackageCollectionProviderTests: XCTestCase { let provider = JSONPackageCollectionProvider(httpClient: httpClient, signatureValidator: signatureValidator, sourceCertPolicy: sourceCertPolicy) let source = PackageCollectionsModel.CollectionSource(type: .json, url: url) - let collection = try tsc_await { callback in provider.get(source, callback: callback) } + let collection = try temp_await { callback in provider.get(source, callback: callback) } XCTAssertEqual(collection.name, "Sample Package Collection") XCTAssertEqual(collection.overview, "This is a sample package collection listing made-up packages.") @@ -768,7 +767,7 @@ class JSONPackageCollectionProviderTests: XCTestCase { let provider = JSONPackageCollectionProvider(httpClient: httpClient, signatureValidator: signatureValidator, sourceCertPolicy: sourceCertPolicy) let source = PackageCollectionsModel.CollectionSource(type: .json, url: url) - let collection = try tsc_await { callback in provider.get(source, callback: callback) } + let collection = try temp_await { callback in provider.get(source, callback: callback) } XCTAssertEqual(collection.name, "Sample Package Collection") XCTAssertEqual(collection.overview, "This is a sample package collection listing made-up packages.") @@ -843,7 +842,7 @@ class JSONPackageCollectionProviderTests: XCTestCase { sourceCertPolicy: sourceCertPolicy) let source = PackageCollectionsModel.CollectionSource(type: .json, url: url) - XCTAssertThrowsError(try tsc_await { callback in provider.get(source, callback: callback) }, "expected error", { error in + XCTAssertThrowsError(try temp_await { callback in provider.get(source, callback: callback) }, "expected error", { error in switch error { case PackageCollectionError.missingSignature: break diff --git a/Tests/PackageCollectionsTests/PackageCollectionsModelTests.swift b/Tests/PackageCollectionsTests/PackageCollectionsModelTests.swift index afa641cc73f..94e929034f2 100644 --- a/Tests/PackageCollectionsTests/PackageCollectionsModelTests.swift +++ b/Tests/PackageCollectionsTests/PackageCollectionsModelTests.swift @@ -10,12 +10,11 @@ // //===----------------------------------------------------------------------===// -import SPMTestSupport -import TSCBasic -import XCTest - +import Basics @testable import PackageCollections @testable import PackageModel +import SPMTestSupport +import XCTest final class PackageCollectionsModelTests: XCTestCase { func testLatestVersions() { diff --git a/Tests/PackageCollectionsTests/PackageCollectionsSourcesStorageTest.swift b/Tests/PackageCollectionsTests/PackageCollectionsSourcesStorageTest.swift index 7eb85a5cea5..c10581cddee 100644 --- a/Tests/PackageCollectionsTests/PackageCollectionsSourcesStorageTest.swift +++ b/Tests/PackageCollectionsTests/PackageCollectionsSourcesStorageTest.swift @@ -10,11 +10,13 @@ // //===----------------------------------------------------------------------===// +import Basics @testable import PackageCollections -import TSCBasic -import TSCTestSupport +import SPMTestSupport import XCTest +import class TSCBasic.InMemoryFileSystem + final class PackageCollectionsSourcesStorageTest: XCTestCase { func testHappyCase() throws { let mockFileSystem = InMemoryFileSystem() @@ -45,58 +47,58 @@ final class PackageCollectionsSourcesStorageTest: XCTestCase { let sources = makeMockSources() try sources.forEach { source in - _ = try tsc_await { callback in storage.add(source: source, order: nil, callback: callback) } + _ = try temp_await { callback in storage.add(source: source, order: nil, callback: callback) } } do { - let list = try tsc_await { callback in storage.list(callback: callback) } + let list = try temp_await { callback in storage.list(callback: callback) } XCTAssertEqual(list.count, sources.count, "sources should match") } let remove = sources.enumerated().filter { index, _ in index % 2 == 0 }.map { $1 } try remove.forEach { source in - _ = try tsc_await { callback in storage.remove(source: source, callback: callback) } + _ = try temp_await { callback in storage.remove(source: source, callback: callback) } } do { - let list = try tsc_await { callback in storage.list(callback: callback) } + let list = try temp_await { callback in storage.list(callback: callback) } XCTAssertEqual(list.count, sources.count - remove.count, "sources should match") } let remaining = sources.filter { !remove.contains($0) } try sources.forEach { source in - XCTAssertEqual(try tsc_await { callback in storage.exists(source: source, callback: callback) }, remaining.contains(source)) + XCTAssertEqual(try temp_await { callback in storage.exists(source: source, callback: callback) }, remaining.contains(source)) } do { - _ = try tsc_await { callback in storage.move(source: remaining.last!, to: 0, callback: callback) } - let list = try tsc_await { callback in storage.list(callback: callback) } + _ = try temp_await { callback in storage.move(source: remaining.last!, to: 0, callback: callback) } + let list = try temp_await { callback in storage.list(callback: callback) } XCTAssertEqual(list.count, remaining.count, "sources should match") XCTAssertEqual(list.first, remaining.last, "item should match") } do { - _ = try tsc_await { callback in storage.move(source: remaining.last!, to: remaining.count - 1, callback: callback) } - let list = try tsc_await { callback in storage.list(callback: callback) } + _ = try temp_await { callback in storage.move(source: remaining.last!, to: remaining.count - 1, callback: callback) } + let list = try temp_await { callback in storage.list(callback: callback) } XCTAssertEqual(list.count, remaining.count, "sources should match") XCTAssertEqual(list.last, remaining.last, "item should match") } do { - let list = try tsc_await { callback in storage.list(callback: callback) } + let list = try temp_await { callback in storage.list(callback: callback) } var source = list.first! source.isTrusted = !(source.isTrusted ?? false) - _ = try tsc_await { callback in storage.update(source: source, callback: callback) } - let listAfter = try tsc_await { callback in storage.list(callback: callback) } + _ = try temp_await { callback in storage.update(source: source, callback: callback) } + let listAfter = try temp_await { callback in storage.list(callback: callback) } XCTAssertEqual(source.isTrusted, listAfter.first!.isTrusted, "isTrusted should match") } do { - let list = try tsc_await { callback in storage.list(callback: callback) } + let list = try temp_await { callback in storage.list(callback: callback) } var source = list.first! source.skipSignatureCheck = !source.skipSignatureCheck - _ = try tsc_await { callback in storage.update(source: source, callback: callback) } - let listAfter = try tsc_await { callback in storage.list(callback: callback) } + _ = try temp_await { callback in storage.update(source: source, callback: callback) } + let listAfter = try temp_await { callback in storage.list(callback: callback) } XCTAssertEqual(source.skipSignatureCheck, listAfter.first!.skipSignatureCheck, "skipSignatureCheck should match") } } @@ -108,11 +110,11 @@ final class PackageCollectionsSourcesStorageTest: XCTestCase { let sources = makeMockSources() try sources.forEach { source in - _ = try tsc_await { callback in storage.add(source: source, order: nil, callback: callback) } + _ = try temp_await { callback in storage.add(source: source, order: nil, callback: callback) } } do { - let list = try tsc_await { callback in storage.list(callback: callback) } + let list = try temp_await { callback in storage.list(callback: callback) } XCTAssertEqual(list.count, sources.count, "collections should match") } @@ -120,7 +122,7 @@ final class PackageCollectionsSourcesStorageTest: XCTestCase { XCTAssertFalse(mockFileSystem.exists(storage.path), "expected file to be deleted") do { - let list = try tsc_await { callback in storage.list(callback: callback) } + let list = try temp_await { callback in storage.list(callback: callback) } XCTAssertEqual(list.count, 0, "collections should match") } } @@ -132,11 +134,11 @@ final class PackageCollectionsSourcesStorageTest: XCTestCase { let sources = makeMockSources() try sources.forEach { source in - _ = try tsc_await { callback in storage.add(source: source, order: nil, callback: callback) } + _ = try temp_await { callback in storage.add(source: source, order: nil, callback: callback) } } do { - let list = try tsc_await { callback in storage.list(callback: callback) } + let list = try temp_await { callback in storage.list(callback: callback) } XCTAssertEqual(list.count, sources.count, "collections should match") } @@ -145,7 +147,7 @@ final class PackageCollectionsSourcesStorageTest: XCTestCase { XCTAssertEqual(buffer.count, 0, "expected file to be empty") do { - let list = try tsc_await { callback in storage.list(callback: callback) } + let list = try temp_await { callback in storage.list(callback: callback) } XCTAssertEqual(list.count, 0, "collections should match") } } @@ -157,10 +159,10 @@ final class PackageCollectionsSourcesStorageTest: XCTestCase { let sources = makeMockSources() try sources.forEach { source in - _ = try tsc_await { callback in storage.add(source: source, order: nil, callback: callback) } + _ = try temp_await { callback in storage.add(source: source, order: nil, callback: callback) } } - let list = try tsc_await { callback in storage.list(callback: callback) } + let list = try temp_await { callback in storage.list(callback: callback) } XCTAssertEqual(list.count, sources.count, "collections should match") try mockFileSystem.writeFileContents(storage.path, string: "{") @@ -169,7 +171,7 @@ final class PackageCollectionsSourcesStorageTest: XCTestCase { XCTAssertNotEqual(buffer.count, 0, "expected file to be written") print(buffer) - XCTAssertThrowsError(try tsc_await { callback in storage.list(callback: callback) }, "expected an error", { error in + XCTAssertThrowsError(try temp_await { callback in storage.list(callback: callback) }, "expected an error", { error in XCTAssert(error is DecodingError, "expected error to match") }) } diff --git a/Tests/PackageCollectionsTests/PackageCollectionsStorageTests.swift b/Tests/PackageCollectionsTests/PackageCollectionsStorageTests.swift index 4b9cc8f9919..2dc15570b1c 100644 --- a/Tests/PackageCollectionsTests/PackageCollectionsStorageTests.swift +++ b/Tests/PackageCollectionsTests/PackageCollectionsStorageTests.swift @@ -12,8 +12,7 @@ import Basics @testable import PackageCollections -import TSCBasic -import TSCTestSupport +import SPMTestSupport import tsan_utils import XCTest @@ -26,39 +25,39 @@ class PackageCollectionsStorageTests: XCTestCase { let mockSources = makeMockSources() try mockSources.forEach { source in - XCTAssertThrowsError(try tsc_await { callback in storage.get(identifier: .init(from: source), callback: callback) }, "expected error", { error in + XCTAssertThrowsError(try temp_await { callback in storage.get(identifier: .init(from: source), callback: callback) }, "expected error", { error in XCTAssert(error is NotFoundError, "Expected NotFoundError") }) } let mockCollections = makeMockCollections(count: 50) try mockCollections.forEach { collection in - _ = try tsc_await { callback in storage.put(collection: collection, callback: callback) } + _ = try temp_await { callback in storage.put(collection: collection, callback: callback) } } try mockCollections.forEach { collection in - let retVal = try tsc_await { callback in storage.get(identifier: collection.identifier, callback: callback) } + let retVal = try temp_await { callback in storage.get(identifier: collection.identifier, callback: callback) } XCTAssertEqual(retVal.identifier, collection.identifier) } do { - let list = try tsc_await { callback in storage.list(callback: callback) } + let list = try temp_await { callback in storage.list(callback: callback) } XCTAssertEqual(list.count, mockCollections.count) } do { let count = Int.random(in: 1 ..< mockCollections.count) - let list = try tsc_await { callback in storage.list(identifiers: mockCollections.prefix(count).map { $0.identifier }, callback: callback) } + let list = try temp_await { callback in storage.list(identifiers: mockCollections.prefix(count).map { $0.identifier }, callback: callback) } XCTAssertEqual(list.count, count) } do { - _ = try tsc_await { callback in storage.remove(identifier: mockCollections.first!.identifier, callback: callback) } - let list = try tsc_await { callback in storage.list(callback: callback) } + _ = try temp_await { callback in storage.remove(identifier: mockCollections.first!.identifier, callback: callback) } + let list = try temp_await { callback in storage.list(callback: callback) } XCTAssertEqual(list.count, mockCollections.count - 1) } - XCTAssertThrowsError(try tsc_await { callback in storage.get(identifier: mockCollections.first!.identifier, callback: callback) }, "expected error", { error in + XCTAssertThrowsError(try temp_await { callback in storage.get(identifier: mockCollections.first!.identifier, callback: callback) }, "expected error", { error in XCTAssert(error is NotFoundError, "Expected NotFoundError") }) @@ -83,11 +82,11 @@ class PackageCollectionsStorageTests: XCTestCase { let mockCollections = makeMockCollections(count: 3) try mockCollections.forEach { collection in - _ = try tsc_await { callback in storage.put(collection: collection, callback: callback) } + _ = try temp_await { callback in storage.put(collection: collection, callback: callback) } } try mockCollections.forEach { collection in - let retVal = try tsc_await { callback in storage.get(identifier: collection.identifier, callback: callback) } + let retVal = try temp_await { callback in storage.get(identifier: collection.identifier, callback: callback) } XCTAssertEqual(retVal.identifier, collection.identifier) } @@ -100,12 +99,12 @@ class PackageCollectionsStorageTests: XCTestCase { try storage.fileSystem.removeFileTree(storagePath) storage.resetCache() - XCTAssertThrowsError(try tsc_await { callback in storage.get(identifier: mockCollections.first!.identifier, callback: callback) }, "expected error", { error in + XCTAssertThrowsError(try temp_await { callback in storage.get(identifier: mockCollections.first!.identifier, callback: callback) }, "expected error", { error in XCTAssert(error is NotFoundError, "Expected NotFoundError") }) - XCTAssertNoThrow(try tsc_await { callback in storage.put(collection: mockCollections.first!, callback: callback) }) - let retVal = try tsc_await { callback in storage.get(identifier: mockCollections.first!.identifier, callback: callback) } + XCTAssertNoThrow(try temp_await { callback in storage.put(collection: mockCollections.first!, callback: callback) }) + let retVal = try temp_await { callback in storage.get(identifier: mockCollections.first!.identifier, callback: callback) } XCTAssertEqual(retVal.identifier, mockCollections.first!.identifier) XCTAssertTrue(storage.fileSystem.exists(storagePath), "expected file to exist at \(storagePath)") @@ -125,11 +124,11 @@ class PackageCollectionsStorageTests: XCTestCase { let mockCollections = makeMockCollections(count: 3) try mockCollections.forEach { collection in - _ = try tsc_await { callback in storage.put(collection: collection, callback: callback) } + _ = try temp_await { callback in storage.put(collection: collection, callback: callback) } } try mockCollections.forEach { collection in - let retVal = try tsc_await { callback in storage.get(identifier: collection.identifier, callback: callback) } + let retVal = try temp_await { callback in storage.get(identifier: collection.identifier, callback: callback) } XCTAssertEqual(retVal.identifier, collection.identifier) } @@ -144,11 +143,11 @@ class PackageCollectionsStorageTests: XCTestCase { let storage2 = SQLitePackageCollectionsStorage(path: path) defer { XCTAssertNoThrow(try storage2.close()) } - XCTAssertThrowsError(try tsc_await { callback in storage2.get(identifier: mockCollections.first!.identifier, callback: callback) }, "expected error", { error in + XCTAssertThrowsError(try temp_await { callback in storage2.get(identifier: mockCollections.first!.identifier, callback: callback) }, "expected error", { error in XCTAssert("\(error)".contains("is not a database"), "Expected file is not a database error") }) - XCTAssertThrowsError(try tsc_await { callback in storage2.put(collection: mockCollections.first!, callback: callback) }, "expected error", { error in + XCTAssertThrowsError(try temp_await { callback in storage2.put(collection: mockCollections.first!, callback: callback) }, "expected error", { error in XCTAssert("\(error)".contains("is not a database"), "Expected file is not a database error") }) } @@ -163,10 +162,10 @@ class PackageCollectionsStorageTests: XCTestCase { let count = configuration.batchSize / 2 let mockCollections = makeMockCollections(count: count) try mockCollections.forEach { collection in - _ = try tsc_await { callback in storage.put(collection: collection, callback: callback) } + _ = try temp_await { callback in storage.put(collection: collection, callback: callback) } } - let list = try tsc_await { callback in storage.list(callback: callback) } + let list = try temp_await { callback in storage.list(callback: callback) } XCTAssertEqual(list.count, mockCollections.count) } @@ -179,10 +178,10 @@ class PackageCollectionsStorageTests: XCTestCase { let count = Int(Double(configuration.batchSize) * 2.5) let mockCollections = makeMockCollections(count: count) try mockCollections.forEach { collection in - _ = try tsc_await { callback in storage.put(collection: collection, callback: callback) } + _ = try temp_await { callback in storage.put(collection: collection, callback: callback) } } - let list = try tsc_await { callback in storage.list(callback: callback) } + let list = try temp_await { callback in storage.list(callback: callback) } XCTAssertEqual(list.count, mockCollections.count) } @@ -195,10 +194,10 @@ class PackageCollectionsStorageTests: XCTestCase { let count = Int(Double(configuration.batchSize) * 2.5) let mockCollections = makeMockCollections(count: count) try mockCollections.forEach { collection in - _ = try tsc_await { callback in storage.put(collection: collection, callback: callback) } + _ = try temp_await { callback in storage.put(collection: collection, callback: callback) } } - let list = try tsc_await { callback in storage.list(identifiers: mockCollections.map { $0.identifier }, callback: callback) } + let list = try temp_await { callback in storage.list(identifiers: mockCollections.map { $0.identifier }, callback: callback) } XCTAssertEqual(list.count, mockCollections.count) } @@ -208,13 +207,13 @@ class PackageCollectionsStorageTests: XCTestCase { let mockCollections = makeMockCollections(count: 3) try mockCollections.forEach { collection in - _ = try tsc_await { callback in storage.put(collection: collection, callback: callback) } + _ = try temp_await { callback in storage.put(collection: collection, callback: callback) } } - let list = try tsc_await { callback in storage.list(identifiers: mockCollections.map { $0.identifier }, callback: callback) } + let list = try temp_await { callback in storage.list(identifiers: mockCollections.map { $0.identifier }, callback: callback) } XCTAssertEqual(list.count, mockCollections.count) - _ = try tsc_await { callback in storage.put(collection: mockCollections.last!, callback: callback) } + _ = try temp_await { callback in storage.put(collection: mockCollections.last!, callback: callback) } XCTAssertEqual(list.count, mockCollections.count) } @@ -226,14 +225,14 @@ class PackageCollectionsStorageTests: XCTestCase { let mockCollections = makeMockCollections(count: 3) try mockCollections.forEach { collection in - _ = try tsc_await { callback in storage.put(collection: collection, callback: callback) } + _ = try temp_await { callback in storage.put(collection: collection, callback: callback) } } let version = mockCollections.last!.packages.last!.versions.last! let targetName = version.defaultManifest!.targets.last!.name do { - let searchResult = try tsc_await { callback in storage.searchTargets(query: targetName, type: .exactMatch, callback: callback) } + let searchResult = try temp_await { callback in storage.searchTargets(query: targetName, type: .exactMatch, callback: callback) } XCTAssert(searchResult.items.count > 0, "should get results") } @@ -244,9 +243,9 @@ class PackageCollectionsStorageTests: XCTestCase { // populateTargetTrie is called in `.init`; call it again explicitly so we know when it's finished do { - try tsc_await { callback in storage2.populateTargetTrie(callback: callback) } + try temp_await { callback in storage2.populateTargetTrie(callback: callback) } - let searchResult = try tsc_await { callback in storage2.searchTargets(query: targetName, type: .exactMatch, callback: callback) } + let searchResult = try temp_await { callback in storage2.searchTargets(query: targetName, type: .exactMatch, callback: callback) } XCTAssert(searchResult.items.count > 0, "should get results") } catch { // It's possible that some platforms don't have support FTS diff --git a/Tests/PackageCollectionsTests/PackageCollectionsTests.swift b/Tests/PackageCollectionsTests/PackageCollectionsTests.swift index 02362970553..64657b591de 100644 --- a/Tests/PackageCollectionsTests/PackageCollectionsTests.swift +++ b/Tests/PackageCollectionsTests/PackageCollectionsTests.swift @@ -17,7 +17,6 @@ import Basics @testable import PackageCollections import PackageModel import SourceControl -import TSCBasic import struct TSCUtility.Version @@ -70,16 +69,16 @@ final class PackageCollectionsTests: XCTestCase { let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider) do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") } try mockCollections.forEach { collection in - _ = try tsc_await { callback in packageCollections.addCollection(collection.source, order: nil, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(collection.source, order: nil, callback: callback) } } do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list, mockCollections, "list count should match") } } @@ -98,16 +97,16 @@ final class PackageCollectionsTests: XCTestCase { let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider) do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") } - _ = try tsc_await { callback in packageCollections.addCollection(mockCollection.source, order: nil, callback: callback) } - _ = try tsc_await { callback in packageCollections.addCollection(mockCollection.source, order: nil, callback: callback) } - _ = try tsc_await { callback in packageCollections.addCollection(mockCollection.source, order: nil, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(mockCollection.source, order: nil, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(mockCollection.source, order: nil, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(mockCollection.source, order: nil, callback: callback) } do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 1, "list count should match") } } @@ -126,15 +125,15 @@ final class PackageCollectionsTests: XCTestCase { let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider) do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") } // User trusted - _ = try tsc_await { callback in packageCollections.addCollection(mockCollections[0].source, order: nil, trustConfirmationProvider: { _, cb in cb(true) }, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(mockCollections[0].source, order: nil, trustConfirmationProvider: { _, cb in cb(true) }, callback: callback) } // User untrusted XCTAssertThrowsError( - try tsc_await { callback in + try temp_await { callback in packageCollections.addCollection(mockCollections[1].source, order: nil, trustConfirmationProvider: { _, cb in cb(false) }, callback: callback) }) { error in guard case PackageCollectionError.untrusted = error else { @@ -143,14 +142,14 @@ final class PackageCollectionsTests: XCTestCase { } // User preference unknown XCTAssertThrowsError( - try tsc_await { callback in packageCollections.addCollection(mockCollections[2].source, order: nil, trustConfirmationProvider: nil, callback: callback) }) { error in + try temp_await { callback in packageCollections.addCollection(mockCollections[2].source, order: nil, trustConfirmationProvider: nil, callback: callback) }) { error in guard case PackageCollectionError.trustConfirmationRequired = error else { return XCTFail("Expected PackageCollectionError.trustConfirmationRequired") } } do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 1, "list count should match") } } @@ -171,24 +170,24 @@ final class PackageCollectionsTests: XCTestCase { let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider) do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") - let sources = try tsc_await { callback in storage.sources.list(callback: callback) } + let sources = try temp_await { callback in storage.sources.list(callback: callback) } XCTAssertEqual(sources.count, 0, "sources should be empty") } // add fails because collection is not found - guard case .failure(let error) = tsc_await({ callback in packageCollections.addCollection(mockCollection.source, order: nil, callback: callback) }), + guard case .failure(let error) = temp_await({ callback in packageCollections.addCollection(mockCollection.source, order: nil, callback: callback) }), error is NotFoundError else { return XCTFail("expected error") } do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list count should match") - let sources = try tsc_await { callback in storage.sources.list(callback: callback) } + let sources = try temp_await { callback in storage.sources.list(callback: callback) } XCTAssertEqual(sources.count, 0, "sources should be empty") } } @@ -209,24 +208,24 @@ final class PackageCollectionsTests: XCTestCase { let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider) do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") - let sources = try tsc_await { callback in storage.sources.list(callback: callback) } + let sources = try temp_await { callback in storage.sources.list(callback: callback) } XCTAssertEqual(sources.count, 0, "sources should be empty") } // add fails because collection requires trust confirmation - guard case .failure(let error) = tsc_await({ callback in packageCollections.addCollection(mockCollection.source, order: nil, callback: callback) }), + guard case .failure(let error) = temp_await({ callback in packageCollections.addCollection(mockCollection.source, order: nil, callback: callback) }), case PackageCollectionError.trustConfirmationRequired = error else { return XCTFail("expected error") } do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list count should match") - let sources = try tsc_await { callback in storage.sources.list(callback: callback) } + let sources = try temp_await { callback in storage.sources.list(callback: callback) } XCTAssertEqual(sources.count, 1, "sources should match") } } @@ -247,24 +246,24 @@ final class PackageCollectionsTests: XCTestCase { let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider) do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") - let sources = try tsc_await { callback in storage.sources.list(callback: callback) } + let sources = try temp_await { callback in storage.sources.list(callback: callback) } XCTAssertEqual(sources.count, 0, "sources should be empty") } // add fails because collection's signature is invalid - guard case .failure(let error) = tsc_await({ callback in packageCollections.addCollection(mockCollection.source, order: nil, callback: callback) }), + guard case .failure(let error) = temp_await({ callback in packageCollections.addCollection(mockCollection.source, order: nil, callback: callback) }), case PackageCollectionError.invalidSignature = error else { return XCTFail("expected PackageCollectionError.invalidSignature") } do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list count should match") - let sources = try tsc_await { callback in storage.sources.list(callback: callback) } + let sources = try temp_await { callback in storage.sources.list(callback: callback) } XCTAssertEqual(sources.count, 0, "sources should be empty") } } @@ -282,40 +281,40 @@ final class PackageCollectionsTests: XCTestCase { let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider) do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") } do { try mockCollections.forEach { collection in - _ = try tsc_await { callback in packageCollections.addCollection(collection.source, order: nil, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(collection.source, order: nil, callback: callback) } } - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list, mockCollections, "list count should match") } do { - _ = try tsc_await { callback in packageCollections.removeCollection(mockCollections.first!.source, callback: callback) } - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + _ = try temp_await { callback in packageCollections.removeCollection(mockCollections.first!.source, callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, mockCollections.count - 1, "list count should match") } do { - _ = try tsc_await { callback in packageCollections.removeCollection(mockCollections.first!.source, callback: callback) } - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + _ = try temp_await { callback in packageCollections.removeCollection(mockCollections.first!.source, callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, mockCollections.count - 1, "list count should match") } do { - _ = try tsc_await { callback in packageCollections.removeCollection(mockCollections[mockCollections.count - 1].source, callback: callback) } - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + _ = try temp_await { callback in packageCollections.removeCollection(mockCollections[mockCollections.count - 1].source, callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, mockCollections.count - 2, "list count should match") } do { let unknownSource = makeMockSources(count: 1).first! - _ = try tsc_await { callback in packageCollections.removeCollection(unknownSource, callback: callback) } - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + _ = try temp_await { callback in packageCollections.removeCollection(unknownSource, callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, mockCollections.count - 2, "list should be empty") } } @@ -334,24 +333,24 @@ final class PackageCollectionsTests: XCTestCase { let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider) do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") } - _ = try tsc_await { callback in packageCollections.addCollection(mockCollection.source, order: nil, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(mockCollection.source, order: nil, callback: callback) } do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 1, "list count should match") } do { - _ = try tsc_await { callback in packageCollections.removeCollection(mockCollection.source, callback: callback) } - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + _ = try temp_await { callback in packageCollections.removeCollection(mockCollection.source, callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list count should match") // check if exists in storage - XCTAssertThrowsError(try tsc_await { callback in storage.collections.get(identifier: mockCollection.identifier, callback: callback) }, "expected error") + XCTAssertThrowsError(try temp_await { callback in storage.collections.get(identifier: mockCollection.identifier, callback: callback) }, "expected error") } } @@ -368,18 +367,18 @@ final class PackageCollectionsTests: XCTestCase { let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider) do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") } do { - _ = try tsc_await { callback in packageCollections.addCollection(mockCollections[0].source, order: 0, callback: callback) } - _ = try tsc_await { callback in packageCollections.addCollection(mockCollections[1].source, order: 1, callback: callback) } - _ = try tsc_await { callback in packageCollections.addCollection(mockCollections[2].source, order: 2, callback: callback) } - _ = try tsc_await { callback in packageCollections.addCollection(mockCollections[3].source, order: Int.min, callback: callback) } - _ = try tsc_await { callback in packageCollections.addCollection(mockCollections[4].source, order: Int.max, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(mockCollections[0].source, order: 0, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(mockCollections[1].source, order: 1, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(mockCollections[2].source, order: 2, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(mockCollections[3].source, order: Int.min, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(mockCollections[4].source, order: Int.max, callback: callback) } - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 5, "list count should match") let expectedOrder = [ @@ -399,12 +398,12 @@ final class PackageCollectionsTests: XCTestCase { // bump the order do { - _ = try tsc_await { callback in packageCollections.addCollection(mockCollections[5].source, order: 2, callback: callback) } - _ = try tsc_await { callback in packageCollections.addCollection(mockCollections[6].source, order: 2, callback: callback) } - _ = try tsc_await { callback in packageCollections.addCollection(mockCollections[7].source, order: 0, callback: callback) } - _ = try tsc_await { callback in packageCollections.addCollection(mockCollections[8].source, order: -1, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(mockCollections[5].source, order: 2, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(mockCollections[6].source, order: 2, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(mockCollections[7].source, order: 0, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(mockCollections[8].source, order: -1, callback: callback) } - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 9, "list count should match") let expectedOrder = [ @@ -439,16 +438,16 @@ final class PackageCollectionsTests: XCTestCase { let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider) do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") } do { - _ = try tsc_await { callback in packageCollections.addCollection(mockCollections[0].source, order: 0, callback: callback) } - _ = try tsc_await { callback in packageCollections.addCollection(mockCollections[1].source, order: 1, callback: callback) } - _ = try tsc_await { callback in packageCollections.addCollection(mockCollections[2].source, order: 2, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(mockCollections[0].source, order: 0, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(mockCollections[1].source, order: 1, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(mockCollections[2].source, order: 2, callback: callback) } - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 3, "list count should match") let expectedOrder = [ @@ -464,8 +463,8 @@ final class PackageCollectionsTests: XCTestCase { } do { - _ = try tsc_await { callback in packageCollections.moveCollection(mockCollections[2].source, to: -1, callback: callback) } - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + _ = try temp_await { callback in packageCollections.moveCollection(mockCollections[2].source, to: -1, callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } let expectedOrder = [ mockCollections[0].identifier: 0, @@ -480,8 +479,8 @@ final class PackageCollectionsTests: XCTestCase { } do { - _ = try tsc_await { callback in packageCollections.moveCollection(mockCollections[2].source, to: Int.max, callback: callback) } - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + _ = try temp_await { callback in packageCollections.moveCollection(mockCollections[2].source, to: Int.max, callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } let expectedOrder = [ mockCollections[0].identifier: 0, @@ -496,8 +495,8 @@ final class PackageCollectionsTests: XCTestCase { } do { - _ = try tsc_await { callback in packageCollections.moveCollection(mockCollections[2].source, to: 0, callback: callback) } - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + _ = try temp_await { callback in packageCollections.moveCollection(mockCollections[2].source, to: 0, callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } let expectedOrder = [ mockCollections[0].identifier: 1, @@ -512,8 +511,8 @@ final class PackageCollectionsTests: XCTestCase { } do { - _ = try tsc_await { callback in packageCollections.moveCollection(mockCollections[2].source, to: 1, callback: callback) } - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + _ = try temp_await { callback in packageCollections.moveCollection(mockCollections[2].source, to: 1, callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } let expectedOrder = [ mockCollections[0].identifier: 0, @@ -542,15 +541,15 @@ final class PackageCollectionsTests: XCTestCase { let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider) do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") } // User preference unknown - collection not saved to storage - _ = try? tsc_await { callback in packageCollections.addCollection(mockCollections.first!.source, order: nil, trustConfirmationProvider: nil, callback: callback) } + _ = try? temp_await { callback in packageCollections.addCollection(mockCollections.first!.source, order: nil, trustConfirmationProvider: nil, callback: callback) } do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") } @@ -558,23 +557,23 @@ final class PackageCollectionsTests: XCTestCase { // Update to trust the source. It will trigger a collection refresh which will save collection to storage. source.isTrusted = true - _ = try tsc_await { callback in packageCollections.updateCollection(source, callback: callback) } + _ = try temp_await { callback in packageCollections.updateCollection(source, callback: callback) } do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 1, "list count should match") } // Update to untrust the source. It will trigger a collection refresh which will remove collection from storage. source.isTrusted = false - XCTAssertThrowsError(try tsc_await { callback in packageCollections.updateCollection(source, callback: callback) }) { error in + XCTAssertThrowsError(try temp_await { callback in packageCollections.updateCollection(source, callback: callback) }) { error in guard case PackageCollectionError.untrusted = error else { return XCTFail("Expected PackageCollectionError.untrusted") } } do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") } } @@ -594,10 +593,10 @@ final class PackageCollectionsTests: XCTestCase { let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider) try mockCollections.forEach { collection in - _ = try tsc_await { callback in packageCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) }, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) }, callback: callback) } } - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, mockCollections.count, "list count should match") } @@ -616,11 +615,11 @@ final class PackageCollectionsTests: XCTestCase { let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider) try mockCollections.forEach { collection in - _ = try tsc_await { callback in packageCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) }, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) }, callback: callback) } } let expectedCollections = Set([mockCollections.first!.identifier, mockCollections.last!.identifier]) - let list = try tsc_await { callback in packageCollections.listCollections(identifiers: expectedCollections, callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(identifiers: expectedCollections, callback: callback) } XCTAssertEqual(list.count, expectedCollections.count, "list count should match") } @@ -653,7 +652,7 @@ final class PackageCollectionsTests: XCTestCase { sync.wait() let start = Date() - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, mockCollections.count, "list count should match") let delta = Date().timeIntervalSince(start) XCTAssert(delta < 1.0, "should list quickly, took \(delta)") @@ -734,61 +733,61 @@ final class PackageCollectionsTests: XCTestCase { let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider) try mockCollections.forEach { collection in - _ = try tsc_await { callback in packageCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) }, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) }, callback: callback) } } do { // search by package name - let searchResult = try tsc_await { callback in packageCollections.findPackages(mockManifest.packageName, callback: callback) } + let searchResult = try temp_await { callback in packageCollections.findPackages(mockManifest.packageName, callback: callback) } XCTAssertEqual(searchResult.items.count, 1, "list count should match") XCTAssertEqual(searchResult.items.first?.collections.sorted(), expectedCollectionsIdentifiers, "list count should match") } do { // search by package description/summary - let searchResult = try tsc_await { callback in packageCollections.findPackages(mockPackage.summary!, callback: callback) } + let searchResult = try temp_await { callback in packageCollections.findPackages(mockPackage.summary!, callback: callback) } XCTAssertEqual(searchResult.items.count, 1, "list count should match") XCTAssertEqual(searchResult.items.first?.collections.sorted(), expectedCollectionsIdentifiers, "list count should match") } do { // search by package keywords - let searchResult = try tsc_await { callback in packageCollections.findPackages(mockPackage.keywords!.first!, callback: callback) } + let searchResult = try temp_await { callback in packageCollections.findPackages(mockPackage.keywords!.first!, callback: callback) } XCTAssertEqual(searchResult.items.count, 1, "list count should match") XCTAssertEqual(searchResult.items.first?.collections.sorted(), expectedCollectionsIdentifiers, "list count should match") } do { // search by package repository url - let searchResult = try tsc_await { callback in packageCollections.findPackages(mockPackage.location, callback: callback) } + let searchResult = try temp_await { callback in packageCollections.findPackages(mockPackage.location, callback: callback) } XCTAssertEqual(searchResult.items.count, 1, "list count should match") XCTAssertEqual(searchResult.items.first?.collections.sorted(), expectedCollectionsIdentifiers, "collections should match") } do { // search by package identity - let searchResult = try tsc_await { callback in packageCollections.findPackages(mockPackage.identity.description, callback: callback) } + let searchResult = try temp_await { callback in packageCollections.findPackages(mockPackage.identity.description, callback: callback) } XCTAssertEqual(searchResult.items.count, 1, "list count should match") XCTAssertEqual(searchResult.items.first?.collections.sorted(), expectedCollectionsIdentifiers, "collections should match") } do { // search by product name - let searchResult = try tsc_await { callback in packageCollections.findPackages(mockProducts.first!.name, callback: callback) } + let searchResult = try temp_await { callback in packageCollections.findPackages(mockProducts.first!.name, callback: callback) } XCTAssertEqual(searchResult.items.count, 1, "list count should match") XCTAssertEqual(searchResult.items.first?.collections.sorted(), expectedCollectionsIdentifiers, "list count should match") } do { // search by target name - let searchResult = try tsc_await { callback in packageCollections.findPackages(mockTargets.first!.name, callback: callback) } + let searchResult = try temp_await { callback in packageCollections.findPackages(mockTargets.first!.name, callback: callback) } XCTAssertEqual(searchResult.items.count, 1, "list count should match") XCTAssertEqual(searchResult.items.first?.collections.sorted(), expectedCollectionsIdentifiers, "collections should match") } do { // empty search - let searchResult = try tsc_await { callback in packageCollections.findPackages(UUID().uuidString, callback: callback) } + let searchResult = try temp_await { callback in packageCollections.findPackages(UUID().uuidString, callback: callback) } XCTAssertEqual(searchResult.items.count, 0, "list count should match") } } @@ -822,7 +821,7 @@ final class PackageCollectionsTests: XCTestCase { // search by package name let start = Date() let repoName = mockCollections.last!.packages.last!.identity.description - let searchResult = try tsc_await { callback in packageCollections.findPackages(repoName, callback: callback) } + let searchResult = try temp_await { callback in packageCollections.findPackages(repoName, callback: callback) } XCTAssert(searchResult.items.count > 0, "should get results") let delta = Date().timeIntervalSince(start) XCTAssert(delta < 1.0, "should search quickly, took \(delta)") @@ -903,12 +902,12 @@ final class PackageCollectionsTests: XCTestCase { let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider) try mockCollections.forEach { collection in - _ = try tsc_await { callback in packageCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) }, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) }, callback: callback) } } do { // search by exact target name - let searchResult = try tsc_await { callback in packageCollections.findTargets(mockTargets.first!.name, searchType: .exactMatch, callback: callback) } + let searchResult = try temp_await { callback in packageCollections.findTargets(mockTargets.first!.name, searchType: .exactMatch, callback: callback) } XCTAssertEqual(searchResult.items.count, 1, "list count should match") XCTAssertEqual(searchResult.items.first?.packages.map { $0.identity }, [mockPackage.identity], "packages should match") XCTAssertEqual(searchResult.items.first?.packages.flatMap { $0.collections }.sorted(), expectedCollectionsIdentifiers, "collections should match") @@ -916,7 +915,7 @@ final class PackageCollectionsTests: XCTestCase { do { // search by prefix target name - let searchResult = try tsc_await { callback in packageCollections.findTargets(String(mockTargets.first!.name.prefix(mockTargets.first!.name.count - 1)), searchType: .prefix, callback: callback) } + let searchResult = try temp_await { callback in packageCollections.findTargets(String(mockTargets.first!.name.prefix(mockTargets.first!.name.count - 1)), searchType: .prefix, callback: callback) } XCTAssertEqual(searchResult.items.count, 1, "list count should match") XCTAssertEqual(searchResult.items.first?.packages.map { $0.identity }, [mockPackage.identity], "packages should match") XCTAssertEqual(searchResult.items.first?.packages.flatMap { $0.collections }.sorted(), expectedCollectionsIdentifiers, "collections should match") @@ -924,7 +923,7 @@ final class PackageCollectionsTests: XCTestCase { do { // empty search - let searchResult = try tsc_await { callback in packageCollections.findTargets(UUID().uuidString, searchType: .exactMatch, callback: callback) } + let searchResult = try temp_await { callback in packageCollections.findTargets(UUID().uuidString, searchType: .exactMatch, callback: callback) } XCTAssertEqual(searchResult.items.count, 0, "list count should match") } } @@ -958,7 +957,7 @@ final class PackageCollectionsTests: XCTestCase { // search by target name let start = Date() let targetName = mockCollections.last!.packages.last!.versions.last!.defaultManifest!.targets.last!.name - let searchResult = try tsc_await { callback in packageCollections.findTargets(targetName, searchType: .exactMatch, callback: callback) } + let searchResult = try temp_await { callback in packageCollections.findTargets(targetName, searchType: .exactMatch, callback: callback) } XCTAssert(searchResult.items.count > 0, "should get results") let delta = Date().timeIntervalSince(start) XCTAssert(delta < 1.0, "should search quickly, took \(delta)") @@ -978,11 +977,11 @@ final class PackageCollectionsTests: XCTestCase { try mockCollections.forEach { collection in // save directly to storage to circumvent refresh on add - _ = try tsc_await { callback in storage.sources.add(source: collection.source, order: nil, callback: callback) } + _ = try temp_await { callback in storage.sources.add(source: collection.source, order: nil, callback: callback) } } - _ = try tsc_await { callback in packageCollections.refreshCollections(callback: callback) } + _ = try temp_await { callback in packageCollections.refreshCollections(callback: callback) } - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, mockCollections.count, "list count should match") } @@ -1031,20 +1030,20 @@ final class PackageCollectionsTests: XCTestCase { let metadataProvider = MockMetadataProvider([:]) let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider) - XCTAssertThrowsError(try tsc_await { callback in packageCollections.addCollection(brokenSources.first!, order: nil, callback: callback) }, "expected error", { error in + XCTAssertThrowsError(try temp_await { callback in packageCollections.addCollection(brokenSources.first!, order: nil, callback: callback) }, "expected error", { error in XCTAssertEqual(error as? MyError, expectedError, "expected error to match") }) // save directly to storage to circumvent refresh on add try goodSources.forEach { source in - _ = try tsc_await { callback in storage.sources.add(source: source, order: nil, callback: callback) } + _ = try temp_await { callback in storage.sources.add(source: source, order: nil, callback: callback) } } try brokenSources.forEach { source in - _ = try tsc_await { callback in storage.sources.add(source: source, order: nil, callback: callback) } + _ = try temp_await { callback in storage.sources.add(source: source, order: nil, callback: callback) } } - _ = try tsc_await { callback in storage.sources.add(source: .init(type: .json, url: "https://feed-\(UUID().uuidString)"), order: nil, callback: callback) } + _ = try temp_await { callback in storage.sources.add(source: .init(type: .json, url: "https://feed-\(UUID().uuidString)"), order: nil, callback: callback) } - XCTAssertThrowsError(try tsc_await { callback in packageCollections.refreshCollections(callback: callback) }, "expected error", { error in + XCTAssertThrowsError(try temp_await { callback in packageCollections.refreshCollections(callback: callback) }, "expected error", { error in if let error = error as? MultipleErrors { XCTAssertEqual(error.errors.count, brokenSources.count, "expected error to match") error.errors.forEach { error in @@ -1056,7 +1055,7 @@ final class PackageCollectionsTests: XCTestCase { }) // test isolation - broken feeds does not impact good ones - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, goodSources.count + 1, "list count should match") } @@ -1074,11 +1073,11 @@ final class PackageCollectionsTests: XCTestCase { try mockCollections.forEach { collection in // save directly to storage to circumvent refresh on add - _ = try tsc_await { callback in storage.sources.add(source: collection.source, order: nil, callback: callback) } + _ = try temp_await { callback in storage.sources.add(source: collection.source, order: nil, callback: callback) } } - _ = try tsc_await { callback in packageCollections.refreshCollection(mockCollections.first!.source, callback: callback) } + _ = try temp_await { callback in packageCollections.refreshCollection(mockCollections.first!.source, callback: callback) } - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, mockCollections.count, "list count should match") } @@ -1095,11 +1094,11 @@ final class PackageCollectionsTests: XCTestCase { let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider) // User trusted - let collection = try tsc_await { callback in packageCollections.addCollection(mockCollections[0].source, order: nil, trustConfirmationProvider: { _, cb in cb(true) }, callback: callback) } + let collection = try temp_await { callback in packageCollections.addCollection(mockCollections[0].source, order: nil, trustConfirmationProvider: { _, cb in cb(true) }, callback: callback) } XCTAssertEqual(true, collection.source.isTrusted) // isTrusted is nil-able // `isTrusted` should be true so refreshCollection should succeed - XCTAssertNoThrow(try tsc_await { callback in packageCollections.refreshCollection(collection.source, callback: callback) }) + XCTAssertNoThrow(try temp_await { callback in packageCollections.refreshCollection(collection.source, callback: callback) }) } func testRefreshOneNotFound() throws { @@ -1115,7 +1114,7 @@ final class PackageCollectionsTests: XCTestCase { let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider) // Don't add collection so it's not found in the config - XCTAssertThrowsError(try tsc_await { callback in packageCollections.refreshCollection(mockCollections[0].source, callback: callback) }, "expected error") { error in + XCTAssertThrowsError(try temp_await { callback in packageCollections.refreshCollection(mockCollections[0].source, callback: callback) }, "expected error") { error in XCTAssert(error is NotFoundError) } } @@ -1133,19 +1132,19 @@ final class PackageCollectionsTests: XCTestCase { let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider) do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") } do { try mockCollections.forEach { collection in - _ = try tsc_await { callback in packageCollections.addCollection(collection.source, order: nil, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(collection.source, order: nil, callback: callback) } } - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, mockCollections.count, "list count should match") } - let targetsList = try tsc_await { callback in packageCollections.listTargets(callback: callback) } + let targetsList = try temp_await { callback in packageCollections.listTargets(callback: callback) } let expectedTargets = Set(mockCollections.flatMap { $0.packages.flatMap { $0.versions.flatMap { $0.defaultManifest!.targets.map { $0.name } } } }) XCTAssertEqual(Set(targetsList.map { $0.target.name }), expectedTargets, "targets should match") @@ -1173,19 +1172,19 @@ final class PackageCollectionsTests: XCTestCase { let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider) do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") } do { try mockCollections.forEach { collection in - _ = try tsc_await { callback in packageCollections.addCollection(collection.source, order: nil, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(collection.source, order: nil, callback: callback) } } - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, mockCollections.count, "list count should match") } - let metadata = try tsc_await { callback in packageCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location, callback: callback) } + let metadata = try temp_await { callback in packageCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location, callback: callback) } let expectedCollections = Set(mockCollections.filter { $0.packages.map { $0.identity }.contains(mockPackage.identity) }.map { $0.identifier }) XCTAssertEqual(Set(metadata.collections), expectedCollections, "collections should match") @@ -1210,19 +1209,19 @@ final class PackageCollectionsTests: XCTestCase { let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider) do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") } do { try mockCollections.forEach { collection in - _ = try tsc_await { callback in packageCollections.addCollection(collection.source, order: nil, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(collection.source, order: nil, callback: callback) } } - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, mockCollections.count, "list count should match") } - let metadata = try tsc_await { callback in packageCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location, callback: callback) } + let metadata = try temp_await { callback in packageCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location, callback: callback) } let expectedCollections = Set(mockCollections.filter { $0.packages.map { $0.identity }.contains(mockPackage.identity) }.map { $0.identifier }) XCTAssertEqual(Set(metadata.collections), expectedCollections, "collections should match") @@ -1248,20 +1247,20 @@ final class PackageCollectionsTests: XCTestCase { let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider) do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") } do { try mockCollections.forEach { collection in - _ = try tsc_await { callback in packageCollections.addCollection(collection.source, order: nil, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(collection.source, order: nil, callback: callback) } } - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, mockCollections.count, "list count should match") } let collectionIdentifiers: Set = [mockCollections.last!.identifier] - let metadata = try tsc_await { callback in packageCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location, collections: collectionIdentifiers, callback: callback) } + let metadata = try temp_await { callback in packageCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location, collections: collectionIdentifiers, callback: callback) } XCTAssertEqual(Set(metadata.collections), collectionIdentifiers, "collections should match") let expectedMetadata = PackageCollections.mergedPackageMetadata(package: mockPackage, basicMetadata: nil) @@ -1378,11 +1377,11 @@ final class PackageCollectionsTests: XCTestCase { let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider) do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") } - XCTAssertThrowsError(try tsc_await { callback in packageCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location, callback: callback) }, "expected error") { error in + XCTAssertThrowsError(try temp_await { callback in packageCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location, callback: callback) }, "expected error") { error in XCTAssert(error is NotFoundError) } } @@ -1401,19 +1400,19 @@ final class PackageCollectionsTests: XCTestCase { let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider) do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") } do { try mockCollections.forEach { collection in - _ = try tsc_await { callback in packageCollections.addCollection(collection.source, order: nil, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(collection.source, order: nil, callback: callback) } } - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, mockCollections.count, "list count should match") } - let metadata = try tsc_await { callback in packageCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location, callback: callback) } + let metadata = try temp_await { callback in packageCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location, callback: callback) } let expectedCollections = Set(mockCollections.filter { $0.packages.map { $0.identity }.contains(mockPackage.identity) }.map { $0.identifier }) XCTAssertEqual(Set(metadata.collections), expectedCollections, "collections should match") @@ -1453,20 +1452,20 @@ final class PackageCollectionsTests: XCTestCase { let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider) do { - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") } do { try mockCollections.forEach { collection in - _ = try tsc_await { callback in packageCollections.addCollection(collection.source, order: nil, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(collection.source, order: nil, callback: callback) } } - let list = try tsc_await { callback in packageCollections.listCollections(callback: callback) } + let list = try temp_await { callback in packageCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, mockCollections.count, "list count should match") } // Despite metadata provider error we should still get back data from storage - let metadata = try tsc_await { callback in packageCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location, callback: callback) } + let metadata = try temp_await { callback in packageCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location, callback: callback) } let expectedMetadata = PackageCollections.mergedPackageMetadata(package: mockPackage, basicMetadata: nil) XCTAssertEqual(metadata.package, expectedMetadata, "package should match") @@ -1503,7 +1502,7 @@ final class PackageCollectionsTests: XCTestCase { sync.wait() let start = Date() - let metadata = try tsc_await { callback in packageCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location, callback: callback) } + let metadata = try temp_await { callback in packageCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location, callback: callback) } XCTAssertNotNil(metadata) let delta = Date().timeIntervalSince(start) XCTAssert(delta < 1.0, "should fetch quickly, took \(delta)") @@ -1582,7 +1581,7 @@ final class PackageCollectionsTests: XCTestCase { let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider) try mockCollections.forEach { collection in - _ = try tsc_await { callback in packageCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) }, callback: callback) } + _ = try temp_await { callback in packageCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) }, callback: callback) } } do { @@ -1590,7 +1589,7 @@ final class PackageCollectionsTests: XCTestCase { let expectedPackages = Set(mockCollections.flatMap { $0.packages.map { $0.identity } } + [mockPackage.identity]) let expectedCollections = Set([mockCollection.identifier, mockCollection2.identifier]) - let searchResult = try tsc_await { callback in packageCollections.listPackages(collections: fetchCollections, callback: callback) } + let searchResult = try temp_await { callback in packageCollections.listPackages(collections: fetchCollections, callback: callback) } XCTAssertEqual(searchResult.items.count, expectedPackages.count, "list count should match") XCTAssertEqual(Set(searchResult.items.map { $0.package.identity }), expectedPackages, "items should match") XCTAssertEqual(Set(searchResult.items.first(where: { $0.package.identity == mockPackage.identity })?.collections ?? []), expectedCollections, "collections should match") @@ -1602,7 +1601,7 @@ final class PackageCollectionsTests: XCTestCase { let expectedPackages = Set(mockCollections[0].packages.map { $0.identity } + [mockPackage.identity]) let expectedCollections = Set([mockCollection.identifier, mockCollection2.identifier]) - let searchResult = try tsc_await { callback in packageCollections.listPackages(collections: fetchCollections, callback: callback) } + let searchResult = try temp_await { callback in packageCollections.listPackages(collections: fetchCollections, callback: callback) } XCTAssertEqual(searchResult.items.count, expectedPackages.count, "list count should match") XCTAssertEqual(Set(searchResult.items.map { $0.package.identity }), expectedPackages, "items should match") XCTAssertEqual(Set(searchResult.items.first(where: { $0.package.identity == mockPackage.identity })?.collections ?? []), expectedCollections, "collections should match") diff --git a/Tests/PackageCollectionsTests/PackageIndexAndCollectionsTests.swift b/Tests/PackageCollectionsTests/PackageIndexAndCollectionsTests.swift index 16d018b0cb4..8afab195fc5 100644 --- a/Tests/PackageCollectionsTests/PackageIndexAndCollectionsTests.swift +++ b/Tests/PackageCollectionsTests/PackageIndexAndCollectionsTests.swift @@ -15,7 +15,6 @@ import Foundation @testable import PackageCollections import PackageModel import SPMTestSupport -import TSCBasic import XCTest import struct TSCUtility.Version @@ -34,26 +33,26 @@ class PackageIndexAndCollectionsTests: XCTestCase { defer { XCTAssertNoThrow(try indexAndCollections.close()) } do { - let list = try tsc_await { callback in indexAndCollections.listCollections(callback: callback) } + let list = try temp_await { callback in indexAndCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") } do { try mockCollections.forEach { collection in - _ = try tsc_await { callback in indexAndCollections.addCollection(collection.source, order: nil, callback: callback) } + _ = try temp_await { callback in indexAndCollections.addCollection(collection.source, order: nil, callback: callback) } } - let list = try tsc_await { callback in indexAndCollections.listCollections(callback: callback) } + let list = try temp_await { callback in indexAndCollections.listCollections(callback: callback) } XCTAssertEqual(list, mockCollections, "list count should match") } do { - let collection = try tsc_await { callback in indexAndCollections.getCollection(mockCollections.first!.source, callback: callback) } + let collection = try temp_await { callback in indexAndCollections.getCollection(mockCollections.first!.source, callback: callback) } XCTAssertEqual(collection, mockCollections.first, "collection should match") } do { - _ = try tsc_await { callback in indexAndCollections.removeCollection(mockCollections.first!.source, callback: callback) } - let list = try tsc_await { callback in indexAndCollections.listCollections(callback: callback) } + _ = try temp_await { callback in indexAndCollections.removeCollection(mockCollections.first!.source, callback: callback) } + let list = try temp_await { callback in indexAndCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, mockCollections.count - 1, "list count should match") } } @@ -72,11 +71,11 @@ class PackageIndexAndCollectionsTests: XCTestCase { try mockCollections.forEach { collection in // save directly to storage to circumvent refresh on add - _ = try tsc_await { callback in storage.sources.add(source: collection.source, order: nil, callback: callback) } + _ = try temp_await { callback in storage.sources.add(source: collection.source, order: nil, callback: callback) } } - _ = try tsc_await { callback in indexAndCollections.refreshCollections(callback: callback) } + _ = try temp_await { callback in indexAndCollections.refreshCollections(callback: callback) } - let list = try tsc_await { callback in indexAndCollections.listCollections(callback: callback) } + let list = try temp_await { callback in indexAndCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, mockCollections.count, "list count should match") } @@ -94,11 +93,11 @@ class PackageIndexAndCollectionsTests: XCTestCase { try mockCollections.forEach { collection in // save directly to storage to circumvent refresh on add - _ = try tsc_await { callback in storage.sources.add(source: collection.source, order: nil, callback: callback) } + _ = try temp_await { callback in storage.sources.add(source: collection.source, order: nil, callback: callback) } } - _ = try tsc_await { callback in indexAndCollections.refreshCollection(mockCollections.first!.source, callback: callback) } + _ = try temp_await { callback in indexAndCollections.refreshCollection(mockCollections.first!.source, callback: callback) } - let collection = try tsc_await { callback in indexAndCollections.getCollection(mockCollections.first!.source, callback: callback) } + let collection = try temp_await { callback in indexAndCollections.getCollection(mockCollections.first!.source, callback: callback) } XCTAssertEqual(collection, mockCollections.first, "collection should match") } @@ -176,7 +175,7 @@ class PackageIndexAndCollectionsTests: XCTestCase { defer { XCTAssertNoThrow(try indexAndCollections.close()) } try mockCollections.forEach { collection in - _ = try tsc_await { callback in indexAndCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) }, callback: callback) } + _ = try temp_await { callback in indexAndCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) }, callback: callback) } } do { @@ -184,7 +183,7 @@ class PackageIndexAndCollectionsTests: XCTestCase { let expectedPackages = Set(mockCollections.flatMap { $0.packages.map { $0.identity } } + [mockPackage.identity]) let expectedCollections = Set([mockCollection.identifier, mockCollection2.identifier]) - let searchResult = try tsc_await { callback in indexAndCollections.listPackages(collections: fetchCollections, callback: callback) } + let searchResult = try temp_await { callback in indexAndCollections.listPackages(collections: fetchCollections, callback: callback) } XCTAssertEqual(searchResult.items.count, expectedPackages.count, "list count should match") XCTAssertEqual(Set(searchResult.items.map { $0.package.identity }), expectedPackages, "items should match") XCTAssertEqual(Set(searchResult.items.first(where: { $0.package.identity == mockPackage.identity })?.collections ?? []), expectedCollections, "collections should match") @@ -196,7 +195,7 @@ class PackageIndexAndCollectionsTests: XCTestCase { let expectedPackages = Set(mockCollections[0].packages.map { $0.identity } + [mockPackage.identity]) let expectedCollections = Set([mockCollection.identifier, mockCollection2.identifier]) - let searchResult = try tsc_await { callback in indexAndCollections.listPackages(collections: fetchCollections, callback: callback) } + let searchResult = try temp_await { callback in indexAndCollections.listPackages(collections: fetchCollections, callback: callback) } XCTAssertEqual(searchResult.items.count, expectedPackages.count, "list count should match") XCTAssertEqual(Set(searchResult.items.map { $0.package.identity }), expectedPackages, "items should match") XCTAssertEqual(Set(searchResult.items.first(where: { $0.package.identity == mockPackage.identity })?.collections ?? []), expectedCollections, "collections should match") @@ -216,19 +215,19 @@ class PackageIndexAndCollectionsTests: XCTestCase { defer { XCTAssertNoThrow(try indexAndCollections.close()) } do { - let list = try tsc_await { callback in indexAndCollections.listCollections(callback: callback) } + let list = try temp_await { callback in indexAndCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") } do { try mockCollections.forEach { collection in - _ = try tsc_await { callback in indexAndCollections.addCollection(collection.source, order: nil, callback: callback) } + _ = try temp_await { callback in indexAndCollections.addCollection(collection.source, order: nil, callback: callback) } } - let list = try tsc_await { callback in indexAndCollections.listCollections(callback: callback) } + let list = try temp_await { callback in indexAndCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, mockCollections.count, "list count should match") } - let targetsList = try tsc_await { callback in indexAndCollections.listTargets(callback: callback) } + let targetsList = try temp_await { callback in indexAndCollections.listTargets(callback: callback) } let expectedTargets = Set(mockCollections.flatMap { $0.packages.flatMap { $0.versions.flatMap { $0.defaultManifest!.targets.map { $0.name } } } }) XCTAssertEqual(Set(targetsList.map { $0.target.name }), expectedTargets, "targets should match") @@ -317,12 +316,12 @@ class PackageIndexAndCollectionsTests: XCTestCase { defer { XCTAssertNoThrow(try indexAndCollections.close()) } try mockCollections.forEach { collection in - _ = try tsc_await { callback in indexAndCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) }, callback: callback) } + _ = try temp_await { callback in indexAndCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) }, callback: callback) } } do { // search by exact target name - let searchResult = try tsc_await { callback in indexAndCollections.findTargets(mockTargets.first!.name, searchType: .exactMatch, callback: callback) } + let searchResult = try temp_await { callback in indexAndCollections.findTargets(mockTargets.first!.name, searchType: .exactMatch, callback: callback) } XCTAssertEqual(searchResult.items.count, 1, "list count should match") XCTAssertEqual(searchResult.items.first?.packages.map { $0.identity }, [mockPackage.identity], "packages should match") XCTAssertEqual(searchResult.items.first?.packages.flatMap { $0.collections }.sorted(), expectedCollectionsIdentifiers, "collections should match") @@ -330,7 +329,7 @@ class PackageIndexAndCollectionsTests: XCTestCase { do { // search by prefix target name - let searchResult = try tsc_await { callback in indexAndCollections.findTargets(String(mockTargets.first!.name.prefix(mockTargets.first!.name.count - 1)), searchType: .prefix, callback: callback) } + let searchResult = try temp_await { callback in indexAndCollections.findTargets(String(mockTargets.first!.name.prefix(mockTargets.first!.name.count - 1)), searchType: .prefix, callback: callback) } XCTAssertEqual(searchResult.items.count, 1, "list count should match") XCTAssertEqual(searchResult.items.first?.packages.map { $0.identity }, [mockPackage.identity], "packages should match") XCTAssertEqual(searchResult.items.first?.packages.flatMap { $0.collections }.sorted(), expectedCollectionsIdentifiers, "collections should match") @@ -338,7 +337,7 @@ class PackageIndexAndCollectionsTests: XCTestCase { do { // empty search - let searchResult = try tsc_await { callback in indexAndCollections.findTargets(UUID().uuidString, searchType: .exactMatch, callback: callback) } + let searchResult = try temp_await { callback in indexAndCollections.findTargets(UUID().uuidString, searchType: .exactMatch, callback: callback) } XCTAssertEqual(searchResult.items.count, 0, "list count should match") } } @@ -355,7 +354,7 @@ class PackageIndexAndCollectionsTests: XCTestCase { let indexAndCollections = PackageIndexAndCollections(index: packageIndex, collections: packageCollections, observabilityScope: ObservabilitySystem.NOOP) defer { XCTAssertNoThrow(try indexAndCollections.close()) } - let result = try tsc_await { callback in indexAndCollections.listPackagesInIndex(offset: 1, limit: 5, callback: callback) } + let result = try temp_await { callback in indexAndCollections.listPackagesInIndex(offset: 1, limit: 5, callback: callback) } XCTAssertFalse(result.items.isEmpty) } @@ -375,19 +374,19 @@ class PackageIndexAndCollectionsTests: XCTestCase { defer { XCTAssertNoThrow(try indexAndCollections.close()) } do { - let list = try tsc_await { callback in indexAndCollections.listCollections(callback: callback) } + let list = try temp_await { callback in indexAndCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") } do { try mockCollections.forEach { collection in - _ = try tsc_await { callback in indexAndCollections.addCollection(collection.source, order: nil, callback: callback) } + _ = try temp_await { callback in indexAndCollections.addCollection(collection.source, order: nil, callback: callback) } } - let list = try tsc_await { callback in indexAndCollections.listCollections(callback: callback) } + let list = try temp_await { callback in indexAndCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, mockCollections.count, "list count should match") } - let metadata = try tsc_await { callback in indexAndCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location, callback: callback) } + let metadata = try temp_await { callback in indexAndCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location, callback: callback) } let expectedCollections = Set(mockCollections.filter { $0.packages.map { $0.identity }.contains(mockPackage.identity) }.map { $0.identifier }) XCTAssertEqual(Set(metadata.collections), expectedCollections, "collections should match") @@ -414,19 +413,19 @@ class PackageIndexAndCollectionsTests: XCTestCase { defer { XCTAssertNoThrow(try indexAndCollections.close()) } do { - let list = try tsc_await { callback in indexAndCollections.listCollections(callback: callback) } + let list = try temp_await { callback in indexAndCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") } do { try mockCollections.forEach { collection in - _ = try tsc_await { callback in indexAndCollections.addCollection(collection.source, order: nil, callback: callback) } + _ = try temp_await { callback in indexAndCollections.addCollection(collection.source, order: nil, callback: callback) } } - let list = try tsc_await { callback in indexAndCollections.listCollections(callback: callback) } + let list = try temp_await { callback in indexAndCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, mockCollections.count, "list count should match") } - let metadata = try tsc_await { callback in indexAndCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location, callback: callback) } + let metadata = try temp_await { callback in indexAndCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location, callback: callback) } let expectedCollections = Set(mockCollections.filter { $0.packages.map { $0.identity }.contains(mockPackage.identity) }.map { $0.identifier }) XCTAssertEqual(Set(metadata.collections), expectedCollections, "collections should match") @@ -451,7 +450,7 @@ class PackageIndexAndCollectionsTests: XCTestCase { let mockPackage = makeMockPackage(id: "test-package") // Package not found in collections; index is broken - XCTAssertThrowsError(try tsc_await { callback in indexAndCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location, callback: callback) }) { error in + XCTAssertThrowsError(try temp_await { callback in indexAndCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location, callback: callback) }) { error in // Index error is returned guard let _ = error as? BrokenPackageIndex.TerribleThing else { return XCTFail("Expected BrokenPackageIndex.TerribleThing") @@ -534,12 +533,12 @@ class PackageIndexAndCollectionsTests: XCTestCase { defer { XCTAssertNoThrow(try indexAndCollections.close()) } try mockCollections.forEach { collection in - _ = try tsc_await { callback in indexAndCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) }, callback: callback) } + _ = try temp_await { callback in indexAndCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) }, callback: callback) } } // both index and collections do { - let searchResult = try tsc_await { callback in indexAndCollections.findPackages(mockPackage.identity.description, in: .both(collections: nil), callback: callback) } + let searchResult = try temp_await { callback in indexAndCollections.findPackages(mockPackage.identity.description, in: .both(collections: nil), callback: callback) } XCTAssertEqual(searchResult.items.count, 1, "list count should match") XCTAssertEqual(searchResult.items.first?.collections.sorted(), expectedCollectionsIdentifiers, "collections should match") XCTAssertEqual(searchResult.items.first?.indexes, [packageIndex.url], "indexes should match") @@ -547,7 +546,7 @@ class PackageIndexAndCollectionsTests: XCTestCase { // index only do { - let searchResult = try tsc_await { callback in indexAndCollections.findPackages(mockPackage.identity.description, in: .index, callback: callback) } + let searchResult = try temp_await { callback in indexAndCollections.findPackages(mockPackage.identity.description, in: .index, callback: callback) } XCTAssertEqual(searchResult.items.count, 1, "list count should match") XCTAssertTrue(searchResult.items.first?.collections.isEmpty ?? true, "collections should match") XCTAssertEqual(searchResult.items.first?.indexes, [packageIndex.url], "indexes should match") @@ -555,7 +554,7 @@ class PackageIndexAndCollectionsTests: XCTestCase { // collections only do { - let searchResult = try tsc_await { callback in indexAndCollections.findPackages(mockPackage.identity.description, in: .collections(nil), callback: callback) } + let searchResult = try temp_await { callback in indexAndCollections.findPackages(mockPackage.identity.description, in: .collections(nil), callback: callback) } XCTAssertEqual(searchResult.items.count, 1, "list count should match") XCTAssertEqual(searchResult.items.first?.collections.sorted(), expectedCollectionsIdentifiers, "collections should match") XCTAssertTrue(searchResult.items.first?.indexes.isEmpty ?? true, "indexes should match") @@ -637,12 +636,12 @@ class PackageIndexAndCollectionsTests: XCTestCase { defer { XCTAssertNoThrow(try indexAndCollections.close()) } try mockCollections.forEach { collection in - _ = try tsc_await { callback in indexAndCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) }, callback: callback) } + _ = try temp_await { callback in indexAndCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) }, callback: callback) } } // both index and collections do { - let searchResult = try tsc_await { callback in indexAndCollections.findPackages(mockPackage.identity.description, in: .both(collections: nil), callback: callback) } + let searchResult = try temp_await { callback in indexAndCollections.findPackages(mockPackage.identity.description, in: .both(collections: nil), callback: callback) } XCTAssertEqual(searchResult.items.count, 1, "list count should match") XCTAssertEqual(searchResult.items.first?.collections.sorted(), expectedCollectionsIdentifiers, "collections should match") // Results come from collections since index is broken @@ -651,7 +650,7 @@ class PackageIndexAndCollectionsTests: XCTestCase { // index only do { - XCTAssertThrowsError(try tsc_await { callback in indexAndCollections.findPackages(mockPackage.identity.description, in: .index, callback: callback) }) { error in + XCTAssertThrowsError(try temp_await { callback in indexAndCollections.findPackages(mockPackage.identity.description, in: .index, callback: callback) }) { error in guard error is BrokenPackageIndex.TerribleThing else { return XCTFail("invalid error \(error)") } @@ -660,7 +659,7 @@ class PackageIndexAndCollectionsTests: XCTestCase { // collections only do { - let searchResult = try tsc_await { callback in indexAndCollections.findPackages(mockPackage.identity.description, in: .collections(nil), callback: callback) } + let searchResult = try temp_await { callback in indexAndCollections.findPackages(mockPackage.identity.description, in: .collections(nil), callback: callback) } XCTAssertEqual(searchResult.items.count, 1, "list count should match") XCTAssertEqual(searchResult.items.first?.collections.sorted(), expectedCollectionsIdentifiers, "collections should match") // Not searching in index so should not be impacted by its error diff --git a/Tests/PackageCollectionsTests/PackageIndexConfigurationTests.swift b/Tests/PackageCollectionsTests/PackageIndexConfigurationTests.swift index 470c594220d..869a48c14bc 100644 --- a/Tests/PackageCollectionsTests/PackageIndexConfigurationTests.swift +++ b/Tests/PackageCollectionsTests/PackageIndexConfigurationTests.swift @@ -11,9 +11,10 @@ //===----------------------------------------------------------------------===// import PackageCollections -import TSCBasic import XCTest +import class TSCBasic.InMemoryFileSystem + class PackageIndexConfigurationTests: XCTestCase { func testSaveAndLoad() throws { let url = URL("https://package-index.test") diff --git a/Tests/PackageCollectionsTests/PackageIndexTests.swift b/Tests/PackageCollectionsTests/PackageIndexTests.swift index 95743014055..87fb27a90e8 100644 --- a/Tests/PackageCollectionsTests/PackageIndexTests.swift +++ b/Tests/PackageCollectionsTests/PackageIndexTests.swift @@ -15,7 +15,6 @@ import Foundation @testable import PackageCollections import PackageModel import SPMTestSupport -import TSCBasic import XCTest class PackageIndexTests: XCTestCase { @@ -46,7 +45,7 @@ class PackageIndexTests: XCTestCase { let index = PackageIndex(configuration: configuration, customHTTPClient: httpClient, callbackQueue: .sharedConcurrent, observabilityScope: ObservabilitySystem.NOOP) defer { XCTAssertNoThrow(try index.close()) } - let metadata = try tsc_await { callback in index.getPackageMetadata(identity: .init(url: repoURL), location: repoURL.absoluteString, callback: callback) } + let metadata = try temp_await { callback in index.getPackageMetadata(identity: .init(url: repoURL), location: repoURL.absoluteString, callback: callback) } XCTAssertEqual(metadata.package.identity, package.identity) XCTAssert(metadata.collections.isEmpty) XCTAssertNotNil(metadata.provider) @@ -61,7 +60,7 @@ class PackageIndexTests: XCTestCase { defer { XCTAssertNoThrow(try index.close()) } let repoURL = URL("https://github.com/octocat/Hello-World.git") - XCTAssertThrowsError(try tsc_await { callback in index.getPackageMetadata(identity: .init(url: repoURL), location: repoURL.absoluteString, callback: callback) }) { error in + XCTAssertThrowsError(try temp_await { callback in index.getPackageMetadata(identity: .init(url: repoURL), location: repoURL.absoluteString, callback: callback) }) { error in XCTAssertEqual(error as? PackageIndexError, .featureDisabled) } } @@ -74,7 +73,7 @@ class PackageIndexTests: XCTestCase { defer { XCTAssertNoThrow(try index.close()) } let repoURL = URL("https://github.com/octocat/Hello-World.git") - XCTAssertThrowsError(try tsc_await { callback in index.getPackageMetadata(identity: .init(url: repoURL), location: repoURL.absoluteString, callback: callback) }) { error in + XCTAssertThrowsError(try temp_await { callback in index.getPackageMetadata(identity: .init(url: repoURL), location: repoURL.absoluteString, callback: callback) }) { error in XCTAssertEqual(error as? PackageIndexError, .notConfigured) } } @@ -107,7 +106,7 @@ class PackageIndexTests: XCTestCase { let index = PackageIndex(configuration: configuration, customHTTPClient: httpClient, callbackQueue: .sharedConcurrent, observabilityScope: ObservabilitySystem.NOOP) defer { XCTAssertNoThrow(try index.close()) } - let result = try tsc_await { callback in index.findPackages(query, callback: callback) } + let result = try temp_await { callback in index.findPackages(query, callback: callback) } XCTAssertEqual(result.items.count, packages.count) for (i, item) in result.items.enumerated() { XCTAssertEqual(item.package.identity, packages[i].identity) @@ -145,7 +144,7 @@ class PackageIndexTests: XCTestCase { let index = PackageIndex(configuration: configuration, customHTTPClient: httpClient, callbackQueue: .sharedConcurrent, observabilityScope: ObservabilitySystem.NOOP) defer { XCTAssertNoThrow(try index.close()) } - let result = try tsc_await { callback in index.findPackages(query, callback: callback) } + let result = try temp_await { callback in index.findPackages(query, callback: callback) } XCTAssertEqual(result.items.count, configuration.searchResultMaxItemsCount) for (i, item) in result.items.enumerated() { XCTAssertEqual(item.package.identity, packages[i].identity) @@ -162,7 +161,7 @@ class PackageIndexTests: XCTestCase { let index = PackageIndex(configuration: configuration, callbackQueue: .sharedConcurrent, observabilityScope: ObservabilitySystem.NOOP) defer { XCTAssertNoThrow(try index.close()) } - XCTAssertThrowsError(try tsc_await { callback in index.findPackages("foobar", callback: callback) }) { error in + XCTAssertThrowsError(try temp_await { callback in index.findPackages("foobar", callback: callback) }) { error in XCTAssertEqual(error as? PackageIndexError, .featureDisabled) } } @@ -174,7 +173,7 @@ class PackageIndexTests: XCTestCase { let index = PackageIndex(configuration: configuration, callbackQueue: .sharedConcurrent, observabilityScope: ObservabilitySystem.NOOP) defer { XCTAssertNoThrow(try index.close()) } - XCTAssertThrowsError(try tsc_await { callback in index.findPackages("foobar", callback: callback) }) { error in + XCTAssertThrowsError(try temp_await { callback in index.findPackages("foobar", callback: callback) }) { error in XCTAssertEqual(error as? PackageIndexError, .notConfigured) } } @@ -210,7 +209,7 @@ class PackageIndexTests: XCTestCase { let index = PackageIndex(configuration: configuration, customHTTPClient: httpClient, callbackQueue: .sharedConcurrent, observabilityScope: ObservabilitySystem.NOOP) defer { XCTAssertNoThrow(try index.close()) } - let result = try tsc_await { callback in index.listPackages(offset: offset, limit: limit, callback: callback) } + let result = try temp_await { callback in index.listPackages(offset: offset, limit: limit, callback: callback) } XCTAssertEqual(result.items.count, packages.count) XCTAssertEqual(result.offset, offset) XCTAssertEqual(result.limit, limit) @@ -225,7 +224,7 @@ class PackageIndexTests: XCTestCase { let index = PackageIndex(configuration: configuration, callbackQueue: .sharedConcurrent, observabilityScope: ObservabilitySystem.NOOP) defer { XCTAssertNoThrow(try index.close()) } - XCTAssertThrowsError(try tsc_await { callback in index.listPackages(offset: 0, limit: 10, callback: callback) }) { error in + XCTAssertThrowsError(try temp_await { callback in index.listPackages(offset: 0, limit: 10, callback: callback) }) { error in XCTAssertEqual(error as? PackageIndexError, .featureDisabled) } } @@ -237,7 +236,7 @@ class PackageIndexTests: XCTestCase { let index = PackageIndex(configuration: configuration, callbackQueue: .sharedConcurrent, observabilityScope: ObservabilitySystem.NOOP) defer { XCTAssertNoThrow(try index.close()) } - XCTAssertThrowsError(try tsc_await { callback in index.listPackages(offset: 0, limit: 10, callback: callback) }) { error in + XCTAssertThrowsError(try temp_await { callback in index.listPackages(offset: 0, limit: 10, callback: callback) }) { error in XCTAssertEqual(error as? PackageIndexError, .notConfigured) } } @@ -303,7 +302,7 @@ class PackageIndexTests: XCTestCase { private extension PackageIndex { func syncGet(identity: PackageIdentity, location: String) throws -> Model.PackageBasicMetadata { - try tsc_await { callback in + try temp_await { callback in self.get(identity: identity, location: location) { result, _ in callback(result) } } } diff --git a/Tests/PackageCollectionsTests/TrieTests.swift b/Tests/PackageCollectionsTests/TrieTests.swift index 91c939a91cb..d55210106c8 100644 --- a/Tests/PackageCollectionsTests/TrieTests.swift +++ b/Tests/PackageCollectionsTests/TrieTests.swift @@ -10,7 +10,6 @@ // //===----------------------------------------------------------------------===// -import TSCBasic import XCTest @testable import PackageCollections diff --git a/Tests/PackageCollectionsTests/Utility.swift b/Tests/PackageCollectionsTests/Utility.swift index 7067522d3ca..ede95299093 100644 --- a/Tests/PackageCollectionsTests/Utility.swift +++ b/Tests/PackageCollectionsTests/Utility.swift @@ -19,7 +19,8 @@ import PackageCollectionsModel import PackageCollectionsSigning import PackageModel import SourceControl -import TSCBasic + +import class TSCBasic.InMemoryFileSystem import struct TSCUtility.Version diff --git a/Tests/PackageFingerprintTests/FilePackageFingerprintStorageTests.swift b/Tests/PackageFingerprintTests/FilePackageFingerprintStorageTests.swift index d0cba0c0a48..eb665f16977 100644 --- a/Tests/PackageFingerprintTests/FilePackageFingerprintStorageTests.swift +++ b/Tests/PackageFingerprintTests/FilePackageFingerprintStorageTests.swift @@ -15,9 +15,10 @@ import struct Foundation.URL @testable import PackageFingerprint import PackageModel import SPMTestSupport -import TSCBasic import XCTest +import class TSCBasic.InMemoryFileSystem + import struct TSCUtility.Version final class FilePackageFingerprintStorageTests: XCTestCase { @@ -406,7 +407,7 @@ extension PackageFingerprintStorage { package: PackageIdentity, version: Version ) throws -> [Fingerprint.Kind: [Fingerprint.ContentType: Fingerprint]] { - try tsc_await { + try temp_await { self.get( package: package, version: version, @@ -423,7 +424,7 @@ extension PackageFingerprintStorage { kind: Fingerprint.Kind, contentType: Fingerprint.ContentType ) throws -> Fingerprint { - try tsc_await { + try temp_await { self.get( package: package, version: version, @@ -441,7 +442,7 @@ extension PackageFingerprintStorage { version: Version, fingerprint: Fingerprint ) throws { - try tsc_await { + try temp_await { self.put( package: package, version: version, @@ -457,7 +458,7 @@ extension PackageFingerprintStorage { package: PackageReference, version: Version ) throws -> [Fingerprint.Kind: [Fingerprint.ContentType: Fingerprint]] { - try tsc_await { + try temp_await { self.get( package: package, version: version, @@ -474,7 +475,7 @@ extension PackageFingerprintStorage { kind: Fingerprint.Kind, contentType: Fingerprint.ContentType ) throws -> Fingerprint { - try tsc_await { + try temp_await { self.get( package: package, version: version, @@ -492,7 +493,7 @@ extension PackageFingerprintStorage { version: Version, fingerprint: Fingerprint ) throws { - try tsc_await { + try temp_await { self.put( package: package, version: version, diff --git a/Tests/PackageGraphPerformanceTests/DependencyResolverPerfTests.swift b/Tests/PackageGraphPerformanceTests/DependencyResolverPerfTests.swift index 204b7d1fd19..6af1668fa63 100644 --- a/Tests/PackageGraphPerformanceTests/DependencyResolverPerfTests.swift +++ b/Tests/PackageGraphPerformanceTests/DependencyResolverPerfTests.swift @@ -16,10 +16,17 @@ import PackageLoading import PackageModel import SourceControl import SPMTestSupport -import TSCBasic -import struct TSCUtility.Version import XCTest +import enum TSCBasic.JSON +import protocol TSCBasic.JSONMappable +import protocol TSCBasic.JSONSerializable + +import func TSCUtility.measure +import struct TSCUtility.Version + +import class TSCTestSupport.XCTestCasePerf + private let v1: Version = "1.0.0" private let v1Range: VersionSetSpecifier = .range("1.0.0" ..< "2.0.0") diff --git a/Tests/PackageGraphPerformanceTests/PackageGraphPerfTests.swift b/Tests/PackageGraphPerformanceTests/PackageGraphPerfTests.swift index 47b68631881..e9a92586f38 100644 --- a/Tests/PackageGraphPerformanceTests/PackageGraphPerfTests.swift +++ b/Tests/PackageGraphPerformanceTests/PackageGraphPerfTests.swift @@ -16,9 +16,12 @@ import PackageGraph import PackageLoading import PackageModel import SPMTestSupport -import TSCBasic import XCTest +import class TSCBasic.InMemoryFileSystem + +import class TSCTestSupport.XCTestCasePerf + class PackageGraphPerfTests: XCTestCasePerf { func testLoading100Packages() throws { diff --git a/Tests/PackageGraphTests/DependencyResolverTests.swift b/Tests/PackageGraphTests/DependencyResolverTests.swift index 8b846f9b748..6247260a906 100644 --- a/Tests/PackageGraphTests/DependencyResolverTests.swift +++ b/Tests/PackageGraphTests/DependencyResolverTests.swift @@ -12,7 +12,6 @@ import XCTest -import TSCBasic import PackageGraph import SourceControl diff --git a/Tests/PackageGraphTests/PackageGraphTests.swift b/Tests/PackageGraphTests/PackageGraphTests.swift index 4448758315a..98d7661db4e 100644 --- a/Tests/PackageGraphTests/PackageGraphTests.swift +++ b/Tests/PackageGraphTests/PackageGraphTests.swift @@ -14,9 +14,11 @@ import Basics @testable import PackageGraph import PackageModel import SPMTestSupport -import TSCBasic import XCTest +import struct TSCBasic.ByteString +import class TSCBasic.InMemoryFileSystem + class PackageGraphTests: XCTestCase { func testBasic() throws { @@ -683,7 +685,7 @@ class PackageGraphTests: XCTestCase { } func testEmptyDependency() throws { - let Bar: AbsolutePath = AbsolutePath("/Bar") + let Bar: AbsolutePath = "/Bar" let fs = InMemoryFileSystem(emptyFiles: "/Foo/Sources/Foo/foo.swift", diff --git a/Tests/PackageGraphTests/PubgrubTests.swift b/Tests/PackageGraphTests/PubgrubTests.swift index c4b9274a767..e19a2dbf1e5 100644 --- a/Tests/PackageGraphTests/PubgrubTests.swift +++ b/Tests/PackageGraphTests/PubgrubTests.swift @@ -17,9 +17,10 @@ import PackageLoading @testable import PackageModel import SourceControl import SPMTestSupport -import TSCBasic import XCTest +import class TSCBasic.InMemoryFileSystem + import struct TSCUtility.Version // There's some useful helper utilities defined below for easier testing: @@ -344,7 +345,7 @@ final class PubgrubTests: XCTestCase { let state1 = PubGrubDependencyResolver.State(root: rootNode) // No decision can be made if no unsatisfied terms are available. - XCTAssertNil(try tsc_await { solver1.makeDecision(state: state1, completion: $0) }) + XCTAssertNil(try temp_await { solver1.makeDecision(state: state1, completion: $0) }) let a = MockContainer(package: aRef, dependenciesByVersion: [ "0.0.0": [:], @@ -360,7 +361,7 @@ final class PubgrubTests: XCTestCase { XCTAssertEqual(state2.incompatibilities.count, 0) - let decision = try tsc_await { solver2.makeDecision(state: state2, completion: $0) } + let decision = try temp_await { solver2.makeDecision(state: state2, completion: $0) } XCTAssertEqual(decision, .product("a", package: "a")) XCTAssertEqual(state2.incompatibilities.count, 3) diff --git a/Tests/PackageGraphTests/TargetTests.swift b/Tests/PackageGraphTests/TargetTests.swift index 2143f266ad2..08c1eec8daf 100644 --- a/Tests/PackageGraphTests/TargetTests.swift +++ b/Tests/PackageGraphTests/TargetTests.swift @@ -11,7 +11,6 @@ //===----------------------------------------------------------------------===// import XCTest -import TSCBasic import PackageGraph import PackageModel diff --git a/Tests/PackageLoadingPerformanceTests/ManifestLoadingTests.swift b/Tests/PackageLoadingPerformanceTests/ManifestLoadingTests.swift index 7b192d04008..ba586cc322a 100644 --- a/Tests/PackageLoadingPerformanceTests/ManifestLoadingTests.swift +++ b/Tests/PackageLoadingPerformanceTests/ManifestLoadingTests.swift @@ -14,9 +14,10 @@ import Basics import PackageModel import PackageLoading import SPMTestSupport -import TSCBasic import XCTest +import class TSCTestSupport.XCTestCasePerf + class ManifestLoadingPerfTests: XCTestCasePerf { let manifestLoader = ManifestLoader(toolchain: try! UserToolchain.default) diff --git a/Tests/PackageLoadingTests/ManifestLoaderSQLiteCacheTests.swift b/Tests/PackageLoadingTests/ManifestLoaderSQLiteCacheTests.swift index ceead5e1de4..97b2d292b8c 100644 --- a/Tests/PackageLoadingTests/ManifestLoaderSQLiteCacheTests.swift +++ b/Tests/PackageLoadingTests/ManifestLoaderSQLiteCacheTests.swift @@ -13,8 +13,7 @@ import Basics @testable import PackageLoading import PackageModel -import TSCBasic -import TSCTestSupport +import SPMTestSupport import XCTest class ManifestLoaderSQLiteCacheTests: XCTestCase { diff --git a/Tests/PackageLoadingTests/ManifestSignatureParserTests.swift b/Tests/PackageLoadingTests/ManifestSignatureParserTests.swift index f51aa6b8032..f93a059235d 100644 --- a/Tests/PackageLoadingTests/ManifestSignatureParserTests.swift +++ b/Tests/PackageLoadingTests/ManifestSignatureParserTests.swift @@ -10,11 +10,10 @@ // //===----------------------------------------------------------------------===// +import Basics import Foundation - import PackageLoading import SPMTestSupport -import TSCBasic import XCTest class ManifestSignatureParserTests: XCTestCase { diff --git a/Tests/PackageLoadingTests/ModuleMapGenerationTests.swift b/Tests/PackageLoadingTests/ModuleMapGenerationTests.swift index ace12aa77ae..80834a55e78 100644 --- a/Tests/PackageLoadingTests/ModuleMapGenerationTests.swift +++ b/Tests/PackageLoadingTests/ModuleMapGenerationTests.swift @@ -14,13 +14,14 @@ import Basics import PackageLoading import PackageModel import SPMTestSupport -import TSCBasic import XCTest +import class TSCBasic.InMemoryFileSystem + class ModuleMapGeneration: XCTestCase { func testModuleNameHeaderInInclude() throws { - let root: AbsolutePath = AbsolutePath.root + let root: AbsolutePath = .root let fs = InMemoryFileSystem(emptyFiles: root.appending(components: "include", "Foo.h").pathString, @@ -38,7 +39,7 @@ class ModuleMapGeneration: XCTestCase { } func testModuleNameDirAndHeaderInInclude() throws { - let root: AbsolutePath = AbsolutePath.root + let root: AbsolutePath = .root let fs = InMemoryFileSystem(emptyFiles: root.appending(components: "include", "Foo", "Foo.h").pathString, @@ -56,7 +57,7 @@ class ModuleMapGeneration: XCTestCase { } func testOtherCases() throws { - let root: AbsolutePath = AbsolutePath.root + let root: AbsolutePath = .root var fs: InMemoryFileSystem fs = InMemoryFileSystem(emptyFiles: @@ -105,7 +106,7 @@ class ModuleMapGeneration: XCTestCase { } func testWarnings() throws { - let root: AbsolutePath = AbsolutePath.root + let root: AbsolutePath = .root var fs = InMemoryFileSystem(emptyFiles: root.appending(components: "Foo.c").pathString @@ -144,7 +145,7 @@ class ModuleMapGeneration: XCTestCase { } func testUnsupportedLayouts() throws { - let include: AbsolutePath = AbsolutePath("/include") + let include: AbsolutePath = "/include" var fs = InMemoryFileSystem(emptyFiles: include.appending(components: "Foo", "Foo.h").pathString, diff --git a/Tests/PackageLoadingTests/PDLoadingTests.swift b/Tests/PackageLoadingTests/PDLoadingTests.swift index da60931605c..e1a21a7c847 100644 --- a/Tests/PackageLoadingTests/PDLoadingTests.swift +++ b/Tests/PackageLoadingTests/PDLoadingTests.swift @@ -14,9 +14,10 @@ import Basics import PackageLoading import PackageModel import SPMTestSupport -import TSCBasic import XCTest +import class TSCBasic.InMemoryFileSystem + class PackageDescriptionLoadingTests: XCTestCase, ManifestLoaderDelegate { lazy var manifestLoader = ManifestLoader(toolchain: try! UserToolchain.default, delegate: self) var parsedManifest = ThreadSafeBox() diff --git a/Tests/PackageLoadingTests/PD_4_0_LoadingTests.swift b/Tests/PackageLoadingTests/PD_4_0_LoadingTests.swift index 3d1fff3a764..e9fe155ea90 100644 --- a/Tests/PackageLoadingTests/PD_4_0_LoadingTests.swift +++ b/Tests/PackageLoadingTests/PD_4_0_LoadingTests.swift @@ -14,9 +14,9 @@ import Basics import PackageLoading import PackageModel import SPMTestSupport -import TSCBasic import XCTest +import class TSCBasic.InMemoryFileSystem class PackageDescription4_0LoadingTests: PackageDescriptionLoadingTests { override var toolsVersion: ToolsVersion { diff --git a/Tests/PackageLoadingTests/PD_4_2_LoadingTests.swift b/Tests/PackageLoadingTests/PD_4_2_LoadingTests.swift index 9fcd6ff519e..eb2c13bc5fc 100644 --- a/Tests/PackageLoadingTests/PD_4_2_LoadingTests.swift +++ b/Tests/PackageLoadingTests/PD_4_2_LoadingTests.swift @@ -15,9 +15,14 @@ import Dispatch import PackageLoading import PackageModel import SPMTestSupport -import TSCBasic import XCTest +import class TSCBasic.DiagnosticsEngine +import class TSCBasic.InMemoryFileSystem +import enum TSCBasic.PathValidationError + +import func TSCTestSupport.withCustomEnv + class PackageDescription4_2LoadingTests: PackageDescriptionLoadingTests { override var toolsVersion: ToolsVersion { .v4_2 @@ -829,7 +834,7 @@ class PackageDescription4_2LoadingTests: PackageDescriptionLoadingTests { // warm up caches delegate.prepare() - let manifest = try tsc_await { + let manifest = try temp_await { manifestLoader.load( manifestPath: manifestPath, manifestToolsVersion: .v4_2, diff --git a/Tests/PackageLoadingTests/PD_5_0_LoadingTests.swift b/Tests/PackageLoadingTests/PD_5_0_LoadingTests.swift index 9d7ef15eb0d..d8382221c8a 100644 --- a/Tests/PackageLoadingTests/PD_5_0_LoadingTests.swift +++ b/Tests/PackageLoadingTests/PD_5_0_LoadingTests.swift @@ -14,9 +14,10 @@ import Basics import PackageLoading import PackageModel import SPMTestSupport -import TSCBasic import XCTest +import struct TSCBasic.ByteString + class PackageDescription5_0LoadingTests: PackageDescriptionLoadingTests { override var toolsVersion: ToolsVersion { .v5 diff --git a/Tests/PackageLoadingTests/PD_5_2_LoadingTests.swift b/Tests/PackageLoadingTests/PD_5_2_LoadingTests.swift index 6f19194bf6b..9a12ae3aa31 100644 --- a/Tests/PackageLoadingTests/PD_5_2_LoadingTests.swift +++ b/Tests/PackageLoadingTests/PD_5_2_LoadingTests.swift @@ -14,7 +14,6 @@ import Basics import PackageLoading import PackageModel import SPMTestSupport -import TSCBasic import XCTest class PackageDescription5_2LoadingTests: PackageDescriptionLoadingTests { diff --git a/Tests/PackageLoadingTests/PD_5_3_LoadingTests.swift b/Tests/PackageLoadingTests/PD_5_3_LoadingTests.swift index 2c95a6d0230..23785048490 100644 --- a/Tests/PackageLoadingTests/PD_5_3_LoadingTests.swift +++ b/Tests/PackageLoadingTests/PD_5_3_LoadingTests.swift @@ -14,9 +14,10 @@ import Basics import PackageModel import PackageLoading import SPMTestSupport -import TSCBasic import XCTest +import enum TSCBasic.PathValidationError + class PackageDescription5_3LoadingTests: PackageDescriptionLoadingTests { override var toolsVersion: ToolsVersion { .v5_3 diff --git a/Tests/PackageLoadingTests/PD_5_4_LoadingTests.swift b/Tests/PackageLoadingTests/PD_5_4_LoadingTests.swift index 38dfdf3c8cc..211a889583f 100644 --- a/Tests/PackageLoadingTests/PD_5_4_LoadingTests.swift +++ b/Tests/PackageLoadingTests/PD_5_4_LoadingTests.swift @@ -14,7 +14,6 @@ import Basics import PackageLoading import PackageModel import SPMTestSupport -import TSCBasic import XCTest class PackageDescription5_4LoadingTests: PackageDescriptionLoadingTests { diff --git a/Tests/PackageLoadingTests/PD_5_5_LoadingTests.swift b/Tests/PackageLoadingTests/PD_5_5_LoadingTests.swift index d5d43cb494c..5096d829c1f 100644 --- a/Tests/PackageLoadingTests/PD_5_5_LoadingTests.swift +++ b/Tests/PackageLoadingTests/PD_5_5_LoadingTests.swift @@ -15,7 +15,6 @@ import Foundation import PackageLoading import PackageModel import SPMTestSupport -import TSCBasic import XCTest class PackageDescription5_5LoadingTests: PackageDescriptionLoadingTests { diff --git a/Tests/PackageLoadingTests/PD_5_6_LoadingTests.swift b/Tests/PackageLoadingTests/PD_5_6_LoadingTests.swift index 27536436f04..4b61a28dc9e 100644 --- a/Tests/PackageLoadingTests/PD_5_6_LoadingTests.swift +++ b/Tests/PackageLoadingTests/PD_5_6_LoadingTests.swift @@ -14,7 +14,6 @@ import Basics import PackageLoading import PackageModel import SPMTestSupport -import TSCBasic import XCTest class PackageDescription5_6LoadingTests: PackageDescriptionLoadingTests { diff --git a/Tests/PackageLoadingTests/PD_5_7_LoadingTests.swift b/Tests/PackageLoadingTests/PD_5_7_LoadingTests.swift index 59997700e82..2f9c7ac22e4 100644 --- a/Tests/PackageLoadingTests/PD_5_7_LoadingTests.swift +++ b/Tests/PackageLoadingTests/PD_5_7_LoadingTests.swift @@ -14,7 +14,6 @@ import Basics import PackageLoading import PackageModel import SPMTestSupport -import TSCBasic import XCTest class PackageDescription5_7LoadingTests: PackageDescriptionLoadingTests { diff --git a/Tests/PackageLoadingTests/PackageBuilderTests.swift b/Tests/PackageLoadingTests/PackageBuilderTests.swift index 46f2f97c570..3eb7aa1437c 100644 --- a/Tests/PackageLoadingTests/PackageBuilderTests.swift +++ b/Tests/PackageLoadingTests/PackageBuilderTests.swift @@ -14,9 +14,10 @@ import Basics import PackageLoading import PackageModel import SPMTestSupport -import TSCBasic import XCTest +import class TSCBasic.InMemoryFileSystem + /// Tests for the handling of source layout conventions. class PackageBuilderTests: XCTestCase { @@ -41,7 +42,7 @@ class PackageBuilderTests: XCTestCase { } func testMixedSources() throws { - let foo: AbsolutePath = AbsolutePath("/Sources/foo") + let foo: AbsolutePath = "/Sources/foo" let fs = InMemoryFileSystem(emptyFiles: foo.appending(components: "main.swift").pathString, @@ -226,7 +227,7 @@ class PackageBuilderTests: XCTestCase { } func testPublicIncludeDirMixedWithSources() throws { - let Sources: AbsolutePath = AbsolutePath("/Sources") + let Sources: AbsolutePath = "/Sources" let fs = InMemoryFileSystem(emptyFiles: Sources.appending(components: "clib", "nested", "nested.h").pathString, @@ -597,7 +598,7 @@ class PackageBuilderTests: XCTestCase { func testMultipleTestEntryPointsError() throws { let name = SwiftTarget.defaultTestEntryPointName - let swift: AbsolutePath = AbsolutePath("/swift") + let swift: AbsolutePath = "/swift" let fs = InMemoryFileSystem(emptyFiles: AbsolutePath.root.appending(components: name).pathString, @@ -621,9 +622,9 @@ class PackageBuilderTests: XCTestCase { } func testCustomTargetPaths() throws { - let Sources: AbsolutePath = AbsolutePath("/Sources") - let swift: RelativePath = RelativePath("swift") - let bar: AbsolutePath = AbsolutePath("/bar") + let Sources: AbsolutePath = "/Sources" + let swift: RelativePath = "swift" + let bar: AbsolutePath = "/bar" let fs = InMemoryFileSystem(emptyFiles: "/mah/target/exe/swift/exe/main.swift", @@ -687,7 +688,7 @@ class PackageBuilderTests: XCTestCase { } func testCustomTargetPathsOverlap() throws { - let bar: AbsolutePath = AbsolutePath("/target/bar") + let bar: AbsolutePath = "/target/bar" let fs = InMemoryFileSystem(emptyFiles: bar.appending(components: "bar.swift").pathString, @@ -741,8 +742,8 @@ class PackageBuilderTests: XCTestCase { } func testPublicHeadersPath() throws { - let Sources: AbsolutePath = AbsolutePath("/Sources") - let Tests: AbsolutePath = AbsolutePath("/Tests") + let Sources: AbsolutePath = "/Sources" + let Tests: AbsolutePath = "/Tests" let fs = InMemoryFileSystem(emptyFiles: Sources.appending(components: "Foo", "inc", "module.modulemap").pathString, @@ -813,7 +814,7 @@ class PackageBuilderTests: XCTestCase { } func testTestsLayoutsv4() throws { - let Sources: AbsolutePath = AbsolutePath("/Sources") + let Sources: AbsolutePath = "/Sources" let fs = InMemoryFileSystem(emptyFiles: Sources.appending(components: "A", "main.swift").pathString, @@ -960,7 +961,7 @@ class PackageBuilderTests: XCTestCase { } func testTargetDependencies() throws { - let Sources: AbsolutePath = AbsolutePath("/Sources") + let Sources: AbsolutePath = "/Sources" let fs = InMemoryFileSystem(emptyFiles: Sources.appending(components: "Foo", "Foo.swift").pathString, @@ -1733,7 +1734,7 @@ class PackageBuilderTests: XCTestCase { } do { - let pkg2: AbsolutePath = AbsolutePath("/Sources/pkg2") + let pkg2: AbsolutePath = "/Sources/pkg2" // Reference a target which doesn't have sources. let fs = InMemoryFileSystem(emptyFiles: @@ -2044,7 +2045,7 @@ class PackageBuilderTests: XCTestCase { } func testSpecialTargetDir() throws { - let src: AbsolutePath = AbsolutePath("/src") + let src: AbsolutePath = "/src" // Special directory should be src because both target and test target are under it. let fs = InMemoryFileSystem(emptyFiles: src.appending(components: "A", "Foo.swift").pathString, @@ -2195,7 +2196,7 @@ class PackageBuilderTests: XCTestCase { } func testSystemLibraryTargetDiagnostics() throws { - let Sources: AbsolutePath = AbsolutePath("/Sources") + let Sources: AbsolutePath = "/Sources" let fs = InMemoryFileSystem(emptyFiles: Sources.appending(components: "foo", "module.modulemap").pathString, @@ -2414,7 +2415,7 @@ class PackageBuilderTests: XCTestCase { } func testUnknownSourceFilesUnderDeclaredSourcesIgnoredInV5_2Manifest() throws { - let lib: AbsolutePath = AbsolutePath("/Sources/lib") + let lib: AbsolutePath = "/Sources/lib" // Files with unknown suffixes under declared sources are not considered valid sources in 5.2 manifest. let fs = InMemoryFileSystem(emptyFiles: @@ -2441,7 +2442,7 @@ class PackageBuilderTests: XCTestCase { } func testUnknownSourceFilesUnderDeclaredSourcesCompiledInV5_3Manifest() throws { - let lib: AbsolutePath = AbsolutePath("/Sources/lib") + let lib: AbsolutePath = "/Sources/lib" // Files with unknown suffixes under declared sources are treated as compilable in 5.3 manifest. let fs = InMemoryFileSystem(emptyFiles: @@ -2853,8 +2854,8 @@ class PackageBuilderTests: XCTestCase { } func testXcodeResources() throws { - let root: AbsolutePath = AbsolutePath("/Foo") - let Foo: AbsolutePath = root.appending(components: "Sources", "Foo") + let root: AbsolutePath = "/Foo" + let Foo = root.appending(components: "Sources", "Foo") let fs = InMemoryFileSystem(emptyFiles: Foo.appending(components: "foo.swift").pathString, diff --git a/Tests/PackageLoadingTests/PkgConfigParserTests.swift b/Tests/PackageLoadingTests/PkgConfigParserTests.swift index 62c5f356567..009f1328ff4 100644 --- a/Tests/PackageLoadingTests/PkgConfigParserTests.swift +++ b/Tests/PackageLoadingTests/PkgConfigParserTests.swift @@ -12,10 +12,14 @@ import Basics @testable import PackageLoading -import TSCBasic import SPMTestSupport import XCTest +import struct TSCBasic.ByteString +import class TSCBasic.InMemoryFileSystem + +import func TSCTestSupport.withCustomEnv + final class PkgConfigParserTests: XCTestCase { func testCircularPCFile() throws { let observability = ObservabilitySystem.makeForTesting() diff --git a/Tests/PackageLoadingTests/PkgConfigTests.swift b/Tests/PackageLoadingTests/PkgConfigTests.swift index b869f4072c4..b35a5d132dd 100644 --- a/Tests/PackageLoadingTests/PkgConfigTests.swift +++ b/Tests/PackageLoadingTests/PkgConfigTests.swift @@ -14,9 +14,10 @@ import Basics @testable import PackageLoading import PackageModel import SPMTestSupport -import TSCBasic import XCTest +import func TSCTestSupport.withCustomEnv + extension SystemLibraryTarget { convenience init(pkgConfig: String, providers: [SystemPackageProviderDescription] = []) { self.init( diff --git a/Tests/PackageLoadingTests/TargetSourcesBuilderTests.swift b/Tests/PackageLoadingTests/TargetSourcesBuilderTests.swift index 02d6d4a033d..8b88b05d5e2 100644 --- a/Tests/PackageLoadingTests/TargetSourcesBuilderTests.swift +++ b/Tests/PackageLoadingTests/TargetSourcesBuilderTests.swift @@ -15,9 +15,10 @@ import Foundation import PackageModel import PackageLoading import SPMTestSupport -import TSCBasic import XCTest +import class TSCBasic.InMemoryFileSystem + class TargetSourcesBuilderTests: XCTestCase { func testBasicFileContentsComputation() throws { let target = try TargetDescription( @@ -33,7 +34,7 @@ class TargetSourcesBuilderTests: XCTestCase { ) let fs = InMemoryFileSystem() - fs.createEmptyFiles(at: .root, files: [ + fs.createEmptyFiles(at: AbsolutePath.root, files: [ "/Foo.swift", "/Bar.swift", "/some/path.swift", @@ -85,7 +86,7 @@ class TargetSourcesBuilderTests: XCTestCase { ) let fs = InMemoryFileSystem() - fs.createEmptyFiles(at: .root, files: [ + fs.createEmptyFiles(at: AbsolutePath.root, files: [ "/some/hello.swift", "/some.thing/hello.txt", ]) @@ -124,7 +125,7 @@ class TargetSourcesBuilderTests: XCTestCase { ) let fs = InMemoryFileSystem() - fs.createEmptyFiles(at: .root, files: [ + fs.createEmptyFiles(at: AbsolutePath.root, files: [ "/some/hello.swift", "/some.thing/hello.txt", ]) @@ -165,7 +166,7 @@ class TargetSourcesBuilderTests: XCTestCase { ) let fs = InMemoryFileSystem() - fs.createEmptyFiles(at: .root, files: [ + fs.createEmptyFiles(at: AbsolutePath.root, files: [ root.appending(components: "some.xcassets", "hello.txt").pathString, root.appending(components: "some", "hello.swift").pathString ]) @@ -208,7 +209,7 @@ class TargetSourcesBuilderTests: XCTestCase { ) let fs = InMemoryFileSystem() - fs.createEmptyFiles(at: .root, files: [ + fs.createEmptyFiles(at: AbsolutePath.root, files: [ "/Foo.swift", "/Bar.swift", "/some/path.swift", @@ -250,7 +251,7 @@ class TargetSourcesBuilderTests: XCTestCase { ] let fs = InMemoryFileSystem() - fs.createEmptyFiles(at: .root, files: files.map(\.pathString)) + fs.createEmptyFiles(at: AbsolutePath.root, files: files.map(\.pathString)) let somethingRule = FileRuleDescription( rule: .compile, @@ -676,7 +677,7 @@ class TargetSourcesBuilderTests: XCTestCase { ) let fs = InMemoryFileSystem() - fs.createEmptyFiles(at: .root, files: [ + fs.createEmptyFiles(at: AbsolutePath.root, files: [ "/Foo.swift", "/Bar.swift" ]) @@ -744,7 +745,7 @@ class TargetSourcesBuilderTests: XCTestCase { ) let fs = InMemoryFileSystem() - fs.createEmptyFiles(at: .root, files: [ + fs.createEmptyFiles(at: AbsolutePath.root, files: [ "/Foo.swift", "/Bar.swift" ]) @@ -813,7 +814,7 @@ class TargetSourcesBuilderTests: XCTestCase { ) let fs = InMemoryFileSystem() - fs.createEmptyFiles(at: .root, files: [ + fs.createEmptyFiles(at: AbsolutePath.root, files: [ "/Foo.swift", "/Bar.swift" ]) @@ -857,7 +858,7 @@ class TargetSourcesBuilderTests: XCTestCase { ) let fs = InMemoryFileSystem() - fs.createEmptyFiles(at: .root, files: [ + fs.createEmptyFiles(at: AbsolutePath.root, files: [ "/File.swift", "/Foo.xcdatamodel" ]) @@ -896,7 +897,7 @@ class TargetSourcesBuilderTests: XCTestCase { ) let fs = InMemoryFileSystem() - fs.createEmptyFiles(at: .root, files: [ + fs.createEmptyFiles(at: AbsolutePath.root, files: [ "/File.swift", "/foo.bar" ]) @@ -957,7 +958,7 @@ class TargetSourcesBuilderTests: XCTestCase { ) let fs = InMemoryFileSystem() - fs.createEmptyFiles(at: .root, files: [ + fs.createEmptyFiles(at: AbsolutePath.root, files: [ "/File.swift", "/Foo.docc" ]) diff --git a/Tests/PackageLoadingTests/ToolsVersionParserTests.swift b/Tests/PackageLoadingTests/ToolsVersionParserTests.swift index 700b8952150..452a5f3a5ba 100644 --- a/Tests/PackageLoadingTests/ToolsVersionParserTests.swift +++ b/Tests/PackageLoadingTests/ToolsVersionParserTests.swift @@ -15,9 +15,10 @@ import Basics import PackageModel import PackageLoading import SPMTestSupport -import TSCBasic import XCTest +import class TSCBasic.InMemoryFileSystem + class ToolsVersionParserTests: XCTestCase { func parse(_ content: String, _ body: ((ToolsVersion) -> Void)? = nil) throws { let toolsVersion = try ToolsVersionParser.parse(utf8String: content) diff --git a/Tests/PackageModelTests/CanonicalPackageLocationTests.swift b/Tests/PackageModelTests/CanonicalPackageLocationTests.swift index 2fb45aa281d..ace25ccadc1 100644 --- a/Tests/PackageModelTests/CanonicalPackageLocationTests.swift +++ b/Tests/PackageModelTests/CanonicalPackageLocationTests.swift @@ -12,8 +12,6 @@ import XCTest -import TSCBasic - @testable import PackageModel final class CanonicalPackageLocationTests: XCTestCase { diff --git a/Tests/PackageModelTests/DestinationTests.swift b/Tests/PackageModelTests/DestinationTests.swift index 605a34d62a2..55908a66086 100644 --- a/Tests/PackageModelTests/DestinationTests.swift +++ b/Tests/PackageModelTests/DestinationTests.swift @@ -13,9 +13,10 @@ import Basics @testable import PackageModel @testable import SPMBuildCore -import TSCBasic import XCTest +import class TSCBasic.InMemoryFileSystem + private let bundleRootPath = try! AbsolutePath(validating: "/tmp/cross-toolchain") private let toolchainBinDir = RelativePath("swift.xctoolchain/usr/bin") private let sdkRootDir = RelativePath("ubuntu-jammy.sdk") @@ -253,9 +254,9 @@ private let parsedToolsetRootDestinationV3 = Destination( final class DestinationTests: XCTestCase { func testDestinationCodable() throws { let fs = InMemoryFileSystem() - try fs.createDirectory(.init(validating: "/tools")) - try fs.createDirectory(.init(validating: "/tmp")) - try fs.createDirectory(.init(validating: "\(bundleRootPath)")) + try fs.createDirectory(AbsolutePath(validating: "/tools")) + try fs.createDirectory(AbsolutePath(validating: "/tmp")) + try fs.createDirectory(AbsolutePath(validating: "\(bundleRootPath)")) for testFile in [ destinationV1, destinationV2, diff --git a/Tests/PackageModelTests/MinimumDeploymentTargetTests.swift b/Tests/PackageModelTests/MinimumDeploymentTargetTests.swift index 8b47a46e2e9..42828726b2b 100644 --- a/Tests/PackageModelTests/MinimumDeploymentTargetTests.swift +++ b/Tests/PackageModelTests/MinimumDeploymentTargetTests.swift @@ -10,10 +10,10 @@ // //===----------------------------------------------------------------------===// -import TSCBasic +@testable import PackageModel import XCTest -@testable import PackageModel +import struct TSCBasic.ProcessResult class MinimumDeploymentTargetTests: XCTestCase { func testDoesNotAssertWithNoOutput() throws { diff --git a/Tests/PackageModelTests/PackageIdentityNameTests.swift b/Tests/PackageModelTests/PackageIdentityNameTests.swift index 048c0dc6cc1..f15f282eb37 100644 --- a/Tests/PackageModelTests/PackageIdentityNameTests.swift +++ b/Tests/PackageModelTests/PackageIdentityNameTests.swift @@ -12,7 +12,6 @@ import XCTest import Basics -import TSCBasic import PackageModel class PackageIdentityNameTests: XCTestCase { diff --git a/Tests/PackageModelTests/PackageIdentityParser.swift b/Tests/PackageModelTests/PackageIdentityParser.swift index 95a35a669cd..99fa9e3341b 100644 --- a/Tests/PackageModelTests/PackageIdentityParser.swift +++ b/Tests/PackageModelTests/PackageIdentityParser.swift @@ -12,8 +12,6 @@ import XCTest -import TSCBasic - @testable import PackageModel final class PackageIdentityParserTests: XCTestCase { diff --git a/Tests/PackageModelTests/PackageIdentityScopeTests.swift b/Tests/PackageModelTests/PackageIdentityScopeTests.swift index 1504b4e0ad9..8e2b239e3c7 100644 --- a/Tests/PackageModelTests/PackageIdentityScopeTests.swift +++ b/Tests/PackageModelTests/PackageIdentityScopeTests.swift @@ -12,7 +12,6 @@ import XCTest import Basics -import TSCBasic import PackageModel class PackageIdentityScopeTests: XCTestCase { diff --git a/Tests/PackageModelTests/PackageModelTests.swift b/Tests/PackageModelTests/PackageModelTests.swift index ffb9dfc23bb..5cbbd707d02 100644 --- a/Tests/PackageModelTests/PackageModelTests.swift +++ b/Tests/PackageModelTests/PackageModelTests.swift @@ -12,9 +12,11 @@ import Basics @testable import PackageModel -import TSCBasic +import func TSCBasic.withTemporaryFile import XCTest +import struct TSCBasic.ByteString + class PackageModelTests: XCTestCase { func testProductTypeCodable() throws { struct Foo: Codable, Equatable { @@ -95,7 +97,7 @@ class PackageModelTests: XCTestCase { #endif let triple = try Triple("x86_64-unknown-windows-msvc") - let fs = TSCBasic.localFileSystem + let fs = localFileSystem try withTemporaryFile { [contents] _ in try withTemporaryDirectory(removeTreeOnDeinit: true) { [contents] tmp in diff --git a/Tests/PackageModelTests/SnippetTests.swift b/Tests/PackageModelTests/SnippetTests.swift index bcff0d74c45..634fe2e22c4 100644 --- a/Tests/PackageModelTests/SnippetTests.swift +++ b/Tests/PackageModelTests/SnippetTests.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// +import Basics @testable import PackageModel -import TSCBasic import XCTest class SnippetTests: XCTestCase { diff --git a/Tests/PackageModelTests/SwiftLanguageVersionTests.swift b/Tests/PackageModelTests/SwiftLanguageVersionTests.swift index dbebec74c0f..d0aa8ea7d51 100644 --- a/Tests/PackageModelTests/SwiftLanguageVersionTests.swift +++ b/Tests/PackageModelTests/SwiftLanguageVersionTests.swift @@ -12,8 +12,6 @@ import XCTest -import TSCBasic - import PackageModel class SwiftLanguageVersionTests: XCTestCase { diff --git a/Tests/PackageModelTests/SwiftSDKBundleTests.swift b/Tests/PackageModelTests/SwiftSDKBundleTests.swift index 1bf3cecda26..f5a1085df3a 100644 --- a/Tests/PackageModelTests/SwiftSDKBundleTests.swift +++ b/Tests/PackageModelTests/SwiftSDKBundleTests.swift @@ -15,7 +15,6 @@ import PackageModel import SPMTestSupport import XCTest -import struct TSCBasic.AbsolutePath import struct TSCBasic.ByteString import class TSCBasic.InMemoryFileSystem diff --git a/Tests/PackageModelTests/ToolsetTests.swift b/Tests/PackageModelTests/ToolsetTests.swift index 61ad7b14dec..1ec328ed903 100644 --- a/Tests/PackageModelTests/ToolsetTests.swift +++ b/Tests/PackageModelTests/ToolsetTests.swift @@ -15,7 +15,6 @@ import Basics import SPMTestSupport import XCTest -import struct TSCBasic.AbsolutePath import class TSCBasic.InMemoryFileSystem private let usrBinTools = Dictionary(uniqueKeysWithValues: Toolset.KnownTool.allCases.map { @@ -99,7 +98,7 @@ private let someToolsWithRelativeRoot = ( final class ToolsetTests: XCTestCase { func testToolset() throws { let fileSystem = InMemoryFileSystem() - try fileSystem.createDirectory(.init(validating: "/tools")) + try fileSystem.createDirectory(AbsolutePath(validating: "/tools")) for testFile in [compilersNoRoot, noValidToolsNoRoot, unknownToolsNoRoot, otherToolsNoRoot, someToolsWithRoot, someToolsWithRelativeRoot] { try fileSystem.writeFileContents(testFile.path, data: .init(testFile.json.utf8)) } diff --git a/Tests/PackageRegistryTests/PackageSigningEntityTOFUTests.swift b/Tests/PackageRegistryTests/PackageSigningEntityTOFUTests.swift index fc2f247acc1..5df3496626f 100644 --- a/Tests/PackageRegistryTests/PackageSigningEntityTOFUTests.swift +++ b/Tests/PackageRegistryTests/PackageSigningEntityTOFUTests.swift @@ -17,7 +17,6 @@ import PackageModel @testable import PackageRegistry @testable import PackageSigning import SPMTestSupport -import TSCBasic import XCTest import struct TSCUtility.Version @@ -55,7 +54,7 @@ final class PackageSigningEntityTOFUTests: XCTestCase { // `signingEntity` meets requirement to be used for TOFU // (i.e., it's .recognized), so it should be saved to storage. - let packageSigners = try tsc_await { callback in + let packageSigners = try temp_await { callback in signingEntityStorage.get( package: package.underlying, observabilityScope: ObservabilitySystem.NOOP, @@ -92,7 +91,7 @@ final class PackageSigningEntityTOFUTests: XCTestCase { ) // `signingEntity` is nil, so it should not be saved to storage. - let packageSigners = try tsc_await { callback in + let packageSigners = try temp_await { callback in signingEntityStorage.get( package: package.underlying, observabilityScope: ObservabilitySystem.NOOP, @@ -133,7 +132,7 @@ final class PackageSigningEntityTOFUTests: XCTestCase { ) // `signingEntity` is not .recognized, so it should not be saved to storage. - let packageSigners = try tsc_await { callback in + let packageSigners = try temp_await { callback in signingEntityStorage.get( package: package.underlying, observabilityScope: ObservabilitySystem.NOOP, @@ -236,7 +235,7 @@ final class PackageSigningEntityTOFUTests: XCTestCase { } // Storage should not be updated - let packageSigners = try tsc_await { callback in + let packageSigners = try temp_await { callback in signingEntityStorage.get( package: package.underlying, observabilityScope: ObservabilitySystem.NOOP, @@ -303,7 +302,7 @@ final class PackageSigningEntityTOFUTests: XCTestCase { } // Storage should not be updated - let packageSigners = try tsc_await { callback in + let packageSigners = try temp_await { callback in signingEntityStorage.get( package: package.underlying, observabilityScope: ObservabilitySystem.NOOP, @@ -361,7 +360,7 @@ final class PackageSigningEntityTOFUTests: XCTestCase { } // Storage should not be updated - let packageSigners = try tsc_await { callback in + let packageSigners = try temp_await { callback in signingEntityStorage.get( package: package.underlying, observabilityScope: ObservabilitySystem.NOOP, @@ -414,7 +413,7 @@ final class PackageSigningEntityTOFUTests: XCTestCase { ) // Storage should be updated with version 1.1.1 added - let packageSigners = try tsc_await { callback in + let packageSigners = try temp_await { callback in signingEntityStorage.get( package: package.underlying, observabilityScope: ObservabilitySystem.NOOP, @@ -487,7 +486,7 @@ final class PackageSigningEntityTOFUTests: XCTestCase { } // Storage should not be updated - let packageSigners = try tsc_await { callback in + let packageSigners = try temp_await { callback in signingEntityStorage.get( package: package.underlying, observabilityScope: ObservabilitySystem.NOOP, @@ -555,7 +554,7 @@ final class PackageSigningEntityTOFUTests: XCTestCase { } // Storage should not be updated - let packageSigners = try tsc_await { callback in + let packageSigners = try temp_await { callback in signingEntityStorage.get( package: package.underlying, observabilityScope: ObservabilitySystem.NOOP, @@ -609,7 +608,7 @@ final class PackageSigningEntityTOFUTests: XCTestCase { ) // Storage should not be updated - let packageSigners = try tsc_await { callback in + let packageSigners = try temp_await { callback in signingEntityStorage.get( package: package.underlying, observabilityScope: ObservabilitySystem.NOOP, @@ -677,7 +676,7 @@ final class PackageSigningEntityTOFUTests: XCTestCase { } // Storage should not be updated - let packageSigners = try tsc_await { callback in + let packageSigners = try temp_await { callback in signingEntityStorage.get( package: package.underlying, observabilityScope: ObservabilitySystem.NOOP, @@ -740,7 +739,7 @@ final class PackageSigningEntityTOFUTests: XCTestCase { } // Storage should not be updated - let packageSigners = try tsc_await { callback in + let packageSigners = try temp_await { callback in signingEntityStorage.get( package: package.underlying, observabilityScope: ObservabilitySystem.NOOP, @@ -796,7 +795,7 @@ final class PackageSigningEntityTOFUTests: XCTestCase { ) // Storage should not be updated - let packageSigners = try tsc_await { callback in + let packageSigners = try temp_await { callback in signingEntityStorage.get( package: package.underlying, observabilityScope: ObservabilitySystem.NOOP, @@ -850,7 +849,7 @@ final class PackageSigningEntityTOFUTests: XCTestCase { ) // Storage should be updated with v2.0.0 added - let packageSigners = try tsc_await { callback in + let packageSigners = try temp_await { callback in signingEntityStorage.get( package: package.underlying, observabilityScope: ObservabilitySystem.NOOP, @@ -919,7 +918,7 @@ final class PackageSigningEntityTOFUTests: XCTestCase { ) // Storage should be updated with v2.0.0 added - let packageSigners = try tsc_await { callback in + let packageSigners = try temp_await { callback in signingEntityStorage.get( package: package.underlying, observabilityScope: ObservabilitySystem.NOOP, @@ -1003,7 +1002,7 @@ final class PackageSigningEntityTOFUTests: XCTestCase { } // Storage should not be updated - let packageSigners = try tsc_await { callback in + let packageSigners = try temp_await { callback in signingEntityStorage.get( package: package.underlying, observabilityScope: ObservabilitySystem.NOOP, @@ -1098,7 +1097,7 @@ extension PackageSigningEntityTOFU { signingEntity: SigningEntity?, observabilityScope: ObservabilityScope? = nil ) throws { - try tsc_await { + try temp_await { self.validate( registry: registry, package: package, diff --git a/Tests/PackageRegistryTests/PackageVersionChecksumTOFUTests.swift b/Tests/PackageRegistryTests/PackageVersionChecksumTOFUTests.swift index e92b49fc029..3dd1b87ae84 100644 --- a/Tests/PackageRegistryTests/PackageVersionChecksumTOFUTests.swift +++ b/Tests/PackageRegistryTests/PackageVersionChecksumTOFUTests.swift @@ -16,7 +16,6 @@ import PackageFingerprint import PackageModel @testable import PackageRegistry import SPMTestSupport -import TSCBasic import XCTest import struct TSCUtility.Version @@ -104,7 +103,7 @@ final class PackageVersionChecksumTOFUTests: XCTestCase { ) // Checksum should have been saved to storage - let fingerprint = try tsc_await { callback in + let fingerprint = try temp_await { callback in fingerprintStorage.get( package: identity, version: version, @@ -700,7 +699,7 @@ final class PackageVersionChecksumTOFUTests: XCTestCase { // Checksums should have been saved to storage do { - let fingerprint = try tsc_await { callback in + let fingerprint = try temp_await { callback in fingerprintStorage.get( package: identity, version: version, @@ -715,7 +714,7 @@ final class PackageVersionChecksumTOFUTests: XCTestCase { XCTAssertEqual("Package.swift checksum", fingerprint.value) } do { - let fingerprint = try tsc_await { callback in + let fingerprint = try temp_await { callback in fingerprintStorage.get( package: identity, version: version, @@ -942,7 +941,7 @@ extension PackageVersionChecksumTOFU { checksum: String, observabilityScope: ObservabilityScope? = nil ) throws { - try tsc_await { + try temp_await { self.validateSourceArchive( registry: registry, package: package, @@ -964,7 +963,7 @@ extension PackageVersionChecksumTOFU { checksum: String, observabilityScope: ObservabilityScope? = nil ) throws { - try tsc_await { + try temp_await { self.validateManifest( registry: registry, package: package, diff --git a/Tests/PackageRegistryTests/RegistryClientTests.swift b/Tests/PackageRegistryTests/RegistryClientTests.swift index 85dafa67222..4805995aafc 100644 --- a/Tests/PackageRegistryTests/RegistryClientTests.swift +++ b/Tests/PackageRegistryTests/RegistryClientTests.swift @@ -18,9 +18,11 @@ import PackageModel @testable import PackageRegistry import PackageSigning import SPMTestSupport -import TSCBasic import XCTest +import protocol TSCBasic.HashAlgorithm +import class TSCBasic.InMemoryFileSystem + import struct TSCUtility.Version final class RegistryClientTests: XCTestCase { @@ -2536,7 +2538,7 @@ final class RegistryClientTests: XCTestCase { XCTAssertEqual(contents.sorted(), [RegistryReleaseMetadataStorage.fileName, "Package.swift"].sorted()) // Expected checksum is not found in storage so the metadata API will be called - let fingerprint = try tsc_await { callback in + let fingerprint = try temp_await { callback in fingerprintStorage.get( package: identity, version: version, @@ -3819,7 +3821,7 @@ final class RegistryClientTests: XCTestCase { extension RegistryClient { fileprivate func getPackageMetadata(package: PackageIdentity) throws -> RegistryClient.PackageMetadata { - try tsc_await { + try temp_await { self.getPackageMetadata( package: package, observabilityScope: ObservabilitySystem.NOOP, @@ -3833,7 +3835,7 @@ extension RegistryClient { package: PackageIdentity, version: Version ) throws -> PackageVersionMetadata { - try tsc_await { + try temp_await { self.getPackageVersionMetadata( package: package, version: version, @@ -3860,7 +3862,7 @@ extension RegistryClient { version: Version, observabilityScope: ObservabilityScope = ObservabilitySystem.NOOP ) throws -> [String: (toolsVersion: ToolsVersion, content: String?)] { - try tsc_await { + try temp_await { self.getAvailableManifests( package: package, version: version, @@ -3877,7 +3879,7 @@ extension RegistryClient { customToolsVersion: ToolsVersion?, observabilityScope: ObservabilityScope = ObservabilitySystem.NOOP ) throws -> String { - try tsc_await { + try temp_await { self.getManifestContent( package: package, version: version, @@ -3896,7 +3898,7 @@ extension RegistryClient { destinationPath: AbsolutePath, observabilityScope: ObservabilityScope = ObservabilitySystem.NOOP ) throws { - try tsc_await { + try temp_await { self.downloadSourceArchive( package: package, version: version, @@ -3911,7 +3913,7 @@ extension RegistryClient { } fileprivate func lookupIdentities(scmURL: URL) throws -> Set { - try tsc_await { + try temp_await { self.lookupIdentities( scmURL: scmURL, observabilityScope: ObservabilitySystem.NOOP, @@ -3922,7 +3924,7 @@ extension RegistryClient { } fileprivate func login(loginURL: URL) throws { - try tsc_await { + try temp_await { self.login( loginURL: loginURL, observabilityScope: ObservabilitySystem.NOOP, @@ -3943,7 +3945,7 @@ extension RegistryClient { signatureFormat: SignatureFormat?, fileSystem: FileSystem ) throws -> RegistryClient.PublishResult { - try tsc_await { + try temp_await { self.publish( registryURL: registryURL, packageIdentity: packageIdentity, @@ -3962,7 +3964,7 @@ extension RegistryClient { } func checkAvailability(registry: Registry) throws -> AvailabilityStatus { - try tsc_await { + try temp_await { self.checkAvailability( registry: registry, observabilityScope: ObservabilitySystem.NOOP, diff --git a/Tests/PackageRegistryTests/RegistryDownloadsManagerTests.swift b/Tests/PackageRegistryTests/RegistryDownloadsManagerTests.swift index f6ec962cb00..3d09927deeb 100644 --- a/Tests/PackageRegistryTests/RegistryDownloadsManagerTests.swift +++ b/Tests/PackageRegistryTests/RegistryDownloadsManagerTests.swift @@ -15,9 +15,10 @@ import PackageModel import PackageLoading @testable import PackageRegistry import SPMTestSupport -import TSCBasic import XCTest +import class TSCBasic.InMemoryFileSystem + import struct TSCUtility.Version class RegistryDownloadsManagerTests: XCTestCase { @@ -419,7 +420,7 @@ private class MockRegistryDownloadsManagerDelegate: RegistryDownloadsManagerDele extension RegistryDownloadsManager { fileprivate func lookup(package: PackageIdentity, version: Version, observabilityScope: ObservabilityScope) throws -> AbsolutePath { - return try tsc_await { + return try temp_await { self.lookup( package: package, version: version, diff --git a/Tests/PackageRegistryTests/SignatureValidationTests.swift b/Tests/PackageRegistryTests/SignatureValidationTests.swift index 4efb5d7b6d8..3aeee90812c 100644 --- a/Tests/PackageRegistryTests/SignatureValidationTests.swift +++ b/Tests/PackageRegistryTests/SignatureValidationTests.swift @@ -16,7 +16,6 @@ import PackageModel @testable import PackageRegistry import PackageSigning import SPMTestSupport -import TSCBasic import X509 // FIXME: need this import or else SwiftSigningIdentity init crashes import XCTest @@ -550,7 +549,7 @@ final class SignatureValidationTests: XCTestCase { let metadataURL = URL("\(registryURL)/\(package.scope)/\(package.name)/\(version)") let checksum = "a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812" - let keyAndCertChain = try tsc_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } let signingIdentity = try SwiftSigningIdentity( derEncodedCertificate: keyAndCertChain.leafCertificate, derEncodedPrivateKey: keyAndCertChain.privateKey, @@ -630,7 +629,7 @@ final class SignatureValidationTests: XCTestCase { let metadataURL = URL("\(registryURL)/\(package.scope)/\(package.name)/\(version)") let checksum = "a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812" - let keyAndCertChain = try tsc_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } let signingIdentity = try SwiftSigningIdentity( derEncodedCertificate: keyAndCertChain.leafCertificate, derEncodedPrivateKey: keyAndCertChain.privateKey, @@ -719,7 +718,7 @@ final class SignatureValidationTests: XCTestCase { let metadataURL = URL("\(registryURL)/\(package.scope)/\(package.name)/\(version)") let checksum = "a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812" - let keyAndCertChain = try tsc_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } let signingIdentity = try SwiftSigningIdentity( derEncodedCertificate: keyAndCertChain.leafCertificate, derEncodedPrivateKey: keyAndCertChain.privateKey, @@ -805,7 +804,7 @@ final class SignatureValidationTests: XCTestCase { let metadataURL = URL("\(registryURL)/\(package.scope)/\(package.name)/\(version)") let checksum = "a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812" - let keyAndCertChain = try tsc_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } let signingIdentity = try SwiftSigningIdentity( derEncodedCertificate: keyAndCertChain.leafCertificate, derEncodedPrivateKey: keyAndCertChain.privateKey, @@ -1017,7 +1016,7 @@ final class SignatureValidationTests: XCTestCase { let metadataURL = URL("\(registryURL)/\(package.scope)/\(package.name)/\(version)") let checksum = "a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812" - let keyAndCertChain = try tsc_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } let signingIdentity = try SwiftSigningIdentity( derEncodedCertificate: keyAndCertChain.leafCertificate, derEncodedPrivateKey: keyAndCertChain.privateKey, @@ -1111,7 +1110,7 @@ final class SignatureValidationTests: XCTestCase { let metadataURL = URL("\(registryURL)/\(package.scope)/\(package.name)/\(version)") let checksum = "a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812" - let keyAndCertChain = try tsc_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } let signingIdentity = try SwiftSigningIdentity( derEncodedCertificate: keyAndCertChain.leafCertificate, derEncodedPrivateKey: keyAndCertChain.privateKey, @@ -1196,7 +1195,7 @@ final class SignatureValidationTests: XCTestCase { let metadataURL = URL("\(registryURL)/\(package.scope)/\(package.name)/\(version)") let checksum = "a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812" - let keyAndCertChain = try tsc_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } let signingIdentity = try SwiftSigningIdentity( derEncodedCertificate: keyAndCertChain.leafCertificate, derEncodedPrivateKey: keyAndCertChain.privateKey, @@ -1305,7 +1304,7 @@ final class SignatureValidationTests: XCTestCase { let metadataURL = URL("\(registryURL)/\(package.scope)/\(package.name)/\(version)") let checksum = "a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812" - let keyAndCertChain = try tsc_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } let signingIdentity = try SwiftSigningIdentity( derEncodedCertificate: keyAndCertChain.leafCertificate, derEncodedPrivateKey: keyAndCertChain.privateKey, @@ -1394,7 +1393,7 @@ final class SignatureValidationTests: XCTestCase { let metadataURL = URL("\(registryURL)/\(package.scope)/\(package.name)/\(version)") let checksum = "a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812" - let keyAndCertChain = try tsc_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } let signingIdentity = try SwiftSigningIdentity( derEncodedCertificate: keyAndCertChain.leafCertificate, derEncodedPrivateKey: keyAndCertChain.privateKey, @@ -1495,7 +1494,7 @@ final class SignatureValidationTests: XCTestCase { let metadataURL = URL("\(registryURL)/\(package.scope)/\(package.name)/\(version)") let checksum = "a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812" - let keyAndCertChain = try tsc_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } let signingIdentity = try SwiftSigningIdentity( derEncodedCertificate: keyAndCertChain.leafCertificate, derEncodedPrivateKey: keyAndCertChain.privateKey, @@ -1577,7 +1576,7 @@ final class SignatureValidationTests: XCTestCase { let metadataURL = URL("\(registryURL)/\(package.scope)/\(package.name)/\(version)") let checksum = "a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812" - let keyAndCertChain = try tsc_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } let signingIdentity = try SwiftSigningIdentity( derEncodedCertificate: keyAndCertChain.leafCertificate, derEncodedPrivateKey: keyAndCertChain.privateKey, @@ -1656,7 +1655,7 @@ final class SignatureValidationTests: XCTestCase { let metadataURL = URL("\(registryURL)/\(package.scope)/\(package.name)/\(version)") let checksum = "a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812" - let keyAndCertChain = try tsc_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } let signingIdentity = try SwiftSigningIdentity( derEncodedCertificate: keyAndCertChain.leafCertificate, derEncodedPrivateKey: keyAndCertChain.privateKey, @@ -1761,7 +1760,7 @@ final class SignatureValidationTests: XCTestCase { let metadataURL = URL("\(registryURL)/\(package.scope)/\(package.name)/\(version)") let checksum = "a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812" - let keyAndCertChain = try tsc_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } let signingIdentity = try SwiftSigningIdentity( derEncodedCertificate: keyAndCertChain.leafCertificate, derEncodedPrivateKey: keyAndCertChain.privateKey, @@ -1882,7 +1881,7 @@ final class SignatureValidationTests: XCTestCase { let metadataURL = URL("\(registryURL)/\(package.scope)/\(package.name)/\(version)") let checksum = "a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812" - let keyAndCertChain = try tsc_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } let signingIdentity = try SwiftSigningIdentity( derEncodedCertificate: keyAndCertChain.leafCertificate, derEncodedPrivateKey: keyAndCertChain.privateKey, @@ -2042,7 +2041,7 @@ extension SignatureValidation { configuration: RegistryConfiguration.Security.Signing, observabilityScope: ObservabilityScope? = nil ) throws -> SigningEntity? { - try tsc_await { + try temp_await { self.validate( registry: registry, package: package, @@ -2067,7 +2066,7 @@ extension SignatureValidation { configuration: RegistryConfiguration.Security.Signing, observabilityScope: ObservabilityScope? = nil ) throws -> SigningEntity? { - try tsc_await { + try temp_await { self.validate( registry: registry, package: package, @@ -2127,7 +2126,7 @@ private struct AcceptingSignatureValidationDelegate: SignatureValidation.Delegat extension PackageSigningEntityStorage { fileprivate func get(package: PackageIdentity) throws -> PackageSigners { - try tsc_await { + try temp_await { self.get( package: package, observabilityScope: ObservabilitySystem.NOOP, diff --git a/Tests/PackageSigningTests/FilePackageSigningEntityStorageTests.swift b/Tests/PackageSigningTests/FilePackageSigningEntityStorageTests.swift index 2f0d2b94068..936c805e8d8 100644 --- a/Tests/PackageSigningTests/FilePackageSigningEntityStorageTests.swift +++ b/Tests/PackageSigningTests/FilePackageSigningEntityStorageTests.swift @@ -16,9 +16,10 @@ import Basics import PackageModel @testable import PackageSigning import SPMTestSupport -import TSCBasic import XCTest +import class TSCBasic.InMemoryFileSystem + import struct TSCUtility.Version final class FilePackageSigningEntityStorageTests: XCTestCase { @@ -430,7 +431,7 @@ final class FilePackageSigningEntityStorageTests: XCTestCase { extension PackageSigningEntityStorage { fileprivate func get(package: PackageIdentity) throws -> PackageSigners { - try tsc_await { + try temp_await { self.get( package: package, observabilityScope: ObservabilitySystem.NOOP, @@ -446,7 +447,7 @@ extension PackageSigningEntityStorage { signingEntity: SigningEntity, origin: SigningEntity.Origin ) throws { - try tsc_await { + try temp_await { self.put( package: package, version: version, @@ -465,7 +466,7 @@ extension PackageSigningEntityStorage { signingEntity: SigningEntity, origin: SigningEntity.Origin ) throws { - try tsc_await { + try temp_await { self.add( package: package, version: version, @@ -484,7 +485,7 @@ extension PackageSigningEntityStorage { signingEntity: SigningEntity, origin: SigningEntity.Origin ) throws { - try tsc_await { + try temp_await { self.changeSigningEntityFromVersion( package: package, version: version, @@ -503,7 +504,7 @@ extension PackageSigningEntityStorage { signingEntity: SigningEntity, origin: SigningEntity.Origin ) throws { - try tsc_await { + try temp_await { self.changeSigningEntityForAllVersions( package: package, version: version, diff --git a/Tests/PackageSigningTests/SigningTests.swift b/Tests/PackageSigningTests/SigningTests.swift index 06e7ad01979..a0f8351e367 100644 --- a/Tests/PackageSigningTests/SigningTests.swift +++ b/Tests/PackageSigningTests/SigningTests.swift @@ -10,21 +10,19 @@ // //===----------------------------------------------------------------------===// -import Foundation -import XCTest - import _CryptoExtras // for RSA import Basics import Crypto +import Foundation @testable import PackageSigning import SPMTestSupport import SwiftASN1 -import func TSCBasic.tsc_await @testable import X509 // need internal APIs for OCSP testing +import XCTest final class SigningTests: XCTestCase { func testCMS1_0_0EndToEnd() async throws { - let keyAndCertChain = try tsc_await { self.ecTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.ecTestKeyAndCertChain(callback: $0) } let signingIdentity = SwiftSigningIdentity( certificate: try Certificate(keyAndCertChain.leafCertificate), privateKey: try Certificate @@ -68,7 +66,7 @@ final class SigningTests: XCTestCase { } func testCMSEndToEndWithECSigningIdentity() async throws { - let keyAndCertChain = try tsc_await { self.ecTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.ecTestKeyAndCertChain(callback: $0) } let signingIdentity = SwiftSigningIdentity( certificate: try Certificate(keyAndCertChain.leafCertificate), privateKey: try Certificate @@ -110,7 +108,7 @@ final class SigningTests: XCTestCase { } func testCMSEndToEndWithRSASigningIdentity() async throws { - let keyAndCertChain = try tsc_await { self.rsaTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.rsaTestKeyAndCertChain(callback: $0) } let signingIdentity = SwiftSigningIdentity( certificate: try Certificate(keyAndCertChain.leafCertificate), privateKey: try Certificate @@ -152,7 +150,7 @@ final class SigningTests: XCTestCase { } func testCMSWrongKeyTypeForSignatureAlgorithm() async throws { - let keyAndCertChain = try tsc_await { self.ecTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.ecTestKeyAndCertChain(callback: $0) } let signingIdentity = SwiftSigningIdentity( certificate: try Certificate(keyAndCertChain.leafCertificate), privateKey: try Certificate @@ -179,7 +177,7 @@ final class SigningTests: XCTestCase { } func testCMS1_0_0EndToEndWithSelfSignedCertificate() async throws { - let keyAndCertChain = try tsc_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } let signingIdentity = SwiftSigningIdentity( certificate: try Certificate(keyAndCertChain.leafCertificate), privateKey: try Certificate @@ -223,7 +221,7 @@ final class SigningTests: XCTestCase { } func testCMSEndToEndWithSelfSignedECSigningIdentity() async throws { - let keyAndCertChain = try tsc_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } let signingIdentity = SwiftSigningIdentity( certificate: try Certificate(keyAndCertChain.leafCertificate), privateKey: try Certificate @@ -265,7 +263,7 @@ final class SigningTests: XCTestCase { } func testCMSEndToEndWithSelfSignedRSASigningIdentity() async throws { - let keyAndCertChain = try tsc_await { self.rsaSelfSignedTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.rsaSelfSignedTestKeyAndCertChain(callback: $0) } let signingIdentity = SwiftSigningIdentity( certificate: try Certificate(keyAndCertChain.leafCertificate), privateKey: try Certificate @@ -324,7 +322,7 @@ final class SigningTests: XCTestCase { } func testCMSInvalidSignature() async throws { - let keyAndCertChain = try tsc_await { self.ecTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.ecTestKeyAndCertChain(callback: $0) } let signingIdentity = SwiftSigningIdentity( certificate: try Certificate(keyAndCertChain.leafCertificate), privateKey: try Certificate @@ -361,7 +359,7 @@ final class SigningTests: XCTestCase { } func testCMSUntrustedCertificate() async throws { - let keyAndCertChain = try tsc_await { self.ecTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.ecTestKeyAndCertChain(callback: $0) } let signingIdentity = SwiftSigningIdentity( certificate: try Certificate(keyAndCertChain.leafCertificate), privateKey: try Certificate @@ -397,7 +395,7 @@ final class SigningTests: XCTestCase { } func testCMSCheckCertificateValidityPeriod() async throws { - let keyAndCertChain = try tsc_await { self.ecTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.ecTestKeyAndCertChain(callback: $0) } let signingIdentity = SwiftSigningIdentity( certificate: try Certificate(keyAndCertChain.leafCertificate), privateKey: try Certificate @@ -591,7 +589,7 @@ final class SigningTests: XCTestCase { try XCTSkipIf(true) #endif - let keyAndCertChain = try tsc_await { rsaADPKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { rsaADPKeyAndCertChain(callback: $0) } let signingIdentity = SwiftSigningIdentity( certificate: try Certificate(keyAndCertChain.leafCertificate), privateKey: try Certificate @@ -654,7 +652,7 @@ final class SigningTests: XCTestCase { try XCTSkipIf(true) #endif - let keyAndCertChain = try tsc_await { ecADPKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { ecADPKeyAndCertChain(callback: $0) } let signingIdentity = SwiftSigningIdentity( certificate: try Certificate(keyAndCertChain.leafCertificate), privateKey: try Certificate @@ -882,7 +880,7 @@ final class SigningTests: XCTestCase { #endif func testCMS1_0_0ExtractSigningEntity() async throws { - let keyAndCertChain = try tsc_await { self.ecTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.ecTestKeyAndCertChain(callback: $0) } let signingIdentity = SwiftSigningIdentity( certificate: try Certificate(keyAndCertChain.leafCertificate), privateKey: try Certificate @@ -921,7 +919,7 @@ final class SigningTests: XCTestCase { } func testCMS1_0_0ExtractSigningEntityWithSelfSignedCertificate() async throws { - let keyAndCertChain = try tsc_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.ecSelfSignedTestKeyAndCertChain(callback: $0) } let signingIdentity = SwiftSigningIdentity( certificate: try Certificate(keyAndCertChain.leafCertificate), privateKey: try Certificate @@ -960,7 +958,7 @@ final class SigningTests: XCTestCase { } func testCMS1_0_0ExtractSigningEntityWithUntrustedCertificate() async throws { - let keyAndCertChain = try tsc_await { self.ecTestKeyAndCertChain(callback: $0) } + let keyAndCertChain = try temp_await { self.ecTestKeyAndCertChain(callback: $0) } let signingIdentity = SwiftSigningIdentity( certificate: try Certificate(keyAndCertChain.leafCertificate), privateKey: try Certificate diff --git a/Tests/PackageSigningTests/Utilities.swift b/Tests/PackageSigningTests/Utilities.swift index e323b99b262..6f5f7baefa7 100644 --- a/Tests/PackageSigningTests/Utilities.swift +++ b/Tests/PackageSigningTests/Utilities.swift @@ -10,10 +10,9 @@ // //===----------------------------------------------------------------------===// +import Basics import XCTest -import TSCBasic - func readFileContents( in basePath: AbsolutePath, pathComponents: String..., diff --git a/Tests/SPMBuildCoreTests/ArtifactsArchiveMetadataTests.swift b/Tests/SPMBuildCoreTests/ArtifactsArchiveMetadataTests.swift index 8d183e5a860..4e3690ef2f4 100644 --- a/Tests/SPMBuildCoreTests/ArtifactsArchiveMetadataTests.swift +++ b/Tests/SPMBuildCoreTests/ArtifactsArchiveMetadataTests.swift @@ -10,11 +10,11 @@ // //===----------------------------------------------------------------------===// +import Basics import PackageModel -import TSCBasic import XCTest -import struct Basics.Triple +import class TSCBasic.InMemoryFileSystem final class ArtifactsArchiveMetadataTests: XCTestCase { func testParseMetadata() throws { diff --git a/Tests/SPMBuildCoreTests/PluginInvocationTests.swift b/Tests/SPMBuildCoreTests/PluginInvocationTests.swift index c14fc027e2a..04300f12f1c 100644 --- a/Tests/SPMBuildCoreTests/PluginInvocationTests.swift +++ b/Tests/SPMBuildCoreTests/PluginInvocationTests.swift @@ -16,10 +16,11 @@ import PackageLoading import PackageModel @testable import SPMBuildCore import SPMTestSupport -import TSCBasic import Workspace import XCTest +import class TSCBasic.InMemoryFileSystem + import struct TSCUtility.SerializedDiagnostics class PluginInvocationTests: XCTestCase { @@ -284,7 +285,7 @@ class PluginInvocationTests: XCTestCase { // Load the root manifest. let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: []) - let rootManifests = try tsc_await { + let rootManifests = try temp_await { workspace.loadRootManifests( packages: rootInput.packages, observabilityScope: observability.topScope, @@ -334,7 +335,7 @@ class PluginInvocationTests: XCTestCase { // Try to compile the broken plugin script. do { let delegate = Delegate() - let result = try tsc_await { + let result = try temp_await { pluginScriptRunner.compilePluginScript( sourceFiles: buildToolPlugin.sources.paths, pluginName: buildToolPlugin.name, @@ -388,7 +389,7 @@ class PluginInvocationTests: XCTestCase { let firstExecModTime: Date do { let delegate = Delegate() - let result = try tsc_await { + let result = try temp_await { pluginScriptRunner.compilePluginScript( sourceFiles: buildToolPlugin.sources.paths, pluginName: buildToolPlugin.name, @@ -440,7 +441,7 @@ class PluginInvocationTests: XCTestCase { let secondExecModTime: Date do { let delegate = Delegate() - let result = try tsc_await { + let result = try temp_await { pluginScriptRunner.compilePluginScript( sourceFiles: buildToolPlugin.sources.paths, pluginName: buildToolPlugin.name, @@ -499,7 +500,7 @@ class PluginInvocationTests: XCTestCase { let thirdExecModTime: Date do { let delegate = Delegate() - let result = try tsc_await { + let result = try temp_await { pluginScriptRunner.compilePluginScript( sourceFiles: buildToolPlugin.sources.paths, pluginName: buildToolPlugin.name, @@ -554,7 +555,7 @@ class PluginInvocationTests: XCTestCase { // Recompile the plugin again. do { let delegate = Delegate() - let result = try tsc_await { + let result = try temp_await { pluginScriptRunner.compilePluginScript( sourceFiles: buildToolPlugin.sources.paths, pluginName: buildToolPlugin.name, @@ -669,7 +670,7 @@ class PluginInvocationTests: XCTestCase { // Load the root manifest. let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: []) - let rootManifests = try tsc_await { + let rootManifests = try temp_await { workspace.loadRootManifests( packages: rootInput.packages, observabilityScope: observability.topScope, @@ -748,7 +749,7 @@ class PluginInvocationTests: XCTestCase { // Load the root manifest. let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: []) - let rootManifests = try tsc_await { + let rootManifests = try temp_await { workspace.loadRootManifests( packages: rootInput.packages, observabilityScope: observability.topScope, @@ -858,7 +859,7 @@ class PluginInvocationTests: XCTestCase { // Load the root manifest. let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: []) - let rootManifests = try tsc_await { + let rootManifests = try temp_await { workspace.loadRootManifests( packages: rootInput.packages, observabilityScope: observability.topScope, @@ -1041,7 +1042,7 @@ class PluginInvocationTests: XCTestCase { // Load the root manifest. let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: []) - let rootManifests = try tsc_await { + let rootManifests = try temp_await { workspace.loadRootManifests( packages: rootInput.packages, observabilityScope: observability.topScope, @@ -1189,7 +1190,7 @@ class PluginInvocationTests: XCTestCase { // Load the root manifest. let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: []) - let rootManifests = try tsc_await { + let rootManifests = try temp_await { workspace.loadRootManifests( packages: rootInput.packages, observabilityScope: observability.topScope, diff --git a/Tests/SPMBuildCoreTests/XCFrameworkMetadataTests.swift b/Tests/SPMBuildCoreTests/XCFrameworkMetadataTests.swift index e086c0c4465..ccd2669d53a 100644 --- a/Tests/SPMBuildCoreTests/XCFrameworkMetadataTests.swift +++ b/Tests/SPMBuildCoreTests/XCFrameworkMetadataTests.swift @@ -11,9 +11,10 @@ //===----------------------------------------------------------------------===// import SPMBuildCore -import TSCBasic import XCTest +import class TSCBasic.InMemoryFileSystem + final class XCFrameworkMetadataTests: XCTestCase { func testParseFramework() throws { let fileSystem = InMemoryFileSystem(files: [ diff --git a/Tests/SourceControlTests/GitRepositoryProviderTests.swift b/Tests/SourceControlTests/GitRepositoryProviderTests.swift index 7e49667c317..ebe3a01eec6 100644 --- a/Tests/SourceControlTests/GitRepositoryProviderTests.swift +++ b/Tests/SourceControlTests/GitRepositoryProviderTests.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import TSCBasic +import Basics import SPMTestSupport @testable import SourceControl import XCTest diff --git a/Tests/SourceControlTests/GitRepositoryTests.swift b/Tests/SourceControlTests/GitRepositoryTests.swift index bd20c9c8de3..43a3fd46aec 100644 --- a/Tests/SourceControlTests/GitRepositoryTests.swift +++ b/Tests/SourceControlTests/GitRepositoryTests.swift @@ -10,12 +10,14 @@ // //===----------------------------------------------------------------------===// -import XCTest - -import TSCBasic +import Basics @testable import SourceControl - import SPMTestSupport +import XCTest + +import struct TSCBasic.FileSystemError +import func TSCBasic.makeDirectories +import class TSCBasic.Process import enum TSCUtility.Git @@ -262,7 +264,7 @@ class GitRepositoryTests: XCTestCase { } // Check read versus root. - XCTAssertThrows(FileSystemError(.isDirectory, .root)) { + XCTAssertThrows(FileSystemError(.isDirectory, AbsolutePath.root)) { _ = try view.readFileContents(.root) } diff --git a/Tests/SourceControlTests/InMemoryGitRepositoryTests.swift b/Tests/SourceControlTests/InMemoryGitRepositoryTests.swift index 6fad656b9d2..8b643ec8a4f 100644 --- a/Tests/SourceControlTests/InMemoryGitRepositoryTests.swift +++ b/Tests/SourceControlTests/InMemoryGitRepositoryTests.swift @@ -10,12 +10,12 @@ // //===----------------------------------------------------------------------===// -import XCTest - -import TSCBasic +import Basics import SourceControl - import SPMTestSupport +import XCTest + +import class TSCBasic.InMemoryFileSystem class InMemoryGitRepositoryTests: XCTestCase { func testBasics() throws { diff --git a/Tests/SourceControlTests/RepositoryManagerTests.swift b/Tests/SourceControlTests/RepositoryManagerTests.swift index 0b3e8cbc9fa..53fab206c83 100644 --- a/Tests/SourceControlTests/RepositoryManagerTests.swift +++ b/Tests/SourceControlTests/RepositoryManagerTests.swift @@ -14,9 +14,11 @@ import PackageModel import SPMTestSupport @testable import SourceControl -import TSCBasic import XCTest +import class TSCBasic.InMemoryFileSystem +import enum TSCBasic.ProcessEnv + class RepositoryManagerTests: XCTestCase { func testBasics() throws { let fs = localFileSystem @@ -135,7 +137,7 @@ class RepositoryManagerTests: XCTestCase { let fs = localFileSystem let observability = ObservabilitySystem.makeForTesting() - try fixture(name: "DependencyResolution/External/Simple") { fixturePath in + try fixture(name: "DependencyResolution/External/Simple") { (fixturePath: AbsolutePath) in let cachePath = fixturePath.appending("cache") let repositoriesPath = fixturePath.appending("repositories") let repo = RepositorySpecifier(path: fixturePath.appending("Foo")) @@ -590,7 +592,7 @@ extension RepositoryManager { } fileprivate func lookup(repository: RepositorySpecifier, skipUpdate: Bool = false, observabilityScope: ObservabilityScope) throws -> RepositoryHandle { - return try tsc_await { + return try temp_await { self.lookup( package: .init(url: repository.url), repository: repository, diff --git a/Tests/WorkspaceTests/AuthorizationProviderTests.swift b/Tests/WorkspaceTests/AuthorizationProviderTests.swift index dfe169fc064..07c9116bed8 100644 --- a/Tests/WorkspaceTests/AuthorizationProviderTests.swift +++ b/Tests/WorkspaceTests/AuthorizationProviderTests.swift @@ -12,18 +12,18 @@ @testable import Basics import SPMTestSupport -import TSCBasic -import TSCUtility import Workspace import XCTest +import class TSCBasic.InMemoryFileSystem + final class AuthorizationProviderTests: XCTestCase { func testNetrcAuthorizationProviders() throws { let observability = ObservabilitySystem.makeForTesting() // custom .netrc file do { - let fileSystem = InMemoryFileSystem() + let fileSystem: FileSystem = InMemoryFileSystem() let customPath = try fileSystem.homeDirectory.appending(components: UUID().uuidString, "custom-netrc-file") try fileSystem.createDirectory(customPath.parentDirectory, recursive: true) @@ -87,7 +87,7 @@ final class AuthorizationProviderTests: XCTestCase { // custom .netrc file do { - let fileSystem = InMemoryFileSystem() + let fileSystem: FileSystem = InMemoryFileSystem() let customPath = try fileSystem.homeDirectory.appending(components: UUID().uuidString, "custom-netrc-file") try fileSystem.createDirectory(customPath.parentDirectory, recursive: true) diff --git a/Tests/WorkspaceTests/InitTests.swift b/Tests/WorkspaceTests/InitTests.swift index 67ebca698dd..6113c41f10d 100644 --- a/Tests/WorkspaceTests/InitTests.swift +++ b/Tests/WorkspaceTests/InitTests.swift @@ -10,11 +10,11 @@ // //===----------------------------------------------------------------------===// -import XCTest +import Basics import SPMTestSupport -import TSCBasic import PackageModel import Workspace +import XCTest class InitTests: XCTestCase { diff --git a/Tests/WorkspaceTests/ManifestSourceGenerationTests.swift b/Tests/WorkspaceTests/ManifestSourceGenerationTests.swift index d06aa0e1049..ee416aa66b8 100644 --- a/Tests/WorkspaceTests/ManifestSourceGenerationTests.swift +++ b/Tests/WorkspaceTests/ManifestSourceGenerationTests.swift @@ -15,7 +15,6 @@ import PackageGraph import PackageLoading import PackageModel import SPMTestSupport -import TSCBasic import Workspace import XCTest @@ -53,7 +52,7 @@ class ManifestSourceGenerationTests: XCTestCase { try fs.writeFileContents(manifestPath, string: manifestContents) let manifestLoader = ManifestLoader(toolchain: try UserToolchain.default) let identityResolver = DefaultIdentityResolver() - let manifest = try tsc_await { + let manifest = try temp_await { manifestLoader.load( manifestPath: manifestPath, manifestToolsVersion: toolsVersion, @@ -84,7 +83,7 @@ class ManifestSourceGenerationTests: XCTestCase { // Write out the generated manifest to replace the old manifest file contents, and load it again. try fs.writeFileContents(manifestPath, string: newContents) - let newManifest = try tsc_await { + let newManifest = try temp_await { manifestLoader.load( manifestPath: manifestPath, manifestToolsVersion: toolsVersion, diff --git a/Tests/WorkspaceTests/MirrorsConfigurationTests.swift b/Tests/WorkspaceTests/MirrorsConfigurationTests.swift index 8660cc9d9aa..9a5050708cb 100644 --- a/Tests/WorkspaceTests/MirrorsConfigurationTests.swift +++ b/Tests/WorkspaceTests/MirrorsConfigurationTests.swift @@ -10,11 +10,13 @@ // //===----------------------------------------------------------------------===// +import Basics import SPMTestSupport -import TSCBasic import Workspace import XCTest +import class TSCBasic.InMemoryFileSystem + final class MirrorsConfigurationTests: XCTestCase { func testLoadingSchema1() throws { let fs = InMemoryFileSystem() diff --git a/Tests/WorkspaceTests/PinsStoreTests.swift b/Tests/WorkspaceTests/PinsStoreTests.swift index 6e631f9d395..99d1f39a0d7 100644 --- a/Tests/WorkspaceTests/PinsStoreTests.swift +++ b/Tests/WorkspaceTests/PinsStoreTests.swift @@ -10,14 +10,15 @@ // //===----------------------------------------------------------------------===// -import XCTest - -import TSCBasic +import Basics import PackageModel import PackageGraph import SPMTestSupport import SourceControl import Workspace +import XCTest + +import class TSCBasic.InMemoryFileSystem import struct TSCUtility.Version diff --git a/Tests/WorkspaceTests/RegistryPackageContainerTests.swift b/Tests/WorkspaceTests/RegistryPackageContainerTests.swift index 2b1ab8378a5..598736b415f 100644 --- a/Tests/WorkspaceTests/RegistryPackageContainerTests.swift +++ b/Tests/WorkspaceTests/RegistryPackageContainerTests.swift @@ -17,10 +17,11 @@ import PackageLoading import PackageModel import PackageRegistry import SPMTestSupport -import TSCBasic @testable import Workspace import XCTest +import class TSCBasic.InMemoryFileSystem + import struct TSCUtility.Version class RegistryPackageContainerTests: XCTestCase { @@ -485,6 +486,6 @@ class RegistryPackageContainerTests: XCTestCase { extension PackageContainerProvider { fileprivate func getContainer(for package: PackageReference, skipUpdate: Bool) throws -> PackageContainer { - try tsc_await { self.getContainer(for: package, skipUpdate: skipUpdate, observabilityScope: ObservabilitySystem.NOOP, on: .global(), completion: $0) } + try temp_await { self.getContainer(for: package, skipUpdate: skipUpdate, observabilityScope: ObservabilitySystem.NOOP, on: .global(), completion: $0) } } } diff --git a/Tests/WorkspaceTests/SourceControlPackageContainerTests.swift b/Tests/WorkspaceTests/SourceControlPackageContainerTests.swift index 85371e662c1..4cb9b97663a 100644 --- a/Tests/WorkspaceTests/SourceControlPackageContainerTests.swift +++ b/Tests/WorkspaceTests/SourceControlPackageContainerTests.swift @@ -17,10 +17,11 @@ import PackageLoading import PackageModel import SourceControl import SPMTestSupport -import TSCBasic @testable import Workspace import XCTest +import class TSCBasic.InMemoryFileSystem + import enum TSCUtility.Git import struct TSCUtility.Version @@ -683,7 +684,7 @@ class SourceControlPackageContainerTests: XCTestCase { extension PackageContainerProvider { fileprivate func getContainer(for package: PackageReference, skipUpdate: Bool) throws -> PackageContainer { - try tsc_await { self.getContainer(for: package, skipUpdate: skipUpdate, observabilityScope: ObservabilitySystem.NOOP, on: .global(), completion: $0) } + try temp_await { self.getContainer(for: package, skipUpdate: skipUpdate, observabilityScope: ObservabilitySystem.NOOP, on: .global(), completion: $0) } } } diff --git a/Tests/WorkspaceTests/ToolsVersionSpecificationRewriterTests.swift b/Tests/WorkspaceTests/ToolsVersionSpecificationRewriterTests.swift index 9ea91e5904c..b3265ae2add 100644 --- a/Tests/WorkspaceTests/ToolsVersionSpecificationRewriterTests.swift +++ b/Tests/WorkspaceTests/ToolsVersionSpecificationRewriterTests.swift @@ -14,11 +14,12 @@ /// This file tests `Workspace.rewriteToolsVersionSpecification(toDefaultManifestIn:specifying:fileSystem:)`. /// -import XCTest - -import TSCBasic +import Basics import PackageModel @testable import Workspace +import XCTest + +import class TSCBasic.InMemoryFileSystem /// Test cases for `rewriteToolsVersionSpecification(toDefaultManifestIn:specifying:fileSystem:)` class ToolsVersionSpecificationRewriterTests: XCTestCase { diff --git a/Tests/WorkspaceTests/WorkspaceStateTests.swift b/Tests/WorkspaceTests/WorkspaceStateTests.swift index 8b2da9a4902..a0d6ca66370 100644 --- a/Tests/WorkspaceTests/WorkspaceStateTests.swift +++ b/Tests/WorkspaceTests/WorkspaceStateTests.swift @@ -12,9 +12,10 @@ import Basics @testable import Workspace -import TSCBasic import XCTest +import class TSCBasic.InMemoryFileSystem + final class WorkspaceStateTests: XCTestCase { func testV4Format() throws { let fs = InMemoryFileSystem() diff --git a/Tests/WorkspaceTests/WorkspaceTests.swift b/Tests/WorkspaceTests/WorkspaceTests.swift index c4f7febeaa2..096440ff0d0 100644 --- a/Tests/WorkspaceTests/WorkspaceTests.swift +++ b/Tests/WorkspaceTests/WorkspaceTests.swift @@ -20,10 +20,12 @@ import PackageSigning import SourceControl import SPMBuildCore import SPMTestSupport -import TSCBasic @testable import Workspace import XCTest +import struct TSCBasic.ByteString +import class TSCBasic.InMemoryFileSystem + import enum TSCUtility.Diagnostics import struct TSCUtility.Version @@ -228,7 +230,7 @@ final class WorkspaceTests: XCTestCase { delegate: MockWorkspaceDelegate() ) let rootInput = PackageGraphRootInput(packages: [pkgDir], dependencies: []) - let rootManifests = try tsc_await { + let rootManifests = try temp_await { workspace.loadRootManifests( packages: rootInput.packages, observabilityScope: observability.topScope, @@ -4963,7 +4965,7 @@ final class WorkspaceTests: XCTestCase { ) // From here the API should be simple and straightforward: - let manifest = try tsc_await { + let manifest = try temp_await { workspace.loadRootManifest( at: packagePath, observabilityScope: observability.topScope, @@ -4973,7 +4975,7 @@ final class WorkspaceTests: XCTestCase { XCTAssertFalse(observability.hasWarningDiagnostics, observability.diagnostics.description) XCTAssertFalse(observability.hasErrorDiagnostics, observability.diagnostics.description) - let package = try tsc_await { + let package = try temp_await { workspace.loadRootPackage( at: packagePath, observabilityScope: observability.topScope, @@ -4994,7 +4996,7 @@ final class WorkspaceTests: XCTestCase { XCTAssertEqual(package.identity, .plain(manifest.displayName)) XCTAssert(graph.reachableProducts.contains(where: { $0.name == "MyPkg" })) - let reloadedPackage = try tsc_await { + let reloadedPackage = try temp_await { workspace.loadPackage( with: package.identity, packageGraph: graph, @@ -8519,7 +8521,7 @@ final class WorkspaceTests: XCTestCase { let observability = ObservabilitySystem.makeForTesting() let wks = try workspace.getOrCreateWorkspace() - XCTAssertNoThrow(try tsc_await { + XCTAssertNoThrow(try temp_await { wks.loadRootPackage( at: workspace.rootsDir.appending("Root"), observabilityScope: observability.topScope, @@ -13626,7 +13628,7 @@ final class WorkspaceTests: XCTestCase { XCTAssertNoDiagnostics(diagnostics) PackageGraphTester(graph) { result in guard let foo = result.find(package: "org.foo") else { - return XCTFail("missing pacakge") + return XCTFail("missing package") } XCTAssertNotNil(foo.registryMetadata, "expecting registry metadata") XCTAssertEqual(foo.registryMetadata?.source, .registry(registryURL)) diff --git a/Tests/XCBuildSupportTests/PIFBuilderTests.swift b/Tests/XCBuildSupportTests/PIFBuilderTests.swift index 6171aedc971..2b215ff9f45 100644 --- a/Tests/XCBuildSupportTests/PIFBuilderTests.swift +++ b/Tests/XCBuildSupportTests/PIFBuilderTests.swift @@ -17,10 +17,13 @@ import PackageGraph import PackageLoading import SPMBuildCore import SPMTestSupport -import TSCBasic @testable import XCBuildSupport import XCTest +import class TSCBasic.InMemoryFileSystem + +import func TSCTestSupport.withCustomEnv + class PIFBuilderTests: XCTestCase { let inputsDir = AbsolutePath(#file).parentDirectory.appending(components: "Inputs") diff --git a/Tests/XCBuildSupportTests/PIFTests.swift b/Tests/XCBuildSupportTests/PIFTests.swift index c0b7175136b..f43385fe89e 100644 --- a/Tests/XCBuildSupportTests/PIFTests.swift +++ b/Tests/XCBuildSupportTests/PIFTests.swift @@ -12,12 +12,13 @@ import XCTest import Basics -import TSCBasic import PackageModel import SPMBuildCore import XCBuildSupport import SPMTestSupport +import enum TSCBasic.JSON + class PIFTests: XCTestCase { let topLevelObject = PIF.TopLevelObject(workspace: PIF.Workspace(