Zip.swift 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. * Copyright 2019 Google
  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. import Utils
  18. /// Convenience
  19. struct Zip {
  20. /// Compresses the contents of the directory into a Zip file that resides beside the directory
  21. /// being compressed and has the same name as the directory with a `.zip` suffix.
  22. ///
  23. /// - Parameter directory: The directory to compress.
  24. /// - Parameter name: The name of the Zip file.
  25. /// - Returns: A URL to the Zip file created.
  26. static func zipContents(ofDir directory: URL, name: String) -> URL {
  27. // Ensure the directory being compressed exists.
  28. guard FileManager.default.directoryExists(at: directory) else {
  29. fatalError("Attempted to compress contents of \(directory) but the directory does not exist.")
  30. }
  31. // This `zip` command needs to be run in the parent directory.
  32. let parentDir = directory.deletingLastPathComponent()
  33. let zip = parentDir.appendingPathComponent(name)
  34. // If it exists already, try to remove it.
  35. if FileManager.default.fileExists(atPath: zip.path) {
  36. try? FileManager.default.removeItem(at: zip)
  37. }
  38. // Run the `zip` command. This could be replaced with a proper Zip library in the future.
  39. let command = "zip --symlinks -q -r -dg \(zip.lastPathComponent) \(directory.lastPathComponent)"
  40. let result = Shell.executeCommandFromScript(command, workingDir: parentDir)
  41. switch result {
  42. case .success:
  43. print("Successfully built Zip file.")
  44. return zip
  45. case let .error(code, output):
  46. fatalError("Error \(code) building zip file: \(output)")
  47. }
  48. }
  49. // Mark initialization as unavailable.
  50. @available(*, unavailable)
  51. init() { fatalError() }
  52. }