-
Notifications
You must be signed in to change notification settings - Fork 19
feat(snapshots): Add CI image export via SNAPSHOTS_EXPORT_DIR env var (EME-931) #252
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
6712190
Add image export by way of `SNAPSHOTS_EXPORT_DIR` env var
cameroncooke ef641a4
fix(snapshots): Include underscore in filename sanitize keep-set
cameroncooke 45d9c39
fix(snapshots): Add @MainActor to shared instance management
cameroncooke d2bab88
fix(snapshots): Remove redundant directory-existence guard in drain
cameroncooke ab8f9a5
ref(snapshots): Simplify drain with waitUntilAllOperationsAreFinished
cameroncooke e66fb8e
fix(snapshots): Use defer for color scheme override cleanup
cameroncooke 7b4d634
fix(snapshots): Unify grouping key via shared canonicalGroup method
cameroncooke 60db1ec
fix(snapshots): Sanitize baseFileName at construction, not export time
cameroncooke ca879ff
fix(snapshots): Remove color scheme override support
cameroncooke 8c623c5
fix(snapshots): Skip oversized snapshot exports
cameroncooke c58a343
fix(snapshots): Address PR review feedback
cameroncooke File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
264 changes: 264 additions & 0 deletions
264
Sources/SnapshottingTests/SnapshotCIExportCoordinator.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,264 @@ | ||
| // | ||
| // SnapshotCIExportCoordinator.swift | ||
| // SnapshottingTests | ||
| // | ||
| // Manages CI export of snapshot PNGs and JSON sidecar metadata | ||
| // directly to the filesystem when SNAPSHOTS_EXPORT_DIR is set. | ||
| // | ||
|
|
||
| import Foundation | ||
| import XCTest | ||
| @_implementationOnly import SnapshotPreviewsCore | ||
|
|
||
| // MARK: - Snapshot Context | ||
|
|
||
| struct SnapshotContext: Sendable, Encodable { | ||
| let baseFileName: String | ||
| let testName: String | ||
| let typeName: String | ||
| let typeDisplayName: String | ||
| let fileId: String? | ||
| let line: Int? | ||
| let previewDisplayName: String? | ||
| let previewIndex: Int | ||
| let previewId: String | ||
| let orientation: String | ||
| let declaredDevice: String? | ||
| let simulatorDeviceName: String? | ||
| let simulatorModelIdentifier: String? | ||
| let precision: Float? | ||
| let accessibilityEnabled: Bool? | ||
| let colorScheme: String? | ||
| let appStoreSnapshot: Bool? | ||
| } | ||
|
|
||
| // MARK: - Sidecar Model | ||
|
|
||
| private struct SnapshotCIExportSidecar: Sendable, Encodable { | ||
| let context: SnapshotContext | ||
| let imageFileName: String | ||
| let displayName: String | ||
| let group: String | ||
|
|
||
| private enum ExtraKeys: String, CodingKey { | ||
| case image_file_name | ||
| case display_name | ||
| case group | ||
| } | ||
|
|
||
| func encode(to encoder: Encoder) throws { | ||
| try context.encode(to: encoder) | ||
| var container = encoder.container(keyedBy: ExtraKeys.self) | ||
| try container.encode(imageFileName, forKey: .image_file_name) | ||
| try container.encode(displayName, forKey: .display_name) | ||
| try container.encode(group, forKey: .group) | ||
| } | ||
| } | ||
|
|
||
| // MARK: - Coordinator | ||
|
|
||
| final class SnapshotCIExportCoordinator: NSObject, XCTestObservation { | ||
|
|
||
| static let envKey = "SNAPSHOTS_EXPORT_DIR" | ||
|
|
||
| private let exportDirectoryURL: URL | ||
| private let writeQueue: OperationQueue | ||
| private let fileManager: FileManager | ||
| private let stateLock = NSLock() | ||
| private var hasDrained = false | ||
|
|
||
| // MARK: - Factory | ||
|
|
||
| static func createFromEnvironment( | ||
| environment: [String: String] = ProcessInfo.processInfo.environment | ||
| ) -> SnapshotCIExportCoordinator? { | ||
| guard let exportDir = environment[envKey] else { | ||
| return nil | ||
| } | ||
|
|
||
| let trimmed = exportDir.trimmingCharacters(in: .whitespacesAndNewlines) | ||
| guard !trimmed.isEmpty else { | ||
| preconditionFailure( | ||
| "\(envKey) is set but empty. Provide a valid directory path." | ||
| ) | ||
| } | ||
|
|
||
| let url: URL | ||
| if trimmed.hasPrefix("/") { | ||
| url = URL(fileURLWithPath: trimmed, isDirectory: true).standardizedFileURL | ||
| } else { | ||
| url = URL( | ||
| fileURLWithPath: FileManager.default.currentDirectoryPath, | ||
| isDirectory: true | ||
| ) | ||
| .appendingPathComponent(trimmed, isDirectory: true) | ||
| .standardizedFileURL | ||
| } | ||
|
|
||
| let coordinator = Self(exportDirectoryURL: url) | ||
| XCTestObservationCenter.shared.addTestObserver(coordinator) | ||
| return coordinator | ||
| } | ||
|
|
||
| // MARK: - Init | ||
|
|
||
| init( | ||
| exportDirectoryURL: URL, | ||
| fileManager: FileManager = .default, | ||
| writeQueue: OperationQueue = .defaultQueue | ||
| ) { | ||
| self.exportDirectoryURL = exportDirectoryURL | ||
| self.fileManager = fileManager | ||
| self.writeQueue = writeQueue | ||
|
|
||
| super.init() | ||
|
|
||
| do { | ||
| try self.fileManager.createDirectory( | ||
| at: exportDirectoryURL, | ||
| withIntermediateDirectories: true | ||
| ) | ||
| } catch { | ||
| preconditionFailure( | ||
| "Failed to create snapshot export directory at \(exportDirectoryURL.path): \(error)" | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| // MARK: - Filename Sanitization | ||
|
|
||
| static func sanitize(_ raw: String) -> String { | ||
| var result = "" | ||
| var lastWasUnderscore = false | ||
|
|
||
| for c in raw { | ||
| if c.isLetter || c.isNumber || c == "." || c == "-" || c == "_" { | ||
| result.append(c) | ||
| lastWasUnderscore = false | ||
| } else if !lastWasUnderscore { | ||
| result.append("_") | ||
| lastWasUnderscore = true | ||
| } | ||
| } | ||
|
|
||
| result = result.trimmingCharacters(in: CharacterSet(charactersIn: "_.-")) | ||
|
|
||
| return result.isEmpty ? "snapshot" : result | ||
| } | ||
|
|
||
| // MARK: - Export | ||
|
|
||
| static func canonicalGroup( | ||
| fileId: String?, | ||
| typeDisplayName: String, | ||
| typeName: String | ||
| ) -> String { | ||
| if let fileId, !fileId.isEmpty { | ||
| return fileId | ||
| } | ||
|
|
||
| if !typeDisplayName.isEmpty { | ||
| return typeDisplayName | ||
| } | ||
|
|
||
| return typeName | ||
| } | ||
|
|
||
| private static func canonicalDisplayName(for context: SnapshotContext) -> String { | ||
| if let previewDisplayName = context.previewDisplayName, !previewDisplayName.isEmpty { | ||
| return previewDisplayName | ||
| } | ||
|
|
||
| if context.fileId != nil, let line = context.line { | ||
| return "At line #\(line)" | ||
| } | ||
|
|
||
| return String(context.previewIndex) | ||
| } | ||
|
|
||
| /// Enqueues a snapshot export (PNG + JSON sidecar) to the export directory. | ||
| /// | ||
| /// PNG encoding and file writes are dispatched to a concurrent background queue | ||
| /// so the calling test can proceed to the next preview immediately. | ||
| func enqueueExport( | ||
| result: SnapshotResult, | ||
| context: SnapshotContext | ||
| ) { | ||
| let pngFileName = "\(context.baseFileName).png" | ||
| let jsonFileName = "\(context.baseFileName).json" | ||
|
|
||
| let displayName = Self.canonicalDisplayName(for: context) | ||
| let group = Self.canonicalGroup( | ||
| fileId: context.fileId, | ||
| typeDisplayName: context.typeDisplayName, | ||
| typeName: context.typeName | ||
| ) | ||
| let exportDir = exportDirectoryURL | ||
|
|
||
| guard case .success(let image) = result.image else { return } | ||
|
|
||
| writeQueue.addOperation { | ||
| let pngURL = exportDir.appendingPathComponent(pngFileName) | ||
| guard let pngData = image.emg.pngData() else { | ||
| NSLog("[SnapshotCIExport] Failed to encode PNG for %@", pngFileName) | ||
| return | ||
| } | ||
| do { | ||
| try pngData.write(to: pngURL, options: .atomic) | ||
| } catch { | ||
| NSLog("[SnapshotCIExport] Failed to write PNG %@: %@", pngFileName, "\(error)") | ||
| return | ||
| } | ||
|
|
||
| let sidecar = SnapshotCIExportSidecar( | ||
| context: context, | ||
| imageFileName: context.baseFileName, | ||
| displayName: displayName, | ||
| group: group | ||
| ) | ||
|
|
||
| let jsonURL = exportDir.appendingPathComponent(jsonFileName) | ||
| do { | ||
| let encoder = JSONEncoder() | ||
| encoder.outputFormatting = [.prettyPrinted, .sortedKeys] | ||
| let data = try encoder.encode(sidecar) | ||
| try data.write(to: jsonURL, options: .atomic) | ||
| } catch { | ||
| NSLog("[SnapshotCIExport] Failed to write sidecar %@: %@", jsonFileName, "\(error)") | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // MARK: - Drain | ||
|
|
||
| /// Waits for all queued PNG and sidecar writes to complete. | ||
| /// | ||
| /// Called automatically via `testBundleDidFinish`. Safe to call multiple times — | ||
| /// only the first call performs the drain. | ||
| func drain() { | ||
| stateLock.lock() | ||
| guard !hasDrained else { | ||
| stateLock.unlock() | ||
| return | ||
| } | ||
| hasDrained = true | ||
| stateLock.unlock() | ||
|
|
||
| writeQueue.waitUntilAllOperationsAreFinished() | ||
| } | ||
|
|
||
| // MARK: - XCTestObservation | ||
|
|
||
| func testBundleDidFinish(_ testBundle: Bundle) { | ||
| drain() | ||
| } | ||
| } | ||
|
|
||
| private extension OperationQueue { | ||
| static var defaultQueue: OperationQueue { | ||
| let queue = OperationQueue() | ||
| queue.maxConcurrentOperationCount = 20 | ||
| queue.qualityOfService = .userInitiated | ||
| return queue | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.