-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSaveFile.swift
51 lines (42 loc) · 2.07 KB
/
SaveFile.swift
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
import Foundation
import SwiftCICDCore
public struct SaveFile: Action {
@Value var savedFilePath: String?
let fileName: String
let contents: Data
var attributes: [FileAttributeKey: Any]?
var parentDirectoryPath: String?
public init(name: String, contents: Data, attributes: [FileAttributeKey: Any]? = nil, parentDirectoryPath: String? = nil) {
self.fileName = name
self.contents = contents
self.attributes = attributes
self.parentDirectoryPath = parentDirectoryPath
}
public init(name: String, contents: String, attributes: [FileAttributeKey: Any]? = nil, parentDirectoryPath: String? = nil) {
self.init(name: name, contents: contents.data, attributes: attributes, parentDirectoryPath: parentDirectoryPath)
}
public struct Output {
public let filePath: String
}
public func run() async throws -> Output {
let filePath = (parentDirectoryPath ?? context.fileManager.temporaryDirectory.path)/fileName
self.savedFilePath = filePath
guard context.fileManager.createFile(atPath: filePath, contents: contents, attributes: attributes) else {
throw ActionError("Failed to save temporary file \(filePath)")
}
return Output(filePath: filePath)
}
public func cleanUp(error: Error?) async throws {
if let savedFilePath {
try context.fileManager.removeItemIfItExists(atPath: savedFilePath)
}
}
}
public extension Action {
func saveFile(name: String, contents: Data, attributes: [FileAttributeKey: Any]? = nil, into parentDirectoryPath: String? = nil) async throws -> SaveFile.Output {
try await run(SaveFile(name: name, contents: contents, attributes: attributes, parentDirectoryPath: parentDirectoryPath))
}
func saveFile(name: String, contents: String, attributes: [FileAttributeKey: Any]? = nil, into parentDirectoryPath: String? = nil) async throws -> SaveFile.Output {
try await run(SaveFile(name: name, contents: contents, attributes: attributes, parentDirectoryPath: parentDirectoryPath))
}
}