|
| 1 | +/* |
| 2 | + This source file is part of the Swift.org open source project |
| 3 | + |
| 4 | + Copyright (c) 2021 Apple Inc. and the Swift project authors |
| 5 | + Licensed under Apache License v2.0 with Runtime Library Exception |
| 6 | + |
| 7 | + See http://swift.org/LICENSE.txt for license information |
| 8 | + See http://swift.org/CONTRIBUTORS.txt for Swift project authors |
| 9 | + */ |
| 10 | + |
| 11 | +import Basics |
| 12 | +import TSCBasic |
| 13 | +import TSCUtility |
| 14 | + |
| 15 | +import Dispatch |
| 16 | + |
| 17 | +/// An `Archiver` that handles source archives. |
| 18 | +/// |
| 19 | +/// Source archives created with `swift package archive-source` |
| 20 | +/// have a top-level directory prefix (for example, `LinkedList-1.1.1/`). |
| 21 | +/// Unfortunately, the `unzip` command used by `ZipArchiver` doesn't have an option for |
| 22 | +/// ignoring this top-level prefix. |
| 23 | +/// Rather than performing additional (possibly unsafe) file system operations, |
| 24 | +/// this `Archiver` delegates to `tar`, which has a built-in `--strip-components=` option. |
| 25 | +struct SourceArchiver: Archiver { |
| 26 | + public var supportedExtensions: Set<String> { ["zip"] } |
| 27 | + |
| 28 | + /// The file-system implementation used for various file-system operations and checks. |
| 29 | + private let fileSystem: FileSystem |
| 30 | + |
| 31 | + /// Creates a `SourceArchiver`. |
| 32 | + /// |
| 33 | + /// - Parameters: |
| 34 | + /// - fileSystem: The file-system to used by the `SourceArchiver`. |
| 35 | + public init(fileSystem: FileSystem = localFileSystem) { |
| 36 | + self.fileSystem = fileSystem |
| 37 | + } |
| 38 | + |
| 39 | + public func extract( |
| 40 | + from archivePath: AbsolutePath, |
| 41 | + to destinationPath: AbsolutePath, |
| 42 | + completion: @escaping (Result<Void, Error>) -> Void |
| 43 | + ) { |
| 44 | + guard fileSystem.exists(archivePath) else { |
| 45 | + completion(.failure(FileSystemError(.noEntry, archivePath))) |
| 46 | + return |
| 47 | + } |
| 48 | + |
| 49 | + guard fileSystem.isDirectory(destinationPath) else { |
| 50 | + completion(.failure(FileSystemError(.notDirectory, destinationPath))) |
| 51 | + return |
| 52 | + } |
| 53 | + |
| 54 | + // TODO: consider calling `libarchive` or some other library directly instead of spawning a process |
| 55 | + DispatchQueue.global(qos: .userInitiated).async { |
| 56 | + do { |
| 57 | + let result = try Process.popen(args: "bsdtar", |
| 58 | + "--strip-components=1", |
| 59 | + "-xvf", |
| 60 | + archivePath.pathString, |
| 61 | + "-C", destinationPath.pathString) |
| 62 | + guard result.exitStatus == .terminated(code: 0) else { |
| 63 | + throw try StringError(result.utf8stderrOutput()) |
| 64 | + } |
| 65 | + |
| 66 | + completion(.success(())) |
| 67 | + } catch { |
| 68 | + completion(.failure(error)) |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments