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
14 changes: 13 additions & 1 deletion MacCleaner/AppsModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -589,8 +589,17 @@ enum AppEngine {
}
}

#if MACCLEANER_TEST_HOOKS
/// Self-test only (test-hooks build): stand in for "is it running" / "did it quit" without a real process.
nonisolated(unsafe) static var testRunningOverride: Bool?
nonisolated(unsafe) static var testQuitOverride: Bool?
#endif

static func isRunning(_ a: AppInfo) -> Bool {
!a.bundleID.isEmpty && !NSRunningApplication.runningApplications(withBundleIdentifier: a.bundleID).isEmpty
#if MACCLEANER_TEST_HOOKS
if let o = testRunningOverride { return o }
#endif
return !a.bundleID.isEmpty && !NSRunningApplication.runningApplications(withBundleIdentifier: a.bundleID).isEmpty
}

private static func alive(_ pids: [pid_t]) -> Bool {
Expand All @@ -599,6 +608,9 @@ enum AppEngine {

/// Stops the app's launch agents, asks it to quit, waits 5 s, then force-quits. Blocks up to ~8 s.
static func quit(_ a: AppInfo) -> Bool {
#if MACCLEANER_TEST_HOOKS
if let o = testQuitOverride { return o }
#endif
guard !a.isSelf, !a.isApple else { return false }
let uid = getuid()
for l in a.leftovers where !l.needsAdmin {
Expand Down
1 change: 1 addition & 0 deletions MacCleaner/MacCleanerApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ enum Entry {
print("trash-destination: " + (SelfTest.trashIsIsolated ? SelfTest.isolatedTrash.path : "system"))
exit(0)
}
TestHooks.installFromEnvironment()
if args.count > 1 && args[1] == "--selftest-child" {
exit(SelfTest.child(Array(args.dropFirst(2))))
}
Expand Down
3 changes: 2 additions & 1 deletion MacCleaner/SelfTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ enum SelfTest {
private static var passed = 0
private static var failed: [String] = []

private static func check(_ name: String, _ ok: Bool) {
static func check(_ name: String, _ ok: Bool) {
if ok { passed += 1 } else { failed.append(name) }
print((ok ? " ✓ " : " ✗ ") + name)
}
Expand Down Expand Up @@ -1439,6 +1439,7 @@ extension SelfTest {
trashLogDurability(dir: dir, runID: runID, file: file, run: run, putBack: putBack)
sharedFileLocking(dir: dir)
mcpAndCLITrash(dir: dir, runID: runID)
subprocessPins(dir: dir, runID: runID)
engineTrash(dir: dir, runID: runID)
shredReview(dir: dir, runID: runID, savedProtected: savedProtected)
shredScreen(dir: dir, runID: runID, savedProtected: savedProtected)
Expand Down
596 changes: 596 additions & 0 deletions MacCleaner/SelfTestSubprocess.swift

Large diffs are not rendered by default.

46 changes: 46 additions & 0 deletions MacCleaner/TestHooks.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#if MACCLEANER_TEST_HOOKS
import AppKit
import CoreFoundation
import Foundation

/// Test-only probes for the self-test's child processes (`--mcp`, `--cli`). Compiled only into the test-hooks build
/// (scripts/build-test-hooks.sh), never into Release: scripts/check-no-test-hooks.sh greps the Release binary for
/// every environment variable named here. Nothing writes to stdout (stdout is the MCP JSON-RPC channel).
enum TestHooks {
/// Run-loop fingerprint: bumped by a repeating timer on the main run loop (common modes). It only advances while
/// something is spinning the main run loop.
nonisolated(unsafe) static var ticks = 0

private static func append(_ line: String, to path: String) {
let url = URL(fileURLWithPath: path)
if !FileManager.default.fileExists(atPath: path) { FileManager.default.createFile(atPath: path, contents: nil) }
guard let h = try? FileHandle(forWritingTo: url) else { return }
defer { try? h.close() }
_ = try? h.seekToEnd()
try? h.write(contentsOf: Data((line + "\n").utf8))
}

/// Called once from `Entry.main`, in the test-hooks block, before any dispatch.
static func installFromEnvironment() {
let env = ProcessInfo.processInfo.environment

if let path = env["MACCLEANER_TEST_HOME_PROBE"] { append(SafetyGuard.home.path, to: path) }

if let path = env["MACCLEANER_TEST_APPROVAL_PROBE"] {
let answer = env["MACCLEANER_TEST_APPROVAL_ANSWER"] == "yes" // default: the probe says no
let delayMS = env["MACCLEANER_TEST_APPROVAL_DELAY_MS"].flatMap(Int.init) ?? 0
let timer = CFRunLoopTimerCreateWithHandler(nil, CFAbsoluteTimeGetCurrent() + 0.05, 0.05, 0, 0) { _ in
ticks += 1
}
CFRunLoopAddTimer(CFRunLoopGetMain(), timer, .commonModes)
HumanApproval.ask = { _ in
if delayMS > 0 { usleep(UInt32(delayMS) * 1000) } // stands in for an open dialog
let mode = CFRunLoopCopyCurrentMode(CFRunLoopGetCurrent()).map { ($0.rawValue as String) } ?? "nil"
append("main=\(pthread_main_np()) isMainThread=\(Thread.isMainThread) "
+ "mainRunLoop=\(CFRunLoopGetCurrent() == CFRunLoopGetMain()) mode=\(mode) ticks=\(ticks)", to: path)
return answer
}
}
}
}
#endif
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,39 @@ struct ExecutorRealDiskTests {
#expect(fm.fileExists(atPath: outside + "/precious") && fm.fileExists(atPath: cache))
#expect(try fm.contentsOfDirectory(atPath: cache).sorted() == ["added-later", "swap-me"]) // no staging left
}

/// Pins today's cancellation on real files (M01-04d slice 4): cancelling the parent Task while the first item is
/// being moved lets that move finish, and the second item is skipped as cancelled and left on disk.
@Test func cancellingWhileTheFirstItemIsMovedLeavesTheSecondOnDisk() async throws {
let fm = FileManager.default
let base = fm.temporaryDirectory.appendingPathComponent("maccleaner-exec-cancel-\(UUID().uuidString)")
try fm.createDirectory(at: base, withIntermediateDirectories: true)
defer { try? fm.removeItem(at: base) }
let root = realPath(base.path)
let trash = root + "/trash"
try fm.createDirectory(atPath: trash, withIntermediateDirectories: true)
let one = root + "/one.txt", two = root + "/two.txt"
try Data("one".utf8).write(to: URL(fileURLWithPath: one))
try Data("two".utf8).write(to: URL(fileURLWithPath: two))
// The "Trash" is a folder in this sandbox. The first move cancels the running task, then really moves the file.
let fs = LocalFileSystem(trashMover: { url in
withUnsafeCurrentTask { $0?.cancel() }
let dest = URL(fileURLWithPath: trash).appendingPathComponent(url.lastPathComponent)
try FileManager.default.moveItem(at: url, to: dest)
return dest
})
let a = try #require(try fs.identity(at: one)), b = try #require(try fs.identity(at: two))
let p = try plan([.init(candidate("one", [.file(a)]), .trash), .init(candidate("two", [.file(b)]), .trash)])
let exec = CleanupExecutor(fileSystem: fs, protection: Protected())
let approval = try await exec.approve(p, by: .userInApp)
let report = try await Task { try await exec.execute(p, approval: approval) }.value
let r = results(report)
#expect(report.wasCancelled && !report.allSucceeded)
if case .trashed? = r[one] {} else { Issue.record("first item: \(String(describing: r[one]))") }
#expect(r[two] == .skipped(.cancelled))
#expect(!fm.fileExists(atPath: one) && fm.fileExists(atPath: trash + "/one.txt"))
#expect(fm.fileExists(atPath: two) && (try? String(contentsOfFile: two, encoding: .utf8)) == "two")
}
}

/// The path with every symlink resolved (realpath). URL.resolvingSymlinksInPath turns /private/var back into
Expand Down
6 changes: 4 additions & 2 deletions scripts/check-no-test-hooks.sh
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@ EXPECT=0
if [ "${1:-}" = "--expect-hooks" ]; then EXPECT=1; shift; fi
BIN="${1:?usage: check-no-test-hooks.sh [--expect-hooks] path/to/Mac Cleaner.app}/Contents/MacOS/Mac Cleaner"
test -x "$BIN"
N=$(strings -a "$BIN" | grep -c -e '--selftest-child' -e 'MACCLEANER_TEST_TRASH_DIR' -e 'MACCLEANER_TEST_TRASH_PROBE' || true)
N=$(strings -a "$BIN" | grep -c -e '--selftest-child' -e 'MACCLEANER_TEST_TRASH_DIR' -e 'MACCLEANER_TEST_TRASH_PROBE' \
-e 'MACCLEANER_TEST_APPROVAL_PROBE' -e 'MACCLEANER_TEST_APPROVAL_DELAY_MS' -e 'MACCLEANER_TEST_HOME_PROBE' \
-e 'MACCLEANER_TEST_APPROVAL_ANSWER' || true)
if [ "$EXPECT" = 1 ]; then
[ "$N" -gt 0 ] || { echo "✗ expected the test-hooks build to contain its test-only modes"; exit 1; }
echo "✓ the test-hooks build contains its test-only mode (the check can see it)"
else
[ "$N" = 0 ] || { echo "✗ $BIN contains a test-only mode (--selftest-child or MACCLEANER_TEST_TRASH_DIR)"; exit 1; }
[ "$N" = 0 ] || { echo "✗ $BIN contains a test-only mode (--selftest-child or a MACCLEANER_TEST_* variable)"; exit 1; }
echo "✓ no test-only mode in $BIN"
fi
Loading