Skip to content

armgit / peel

Public Imported from GitHub
0

Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.

Look at projects again once the scan is old, and before moving their folders

Țugui Dragoșb8102608b2e5
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Commands/FileCommands.swift b/Packages/PeelCore/Sources/PeelCommandLine/Commands/FileCommands.swift
index ca528cd1..399f7117 100644
--- a/Packages/PeelCore/Sources/PeelCommandLine/Commands/FileCommands.swift
+++ b/Packages/PeelCore/Sources/PeelCommandLine/Commands/FileCommands.swift
@@ -635,7 +635,12 @@ struct ProjectsCommand: AsyncParsableCommand {
yes: removal.yes,
using: service,
recordingIn: log,
- refusals: refusals
+ refusals: refusals,
+ move: { service, urls in
+ // The question takes time, and work may have started in a project meanwhile.
+ let changed = await ProjectArtifacts.changedSinceScan(suggested, among: artifacts)
+ return await service.trash(urls, refusing: { changed.contains($0) ? .changedSinceScan : nil })
+ }
)
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Developer/ProjectArtifacts.swift b/Packages/PeelCore/Sources/PeelCore/Developer/ProjectArtifacts.swift
index 5f4684d7..89fbfa31 100644
--- a/Packages/PeelCore/Sources/PeelCore/Developer/ProjectArtifacts.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Developer/ProjectArtifacts.swift
@@ -821,6 +821,21 @@ public enum ProjectArtifacts {
definitions.flatMap(\.markers).filter { $0.hasPrefix("*") }.map { String($0.dropFirst()) }
)
+ /// Read again right before a move: the artifacts of `chosen` Peel would suggest whose project has changed in the
+ /// last 7 days, or can't be read whole anymore. A folder chosen though Peel didn't suggest it stays chosen. `all`
+ /// is every artifact the scan found.
+ @concurrent
+ public static func changedSinceScan(_ chosen: [ProjectArtifact], among all: [ProjectArtifact]) async -> Set<URL> {
+ let suggested = chosen.filter(\.isRecommended)
+ guard !suggested.isEmpty else { return [] }
+ let activities = await lastActivities(of: suggested.map(\.project), passingBy: all.map(\.url))
+ let cutoff = Date.now.addingTimeInterval(-recentlyActive)
+ return Set(suggested.filter { artifact in
+ guard let activity = activities[key(of: artifact.project)], activity.isCertain else { return true }
+ return activity.date.map { $0 > cutoff } ?? false
+ }.map(\.url))
+ }
+
/// Each project's name as a list shows it: its folder's name, or, while another of `projects` has a folder of the
/// same name, as many folders above it as tell them apart, as in `acme/frontend`.
public static func names(of projects: [URL]) -> [String] {
@@ -1060,13 +1075,37 @@ public enum ProjectArtifacts {
/// Builds write into artifacts while nobody works on a project, so its last change passes by every one inside.
private static func withLastActivity(_ pending: [Pending]) async -> [ProjectArtifact] {
- let projects = Dictionary(
- pending.map { (key(of: $0.project), $0.project) }, uniquingKeysWith: { first, _ in first }
- )
+ let activities = await lastActivities(of: pending.map(\.project), passingBy: pending.map(\.url))
+ return pending.map { artifact in
+ let activity = activities[key(of: artifact.project)] ?? (date: nil, isCertain: false)
+ let heldBack = HoldBack.seen(in: artifact.contents)
+ return ProjectArtifact(
+ url: artifact.url,
+ project: artifact.project,
+ name: artifact.found.name,
+ tool: artifact.found.definition?.tool,
+ size: artifact.contents.flatMap { $0.couldNotBeRead ? nil : $0.size },
+ lastActivity: activity.date,
+ lastActivityIsCertain: activity.isCertain,
+ hasGenericName: artifact.found.definition?.isGeneric ?? false,
+ isEnvironment: artifact.found.definition?.isEnvironment ?? false,
+ heldBack: (heldBack == .holdsRepository && artifact.found.remakesItsClones ? nil : heldBack)
+ ?? (artifact.found.definition?.keepsItsSetup == true ? .keepsItsSetup : nil)
+ )
+ }
+ }
+
+ /// Each project's last change, keyed by `key(of:)`, passing by every one of `artifacts` inside it, those of the
+ /// projects inside it included.
+ private static func lastActivities(
+ of projects: [URL],
+ passingBy artifacts: [URL]
+ ) async -> [String: (date: Date?, isCertain: Bool)] {
+ let projects = Dictionary(projects.map { (key(of: $0), $0) }, uniquingKeysWith: { first, _ in first })
var inside: [String: Set<String>] = [:]
- for artifact in pending {
- let path = key(of: artifact.url)
- var above = artifact.url.deletingLastPathComponent()
+ for artifact in artifacts {
+ let path = key(of: artifact)
+ var above = artifact.deletingLastPathComponent()
while true {
let folder = key(of: above)
if projects[folder] != nil {
@@ -1084,23 +1123,7 @@ public enum ProjectArtifacts {
lastActivity(in: folder, ignoring: ignoring, isGivenUp: isGivenUp)
} ?? (date: nil, isCertain: false)
}
- return pending.map { artifact in
- let activity = activities[key(of: artifact.project)] ?? (date: nil, isCertain: false)
- let heldBack = HoldBack.seen(in: artifact.contents)
- return ProjectArtifact(
- url: artifact.url,
- project: artifact.project,
- name: artifact.found.name,
- tool: artifact.found.definition?.tool,
- size: artifact.contents.flatMap { $0.couldNotBeRead ? nil : $0.size },
- lastActivity: activity.date,
- lastActivityIsCertain: activity.isCertain,
- hasGenericName: artifact.found.definition?.isGeneric ?? false,
- isEnvironment: artifact.found.definition?.isEnvironment ?? false,
- heldBack: (heldBack == .holdsRepository && artifact.found.remakesItsClones ? nil : heldBack)
- ?? (artifact.found.definition?.keepsItsSetup == true ? .keepsItsSetup : nil)
- )
- }
+ return activities
}
/// The nearest folder from `folder` up to `root` holding a repository or a tool's project file, else `folder`.
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/ProjectArtifactsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/ProjectArtifactsTests.swift
index 1481909b..b834db11 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/ProjectArtifactsTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/ProjectArtifactsTests.swift
@@ -341,6 +341,29 @@ struct ProjectArtifactsTests {
#expect(artifact("DerivedData").keptBecause == nil && artifact("DerivedData").isRecommended)
}
+ @Test func refusesASuggestedFolderWhoseProjectChangedSinceTheScan() async throws {
+ let directory = try TemporaryDirectory()
+ for project in ["app", "tool"] {
+ try directory.file("Code/\(project)/package.json", bytes: 16)
+ try directory.file("Code/\(project)/src/index.js", bytes: 16)
+ try directory.file("Code/\(project)/node_modules/left-pad/index.js", bytes: 16)
+ }
+ try directory.file("Code/app/.venv/pyvenv.cfg", bytes: 16)
+ try directory.file("Code/app/requirements.txt", bytes: 16)
+ try age(directory.url, days: 60)
+ let scan = await ProjectArtifacts.scan(roots: [directory.url.appending(path: "Code")])
+ try FileManager.default.setAttributes(
+ [.modificationDate: Date.now],
+ ofItemAtPath: directory.url.appending(path: "Code/app/src/index.js").path(percentEncoded: false)
+ )
+
+ let changed = await ProjectArtifacts.changedSinceScan(scan.artifacts, among: scan.artifacts)
+
+ #expect(scan.artifacts.filter(\.isRecommended).count == 2)
+ #expect(changed.map(\.lastPathComponent) == ["node_modules"])
+ #expect(changed.allSatisfy { $0.path(percentEncoded: false).contains("/app/") })
+ }
+
@Test func findsWhatJavaScriptToolsBuild() async throws {
try await expectFound([
Kind(artifact: ".nuxt", marker: "nuxt.config.ts", tool: "Nuxt", isGeneric: false),
diff --git a/Peel/Model/ProjectLibrary.swift b/Peel/Model/ProjectLibrary.swift
index a52e01af..d5b50b2b 100644
--- a/Peel/Model/ProjectLibrary.swift
+++ b/Peel/Model/ProjectLibrary.swift
@@ -45,11 +45,26 @@ final class ProjectLibrary {
var selection: URL?
var selectedURLs: Set<URL> = []
- init() {
- folders = (UserDefaults.standard.array(forKey: Self.foldersKey) as? [String] ?? [])
+ private let defaults: UserDefaults
+ @ObservationIgnored private var scannedAt: ContinuousClock.Instant?
+
+ /// How long what a scan saw is shown before the page, appearing or with Peel coming forward, looks again.
+ static let scanAgainAfter: Duration = .seconds(60 * 60)
+
+ init(defaults: UserDefaults = .standard) {
+ self.defaults = defaults
+ folders = (defaults.array(forKey: Self.foldersKey) as? [String] ?? [])
.map { URL(filePath: $0, directoryHint: .isDirectory) }
}
+ /// Scans unless the last scan ended less than `age` ago, one or a removal runs, or the last scan was stopped: a
+ /// project changed in the last 7 days is held back, so what a scan saw ages.
+ func refreshUnlessScanned(within age: Duration) async {
+ guard !isScanning, !isRemoving, !scanRun.wasStopped else { return }
+ if let scannedAt, ContinuousClock.now - scannedAt < age { return }
+ await refresh()
+ }
+
var selectedGroup: ProjectGroup? {
groups?.first { $0.project == selection }
}
@@ -62,6 +77,7 @@ final class ProjectLibrary {
let scan = await ProjectArtifacts.scan(roots: folders, exclusions: ExclusionsStore.shared.exclusions)
return (scan, await TimeMachineExclusion.standings(of: scan.artifacts.map(\.url)))
}) else { return }
+ scannedAt = .now
let artifacts = scan.artifacts
wasCutShort = scan.wasCutShort
needsFullDiskAccess = scan.needsFullDiskAccess
@@ -163,7 +179,7 @@ final class ProjectLibrary {
}
private func save() {
- UserDefaults.standard.set(folders.map { $0.path(percentEncoded: false) }, forKey: Self.foldersKey)
+ defaults.set(folders.map { $0.path(percentEncoded: false) }, forKey: Self.foldersKey)
}
private func group(of page: CarriedSelection.Page) -> ProjectGroup? {
@@ -190,8 +206,12 @@ extension ProjectLibrary: CarriesSelection {
guard let group = group(of: part.page) else { return TrashResult() }
isRemoving = true
defer { isRemoving = false }
- let urls = group.artifacts.map(\.url).filter { selectedURLs.contains($0) && part.sizes.keys.contains($0) }
- return await TrashService(exclusions: ExclusionsStore.shared.exclusions).trash(urls)
+ let chosen = group.artifacts.filter { selectedURLs.contains($0.url) && part.sizes.keys.contains($0.url) }
+ let changed = await ProjectArtifacts.changedSinceScan(chosen, among: (groups ?? []).flatMap(\.artifacts))
+ return await TrashService(exclusions: ExclusionsStore.shared.exclusions).trash(
+ chosen.map(\.url),
+ refusing: { changed.contains($0) ? .changedSinceScan : nil }
+ )
}
func refresh(after parts: [CarriedSelection.Part], apps: AppLibrary) async {
diff --git a/Peel/Views/Projects/ProjectList.swift b/Peel/Views/Projects/ProjectList.swift
index 935508c2..0c4e7ecf 100644
--- a/Peel/Views/Projects/ProjectList.swift
+++ b/Peel/Views/Projects/ProjectList.swift
@@ -164,8 +164,10 @@ struct ProjectList: View {
}
}
.task {
- guard projects.groups == nil, !projects.isScanning, !projects.scanRun.wasStopped else { return }
- await projects.refresh()
+ await projects.refreshUnlessScanned(within: ProjectLibrary.scanAgainAfter)
+ }
+ .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
+ Task { await projects.refreshUnlessScanned(within: ProjectLibrary.scanAgainAfter) }
}
.rescanOnExclusionChange("ProjectList") { await projects.refresh() }
.rescanAfterPutBack(.projects) { await projects.refresh() }
diff --git a/PeelTests/ProjectLibraryTests.swift b/PeelTests/ProjectLibraryTests.swift
new file mode 100644
index 00000000..fb4880f9
--- /dev/null
+++ b/PeelTests/ProjectLibraryTests.swift
@@ -0,0 +1,34 @@
+import Foundation
+@testable import Peel
+import Testing
+
+@MainActor
+struct ProjectLibraryTests {
+ @Test func scansAgainOnlyOnceItsLastScanIsOld() async throws {
+ let made = try MadeUpDefaults()
+ defer { made.forget() }
+ let root = FileManager.default.temporaryDirectory.appending(
+ path: "ProjectLibraryTests-\(UUID().uuidString)", directoryHint: .isDirectory
+ )
+ defer { try? FileManager.default.removeItem(at: root) }
+ try project("app", in: root)
+ made.defaults.set([root.path(percentEncoded: false)], forKey: "projectFolders")
+ let library = ProjectLibrary(defaults: made.defaults)
+
+ await library.refreshUnlessScanned(within: .seconds(3_600))
+ try project("tool", in: root)
+ await library.refreshUnlessScanned(within: .seconds(3_600))
+ let soon = library.groups?.map(\.name)
+ await library.refreshUnlessScanned(within: .zero)
+
+ #expect(soon == ["app"])
+ #expect(library.groups?.map(\.name).sorted() == ["app", "tool"])
+ }
+
+ private func project(_ name: String, in root: URL) throws {
+ let folder = root.appending(path: "\(name)/node_modules/left-pad", directoryHint: .isDirectory)
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ try Data("{}".utf8).write(to: root.appending(path: "\(name)/package.json"))
+ try Data("//".utf8).write(to: folder.appending(path: "index.js"))
+ }
+}