From 0b44dd5a48888bdb310c9b12925c595d1c17f7cc Mon Sep 17 00:00:00 2001 From: Dabezt Date: Fri, 31 Dec 2021 14:07:42 +0300 Subject: [PATCH] Make trash.swift safer and more modern --- Library/Homebrew/cask/utils/trash.swift | 30 ++++++++++++++----------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/Library/Homebrew/cask/utils/trash.swift b/Library/Homebrew/cask/utils/trash.swift index a55c0dacd9..cfdd3d896a 100755 --- a/Library/Homebrew/cask/utils/trash.swift +++ b/Library/Homebrew/cask/utils/trash.swift @@ -4,28 +4,32 @@ import Foundation extension FileHandle : TextOutputStream { public func write(_ string: String) { - self.write(string.data(using: .utf8)!) + if let data = string.data(using: .utf8) { self.write(data) } } } var stderr = FileHandle.standardError -let manager: FileManager = FileManager() +let manager = FileManager.default var success = true -for item in CommandLine.arguments[1...] { - do { - let path: URL = URL(fileURLWithPath: item) - var trashedPath: NSURL! - try manager.trashItem(at: path, resultingItemURL: &trashedPath) - print((trashedPath as URL).path, terminator: ":") - } catch { - print(item, terminator: ":", to: &stderr) - success = false - } +// The command line arguments given but without the script's name +let CMDLineArgs = Array(CommandLine.arguments.dropFirst()) + +for item in CMDLineArgs { + do { + let url = URL(fileURLWithPath: item) + var trashedPath: NSURL! + try manager.trashItem(at: url, resultingItemURL: &trashedPath) + print((trashedPath as URL).path, terminator: ":") + success = true + } catch { + print(item, terminator: ":", to: &stderr) + success = false + } } guard success else { - exit(1) + exit(1) }