From 1b36b871ebb75dd47f9a0d7406215c91a3406381 Mon Sep 17 00:00:00 2001 From: Jason Morley Date: Fri, 14 Feb 2025 15:39:24 -1000 Subject: [PATCH] refactor: Separate report generation into different functions (#38) This will hopefully make it easier to change and test different aspects. --- Sources/ReporterCore/Configuration.swift | 6 ++++++ Sources/ReporterCore/Reporter.swift | 27 ++++++++++++++---------- 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/Sources/ReporterCore/Configuration.swift b/Sources/ReporterCore/Configuration.swift index 08cb2f2..cf514e7 100644 --- a/Sources/ReporterCore/Configuration.swift +++ b/Sources/ReporterCore/Configuration.swift @@ -44,4 +44,10 @@ struct Configuration: Codable { let mailServer: Server let folders: [String: Policy] + init(contentsOf url: URL) throws { + let data = try Data(contentsOf: url) + let decoder = JSONDecoder() + self = try decoder.decode(Self.self, from: data) + } + } diff --git a/Sources/ReporterCore/Reporter.swift b/Sources/ReporterCore/Reporter.swift index d73e417..9cd2d1f 100644 --- a/Sources/ReporterCore/Reporter.swift +++ b/Sources/ReporterCore/Reporter.swift @@ -98,20 +98,11 @@ public class Reporter { return Data(md5.finalize()) } - public static func run(configurationURL: URL, snapshotURL: URL) async throws { - let fileManager = FileManager.default - - let console = Console() - - // Load the configuration - console.log("Loading configuration...") - let data = try Data(contentsOf: configurationURL) - let decoder = JSONDecoder() - let configuration = try decoder.decode(Configuration.self, from: data) + static func report(configuration: Configuration, snapshotURL: URL, console: Console) async throws -> Report { // Load the snapshot if it exists. console.log("Loading state...") - let oldState = if fileManager.fileExists(atPath: snapshotURL.path) { + let oldState = if FileManager.default.fileExists(atPath: snapshotURL.path) { try BinaryDecoder().decode(State.self, from: try Data(contentsOf: snapshotURL)) } else { @@ -144,6 +135,20 @@ public class Reporter { report.folders.append(KeyedChanges(url: url, changes: changes)) } + return report + } + + public static func run(configurationURL: URL, snapshotURL: URL) async throws { + + let console = Console() + + // Load the configuration. + console.log("Loading configuration...") + let configuration = try Configuration(contentsOf: configurationURL) + + // Generate the report. + let report = try await report(configuration: configuration, snapshotURL: snapshotURL, console: console) + // Return early if there are no outstanding changes. if report.isEmpty { console.log("No changes detected; skipping report.")