|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// Copyright © 2025 Apple Inc. and the container project authors. |
| 3 | +// |
| 4 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +// you may not use this file except in compliance with the License. |
| 6 | +// You may obtain a copy of the License at |
| 7 | +// |
| 8 | +// https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +// |
| 10 | +// Unless required by applicable law or agreed to in writing, software |
| 11 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +// See the License for the specific language governing permissions and |
| 14 | +// limitations under the License. |
| 15 | +//===----------------------------------------------------------------------===// |
| 16 | + |
| 17 | +import ArgumentParser |
| 18 | +import ContainerClient |
| 19 | +import Darwin |
| 20 | +import Foundation |
| 21 | + |
| 22 | +extension Application.VolumeCommand { |
| 23 | + struct VolumeCopy: AsyncParsableCommand { |
| 24 | + static let configuration = CommandConfiguration( |
| 25 | + commandName: "cp", |
| 26 | + abstract: "Copy files/folders between a container volume and the local filesystem" |
| 27 | + ) |
| 28 | + |
| 29 | + @Argument(help: "Source path (use volume:path for volume paths)") |
| 30 | + var source: String |
| 31 | + |
| 32 | + @Argument(help: "Destination path (use volume:path for volume paths)") |
| 33 | + var destination: String |
| 34 | + |
| 35 | + @Flag(name: .shortAndLong, help: "Copy recursively") |
| 36 | + var recursive: Bool = false |
| 37 | + |
| 38 | + func run() async throws { |
| 39 | + let (sourceVol, sourcePath) = parsePath(source) |
| 40 | + let (destVol, destPath) = parsePath(destination) |
| 41 | + |
| 42 | + try validatePaths(sourceVol, destVol) |
| 43 | + |
| 44 | + if let volName = sourceVol, let volPath = sourcePath { |
| 45 | + try await copyFromVolume(volume: volName, volumePath: volPath, localPath: destination) |
| 46 | + } else if let volName = destVol, let volPath = destPath { |
| 47 | + try await copyToVolume(volume: volName, volumePath: volPath, localPath: source) |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + private func validatePaths(_ sourceVol: String?, _ destVol: String?) throws { |
| 52 | + if sourceVol != nil && destVol != nil { |
| 53 | + throw ValidationError("copying between volumes is not supported") |
| 54 | + } |
| 55 | + if sourceVol == nil && destVol == nil { |
| 56 | + throw ValidationError("one path must be a volume path (use volume:path format)") |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + private func copyFromVolume(volume: String, volumePath: String, localPath: String) async throws { |
| 61 | + let localURL = URL(fileURLWithPath: localPath) |
| 62 | + let pipe = Pipe() |
| 63 | + |
| 64 | + let tempDir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) |
| 65 | + try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true) |
| 66 | + defer { try? FileManager.default.removeItem(at: tempDir) } |
| 67 | + |
| 68 | + let writeFD = dup(pipe.fileHandleForWriting.fileDescriptor) |
| 69 | + let writeHandle = FileHandle(fileDescriptor: writeFD, closeOnDealloc: true) |
| 70 | + |
| 71 | + try await withThrowingTaskGroup(of: Void.self) { group in |
| 72 | + group.addTask { |
| 73 | + defer { try? pipe.fileHandleForWriting.close() } |
| 74 | + try await ClientVolume.copyOut(volume: volume, path: volumePath, fileHandle: writeHandle) |
| 75 | + } |
| 76 | + group.addTask { |
| 77 | + try Archiver.uncompress(from: pipe.fileHandleForReading, to: tempDir) |
| 78 | + } |
| 79 | + try await group.waitForAll() |
| 80 | + } |
| 81 | + |
| 82 | + let contents = try FileManager.default.contentsOfDirectory(at: tempDir, includingPropertiesForKeys: nil) |
| 83 | + if contents.count == 1 { |
| 84 | + let extracted = contents[0] |
| 85 | + var isDir: ObjCBool = false |
| 86 | + _ = FileManager.default.fileExists(atPath: extracted.path, isDirectory: &isDir) |
| 87 | + if isDir.boolValue && !recursive { |
| 88 | + throw ValidationError("source '\(volume):\(volumePath)' is a directory, use -r to copy recursively") |
| 89 | + } |
| 90 | + if FileManager.default.fileExists(atPath: localPath) { |
| 91 | + _ = try FileManager.default.replaceItemAt(localURL, withItemAt: extracted) |
| 92 | + } else { |
| 93 | + try FileManager.default.moveItem(at: extracted, to: localURL) |
| 94 | + } |
| 95 | + } else { |
| 96 | + if !recursive { |
| 97 | + throw ValidationError("source '\(volume):\(volumePath)' is a directory, use -r to copy recursively") |
| 98 | + } |
| 99 | + try FileManager.default.createDirectory(at: localURL, withIntermediateDirectories: true) |
| 100 | + for item in contents { |
| 101 | + let dest = localURL.appendingPathComponent(item.lastPathComponent) |
| 102 | + try FileManager.default.moveItem(at: item, to: dest) |
| 103 | + } |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + private func copyToVolume(volume: String, volumePath: String, localPath: String) async throws { |
| 108 | + let localURL = URL(fileURLWithPath: localPath) |
| 109 | + let pipe = Pipe() |
| 110 | + |
| 111 | + var isDir: ObjCBool = false |
| 112 | + if !FileManager.default.fileExists(atPath: localPath, isDirectory: &isDir) { |
| 113 | + throw ValidationError("source path does not exist: '\(localPath)'") |
| 114 | + } |
| 115 | + if isDir.boolValue && !recursive { |
| 116 | + throw ValidationError("source is a directory, use -r to copy recursively") |
| 117 | + } |
| 118 | + |
| 119 | + let readFD = dup(pipe.fileHandleForReading.fileDescriptor) |
| 120 | + let readHandle = FileHandle(fileDescriptor: readFD, closeOnDealloc: true) |
| 121 | + |
| 122 | + let isDirectory = isDir.boolValue |
| 123 | + |
| 124 | + try await withThrowingTaskGroup(of: Void.self) { group in |
| 125 | + group.addTask { |
| 126 | + defer { try? pipe.fileHandleForWriting.close() } |
| 127 | + try Archiver.compress(source: localURL, to: pipe.fileHandleForWriting) { url in |
| 128 | + let relativePath = self.computeRelativePath(source: localURL, current: url, isDirectory: isDirectory) |
| 129 | + return Archiver.ArchiveEntryInfo( |
| 130 | + pathOnHost: url, |
| 131 | + pathInArchive: URL(fileURLWithPath: relativePath) |
| 132 | + ) |
| 133 | + } |
| 134 | + } |
| 135 | + group.addTask { |
| 136 | + try await ClientVolume.copyIn(volume: volume, path: volumePath, fileHandle: readHandle) |
| 137 | + } |
| 138 | + try await group.waitForAll() |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + private func computeRelativePath(source: URL, current: URL, isDirectory: Bool) -> String { |
| 143 | + guard source.path != current.path else { |
| 144 | + return source.lastPathComponent |
| 145 | + } |
| 146 | + let components = current.pathComponents |
| 147 | + let baseComponents = source.pathComponents |
| 148 | + guard components.count > baseComponents.count && components.prefix(baseComponents.count) == baseComponents[...] else { |
| 149 | + return current.lastPathComponent |
| 150 | + } |
| 151 | + let relativePart = components[baseComponents.count...].joined(separator: "/") |
| 152 | + return "\(source.lastPathComponent)/\(relativePart)" |
| 153 | + } |
| 154 | + |
| 155 | + private func parsePath(_ path: String) -> (String?, String?) { |
| 156 | + let parts = path.split(separator: ":", maxSplits: 1) |
| 157 | + if parts.count == 2 { |
| 158 | + return (String(parts[0]), String(parts[1])) |
| 159 | + } |
| 160 | + return (nil, nil) |
| 161 | + } |
| 162 | + } |
| 163 | +} |
0 commit comments