UTMScriptingImportCommand.swift 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. //
  2. // Copyright © 2024 naveenrajm7. All rights reserved.
  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. // http://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. import Foundation
  17. @MainActor
  18. @objc(UTMScriptingImportCommand)
  19. class UTMScriptingImportCommand: NSCreateCommand, UTMScriptable {
  20. private var data: UTMData? {
  21. (NSApp.scriptingDelegate as? AppDelegate)?.data
  22. }
  23. @objc override func performDefaultImplementation() -> Any? {
  24. if createClassDescription.implementationClassName == "UTMScriptingVirtualMachineImpl" {
  25. withScriptCommand(self) { [self] in
  26. // Retrieve the import file URL from the evaluated arguments
  27. guard let fileUrl = evaluatedArguments?["file"] as? URL else {
  28. throw ScriptingError.fileNotSpecified
  29. }
  30. // Validate the file (UTM is a directory) path
  31. guard FileManager.default.fileExists(atPath: fileUrl.path) else {
  32. throw ScriptingError.fileNotFound
  33. }
  34. return try await importVirtualMachine(from: fileUrl).objectSpecifier
  35. }
  36. return nil
  37. } else {
  38. return super.performDefaultImplementation()
  39. }
  40. }
  41. private func importVirtualMachine(from url: URL) async throws -> UTMScriptingVirtualMachineImpl {
  42. guard let data = data else {
  43. throw ScriptingError.notReady
  44. }
  45. // import the VM
  46. let vm = try await data.importNewUTM(from: url)
  47. // return VM scripting object
  48. return UTMScriptingVirtualMachineImpl(for: vm, data: data)
  49. }
  50. enum ScriptingError: Error, LocalizedError {
  51. case notReady
  52. case fileNotFound
  53. case fileNotSpecified
  54. var errorDescription: String? {
  55. switch self {
  56. case .notReady: return NSLocalizedString("UTM is not ready to accept commands.", comment: "UTMScriptingAppDelegate")
  57. case .fileNotFound: return NSLocalizedString("A valid UTM file must be specified.", comment: "UTMScriptingAppDelegate")
  58. case .fileNotSpecified: return NSLocalizedString("No file specified in the command.", comment: "UTMScriptingAppDelegate")
  59. }
  60. }
  61. }
  62. }