Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@ Headless-сканер для бенчмарков:

## Тесты

158 тестов: сравнение суммы скана с `du`, агрегация мелких файлов, пакеты,
161 тест: сравнение суммы скана с `du`, агрегация мелких файлов, пакеты,
симлинки, Unicode-имена, отказ доступа, отмена, copy-on-write удаление,
свойства squarified-раскладки, вложенные ячейки, полный цикл `AppModel`
(скан → навигация → фильтры), даты создания и изменения, правила очистки,
Expand Down
2 changes: 1 addition & 1 deletion ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` зелёный.

## Принципы
Expand Down
108 changes: 5 additions & 103 deletions Sources/DiskScopeKit/App/AppModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<Int32> = []
@Published public var showCollection = false
@Published public internal(set) var search = SearchModel()
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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()
}
Expand Down
120 changes: 120 additions & 0 deletions Sources/DiskScopeKit/App/CleanupOperationsModel.swift
Original file line number Diff line number Diff line change
@@ -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)"
}
}
}
2 changes: 1 addition & 1 deletion Sources/DiskScopeKit/UI/CleanupView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion Sources/DiskScopeKit/UI/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
72 changes: 72 additions & 0 deletions Tests/DiskScopeKitTests/CleanupOperationsModelTests.swift
Original file line number Diff line number Diff line change
@@ -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)
}
}
2 changes: 1 addition & 1 deletion docs/build.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ MKDOCS_SITE_URL=http://localhost:8000/ .venv/bin/mkdocs build --strict

## Тесты

158 XCTest-тестов покрывают:
161 XCTest-тест покрывает:

- сканер и точность суммы против `du`;
- агрегацию мелких файлов, пакеты, симлинки, Unicode-имена;
Expand Down
Loading