File: Attachment%2BURL.swift

package info (click to toggle)
swiftlang 6.1.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,791,532 kB
  • sloc: cpp: 9,901,743; ansic: 2,201,431; asm: 1,091,827; python: 308,252; objc: 82,166; f90: 80,126; lisp: 38,358; pascal: 25,559; sh: 20,429; ml: 5,058; perl: 4,745; makefile: 4,484; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (161 lines) | stat: -rw-r--r-- 5,843 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2024 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for Swift project authors
//

#if canImport(Foundation)
@_spi(Experimental) @_spi(ForSwiftTestingOnly) public import Testing
public import Foundation

#if SWT_TARGET_OS_APPLE && canImport(UniformTypeIdentifiers)
private import UniformTypeIdentifiers
#endif

#if !SWT_NO_FILE_IO
extension URL {
  /// The file system path of the URL, equivalent to `path`.
  var fileSystemPath: String {
#if os(Windows)
    // BUG: `path` includes a leading slash which makes it invalid on Windows.
    // SEE: https://github.com/swiftlang/swift-foundation/pull/964
    let path = path
    if path.starts(with: /\/[A-Za-z]:\//) {
      return String(path.dropFirst())
    }
#endif
    return path
  }
}

#if SWT_TARGET_OS_APPLE && canImport(UniformTypeIdentifiers)
@available(_uttypesAPI, *)
extension UTType {
  /// A type that represents a `.tgz` archive, or `nil` if the system does not
  /// recognize that content type.
  fileprivate static let tgz = UTType("org.gnu.gnu-zip-tar-archive")
}
#endif

@_spi(Experimental)
extension Attachment where AttachableValue == Data {
  /// Initialize an instance of this type with the contents of the given URL.
  ///
  /// - Parameters:
  ///   - url: The URL containing the attachment's data.
  ///   - preferredName: The preferred name of the attachment when writing it to
  ///     a test report or to disk. If `nil`, the name of the attachment is
  ///     derived from the last path component of `url`.
  ///   - sourceLocation: The source location of the call to this initializer.
  ///     This value is used when recording issues associated with the
  ///     attachment.
  ///
  /// - Throws: Any error that occurs attempting to read from `url`.
  public init(
    contentsOf url: URL,
    named preferredName: String? = nil,
    sourceLocation: SourceLocation = #_sourceLocation
  ) async throws {
    guard url.isFileURL else {
      // TODO: network URLs?
      throw CocoaError(.featureUnsupported, userInfo: [NSLocalizedDescriptionKey: "Attaching downloaded files is not supported"])
    }

    // FIXME: use NSFileCoordinator on Darwin?

    let url = url.resolvingSymlinksInPath()
    let isDirectory = try url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory!

    // Determine the preferred name of the attachment if one was not provided.
    var preferredName = if let preferredName {
      preferredName
    } else if case let lastPathComponent = url.lastPathComponent, !lastPathComponent.isEmpty {
      lastPathComponent
    } else {
      Self.defaultPreferredName
    }

    if isDirectory {
      // Ensure the preferred name of the archive has an appropriate extension.
      preferredName = {
#if SWT_TARGET_OS_APPLE && canImport(UniformTypeIdentifiers)
        if #available(_uttypesAPI, *), let tgz = UTType.tgz {
          return (preferredName as NSString).appendingPathExtension(for: tgz)
        }
#endif
        return (preferredName as NSString).appendingPathExtension("tgz") ?? preferredName
      }()

      try await self.init(Data(compressedContentsOfDirectoryAt: url), named: preferredName, sourceLocation: sourceLocation)
    } else {
      // Load the file.
      try self.init(Data(contentsOf: url, options: [.mappedIfSafe]), named: preferredName, sourceLocation: sourceLocation)
    }
  }
}

// MARK: - Attaching directories

extension Data {
  /// Initialize an instance of this type by compressing the contents of a
  /// directory.
  ///
  /// - Parameters:
  ///   - directoryURL: A URL referring to the directory to attach.
  ///
  /// - Throws: Any error encountered trying to compress the directory, or if
  ///   directories cannot be compressed on this platform.
  ///
  /// This initializer asynchronously compresses the contents of `directoryURL`
  /// into an archive (currently of `.tgz` format, although this is subject to
  /// change) and stores a mapped copy of that archive.
  init(compressedContentsOfDirectoryAt directoryURL: URL) async throws {
    let temporaryName = "\(UUID().uuidString).tgz"
    let temporaryURL = FileManager.default.temporaryDirectory.appendingPathComponent(temporaryName)

#if !SWT_NO_PROCESS_SPAWNING
#if os(Windows)
    let tarPath = #"C:\Windows\System32\tar.exe"#
#else
    let tarPath = "/usr/bin/tar"
#endif
    let sourcePath = directoryURL.fileSystemPath
    let destinationPath = temporaryURL.fileSystemPath
    defer {
      try? FileManager().removeItem(at: temporaryURL)
    }

    try await withCheckedThrowingContinuation { continuation in
      do {
        _ = try Process.run(
          URL(fileURLWithPath: tarPath, isDirectory: false),
          arguments: ["--create", "--gzip", "--directory", sourcePath, "--file", destinationPath, "."]
        ) { process in
          let terminationReason = process.terminationReason
          let terminationStatus = process.terminationStatus
          if terminationReason == .exit && terminationStatus == EXIT_SUCCESS {
            continuation.resume()
          } else {
            let error = CocoaError(.fileWriteUnknown, userInfo: [
              NSLocalizedDescriptionKey: "The directory at '\(sourcePath)' could not be compressed.",
            ])
            continuation.resume(throwing: error)
          }
        }
      } catch {
        continuation.resume(throwing: error)
      }
    }

    try self.init(contentsOf: temporaryURL, options: [.mappedIfSafe])
#else
    throw CocoaError(.featureUnsupported, userInfo: [NSLocalizedDescriptionKey: "This platform does not support attaching directories to tests."])
#endif
  }
}
#endif
#endif