xtool.git
Publicgit clone https://git.maproj.org/xtool.gitxtool.git / Sources / XUtils / Foundation+Utils.swift
Foundation+Utils.swift59 lines · 1.7 KiBRaw
| 1 | import Foundation |
| 2 | #if canImport(Subprocess) |
| 3 | import Subprocess |
| 4 | #endif |
| 5 | |
| 6 | extension Data { |
| 7 | // AsyncBytes is Darwin-only :/ |
| 8 | |
| 9 | package init(reading fileHandle: FileHandle) async throws { |
| 10 | #if canImport(Darwin) |
| 11 | self = try await fileHandle.bytes.reduce(into: Data()) { $0.append($1) } |
| 12 | #else |
| 13 | self = try fileHandle.readToEnd() ?? Data() |
| 14 | #endif |
| 15 | } |
| 16 | |
| 17 | package init(reading file: URL) async throws { |
| 18 | #if canImport(Darwin) |
| 19 | self = try await file.resourceBytes.reduce(into: Data()) { $0.append($1) } |
| 20 | #else |
| 21 | try self.init(contentsOf: file) |
| 22 | #endif |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | extension FileManager { |
| 27 | /// Like `copyItem(at:to:)` but allows opting out of preserving the owner |
| 28 | package func copyItem( |
| 29 | at srcURL: URL, |
| 30 | to dstURL: URL, |
| 31 | preserveOwner: Bool, |
| 32 | ) async throws { |
| 33 | // why this is needed: https://github.com/xtool-org/xtool/issues/254 |
| 34 | |
| 35 | #if canImport(Subprocess) |
| 36 | if !preserveOwner { |
| 37 | let result = try await Subprocess.run( |
| 38 | .name("cp"), |
| 39 | arguments: ["-R", srcURL.path, dstURL.path], |
| 40 | output: .discarded, |
| 41 | error: .string(limit: .max, encoding: UTF8.self), |
| 42 | ) |
| 43 | do { |
| 44 | try result.checkSuccess() |
| 45 | } catch { |
| 46 | print("Error copying \(srcURL.path) to \(dstURL.path): \(result.standardError)") |
| 47 | throw error |
| 48 | } |
| 49 | return |
| 50 | } |
| 51 | #endif |
| 52 | |
| 53 | try self.copyItem(at: srcURL, to: dstURL) |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | package func stderrPrint(_ message: String, terminator: String = "\n") { |
| 58 | try? FileHandle.standardError.write(contentsOf: Data("\(message)\(terminator)".utf8)) |
| 59 | } |