SecretFile.swift 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright 2025 Google LLC
  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 ArgumentParser
  17. import Foundation
  18. /// A representation of a secret file, which should be decrypted for an integration test.
  19. struct SecretFile: Codable {
  20. /// A relative path to the encrypted file.
  21. let encrypted: String
  22. /// A relative path to where the decrypted file should be output to.
  23. let destination: String
  24. }
  25. extension SecretFile {
  26. /// Parses a `SecretFile` from a string.
  27. ///
  28. /// The string should be in the format of "encrypted:destination".
  29. /// If it's not, then a `ValidationError`will be thrown.
  30. ///
  31. /// - Parameters:
  32. /// - string: A string in the format of "encrypted:destination".
  33. init(string: String) throws {
  34. let splits = string.split(separator: ":")
  35. guard splits.count == 2 else {
  36. throw ValidationError(
  37. "Invalid secret file format. Format should be \"encrypted:destination\". Cause: \(string)"
  38. )
  39. }
  40. encrypted = String(splits[0])
  41. destination = String(splits[1])
  42. }
  43. /// Parses an array of `SecretFile` from a JSON file.
  44. ///
  45. /// It's expected that the secrets are encoded in the JSON file in the format of:
  46. /// ```json
  47. /// [
  48. /// {
  49. /// "encrypted": "path-to-encrypted-file",
  50. /// "destination": "where-to-output-decrypted-file"
  51. /// }
  52. /// ]
  53. /// ```
  54. ///
  55. /// - Parameters:
  56. /// - file: The URL of a JSON file which contains an array of `SecretFile`,
  57. /// encoded as JSON.
  58. static func parseArrayFrom(file: URL) throws -> [SecretFile] {
  59. do {
  60. let data = try Data(contentsOf: file)
  61. return try JSONDecoder().decode([SecretFile].self, from: data)
  62. } catch {
  63. throw ValidationError(
  64. "Failed to load secret files from json file. Cause: \(error.localizedDescription)"
  65. )
  66. }
  67. }
  68. }