From ab172fb368232ac2bdf21ba40eef23e9ad0fba62 Mon Sep 17 00:00:00 2001 From: Rudenko Dmitry Date: Fri, 23 Oct 2026 15:24:49 +0300 Subject: [PATCH] refactor: extract ReportModel from AppModel - Move exportReport, app version, report options and filename into ReportModel - Attach tree/navigation/filter providers and toast/error callbacks - Migrate menu and command palette to model.report - Add ReportModelTests for export availability, filename and options - AppModel is now 1064 lines; 150 tests green Refs #66 --- .github/workflows/release.yml | 2 +- README.md | 2 +- ROADMAP.md | 2 +- Sources/DiskScope/DiskScopeApp.swift | 10 +- Sources/DiskScopeKit/App/AppModel.swift | 86 ++++---------- Sources/DiskScopeKit/App/ReportModel.swift | 111 ++++++++++++++++++ Sources/DiskScopeKit/UI/WindowChrome.swift | 4 +- .../DiskScopeKitTests/ReportModelTests.swift | 85 ++++++++++++++ docs/build.md | 2 +- 9 files changed, 229 insertions(+), 75 deletions(-) create mode 100644 Sources/DiskScopeKit/App/ReportModel.swift create mode 100644 Tests/DiskScopeKitTests/ReportModelTests.swift diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2a7408b..06203d9 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -279,5 +279,5 @@ jobs: echo "| SHA-256 DMG | \`${DMG_SHA256}\` |" echo "| SHA-256 ZIP | \`${ZIP_SHA256}\` |" echo "| Архитектуры | arm64 + x86_64 |" - echo "| Тесты | 147 XCTest |" + echo "| Тесты | 150 XCTest |" } >> "$GITHUB_STEP_SUMMARY" diff --git a/README.md b/README.md index b39612f..82d5754 100644 --- a/README.md +++ b/README.md @@ -371,7 +371,7 @@ Headless-сканер для бенчмарков: ## Тесты -147 тестов: сравнение суммы скана с `du`, агрегация мелких файлов, пакеты, +150 тестов: сравнение суммы скана с `du`, агрегация мелких файлов, пакеты, симлинки, Unicode-имена, отказ доступа, отмена, copy-on-write удаление, свойства squarified-раскладки, вложенные ячейки, полный цикл `AppModel` (скан → навигация → фильтры), даты создания и изменения, правила очистки, diff --git a/ROADMAP.md b/ROADMAP.md index ee1a431..cbb9af9 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -23,7 +23,7 @@ | 2.0 — Платформа | 6/6: локализация, notarization/Sparkle/Homebrew, CLI, App Intents, доступность, меню-бар | | Backlog | 5/5: кэш, параллельный скан, бюджеты, старые файлы, APFS-клоны | -Текущая база: **147 XCTest**, 17,9 тыс. строк исходников, 398 ключей +Текущая база: **150 XCTest**, 17,9 тыс. строк исходников, 398 ключей локализации, `main` зелёный. ## Принципы diff --git a/Sources/DiskScope/DiskScopeApp.swift b/Sources/DiskScope/DiskScopeApp.swift index b43d1ef..d1fe1d7 100644 --- a/Sources/DiskScope/DiskScopeApp.swift +++ b/Sources/DiskScope/DiskScopeApp.swift @@ -42,21 +42,21 @@ struct DiskScopeApp: App { CommandGroup(after: .saveItem) { Menu("Экспортировать отчёт") { Button("CSV — текущая папка") { - model.exportReport(format: .csv, scope: .currentFolder) + model.report.exportReport(format: .csv, scope: .currentFolder) } .keyboardShortcut("e", modifiers: [.command, .shift]) Button("HTML — текущая папка") { - model.exportReport(format: .html, scope: .currentFolder) + model.report.exportReport(format: .html, scope: .currentFolder) } Divider() Button("CSV — весь скан") { - model.exportReport(format: .csv, scope: .wholeScan) + model.report.exportReport(format: .csv, scope: .wholeScan) } Button("HTML — весь скан") { - model.exportReport(format: .html, scope: .wholeScan) + model.report.exportReport(format: .html, scope: .wholeScan) } } - .disabled(model.tree == nil) + .disabled(!model.report.canExportReport) } CommandMenu("Диск") { diff --git a/Sources/DiskScopeKit/App/AppModel.swift b/Sources/DiskScopeKit/App/AppModel.swift index 237b2c1..7df4d0e 100644 --- a/Sources/DiskScopeKit/App/AppModel.swift +++ b/Sources/DiskScopeKit/App/AppModel.swift @@ -1,7 +1,6 @@ import AppKit import Combine import Foundation -import UniformTypeIdentifiers @MainActor public final class AppModel: ObservableObject { @@ -106,6 +105,7 @@ public final class AppModel: ObservableObject { @Published public internal(set) var duplicates = DuplicatesModel() @Published public internal(set) var similar = SimilarModel() @Published public internal(set) var inspector = InspectorModel() + @Published public internal(set) var report = ReportModel() @Published public var showInspector = false @Published public internal(set) var budget = BudgetModel() @@ -172,6 +172,19 @@ public final class AppModel: ObservableObject { inspector.objectWillChange.sink { [weak self] _ in self?.objectWillChange.send() }.store(in: &cancellables) + report.attach( + treeProvider: { [weak self] in self?.tree }, + currentIndexProvider: { [weak self] in self?.currentIndex ?? 0 }, + searchProvider: { [weak self] in self?.searchText ?? "" }, + categoryProvider: { [weak self] in self?.categoryFilter }, + currentNameProvider: { [weak self] in self?.currentName ?? "" }, + rootDisplayNameProvider: { [weak self] in self?.rootDisplayName ?? "DiskScope" }, + toast: { [weak self] text, symbol in self?.showToast(text, symbol: symbol) }, + error: { [weak self] message in self?.errorMessage = message } + ) + report.objectWillChange.sink { [weak self] _ in + self?.objectWillChange.send() + }.store(in: &cancellables) trash.objectWillChange.sink { [weak self] _ in self?.objectWillChange.send() }.store(in: &cancellables) @@ -281,6 +294,14 @@ public final class AppModel: ObservableObject { inspector.openInTerminal(index) } + // MARK: - Report compatibility + + public var canExportReport: Bool { report.canExportReport } + + public func exportReport(format: ReportFormat = .csv, scope: ReportScope = .currentFolder) { + report.exportReport(format: format, scope: scope) + } + // MARK: - Derived state public var filteredLargestRows: [ItemRow] { @@ -899,69 +920,6 @@ public enum TreeNaming { } } -extension AppModel { - public var canExportReport: Bool { tree != nil } - - /// Shows a save panel and writes a CSV or HTML report of the current scan. - public func exportReport(format: ReportFormat = .csv, scope: ReportScope = .currentFolder) { - guard let tree else { return } - - let panel = NSSavePanel() - panel.title = "Экспортировать отчёт" - panel.message = "CSV или HTML. Отчёт строится по текущему скану и видимым фильтрам." - panel.prompt = "Экспортировать" - panel.canCreateDirectories = true - panel.isExtensionHidden = false - panel.allowedContentTypes = [format == .csv ? .commaSeparatedText : .html] - panel.nameFieldStringValue = defaultReportFilename(format: format, scope: scope) - guard panel.runModal() == .OK, let url = panel.url else { return } - - let options = ReportOptions( - format: format, - scope: scope, - search: searchText, - category: categoryFilter, - generatedAt: Date(), - appVersion: appVersion - ) - let rootIndex = currentIndex - - DispatchQueue.global(qos: .userInitiated).async { [weak self] in - do { - let text: String - switch format { - case .csv: - text = ReportExporter.makeCSV(tree: tree, rootIndex: rootIndex, options: options) - case .html: - text = ReportExporter.makeHTML(tree: tree, rootIndex: rootIndex, options: options) - } - try ReportExporter.write(text, to: url) - DispatchQueue.main.async { - self?.showToast("Отчёт сохранён: \(url.lastPathComponent)", symbol: "doc.text.fill") - } - } catch { - DispatchQueue.main.async { - self?.errorMessage = "Не удалось сохранить отчёт: \(error.localizedDescription)" - } - } - } - } - - private var appVersion: String { - Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "dev" - } - - private func defaultReportFilename(format: ReportFormat, scope: ReportScope) -> String { - let raw = scope == .currentFolder ? currentName : rootDisplayName - var safe = raw - .replacingOccurrences(of: "/", with: "-") - .replacingOccurrences(of: ":", with: "-") - .trimmingCharacters(in: .whitespacesAndNewlines) - if safe.isEmpty { safe = "DiskScope" } - return "DiskScope-\(safe).\(format.fileExtension)" - } -} - extension AppModel { func runningBundleIdentifiers() -> Set { Set(NSWorkspace.shared.runningApplications.compactMap(\.bundleIdentifier)) diff --git a/Sources/DiskScopeKit/App/ReportModel.swift b/Sources/DiskScopeKit/App/ReportModel.swift new file mode 100644 index 0000000..a9120b7 --- /dev/null +++ b/Sources/DiskScopeKit/App/ReportModel.swift @@ -0,0 +1,111 @@ +import AppKit +import Combine +import Foundation +import UniformTypeIdentifiers + +/// Owns report export: save panel, report options, filename and writing. +@MainActor +public final class ReportModel: ObservableObject { + private var treeProvider: () -> ScanTree? = { nil } + private var currentIndexProvider: () -> Int32 = { 0 } + private var searchProvider: () -> String = { "" } + private var categoryProvider: () -> FileCategory? = { nil } + private var currentNameProvider: () -> String = { "" } + private var rootDisplayNameProvider: () -> String = { "DiskScope" } + private var toastHandler: (String, String) -> Void = { _, _ in } + private var errorHandler: (String) -> Void = { _ in } + private let versionProvider: () -> String + + public init(versionProvider: @escaping () -> String = { + Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "dev" + }) { + self.versionProvider = versionProvider + } + + func attach( + treeProvider: @escaping () -> ScanTree?, + currentIndexProvider: @escaping () -> Int32, + searchProvider: @escaping () -> String, + categoryProvider: @escaping () -> FileCategory?, + currentNameProvider: @escaping () -> String, + rootDisplayNameProvider: @escaping () -> String, + toast: @escaping (String, String) -> Void, + error: @escaping (String) -> Void + ) { + self.treeProvider = treeProvider + self.currentIndexProvider = currentIndexProvider + self.searchProvider = searchProvider + self.categoryProvider = categoryProvider + self.currentNameProvider = currentNameProvider + self.rootDisplayNameProvider = rootDisplayNameProvider + self.toastHandler = toast + self.errorHandler = error + } + + public var canExportReport: Bool { treeProvider() != nil } + + /// Shows a save panel and writes a CSV or HTML report of the current scan. + public func exportReport(format: ReportFormat = .csv, scope: ReportScope = .currentFolder) { + guard let tree = treeProvider() else { return } + + let panel = NSSavePanel() + panel.title = "Экспортировать отчёт" + panel.message = "CSV или HTML. Отчёт строится по текущему скану и видимым фильтрам." + panel.prompt = "Экспортировать" + panel.canCreateDirectories = true + panel.isExtensionHidden = false + panel.allowedContentTypes = [format == .csv ? .commaSeparatedText : .html] + panel.nameFieldStringValue = defaultReportFilename(format: format, scope: scope) + guard panel.runModal() == .OK, let url = panel.url else { return } + + let options = options(format: format, scope: scope) + let rootIndex = currentIndexProvider() + + DispatchQueue.global(qos: .userInitiated).async { [weak self] in + do { + let text: String + switch format { + case .csv: + text = ReportExporter.makeCSV(tree: tree, rootIndex: rootIndex, options: options) + case .html: + text = ReportExporter.makeHTML(tree: tree, rootIndex: rootIndex, options: options) + } + try ReportExporter.write(text, to: url) + DispatchQueue.main.async { + self?.toastHandler("Отчёт сохранён: \(url.lastPathComponent)", "doc.text.fill") + } + } catch { + DispatchQueue.main.async { + self?.errorHandler("Не удалось сохранить отчёт: \(error.localizedDescription)") + } + } + } + } + + var appVersion: String { versionProvider() } + + func options( + format: ReportFormat, + scope: ReportScope, + generatedAt: Date = Date() + ) -> ReportOptions { + ReportOptions( + format: format, + scope: scope, + search: searchProvider(), + category: categoryProvider(), + generatedAt: generatedAt, + appVersion: appVersion + ) + } + + func defaultReportFilename(format: ReportFormat, scope: ReportScope) -> String { + let raw = scope == .currentFolder ? currentNameProvider() : rootDisplayNameProvider() + var safe = raw + .replacingOccurrences(of: "/", with: "-") + .replacingOccurrences(of: ":", with: "-") + .trimmingCharacters(in: .whitespacesAndNewlines) + if safe.isEmpty { safe = "DiskScope" } + return "DiskScope-\(safe).\(format.fileExtension)" + } +} diff --git a/Sources/DiskScopeKit/UI/WindowChrome.swift b/Sources/DiskScopeKit/UI/WindowChrome.swift index 36e96a7..7fe687d 100644 --- a/Sources/DiskScopeKit/UI/WindowChrome.swift +++ b/Sources/DiskScopeKit/UI/WindowChrome.swift @@ -528,7 +528,7 @@ struct CommandPaletteView: View { symbol: "square.and.arrow.up", shortcut: "⇧⌘E" ) { - model.exportReport(format: .csv, scope: .currentFolder) + model.report.exportReport(format: .csv, scope: .currentFolder) } ) items.append( @@ -539,7 +539,7 @@ struct CommandPaletteView: View { symbol: "square.and.arrow.up", shortcut: nil ) { - model.exportReport(format: .html, scope: .currentFolder) + model.report.exportReport(format: .html, scope: .currentFolder) } ) items.append( diff --git a/Tests/DiskScopeKitTests/ReportModelTests.swift b/Tests/DiskScopeKitTests/ReportModelTests.swift new file mode 100644 index 0000000..b268261 --- /dev/null +++ b/Tests/DiskScopeKitTests/ReportModelTests.swift @@ -0,0 +1,85 @@ +import Foundation +import XCTest +@testable import DiskScopeKit + +@MainActor +final class ReportModelTests: XCTestCase { + private func makeTree() throws -> ScanTree { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("DiskScopeReportModel-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + try Data(repeating: 0x41, count: 5_000).write(to: root.appendingPathComponent("video.mov")) + addTeardownBlock { try? FileManager.default.removeItem(at: root) } + return try DiskScanner(options: .detailed).scan(path: root.path) + } + + private func makeModel( + tree: ScanTree?, + currentIndex: Int32 = 0, + search: String = "", + category: FileCategory? = nil, + currentName: String = "", + rootName: String = "DiskScope", + version: String = "dev" + ) -> ReportModel { + let model = ReportModel(versionProvider: { version }) + model.attach( + treeProvider: { tree }, + currentIndexProvider: { currentIndex }, + searchProvider: { search }, + categoryProvider: { category }, + currentNameProvider: { currentName }, + rootDisplayNameProvider: { rootName }, + toast: { _, _ in }, + error: { _ in } + ) + return model + } + + func testCanExportReportFollowsTree() throws { + let tree = try makeTree() + XCTAssertTrue(makeModel(tree: tree).canExportReport) + XCTAssertFalse(makeModel(tree: nil).canExportReport) + } + + func testDefaultReportFilenameSanitizesAndFallsBack() { + let model = makeModel(tree: nil, currentName: "Folder: A/B", rootName: "Root") + XCTAssertEqual( + model.defaultReportFilename(format: .csv, scope: .currentFolder), + "DiskScope-Folder- A-B.csv" + ) + XCTAssertEqual( + model.defaultReportFilename(format: .html, scope: .wholeScan), + "DiskScope-Root.html" + ) + + let fallback = makeModel(tree: nil, currentName: " ", rootName: "") + XCTAssertEqual( + fallback.defaultReportFilename(format: .csv, scope: .currentFolder), + "DiskScope-DiskScope.csv" + ) + XCTAssertEqual( + fallback.defaultReportFilename(format: .csv, scope: .wholeScan), + "DiskScope-DiskScope.csv" + ) + } + + func testOptionsCaptureFiltersScopeAndVersion() { + let generatedAt = Date(timeIntervalSince1970: 1_800_000_000) + let model = makeModel( + tree: nil, + search: "video", + category: .video, + version: "9.9.9" + ) + let options = model.options(format: .html, scope: .wholeScan, generatedAt: generatedAt) + + XCTAssertEqual(options.format, .html) + XCTAssertEqual(options.scope, .wholeScan) + XCTAssertEqual(options.search, "video") + XCTAssertEqual(options.category, .video) + XCTAssertEqual(options.generatedAt, generatedAt) + XCTAssertEqual(options.appVersion, "9.9.9") + XCTAssertEqual(model.appVersion, "9.9.9") + } +} diff --git a/docs/build.md b/docs/build.md index 9972105..c5e1783 100644 --- a/docs/build.md +++ b/docs/build.md @@ -95,7 +95,7 @@ MKDOCS_SITE_URL=http://localhost:8000/ .venv/bin/mkdocs build --strict ## Тесты -147 XCTest-тестов покрывают: +150 XCTest-тестов покрывают: - сканер и точность суммы против `du`; - агрегацию мелких файлов, пакеты, симлинки, Unicode-имена;