Skip to content
Open
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
8 changes: 6 additions & 2 deletions Xcodes/Frontend/Cleanup/CleanupModel+Cleanup.swift
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,12 @@ extension CleanupModel {
case "chromeLeftovers": tools = ["google chrome"]
default: tools = []
}
let running = activeTools.intersection(tools).sorted()
if !running.isEmpty { return "In use by \(running.joined(separator: ", ")). Stop these processes and try again." }
var running = activeTools.intersection(tools)
if category.id == "derivedData", running.contains("xcodebuild"),
!CleanupOperations.xcodebuildMayUseDerivedData(item.path, scopedPaths: xcodebuildDerivedDataPaths) {
running.remove("xcodebuild")
}
if !running.isEmpty { return "In use by \(running.sorted().joined(separator: ", ")). Stop these processes and try again." }
}
if item.path.bytes.split(separator: 47).contains(where: { $0.elementsEqual("node_modules".utf8) }), !activeTools.isDisjoint(with: ["node", "npm", "pnpm", "yarn"]) {
return "Stop Node.js and package-manager processes before cleanup."
Expand Down
10 changes: 8 additions & 2 deletions Xcodes/Frontend/Cleanup/CleanupModel+Simulators.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,15 @@ extension CleanupModel {
/// Ordinary Trash operations need active-use checks, not a full CoreSimulator inventory.
func refreshRunningTools() async {
protectedPaths = Self.makeProtectedPaths()
let output = try? await Process.runAsync(URL(fileURLWithPath: "/bin/ps"), ["-axo", "comm="])
let output = try? await Process.runAsync(URL(fileURLWithPath: "/bin/ps"), ["-axo", "pid=,comm="])
guard !Task.isCancelled else { return }
activeTools = Set((output?.out ?? "").split(separator: "\n").map { URL(fileURLWithPath: String($0).trimmingCharacters(in: .whitespaces)).lastPathComponent.lowercased() })
let processList = output?.out ?? ""
activeTools = Set(processList.split(separator: "\n").compactMap { line in
let fields = line.split(maxSplits: 1, whereSeparator: \.isWhitespace)
guard fields.count == 2 else { return nil }
return URL(fileURLWithPath: String(fields[1])).lastPathComponent.lowercased()
})
xcodebuildDerivedDataPaths = CleanupOperations.xcodebuildDerivedDataPaths(processList: processList)
runningApplications = NSWorkspace.shared.runningApplications.map {
(name: $0.localizedName ?? "the running app", bundleID: $0.bundleIdentifier, path: $0.bundleURL.flatMap { try? FilesystemPath($0) })
}
Expand Down
1 change: 1 addition & 0 deletions Xcodes/Frontend/Cleanup/CleanupModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ final class CleanupModel: ObservableObject {
var activityUnavailable = true
var runningApplications: [(name: String, bundleID: String?, path: FilesystemPath?)] = []
var activeTools: Set<String> = []
var xcodebuildDerivedDataPaths: [FilesystemPath]?

init(defaults: Defaults = Current.defaults, folderConfigurationURL: URL? = nil, useFileConfiguration: Bool = false) {
folderDefaults = defaults
Expand Down
46 changes: 46 additions & 0 deletions Xcodes/Frontend/Cleanup/CleanupOperations.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,52 @@ enum CleanupOperations {
UInt64(UInt32(bitPattern: metadata.st_dev)) == item.identity.device else { throw CleanupOperationError.changed }
}

/// nil means at least one xcodebuild could be using the default Derived Data location.
static func xcodebuildDerivedDataPaths(
processList: String,
arguments: (pid_t) -> [String]? = processArguments
) -> [FilesystemPath]? {
var paths: [FilesystemPath] = []
for line in processList.split(separator: "\n") {
let fields = line.split(maxSplits: 1, whereSeparator: \.isWhitespace)
guard fields.count == 2, let pid = pid_t(fields[0]),
URL(fileURLWithPath: String(fields[1])).lastPathComponent.lowercased() == "xcodebuild" else { continue }
guard let args = arguments(pid) else { return nil }
let flags = args.indices.filter { args[$0] == "-derivedDataPath" }
guard flags.count == 1, let flag = flags.first, flag + 1 < args.count,
args[flag + 1].hasPrefix("/"),
let path = try? FilesystemPath(URL(fileURLWithPath: args[flag + 1]).resolvingSymlinksInPath())
else { return nil }
paths.append(path)
}
return paths
}

static func xcodebuildMayUseDerivedData(_ path: FilesystemPath, scopedPaths: [FilesystemPath]?) -> Bool {
guard let scopedPaths, !scopedPaths.isEmpty,
let canonicalPath = try? FilesystemPath(path.url.resolvingSymlinksInPath()) else { return true }
return scopedPaths.contains { $0.contains(canonicalPath) || canonicalPath.contains($0) }
}

private static func processArguments(_ pid: pid_t) -> [String]? {
var mib: [Int32] = [CTL_KERN, KERN_PROCARGS2, pid]
var size = 0
guard sysctl(&mib, 3, nil, &size, nil, 0) == 0, size > MemoryLayout<Int32>.size else { return nil }
var bytes = [UInt8](repeating: 0, count: size)
let status = bytes.withUnsafeMutableBytes { sysctl(&mib, 3, $0.baseAddress, &size, nil, 0) }
guard status == 0, size > MemoryLayout<Int32>.size else { return nil }
let count = bytes.withUnsafeBytes { Int($0.loadUnaligned(as: Int32.self)) }
guard count > 0 else { return nil }
// The kernel buffer begins with argc, the executable path, then NUL padding before argv.
let payload = bytes[MemoryLayout<Int32>.size..<size]
guard let executableEnd = payload.firstIndex(of: 0),
let argumentsStart = payload[executableEnd...].firstIndex(where: { $0 != 0 }) else { return nil }
let rawArguments = payload[argumentsStart...].split(separator: 0, maxSplits: count, omittingEmptySubsequences: false)
guard rawArguments.count > count else { return nil }
let arguments = rawArguments.prefix(count).compactMap { String(bytes: $0, encoding: .utf8) }
return arguments.count == count ? arguments : nil
}

struct SimulatorRuntime: Sendable, Codable, Identifiable, Equatable {
let identifier: String
let runtimeIdentifier: String
Expand Down
16 changes: 14 additions & 2 deletions Xcodes/Frontend/Cleanup/CleanupWindow.swift
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,20 @@ struct CleanupWindow: View {
Text(model.cleanupConfirmationMessage)
}
.alert("Cleanup", isPresented: Binding(get: { model.message != nil }, set: { if !$0 { model.message = nil } })) {
Button("OK") { model.message = nil }
} message: { Text(model.message ?? "") }
Button("OK", role: .cancel) { model.message = nil }
if let details = model.message, details != Self.errorPreview(details) {
Button("Copy Details") {
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(details, forType: .string)
}
}
} message: { Text(Self.errorPreview(model.message ?? "")) }
}

private static func errorPreview(_ message: String) -> String {
let lines = message.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline)
let preview = String(lines.prefix(6).joined(separator: "\n").prefix(480))
return preview == message ? preview : preview + "…"
}

private var savingsHelp: some View {
Expand Down
Loading
Loading