1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
|
/*
This source file is part of the Swift.org open source project
Copyright (c) 2021-2024 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
See https://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Foundation
import XCTest
@testable import SwiftDocC
/// A Data provider and file manager that accepts pre-built documentation bundles with files on the local filesystem.
///
/// `TestFileSystem` is a file manager that keeps a directory structure in memory including the file data
/// for fast access without hitting the disk. When you create an instance pass all folders to the initializer like so:
/// ```swift
/// let bundle = Folder(name: "unit-test.docc", content: [
/// ... files ...
/// ])
///
/// let testDataProvider = try TestFileSystem(
/// folders: [bundle, Folder.emptyHTMLTemplateDirectory]
/// )
/// ```
/// This will create or copy from disk the `folders` list and you can use the data provider
/// as a `FileManagerProtocol` and `DocumentationWorkspaceDataProvider`.
///
/// ## Expectations
/// This is a simplistic file system implementation aiming to satisfy our current unit test needs.
/// Care was taken that it mimics real file system behavior but if discrepancies are found while adding new tests
/// we will have to make adjustments.
///
/// Aspects of the current implementation worth noting:
/// 1. The in-memory file system is case sensitive (much like Linux)
/// 2. No support for file links
/// 3. No support for relative paths or traversing the tree upwards (e.g. "/root/nested/../other" will not resolve)
///
/// - Note: This class is thread-safe by using a naive locking for each access to the files dictionary.
/// - Warning: Use this type for unit testing.
package class TestFileSystem: FileManagerProtocol, DocumentationWorkspaceDataProvider {
package let currentDirectoryPath = "/"
package var identifier: String = UUID().uuidString
private var _bundles = [DocumentationBundle]()
package func bundles(options: BundleDiscoveryOptions) throws -> [DocumentationBundle] {
// Ignore the bundle discovery options, these test bundles are already built.
return _bundles
}
/// Thread safe access to the file system.
private var filesLock = NSRecursiveLock()
/// A plain index of paths and their contents.
var files = [String: Data]()
/// Set to `true` to disable write operations for folders and files.
/// For example use this for large conversions when the output is not of interest.
var disableWriting = false
/// A data fixture to use in the `files` index to mark folders.
static let folderFixtureData = "Folder".data(using: .utf8)!
package convenience init(folders: [Folder]) throws {
self.init()
// Default system paths
files["/"] = Self.folderFixtureData
files["/tmp"] = Self.folderFixtureData
// Import given folders
try updateDocumentationBundles(withFolders: folders)
}
func updateDocumentationBundles(withFolders folders: [Folder]) throws {
_bundles.removeAll()
for folder in folders {
let files = try addFolder(folder)
func asCatalog(_ file: File) -> Folder? {
if let folder = file as? Folder, URL(fileURLWithPath: folder.name).pathExtension == "docc" {
return folder
}
return nil
}
if let catalog = asCatalog(folder) ?? folder.recursiveContent.mapFirst(where: asCatalog(_:)) {
let files = files.filter({ $0.hasPrefix(catalog.absoluteURL.path) }).compactMap({ URL(fileURLWithPath: $0) })
let markupFiles = files.filter({ DocumentationBundleFileTypes.isMarkupFile($0) })
let miscFiles = files.filter({ !DocumentationBundleFileTypes.isMarkupFile($0) })
let graphs = files.filter({ DocumentationBundleFileTypes.isSymbolGraphFile($0) })
let customHeader = files.first(where: { DocumentationBundleFileTypes.isCustomHeader($0) })
let customFooter = files.first(where: { DocumentationBundleFileTypes.isCustomFooter($0) })
let info = try DocumentationBundle.Info(
from: try catalog.recursiveContent.mapFirst(where: { $0 as? InfoPlist })?.data(),
bundleDiscoveryOptions: nil,
derivedDisplayName: URL(fileURLWithPath: catalog.name).deletingPathExtension().lastPathComponent
)
let bundle = DocumentationBundle(
info: info,
symbolGraphURLs: graphs,
markupURLs: markupFiles,
miscResourceURLs: miscFiles,
customHeader: customHeader,
customFooter: customFooter
)
_bundles.append(bundle)
}
}
}
package func contentsOfURL(_ url: URL) throws -> Data {
filesLock.lock()
defer { filesLock.unlock() }
guard let file = files[url.path] else {
throw makeFileNotFoundError(url)
}
return file
}
package func contents(of url: URL) throws -> Data {
try contentsOfURL(url)
}
func filesIn(folder: Folder, at: URL) throws -> [String: Data] {
filesLock.lock()
defer { filesLock.unlock() }
var result = [String: Data]()
for file in folder.content {
switch file {
case let folder as Folder:
result[at.appendingPathComponent(folder.name).path] = Self.folderFixtureData
result.merge(try filesIn(folder: folder, at: at.appendingPathComponent(folder.name)), uniquingKeysWith: +)
case let file as File & DataRepresentable:
result[at.appendingPathComponent(file.name).path] = try file.data()
if let copy = file as? CopyOfFile {
result[copy.original.path] = try file.data()
}
default: break
}
}
return result
}
@discardableResult
func addFolder(_ folder: Folder) throws -> [String] {
guard !disableWriting else { return [] }
filesLock.lock()
defer { filesLock.unlock() }
let rootURL = URL(fileURLWithPath: "/\(folder.name)")
files[rootURL.path] = Self.folderFixtureData
let fileList = try filesIn(folder: folder, at: rootURL)
files.merge(fileList, uniquingKeysWith: +)
return Array(fileList.keys)
}
package func fileExists(atPath path: String, isDirectory: UnsafeMutablePointer<ObjCBool>?) -> Bool {
filesLock.lock()
defer { filesLock.unlock() }
guard let data = files[path] else {
isDirectory?.initialize(to: ObjCBool(false))
return false
}
isDirectory?.initialize(to: data == Self.folderFixtureData ? ObjCBool(true) : ObjCBool(false))
return true
}
package func fileExists(atPath path: String) -> Bool {
filesLock.lock()
defer { filesLock.unlock() }
return files.keys.contains(path)
}
package func copyItem(at srcURL: URL, to dstURL: URL) throws {
guard !disableWriting else { return }
filesLock.lock()
defer { filesLock.unlock() }
try ensureParentDirectoryExists(for: dstURL)
let srcPath = srcURL.path
let dstPath = dstURL.path
files[dstPath] = files[srcPath]
for (path, data) in files where path.hasPrefix(srcPath) {
files[path.replacingOccurrences(of: srcPath, with: dstPath)] = data
}
}
package func moveItem(at srcURL: URL, to dstURL: URL) throws {
guard !disableWriting else { return }
filesLock.lock()
defer { filesLock.unlock() }
let srcPath = srcURL.path
try copyItem(at: srcURL, to: dstURL)
files.removeValue(forKey: srcPath)
for (path, _) in files where path.hasPrefix(srcPath) {
files.removeValue(forKey: path)
}
}
func createDirectory(atPath path: String, withIntermediateDirectories createIntermediates: Bool, attributes: [FileAttributeKey : Any]? = nil) throws {
guard !disableWriting else { return }
filesLock.lock()
defer { filesLock.unlock() }
let url = URL(fileURLWithPath: path)
let parent = url.deletingLastPathComponent()
if parent.pathComponents.count > 1 {
// If it's not the root folder, check if parents exist
if createIntermediates == false {
try ensureParentDirectoryExists(for: url)
} else {
// Create missing parent directories
try createDirectory(atPath: parent.path, withIntermediateDirectories: true)
}
}
files[path] = Self.folderFixtureData
}
package func createDirectory(at url: URL, withIntermediateDirectories createIntermediates: Bool, attributes: [FileAttributeKey : Any]? = nil) throws {
guard !disableWriting else { return }
filesLock.lock()
defer { filesLock.unlock() }
try createDirectory(atPath: url.path, withIntermediateDirectories: createIntermediates)
}
package func contentsEqual(atPath path1: String, andPath path2: String) -> Bool {
filesLock.lock()
defer { filesLock.unlock() }
return files[path1] == files[path2]
}
package func removeItem(at: URL) throws {
guard !disableWriting else { return }
filesLock.lock()
defer { filesLock.unlock() }
files.removeValue(forKey: at.path)
for (path, _) in files where path.hasPrefix(at.path) {
files.removeValue(forKey: path)
}
}
package func createFile(at url: URL, contents: Data) throws {
filesLock.lock()
defer { filesLock.unlock() }
try ensureParentDirectoryExists(for: url)
if !disableWriting {
files[url.path] = contents
}
}
package func createFile(at url: URL, contents: Data, options: NSData.WritingOptions?) throws {
try createFile(at: url, contents: contents)
}
package func contents(atPath: String) -> Data? {
filesLock.lock()
defer { filesLock.unlock() }
return files[atPath]
}
package func contentsOfDirectory(atPath path: String) throws -> [String] {
filesLock.lock()
defer { filesLock.unlock() }
var results = Set<String>()
let path = path.appendingTrailingSlash
for subpath in files.keys where subpath.hasPrefix(path) {
let relativePath = subpath.dropFirst(path.count).removingLeadingSlash
guard !relativePath.isEmpty else { continue }
// only need to split twice because we only care about the first component and about identifying multiple components
let pathParts = relativePath.split(separator: "/", maxSplits: 2)
if pathParts.count == 1 {
results.insert(String(pathParts[0]))
}
}
return Array(results)
}
package func contentsOfDirectory(at url: URL, includingPropertiesForKeys keys: [URLResourceKey]?, options mask: FileManager.DirectoryEnumerationOptions) throws -> [URL] {
if let keys {
XCTAssertTrue(keys.isEmpty, "includingPropertiesForKeys is not implemented in contentsOfDirectory in TestFileSystem")
}
if !mask.isSubset(of: [.skipsHiddenFiles]) {
XCTFail("The given directory enumeration option(s) \(mask.rawValue) have not been implemented in the test file system: \(mask)")
}
let skipHiddenFiles = mask == .skipsHiddenFiles
let contents = try contentsOfDirectory(atPath: url.path)
let output: [URL] = contents.filter({ skipHiddenFiles ? !$0.hasPrefix(".") : true}).map {
url.appendingPathComponent($0)
}
return output
}
package func uniqueTemporaryDirectory() -> URL {
URL(fileURLWithPath: "/tmp/\(ProcessInfo.processInfo.globallyUniqueString)", isDirectory: true)
}
enum Errors: DescribedError {
case invalidPath(String)
var errorDescription: String {
switch self {
case .invalidPath(let path): return "Invalid path \(path.singleQuoted)"
}
}
}
/// Returns a stable string representation of the file system from a given subpath.
///
/// - Parameter path: The path to the sub hierarchy to dump to a string representation.
/// - Returns: A stable string representation that can be checked in tests.
package func dump(subHierarchyFrom path: String = "/") -> String {
filesLock.lock()
defer { filesLock.unlock() }
let relevantFilePaths: [String]
if path == "/" {
relevantFilePaths = Array(files.keys)
} else {
let lengthToRemove = path.distance(from: path.startIndex, to: path.lastIndex(of: "/")!) + 1
relevantFilePaths = files.keys
.filter { $0.hasPrefix(path) }
.map { String($0.dropFirst(lengthToRemove)) }
}
return Folder.makeStructure(
filePaths: relevantFilePaths,
isEmptyDirectoryCheck: { files[$0] == Self.folderFixtureData }
)
.map { $0.dump() }
.joined(separator: "\n")
}
// This is a convenience utility for testing, not FileManagerProtocol API
package func recursiveContentsOfDirectory(atPath path: String) throws -> [String] {
var allSubpaths = try contentsOfDirectory(atPath: path)
for subpath in allSubpaths { // This is iterating over a copy
let innerContents = try recursiveContentsOfDirectory(atPath: "\(path)/\(subpath)")
allSubpaths.append(contentsOf: innerContents.map({ "\(subpath)/\($0)" }))
}
return allSubpaths
}
private func ensureParentDirectoryExists(for url: URL) throws {
let parentURL = url.deletingLastPathComponent()
guard directoryExists(atPath: parentURL.path) else {
throw makeFileNotFoundError(parentURL)
}
}
private func makeFileNotFoundError(_ url: URL) -> Error {
return CocoaError(.fileReadNoSuchFile, userInfo: [NSFilePathErrorKey: url.path])
}
}
private extension File {
/// A URL of the file node if it was located in the root of the file system.
var absoluteURL: URL { return URL(string: "/\(name)")! }
}
|