diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 41c591b..bcf1fde 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 "| Тесты | 158 XCTest |" + echo "| Тесты | 161 XCTest |" } >> "$GITHUB_STEP_SUMMARY" diff --git a/README.md b/README.md index 7c3dd46..491115b 100644 --- a/README.md +++ b/README.md @@ -371,7 +371,7 @@ Headless-сканер для бенчмарков: ## Тесты -158 тестов: сравнение суммы скана с `du`, агрегация мелких файлов, пакеты, +161 тест: сравнение суммы скана с `du`, агрегация мелких файлов, пакеты, симлинки, Unicode-имена, отказ доступа, отмена, copy-on-write удаление, свойства squarified-раскладки, вложенные ячейки, полный цикл `AppModel` (скан → навигация → фильтры), даты создания и изменения, правила очистки, diff --git a/ROADMAP.md b/ROADMAP.md index f66d4ab..8e3c18a 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-клоны | -Текущая база: **158 XCTest**, 17,9 тыс. строк исходников, 398 ключей +Текущая база: **161 XCTest**, 17,9 тыс. строк исходников, 398 ключей локализации, `main` зелёный. ## Принципы diff --git a/Sources/DiskScopeKit/App/AppModel.swift b/Sources/DiskScopeKit/App/AppModel.swift index 1554053..977e896 100644 --- a/Sources/DiskScopeKit/App/AppModel.swift +++ b/Sources/DiskScopeKit/App/AppModel.swift @@ -96,6 +96,7 @@ public final class AppModel: ObservableObject { @Published public internal(set) var trash = TrashModel() @Published public internal(set) var trashOperations = TrashOperationsModel() @Published public internal(set) var cleanup = CleanupModel() + @Published public internal(set) var cleanupOperations = CleanupOperationsModel() @Published public internal(set) var collection: Set = [] @Published public var showCollection = false @Published public internal(set) var search = SearchModel() @@ -192,6 +193,10 @@ public final class AppModel: ObservableObject { trashOperations.objectWillChange.sink { [weak self] _ in self?.objectWillChange.send() }.store(in: &cancellables) + cleanupOperations.attach(appModel: self) + cleanupOperations.objectWillChange.sink { [weak self] _ in + self?.objectWillChange.send() + }.store(in: &cancellables) disk.attach { [weak self] in self?.internalVolume } diskCancellable = disk.objectWillChange.sink { [weak self] _ in self?.objectWillChange.send() @@ -461,109 +466,6 @@ public final class AppModel: ObservableObject { // MARK: - Cleanup - public func requestCleanup() { - guard cleanup.canApply else { return } - if cleanup.hasPermanentSelection - || UserDefaults.standard.bool(forKey: AppSettingsKeys.confirmTrash) { - cleanup.showConfirmation = true - } else { - confirmCleanup() - } - } - - public func confirmCleanup() { - cleanup.showConfirmation = false - guard !fileOperationInFlight, !isScanning, let tree else { return } - let selected = cleanup.selectedSuggestions.filter { suggestion in - suggestion.nodeIndex > 0 - && Int(suggestion.nodeIndex) < tree.count - && !tree.isDeleted(suggestion.nodeIndex) - } - guard !selected.isEmpty else { return } - fileOperationInFlight = true - - DispatchQueue.global(qos: .userInitiated).async { [weak self] in - var trashed: [(index: Int32, original: URL, trashed: URL)] = [] - var permanent: [Int32] = [] - var failures: [(url: URL, message: String)] = [] - for suggestion in selected { - let url = URL(fileURLWithPath: suggestion.path) - do { - if suggestion.disposition == .deletePermanently { - try FileManager.default.removeItem(at: url) - permanent.append(suggestion.nodeIndex) - } else { - var resultingURL: NSURL? - try FileManager.default.trashItem(at: url, resultingItemURL: &resultingURL) - trashed.append((suggestion.nodeIndex, url, (resultingURL as URL?) ?? url)) - } - } catch { - failures.append((url, error.localizedDescription)) - } - } - DispatchQueue.main.async { - guard let self else { return } - self.applyCleanup( - tree: tree, - trashed: trashed, - permanent: permanent, - failures: failures - ) - } - } - } - - private func applyCleanup( - tree scanTree: ScanTree, - trashed: [(index: Int32, original: URL, trashed: URL)], - permanent: [Int32], - failures: [(url: URL, message: String)] - ) { - fileOperationInFlight = false - let indices = trashed.map(\.index) + permanent - guard !indices.isEmpty else { - if let failure = failures.first { - errorMessage = "Не удалось очистить «\(failure.url.lastPathComponent)»: \(failure.message)" - } - return - } - - let removed = scanTree.removingSubtrees(at: indices) - let roots = Array(Set(trashed.map(\.index))) - trash.record( - removal: removed, - trashed: trashed, - collectionRoots: roots.filter { collection.contains($0) } - ) - collection = collection.filter { !removed.tree.isDeleted($0) } - resetDuplicates() - resetSimilar() - fileCount = removed.tree.totalFiles - folderCount = removed.tree.directoryCount() - tree = removed.tree - selection = [] - if removed.tree.isDeleted(currentIndex) { - var cursor = currentIndex - while cursor > 0, removed.tree.isDeleted(cursor) { - cursor = removed.tree.node(cursor).parent - } - currentIndex = max(cursor, 0) - } - rebuildCurrentRows() - refreshVolumes() - stats.refresh() - invalidateCleanup() - - var text = "Очищено: \(Plural.items(indices.count)) · \(ByteFormat.string(removed.bytes))" - if !permanent.isEmpty { - text += " · безвозвратно: \(Plural.items(permanent.count))" - } - showToast(text, symbol: "sparkles") - if let failure = failures.first { - errorMessage = "Не удалось очистить «\(failure.url.lastPathComponent)»: \(failure.message)" - } - } - func resetCleanup() { cleanup.reset() } diff --git a/Sources/DiskScopeKit/App/CleanupOperationsModel.swift b/Sources/DiskScopeKit/App/CleanupOperationsModel.swift new file mode 100644 index 0000000..2ac597c --- /dev/null +++ b/Sources/DiskScopeKit/App/CleanupOperationsModel.swift @@ -0,0 +1,120 @@ +import AppKit +import Combine +import Foundation + +/// Owns cleanup confirmation and destructive cleanup operations. +@MainActor +public final class CleanupOperationsModel: ObservableObject { + weak var appModel: AppModel? + + public init() {} + + func attach(appModel: AppModel) { + self.appModel = appModel + } + + public func request() { + guard let model = appModel, model.cleanup.canApply else { return } + if model.cleanup.hasPermanentSelection + || UserDefaults.standard.bool(forKey: AppSettingsKeys.confirmTrash) { + model.cleanup.showConfirmation = true + } else { + confirm() + } + } + + public func confirm() { + guard let model = appModel else { return } + model.cleanup.showConfirmation = false + guard !model.fileOperationInFlight, !model.isScanning, let tree = model.tree else { return } + let selected = model.cleanup.selectedSuggestions.filter { suggestion in + suggestion.nodeIndex > 0 + && Int(suggestion.nodeIndex) < tree.count + && !tree.isDeleted(suggestion.nodeIndex) + } + guard !selected.isEmpty else { return } + model.fileOperationInFlight = true + + DispatchQueue.global(qos: .userInitiated).async { [weak self] in + var trashed: [(index: Int32, original: URL, trashed: URL)] = [] + var permanent: [Int32] = [] + var failures: [(url: URL, message: String)] = [] + for suggestion in selected { + let url = URL(fileURLWithPath: suggestion.path) + do { + if suggestion.disposition == .deletePermanently { + try FileManager.default.removeItem(at: url) + permanent.append(suggestion.nodeIndex) + } else { + var resultingURL: NSURL? + try FileManager.default.trashItem(at: url, resultingItemURL: &resultingURL) + trashed.append((suggestion.nodeIndex, url, (resultingURL as URL?) ?? url)) + } + } catch { + failures.append((url, error.localizedDescription)) + } + } + DispatchQueue.main.async { + guard let self else { return } + self.apply( + tree: tree, + trashed: trashed, + permanent: permanent, + failures: failures + ) + } + } + } + + private func apply( + tree scanTree: ScanTree, + trashed: [(index: Int32, original: URL, trashed: URL)], + permanent: [Int32], + failures: [(url: URL, message: String)] + ) { + guard let model = appModel else { return } + model.fileOperationInFlight = false + let indices = trashed.map(\.index) + permanent + guard !indices.isEmpty else { + if let failure = failures.first { + model.errorMessage = "Не удалось очистить «\(failure.url.lastPathComponent)»: \(failure.message)" + } + return + } + + let removed = scanTree.removingSubtrees(at: indices) + let roots = Array(Set(trashed.map(\.index))) + model.trash.record( + removal: removed, + trashed: trashed, + collectionRoots: roots.filter { model.collection.contains($0) } + ) + model.collection = model.collection.filter { !removed.tree.isDeleted($0) } + model.resetDuplicates() + model.resetSimilar() + model.fileCount = removed.tree.totalFiles + model.folderCount = removed.tree.directoryCount() + model.tree = removed.tree + model.selection = [] + if removed.tree.isDeleted(model.currentIndex) { + var cursor = model.currentIndex + while cursor > 0, removed.tree.isDeleted(cursor) { + cursor = removed.tree.node(cursor).parent + } + model.currentIndex = max(cursor, 0) + } + model.rebuildCurrentRows() + model.refreshVolumes() + model.stats.refresh() + model.invalidateCleanup() + + var text = "Очищено: \(Plural.items(indices.count)) · \(ByteFormat.string(removed.bytes))" + if !permanent.isEmpty { + text += " · безвозвратно: \(Plural.items(permanent.count))" + } + model.showToast(text, symbol: "sparkles") + if let failure = failures.first { + model.errorMessage = "Не удалось очистить «\(failure.url.lastPathComponent)»: \(failure.message)" + } + } +} diff --git a/Sources/DiskScopeKit/UI/CleanupView.swift b/Sources/DiskScopeKit/UI/CleanupView.swift index a843d8f..7535e98 100644 --- a/Sources/DiskScopeKit/UI/CleanupView.swift +++ b/Sources/DiskScopeKit/UI/CleanupView.swift @@ -290,7 +290,7 @@ struct CleanupView: View { model.cleanup.clearSelection() } AccentButton(title: "Очистить…", symbol: "sparkles") { - model.requestCleanup() + model.cleanupOperations.request() } .disabled(!model.cleanup.canApply) .opacity(model.cleanup.canApply ? 1 : 0.45) diff --git a/Sources/DiskScopeKit/UI/ContentView.swift b/Sources/DiskScopeKit/UI/ContentView.swift index 4a93bae..0ec54cd 100644 --- a/Sources/DiskScopeKit/UI/ContentView.swift +++ b/Sources/DiskScopeKit/UI/ContentView.swift @@ -35,7 +35,7 @@ public struct ContentView: View { } .alert("Очистить выбранное?", isPresented: $model.cleanup.showConfirmation) { Button("Отмена", role: .cancel) {} - Button("Очистить", role: .destructive) { model.confirmCleanup() } + Button("Очистить", role: .destructive) { model.cleanupOperations.confirm() } } message: { Text(model.cleanup.confirmationMessage) } diff --git a/Tests/DiskScopeKitTests/CleanupOperationsModelTests.swift b/Tests/DiskScopeKitTests/CleanupOperationsModelTests.swift new file mode 100644 index 0000000..6cf2a4b --- /dev/null +++ b/Tests/DiskScopeKitTests/CleanupOperationsModelTests.swift @@ -0,0 +1,72 @@ +import Foundation +import XCTest +@testable import DiskScopeKit + +@MainActor +final class CleanupOperationsModelTests: XCTestCase { + private var previousConfirmTrash: Any? + + override func setUpWithError() throws { + try super.setUpWithError() + previousConfirmTrash = UserDefaults.standard.object(forKey: AppSettingsKeys.confirmTrash) + UserDefaults.standard.set(true, forKey: AppSettingsKeys.confirmTrash) + } + + override func tearDownWithError() throws { + if let previousConfirmTrash { + UserDefaults.standard.set(previousConfirmTrash, forKey: AppSettingsKeys.confirmTrash) + } else { + UserDefaults.standard.removeObject(forKey: AppSettingsKeys.confirmTrash) + } + try super.tearDownWithError() + } + + private func suggestion(id: String = "preview", selected: Bool = true) -> CleanupSuggestion { + CleanupSuggestion( + id: id, + ruleID: id, + title: id, + nodeIndex: 1, + name: id, + path: "/tmp/\(id)", + relativePath: id, + size: 100, + itemCount: 1, + risk: .safe, + reason: "reason", + isDirectory: false, + disposition: .trash, + isSelectedByDefault: selected + ) + } + + func testRequestShowsConfirmationWhenSelectionExists() { + let model = AppModel() + model.preview.cleanup([suggestion()]) + + model.cleanupOperations.request() + + XCTAssertTrue(model.cleanup.showConfirmation) + } + + func testRequestDoesNothingWithoutSelection() { + let model = AppModel() + model.preview.cleanup([suggestion(selected: false)]) + + model.cleanupOperations.request() + + XCTAssertFalse(model.cleanup.showConfirmation) + } + + func testConfirmWithoutTreeOnlyClosesConfirmation() { + let model = AppModel() + model.preview.cleanup([suggestion()]) + model.cleanup.showConfirmation = true + + model.cleanupOperations.confirm() + + XCTAssertFalse(model.cleanup.showConfirmation) + XCTAssertFalse(model.trash.busy) + XCTAssertFalse(model.cleanup.loading) + } +} diff --git a/docs/build.md b/docs/build.md index 19bea56..083e94c 100644 --- a/docs/build.md +++ b/docs/build.md @@ -95,7 +95,7 @@ MKDOCS_SITE_URL=http://localhost:8000/ .venv/bin/mkdocs build --strict ## Тесты -158 XCTest-тестов покрывают: +161 XCTest-тест покрывает: - сканер и точность суммы против `du`; - агрегацию мелких файлов, пакеты, симлинки, Unicode-имена;