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.

Test the app's own models inside a Peel that starts and shows nothing

Țugui Dragoș744bfd76d7f9
diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml
index 23d87367..c0ffef0d 100644
--- a/.github/workflows/checks.yml
+++ b/.github/workflows/checks.yml
@@ -74,6 +74,24 @@ jobs:
exit 1
fi
+ # The app's own tests run inside Peel, which the scheme launches with `PEEL_HOSTS_TESTS` set, so it starts nothing
+ # and shows nothing. Their build is held to warnings as the Debug build is.
+ - name: Test the app's models in Peel
+ run: |
+ log="$RUNNER_TEMP/app-tests.log"
+ if ! xcodebuild -project Peel.xcodeproj -scheme PeelTests -configuration Debug \
+ -destination "platform=macOS,arch=$(uname -m)" -derivedDataPath build/DerivedData \
+ CODE_SIGNING_ALLOWED=NO test > "$log" 2>&1; then
+ cat "$log"
+ exit 1
+ fi
+ if grep -q "warning:" "$log"; then
+ grep "warning:" "$log"
+ echo "::error::The app's tests build with warnings."
+ exit 1
+ fi
+ grep -E "Test run with" "$log"
+
# Release builds every binary for Apple silicon, with pointer authentication (arm64e) and without, and for Intel,
# with the optimizer a Debug build leaves off. The settings are given here too, since only the command line
# reaches the Swift packages: a package that names no platform would be built for an older macOS, with its class
diff --git a/AGENTS.md b/AGENTS.md
index df8997ff..ab37e814 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -34,8 +34,9 @@ prove, and only then fix.
own page, from several apps' page, from Package Receipts, and through the Homebrew page, so a rule about what may
move an app is asked on each of them.
6. **Build and test after every change**, not only at the end: the whole package suite with warnings as errors,
- and the app's Debug build ([CONTRIBUTING.md](CONTRIBUTING.md#what-you-need) has the commands). Before proposing
- the change, run what the Checks workflow runs too: the Release build with `ENABLE_POINTER_AUTHENTICATION=YES` and
+ the app's Debug build, and the app's own tests, which run inside Peel
+ ([CONTRIBUTING.md](CONTRIBUTING.md#what-you-need) has the commands). Before proposing the change, run what the
+ Checks workflow runs too: the Release build with `ENABLE_POINTER_AUTHENTICATION=YES` and
`MACOSX_DEPLOYMENT_TARGET=26.0`, since some of Swift's checks run only on optimized code, the accessibility audit's
build, and `python3 Scripts/sync_localizations.py --check` and `python3 Scripts/generate_manual.py --check`.
7. **Check it where it shows**, live: open the page the change touches, or run the `peel` command it changes, and
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 257c1870..687b4a74 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -387,6 +387,10 @@ its place (`SettingsView`), whose zap takes Peel's whole folder, `Terminal/` inc
- `swift test --package-path Packages/PeelCore -Xswiftc -warnings-as-errors` runs the whole suite, held to
warnings as errors as the app is. Tests use temporary folders (`TemporaryDirectory`) and never touch the user's
own state.
+- `PeelTests` holds the tests of the app's own models, run inside Peel, which the scheme launches with
+ `PEEL_HOSTS_TESTS` set: Peel then starts none of its work, opens no window, and shows no menu bar item, so the tests
+ drive the models alone and leave the Mac's own Peel as it was. `xcodebuild test -project Peel.xcodeproj -scheme
+ PeelTests -destination "platform=macOS,arch=$(uname -m)" -derivedDataPath build/DerivedData` runs them.
- Scanners take their slow parts as parameters (how to measure a folder, how to run a tool), so a test can
stand in for a folder that never answers or a tool that fails.
- The `Attack*Tests` files try to get past the safety rules on purpose: another case, a link, a `/.vol` path, a
@@ -399,8 +403,8 @@ its place (`SettingsView`), whose zap takes Peel's whole folder, `Terminal/` inc
- `Scripts/sync_localizations.py --check` fails when a string catalog is behind the code, and
`Scripts/generate_manual.py --check` when the manual page of `peel` is behind the tool.
- The Checks workflow (`.github/workflows/checks.yml`) runs on every push and pull request: the suite, Sparkle's
- build, the app in Debug and in Release with every binary's three slices and its class data signed, the
- accessibility audit's build, and both `--check` scripts.
+ build, the app in Debug and its own tests, the app in Release with every binary's three slices and its class data
+ signed, the accessibility audit's build, and both `--check` scripts.
## Releases
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 96210b99..6efec5fc 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -17,10 +17,10 @@ before the fix is written, and the result is checked where it shows, as [AGENTS.
- Xcode 27 or later, with Swift 6.4.
- A team to sign with, even a free one. The project names its maintainer's team, so build with yours: add
`DEVELOPMENT_TEAM=YOUR_TEAM_ID` to the `xcodebuild` command, or choose your team under Signing & Capabilities for each
- of the four targets the Peel scheme builds (and PeelUITests, to run the audit), and leave that change out of your
- commits. launchd starts the helper only as the team named in `Support/com.tuguidragos.Peel.Helper.plist`
- (`SpawnConstraint`), so to install the helper you build, put your team there as well, again outside your commits. The
- package's tests need no signing.
+ of the four targets the Peel scheme builds (and PeelTests and PeelUITests, to run the app's own tests and the audit),
+ and leave that change out of your commits. launchd starts the helper only as the team named in
+ `Support/com.tuguidragos.Peel.Helper.plist` (`SpawnConstraint`), so to install the helper you build, put your team
+ there as well, again outside your commits. The package's tests need no signing.
- Two dependencies: Apple's swift-argument-parser, which Xcode fetches, and Sparkle, which updates Peel. Sparkle is
built from its source, at the commit `Scripts/build_sparkle.sh` names, with arm64e and without its XPC services: run
the script once before the first build. When that commit changes, move `build/SparkleSource` to the Trash first, since
@@ -36,6 +36,14 @@ xcodebuild -project Peel.xcodeproj -scheme Peel -configuration Debug -destinatio
swift test --package-path Packages/PeelCore -Xswiftc -warnings-as-errors
```
+The app's own models are tested inside Peel, which the PeelTests scheme launches with `PEEL_HOSTS_TESTS` set, so that
+it starts nothing and shows nothing:
+
+```bash
+xcodebuild -project Peel.xcodeproj -scheme PeelTests -configuration Debug \
+ -destination "platform=macOS,arch=$(uname -m)" -derivedDataPath build/DerivedData DEVELOPMENT_TEAM=YOUR_TEAM_ID test
+```
+
Build and test after every change, not only at the end. After a Debug build, run
`python3 Scripts/sync_localizations.py` so the string catalogs match the strings in the code; it refuses to run
without build output, or with a build older than the code, rather than empty the catalogs, and `--check` says what
@@ -67,6 +75,7 @@ python3 Scripts/generate_manual.py --check
touching it.
- `PeelFinder/`: the sandboxed Finder Sync extension.
- `PeelCLI/`: the `peel` command-line tool, a thin entry point.
+- `PeelTests/`: the tests of the app's own models, run inside Peel.
- `PeelUITests/`: the accessibility audit, run by hand before a release.
- `Packages/PeelCore/`: everything that decides and acts, with the tests. `PeelCore` scans, matches, and removes;
`PeelPrivileged` is the part the helper shares; `PeelCommandLine` holds the `peel` commands; `PeelLink` is the
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/LineLengthTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/LineLengthTests.swift
index b3f72f68..98c2ce7c 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/LineLengthTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/LineLengthTests.swift
@@ -7,7 +7,9 @@ struct LineLengthTests {
.deletingLastPathComponent().deletingLastPathComponent()
.deletingLastPathComponent()
- static let folders = ["Peel", "PeelCLI", "PeelFinder", "PeelHelper", "PeelUITests", "Scripts", "Packages/PeelCore"]
+ static let folders = [
+ "Peel", "PeelCLI", "PeelFinder", "PeelHelper", "PeelTests", "PeelUITests", "Scripts", "Packages/PeelCore",
+ ]
/// What counts is a line without its string literals, so a sentence is never split and can be searched for.
@Test func everyLineFitsIn120Columns() throws {
diff --git a/Peel.xcodeproj/project.pbxproj b/Peel.xcodeproj/project.pbxproj
index dba46437..5c3ce252 100644
--- a/Peel.xcodeproj/project.pbxproj
+++ b/Peel.xcodeproj/project.pbxproj
@@ -53,6 +53,13 @@
remoteGlobalIDString = AA0000000000000000000006;
remoteInfo = Peel;
};
+ AA0000000000000000000074 /* PBXContainerItemProxy */ = {
+ isa = PBXContainerItemProxy;
+ containerPortal = AA0000000000000000000001 /* Project object */;
+ proxyType = 1;
+ remoteGlobalIDString = AA0000000000000000000006;
+ remoteInfo = Peel;
+ };
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
@@ -125,6 +132,7 @@
AA0000000000000000000051 /* Logo.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Logo.xcassets; sourceTree = "<group>"; };
AA000000000000000000005B /* PeelUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = PeelUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
AA000000000000000000006B /* Sparkle.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Sparkle.framework; path = build/SparkleBuild/Build/Products/Release/Sparkle.framework; sourceTree = SOURCE_ROOT; };
+ AA000000000000000000006E /* PeelTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = PeelTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
/* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedRootGroup section */
@@ -163,6 +171,11 @@
path = PeelUITests;
sourceTree = "<group>";
};
+ AA000000000000000000006F /* PeelTests */ = {
+ isa = PBXFileSystemSynchronizedRootGroup;
+ path = PeelTests;
+ sourceTree = "<group>";
+ };
/* End PBXFileSystemSynchronizedRootGroup section */
/* Begin PBXFrameworksBuildPhase section */
@@ -207,6 +220,13 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
+ AA0000000000000000000072 /* Frameworks */ = {
+ isa = PBXFrameworksBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
@@ -218,6 +238,7 @@
AA0000000000000000000033 /* PeelFinder */,
AA0000000000000000000041 /* PeelCLI */,
AA000000000000000000005A /* PeelUITests */,
+ AA000000000000000000006F /* PeelTests */,
AA0000000000000000000056 /* Localization */,
AA000000000000000000004F /* Logo */,
AA0000000000000000000031 /* Support */,
@@ -234,6 +255,7 @@
AA0000000000000000000035 /* PeelFinder.appex */,
AA0000000000000000000043 /* peel */,
AA000000000000000000005B /* PeelUITests.xctest */,
+ AA000000000000000000006E /* PeelTests.xctest */,
);
name = Products;
sourceTree = "<group>";
@@ -399,6 +421,26 @@
productReference = AA000000000000000000005B /* PeelUITests.xctest */;
productType = "com.apple.product-type.bundle.ui-testing";
};
+ AA0000000000000000000070 /* PeelTests */ = {
+ isa = PBXNativeTarget;
+ buildConfigurationList = AA0000000000000000000075 /* Build configuration list for PBXNativeTarget "PeelTests" */;
+ buildPhases = (
+ AA0000000000000000000071 /* Sources */,
+ AA0000000000000000000072 /* Frameworks */,
+ );
+ buildRules = (
+ );
+ dependencies = (
+ AA0000000000000000000073 /* PBXTargetDependency */,
+ );
+ fileSystemSynchronizedGroups = (
+ AA000000000000000000006F /* PeelTests */,
+ );
+ name = PeelTests;
+ productName = PeelTests;
+ productReference = AA000000000000000000006E /* PeelTests.xctest */;
+ productType = "com.apple.product-type.bundle.unit-test";
+ };
/* End PBXNativeTarget section */
/* Begin PBXProject section */
@@ -466,6 +508,7 @@
AA0000000000000000000034 /* PeelFinder */,
AA0000000000000000000042 /* PeelCLI */,
AA000000000000000000005C /* PeelUITests */,
+ AA0000000000000000000070 /* PeelTests */,
);
};
/* End PBXProject section */
@@ -554,6 +597,13 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
+ AA0000000000000000000071 /* Sources */ = {
+ isa = PBXSourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
@@ -577,6 +627,11 @@
target = AA0000000000000000000006 /* Peel */;
targetProxy = AA0000000000000000000060 /* PBXContainerItemProxy */;
};
+ AA0000000000000000000073 /* PBXTargetDependency */ = {
+ isa = PBXTargetDependency;
+ target = AA0000000000000000000006 /* Peel */;
+ targetProxy = AA0000000000000000000074 /* PBXContainerItemProxy */;
+ };
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
@@ -592,6 +647,7 @@
MARKETING_VERSION = 1.1.0;
OTHER_SWIFT_FLAGS = "$(inherited) -enable-upcoming-feature ImmutableWeakCaptures";
PRODUCT_BUNDLE_IDENTIFIER = com.tuguidragos.Peel.CLI;
+ PRODUCT_MODULE_NAME = PeelCLI;
PRODUCT_NAME = peel;
SKIP_INSTALL = YES;
SWIFT_APPROACHABLE_CONCURRENCY = YES;
@@ -614,6 +670,7 @@
MARKETING_VERSION = 1.1.0;
OTHER_SWIFT_FLAGS = "$(inherited) -enable-upcoming-feature ImmutableWeakCaptures";
PRODUCT_BUNDLE_IDENTIFIER = com.tuguidragos.Peel.CLI;
+ PRODUCT_MODULE_NAME = PeelCLI;
PRODUCT_NAME = peel;
SKIP_INSTALL = YES;
SWIFT_APPROACHABLE_CONCURRENCY = YES;
@@ -980,6 +1037,60 @@
};
name = Release;
};
+ AA0000000000000000000076 /* Debug */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ BUNDLE_LOADER = "$(TEST_HOST)";
+ CODE_SIGN_STYLE = Automatic;
+ CURRENT_PROJECT_VERSION = 261013;
+ DEVELOPMENT_TEAM = 6R6J264YA2;
+ FRAMEWORK_SEARCH_PATHS = (
+ "$(inherited)",
+ "$(PROJECT_DIR)/build/SparkleBuild/Build/Products/Release",
+ );
+ GENERATE_INFOPLIST_FILE = YES;
+ LM_SKIP_METADATA_EXTRACTION = YES;
+ MARKETING_VERSION = 1.1.0;
+ OTHER_SWIFT_FLAGS = "$(inherited) -enable-upcoming-feature ImmutableWeakCaptures";
+ PRODUCT_BUNDLE_IDENTIFIER = com.tuguidragos.Peel.Tests;
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ SWIFT_APPROACHABLE_CONCURRENCY = YES;
+ SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;
+ SWIFT_UPCOMING_FEATURE_EXISTENTIAL_ANY = YES;
+ SWIFT_UPCOMING_FEATURE_INTERNAL_IMPORTS_BY_DEFAULT = YES;
+ SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
+ SWIFT_VERSION = 6.0;
+ TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Peel.app/Contents/MacOS/Peel";
+ };
+ name = Debug;
+ };
+ AA0000000000000000000077 /* Release */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ BUNDLE_LOADER = "$(TEST_HOST)";
+ CODE_SIGN_STYLE = Automatic;
+ CURRENT_PROJECT_VERSION = 261013;
+ DEVELOPMENT_TEAM = 6R6J264YA2;
+ FRAMEWORK_SEARCH_PATHS = (
+ "$(inherited)",
+ "$(PROJECT_DIR)/build/SparkleBuild/Build/Products/Release",
+ );
+ GENERATE_INFOPLIST_FILE = YES;
+ LM_SKIP_METADATA_EXTRACTION = YES;
+ MARKETING_VERSION = 1.1.0;
+ OTHER_SWIFT_FLAGS = "$(inherited) -enable-upcoming-feature ImmutableWeakCaptures";
+ PRODUCT_BUNDLE_IDENTIFIER = com.tuguidragos.Peel.Tests;
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ SWIFT_APPROACHABLE_CONCURRENCY = YES;
+ SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;
+ SWIFT_UPCOMING_FEATURE_EXISTENTIAL_ANY = YES;
+ SWIFT_UPCOMING_FEATURE_INTERNAL_IMPORTS_BY_DEFAULT = YES;
+ SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
+ SWIFT_VERSION = 6.0;
+ TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Peel.app/Contents/MacOS/Peel";
+ };
+ name = Release;
+ };
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
@@ -1037,6 +1148,15 @@
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
+ AA0000000000000000000075 /* Build configuration list for PBXNativeTarget "PeelTests" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ AA0000000000000000000076 /* Debug */,
+ AA0000000000000000000077 /* Release */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Release;
+ };
/* End XCConfigurationList section */
/* Begin XCLocalSwiftPackageReference section */
diff --git a/Peel.xcodeproj/xcshareddata/xcschemes/PeelTests.xcscheme b/Peel.xcodeproj/xcshareddata/xcschemes/PeelTests.xcscheme
new file mode 100644
index 00000000..003b51e0
--- /dev/null
+++ b/Peel.xcodeproj/xcshareddata/xcschemes/PeelTests.xcscheme
@@ -0,0 +1,77 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Scheme
+ LastUpgradeVersion = "2700"
+ version = "1.7">
+ <BuildAction
+ parallelizeBuildables = "YES"
+ buildImplicitDependencies = "YES">
+ <BuildActionEntries>
+ <BuildActionEntry
+ buildForTesting = "YES"
+ buildForRunning = "NO"
+ buildForProfiling = "NO"
+ buildForArchiving = "NO"
+ buildForAnalyzing = "NO">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "AA0000000000000000000070"
+ BuildableName = "PeelTests.xctest"
+ BlueprintName = "PeelTests"
+ ReferencedContainer = "container:Peel.xcodeproj">
+ </BuildableReference>
+ </BuildActionEntry>
+ </BuildActionEntries>
+ </BuildAction>
+ <TestAction
+ buildConfiguration = "Debug"
+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+ shouldUseLaunchSchemeArgsEnv = "NO"
+ systemAttachmentLifetime = "keepNever"
+ preferredScreenCaptureFormat = "screenshots">
+ <Testables>
+ <TestableReference
+ skipped = "NO">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "AA0000000000000000000070"
+ BuildableName = "PeelTests.xctest"
+ BlueprintName = "PeelTests"
+ ReferencedContainer = "container:Peel.xcodeproj">
+ </BuildableReference>
+ </TestableReference>
+ </Testables>
+ <EnvironmentVariables>
+ <EnvironmentVariable
+ key = "PEEL_HOSTS_TESTS"
+ value = "1"
+ isEnabled = "YES">
+ </EnvironmentVariable>
+ </EnvironmentVariables>
+ </TestAction>
+ <LaunchAction
+ buildConfiguration = "Debug"
+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+ launchStyle = "0"
+ useCustomWorkingDirectory = "NO"
+ ignoresPersistentStateOnLaunch = "NO"
+ debugDocumentVersioning = "YES"
+ debugServiceExtension = "internal"
+ allowLocationSimulation = "YES">
+ </LaunchAction>
+ <ProfileAction
+ buildConfiguration = "Release"
+ shouldUseLaunchSchemeArgsEnv = "YES"
+ savedToolIdentifier = ""
+ useCustomWorkingDirectory = "NO"
+ debugDocumentVersioning = "YES">
+ </ProfileAction>
+ <AnalyzeAction
+ buildConfiguration = "Debug">
+ </AnalyzeAction>
+ <ArchiveAction
+ buildConfiguration = "Release"
+ revealArchiveInOrganizer = "YES">
+ </ArchiveAction>
+</Scheme>
diff --git a/Peel/Model/TrashMonitor.swift b/Peel/Model/TrashMonitor.swift
index 2ea84798..c56e6d02 100644
--- a/Peel/Model/TrashMonitor.swift
+++ b/Peel/Model/TrashMonitor.swift
@@ -99,7 +99,7 @@ final class TrashMonitor {
/// first goes to the Trash, and the home's is made again only then after it is deleted. Until it is there, the folder
/// it appears in is watched: the top of the disk, where `.Trashes` appears, or the home folder.
@MainActor
-private final class TrashWatch {
+final class TrashWatch {
enum Start {
case watching
/// macOS refused to let Peel look, which for the home's Trash means Full Disk Access is missing.
diff --git a/Peel/PeelApp.swift b/Peel/PeelApp.swift
index a463f749..0532bbcb 100644
--- a/Peel/PeelApp.swift
+++ b/Peel/PeelApp.swift
@@ -6,6 +6,12 @@ import SwiftUI
/// Peel keeps running without a window only while it shows in the menu bar, so it is never running unseen.
@MainActor
final class PeelAppDelegate: NSObject, NSApplicationDelegate {
+ func applicationWillFinishLaunching(_ notification: Notification) {
+ if PeelApp.isHostingTests {
+ NSApp.setActivationPolicy(.prohibited)
+ }
+ }
+
func applicationShouldTerminateAfterLastWindowClosed(_ application: NSApplication) -> Bool {
!UserDefaults.standard.bool(forKey: SettingsKey.showsInMenuBar)
}
@@ -17,6 +23,10 @@ final class PeelAppDelegate: NSObject, NSApplicationDelegate {
@main
struct PeelApp: App {
+ /// Set by the PeelTests scheme for the Peel that hosts the tests, which drive its models alone: nothing of Peel's
+ /// runs or shows then.
+ static let isHostingTests = ProcessInfo.processInfo.environment["PEEL_HOSTS_TESTS"] != nil
+
@NSApplicationDelegateAdaptor(PeelAppDelegate.self) private var delegate
static let mainWindowID = "main"
/// How often the update round runs. The shortest wait an app can have is six hours, after a failed check
@@ -264,6 +274,7 @@ struct PeelApp: App {
/// Starts what Peel does from launch to quit, from whichever shows first: the main window, or the menu bar item.
/// Each piece starts once, and none is a child of the view that called it, so closing the window stops nothing.
private func start() {
+ guard !Self.isHostingTests else { return }
#if DEBUG
// A render or an export only draws and quits, so it contacts nothing and writes nothing of Peel's.
guard HomeSnapshot.directory == nil, TerminalExport.directory == nil else { return }
@@ -330,7 +341,8 @@ struct PeelApp: App {
/// Whether the menu bar item shows. `MenuBarExtra` writes it back at every scene update, and each write to an
/// `AppStorage` makes every `AppStorage` in the app read again, so a write of the value it holds is left out.
private var menuBarItemIsInserted: Binding<Bool> {
- Binding {
+ guard !Self.isHostingTests else { return .constant(false) }
+ return Binding {
showsInMenuBar
} set: { isInserted in
if isInserted != showsInMenuBar { showsInMenuBar = isInserted }
@@ -396,6 +408,8 @@ struct PeelApp: App {
}
}
.defaultSize(width: 1120, height: 764)
+ .defaultLaunchBehavior(Self.isHostingTests ? .suppressed : .automatic)
+ .restorationBehavior(Self.isHostingTests ? .disabled : .automatic)
.commands {
PeelCommands(
library: library, updater: updater, homebrew: homebrew, textEditing: textEditing,
diff --git a/PeelTests/HostingTests.swift b/PeelTests/HostingTests.swift
new file mode 100644
index 00000000..b63c2251
--- /dev/null
+++ b/PeelTests/HostingTests.swift
@@ -0,0 +1,16 @@
+import AppKit
+import CoreGraphics
+@testable import Peel
+import Testing
+
+struct HostingTests {
+ @Test func peelShowsNothingWhileItHostsThem() {
+ #expect(PeelApp.isHostingTests)
+ #expect(NSApp.activationPolicy() == .prohibited)
+ let windows = CGWindowListCopyWindowInfo([.optionAll], kCGNullWindowID) as? [[String: Any]] ?? []
+ let own = windows.filter {
+ $0[kCGWindowOwnerPID as String] as? pid_t == ProcessInfo.processInfo.processIdentifier
+ }
+ #expect(own.isEmpty)
+ }
+}
diff --git a/PeelTests/QuitGuardTests.swift b/PeelTests/QuitGuardTests.swift
new file mode 100644
index 00000000..703da98e
--- /dev/null
+++ b/PeelTests/QuitGuardTests.swift
@@ -0,0 +1,30 @@
+import AppKit
+@testable import Peel
+import Testing
+
+struct QuitGuardTests {
+ @Test func letsAQuitGoAheadWhileNothingIsUnderWay() {
+ #expect(QuitGuard().replyToQuit() == .terminateNow)
+ }
+
+ @Test func refusesAQuitWhilePeelRemovesItself() async {
+ let guardian = QuitGuard()
+ var reply: NSApplication.TerminateReply?
+
+ await guardian.runRefusingQuit { reply = guardian.replyToQuit() }
+
+ #expect(reply == .terminateCancel)
+ #expect(guardian.replyToQuit() == .terminateNow)
+ }
+
+ @Test func aRefusalOutranksWorkAQuitWouldWaitFor() async {
+ let guardian = QuitGuard()
+ var reply: NSApplication.TerminateReply?
+
+ await guardian.runRefusingQuit {
+ await guardian.run { reply = guardian.replyToQuit() }
+ }
+
+ #expect(reply == .terminateCancel)
+ }
+}
diff --git a/PeelTests/TrashWatchTests.swift b/PeelTests/TrashWatchTests.swift
new file mode 100644
index 00000000..cbb80fb0
--- /dev/null
+++ b/PeelTests/TrashWatchTests.swift
@@ -0,0 +1,44 @@
+import Foundation
+@testable import Peel
+import Testing
+
+struct TrashWatchTests {
+ @Test func tellsOfAnAppThrownAwayAfterItStartedWatching() async throws {
+ let folder = FileManager.default.temporaryDirectory.appending(path: "PeelTests-\(UUID().uuidString)")
+ let trash = folder.appending(path: "Trash", directoryHint: .isDirectory)
+ let staged = folder.appending(path: "Staged/Example.app", directoryHint: .isDirectory)
+ try FileManager.default.createDirectory(
+ at: trash.appending(path: "Earlier.app"), withIntermediateDirectories: true
+ )
+ try FileManager.default.createDirectory(at: staged, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: folder) }
+ var arrived: [URL] = []
+ let watch = TrashWatch(trash: trash, waitsIn: folder) { arrived.append($0) }
+ defer { watch.stop() }
+ guard case .watching = watch.start() else {
+ Issue.record("the watch did not start")
+ return
+ }
+
+ try FileManager.default.moveItem(at: staged, to: trash.appending(path: "Example.app"))
+ for _ in 0..<200 where arrived.isEmpty {
+ try await Task.sleep(for: .milliseconds(25))
+ }
+
+ #expect(arrived.map(\.lastPathComponent) == ["Example.app"])
+ }
+
+ @Test func waitsForATrashThatIsNotThereYet() throws {
+ let folder = FileManager.default.temporaryDirectory.appending(path: "PeelTests-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: folder) }
+ let watch = TrashWatch(trash: folder.appending(path: "Trash"), waitsIn: folder) { _ in }
+ defer { watch.stop() }
+
+ guard case .watching = watch.start() else {
+ Issue.record("a missing Trash was not waited for")
+ return
+ }
+ #expect(watch.isActive)
+ }
+}