Repository Public License
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Secure9// File : Packages/ORIXFileInspection/Sources/ORIXFileInspection/DuplicateFinder.swift10// Description : Finds files with identical content: grouped by size, then11// by SHA-256 of the first 64 KiB, then by full SHA-256 for12// the remaining candidates. States facts only; it removes13// nothing.14// Module : ORIXFileInspection15// Repository : https://git.spboucher.ai/orix-secure16// Created : 2026-11-2117// Last Modified : 2026-11-2118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author : Simon-Pierre Boucher24// Position : Professor of Finance25// Institution : Université du Québec en Outaouais (UQO)26// Department : Département des sciences administratives27// Organization : SP Boucher28//29// Website : https://spboucher.ai30// Git : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General : info@spboucher.ai37// Professional : contact@spboucher.ai38// Direct : simon@spboucher.ai39// Research : research@spboucher.ai40// Development : dev@spboucher.ai41// Support : support@spboucher.ai42// Security/Admin : admin@spboucher.ai43// Notifications : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification : Public70// Distribution : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License : Proprietary, all rights reserved (see license file)84// License File : LICENSE85// Maintainer : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import Foundation93import ORIXSecureModel9495public struct DuplicateScanOptions: Sendable, Codable, Hashable {96 /// Files smaller than this are ignored. The default leaves empty files out: they are identical by definition and free nothing.97 public var minimumFileSize: Int64 = 198 /// Enumeration stops after this many files.99 public var maxFiles: Int = 200_000100 public var skipHiddenFiles: Bool = true101 /// Do not descend into packages (apps, photo libraries, document bundles).102 public var skipPackages: Bool = true103 /// Bytes hashed in the first pass.104 public var prefixLength: Int = 64 << 10105106 public init() {}107}108109public struct DuplicateScanProgress: Sendable, Hashable, Codable {110 public enum Phase: String, Sendable, Codable, Hashable, CaseIterable { case enumerating, comparingSizes, hashingPrefixes, hashingFiles, done }111 public var phase: Phase112 public var filesProcessed: Int113 /// Files to process in this phase; zero while enumerating.114 public var filesTotal: Int115 public var bytesHashed: UInt64116}117118public struct DuplicateGroup: Sendable, Codable, Hashable, Identifiable {119 public var id: String { sha256 }120 /// Lower-case hexadecimal SHA-256 shared by every file of the group.121 public var sha256: String122 /// Size of each file, in bytes.123 public var fileSize: Int64124 /// The identical files, sorted by path.125 public var urls: [URL]126 /// Bytes freed if all copies but one are removed: size × (count − 1).127 public var reclaimableBytes: Int64 { fileSize * Int64(max(0, urls.count - 1)) }128}129130public struct DuplicateReport: Sendable, Codable, Hashable {131 /// Groups of identical files, largest reclaimable space first.132 public var groups: [DuplicateGroup]133 public var filesExamined: Int134 public var bytesHashed: UInt64135 /// Paths that are hard links to a file already counted (same content on disk, nothing to reclaim).136 public var hardLinksIgnored: Int137 /// Enumeration stopped at `maxFiles`.138 public var truncated: Bool139 public var skipped: [SkippedItem]140 public var notInspected: [String]141 public var duration: TimeInterval142143 public var reclaimableBytes: Int64 { groups.reduce(0) { $0 + $1.reclaimableBytes } }144 public var duplicateFileCount: Int { groups.reduce(0) { $0 + max(0, $1.urls.count - 1) } }145}146147public struct DuplicateFinder: Sendable {148 public init() {}149150 /// Duplicates among the regular files of a folder, searched recursively.151 public func findDuplicates(152 inFolder folder: URL,153 options: DuplicateScanOptions = .init(),154 progress: (@Sendable (DuplicateScanProgress) -> Void)? = nil155 ) async throws -> DuplicateReport {156 let scoped = folder.startAccessingSecurityScopedResource()157 defer { if scoped { folder.stopAccessingSecurityScopedResource() } }158 let start = Date()159 let walk = try FolderWalker.walk(root: folder, skipHidden: options.skipHiddenFiles, skipPackages: options.skipPackages, maxFiles: options.maxFiles) { count in160 if count % 500 == 0 { progress?(DuplicateScanProgress(phase: .enumerating, filesProcessed: count, filesTotal: 0, bytesHashed: 0)) }161 }162 return try await compare(walk, options: options, start: start, progress: progress)163 }164165 /// Duplicates among exactly the given files. Folders and missing files are listed as skipped.166 public func findDuplicates(167 among urls: [URL],168 options: DuplicateScanOptions = .init(),169 progress: (@Sendable (DuplicateScanProgress) -> Void)? = nil170 ) async throws -> DuplicateReport {171 let start = Date()172 var walk = WalkResult()173 var seen = Set<String>()174 for (index, url) in urls.enumerated() {175 if index % 256 == 0 { try Task.checkCancellation() }176 guard seen.insert(url.standardizedFileURL.path).inserted else { continue }177 if walk.files.count >= max(1, options.maxFiles) {178 walk.truncated = true179 break180 }181 if let file = FolderWalker.describe(url) {182 walk.files.append(file)183 } else if walk.skipped.count < FolderWalker.maxSkippedListed {184 walk.skipped.append(SkippedItem(url: url, reason: L("Not a readable regular file.")))185 }186 }187 return try await compare(walk, options: options, start: start, progress: progress)188 }189190 private struct FileIdentity: Hashable {191 let device: UInt64192 let inode: UInt64193 }194195 private static func identity(of url: URL) -> FileIdentity? {196 var info = stat()197 guard lstat(url.path, &info) == 0 else { return nil }198 return FileIdentity(device: UInt64(truncatingIfNeeded: info.st_dev), inode: UInt64(truncatingIfNeeded: info.st_ino))199 }200201 private func compare(202 _ walk: WalkResult,203 options: DuplicateScanOptions,204 start: Date,205 progress: (@Sendable (DuplicateScanProgress) -> Void)?206 ) async throws -> DuplicateReport {207 var skipped = walk.skipped208 var bytesHashed: UInt64 = 0209 var hardLinks = 0210 func skip(_ url: URL, _ error: Error) {211 if skipped.count < FolderWalker.maxSkippedListed { skipped.append(SkippedItem(url: url, reason: error.localizedDescription)) }212 }213214 // 1. Same size.215 progress?(DuplicateScanProgress(phase: .comparingSizes, filesProcessed: 0, filesTotal: walk.files.count, bytesHashed: 0))216 var bySize: [Int64: [URL]] = [:]217 for file in walk.files where file.logicalSize >= options.minimumFileSize {218 bySize[file.logicalSize, default: []].append(file.url)219 }220 var candidates: [(size: Int64, urls: [URL])] = []221 for (size, urls) in bySize where urls.count > 1 {222 // Hard links to one file are one copy on disk.223 var identities = Set<FileIdentity>()224 var distinct: [URL] = []225 for url in urls {226 if let identity = Self.identity(of: url), !identities.insert(identity).inserted {227 hardLinks += 1228 continue229 }230 distinct.append(url)231 }232 if distinct.count > 1 { candidates.append((size, distinct)) }233 }234 candidates.sort { $0.size > $1.size }235236 // 2. Same first bytes.237 let prefixLength = UInt64(max(4096, options.prefixLength))238 let prefixTotal = candidates.reduce(0) { $0 + $1.urls.count }239 var processed = 0240 var afterPrefix: [(size: Int64, prefix: String, urls: [URL])] = []241 for candidate in candidates {242 var byPrefix: [String: [URL]] = [:]243 for url in candidate.urls {244 try Task.checkCancellation()245 do {246 let digest = try await FileHasher.sha256(fileAt: url, chunkSize: Int(prefixLength), maxBytes: prefixLength)247 bytesHashed += min(prefixLength, UInt64(candidate.size))248 byPrefix[digest, default: []].append(url)249 } catch let error as CancellationError {250 throw error251 } catch {252 skip(url, error)253 }254 processed += 1255 if processed % 50 == 0 || processed == prefixTotal {256 progress?(DuplicateScanProgress(phase: .hashingPrefixes, filesProcessed: processed, filesTotal: prefixTotal, bytesHashed: bytesHashed))257 }258 }259 for (prefix, urls) in byPrefix where urls.count > 1 { afterPrefix.append((candidate.size, prefix, urls)) }260 }261262 // 3. Same full content, only for what is still a candidate.263 let fullTotal = afterPrefix.reduce(0) { $0 + (UInt64($1.size) > prefixLength ? $1.urls.count : 0) }264 processed = 0265 var groups: [DuplicateGroup] = []266 for candidate in afterPrefix {267 if UInt64(candidate.size) <= prefixLength {268 // The first pass already covered the whole file.269 groups.append(DuplicateGroup(sha256: candidate.prefix, fileSize: candidate.size, urls: candidate.urls.sorted { $0.path < $1.path }))270 continue271 }272 var byDigest: [String: [URL]] = [:]273 for url in candidate.urls {274 try Task.checkCancellation()275 do {276 let before = bytesHashed277 let index = processed278 let digest = try await FileHasher.sha256(fileAt: url) { step in279 progress?(DuplicateScanProgress(phase: .hashingFiles, filesProcessed: index, filesTotal: fullTotal, bytesHashed: before + step.bytesProcessed))280 }281 bytesHashed += UInt64(candidate.size)282 byDigest[digest, default: []].append(url)283 } catch let error as CancellationError {284 throw error285 } catch {286 skip(url, error)287 }288 processed += 1289 }290 for (digest, urls) in byDigest where urls.count > 1 {291 groups.append(DuplicateGroup(sha256: digest, fileSize: candidate.size, urls: urls.sorted { $0.path < $1.path }))292 }293 }294 groups.sort { a, b in295 if a.reclaimableBytes != b.reclaimableBytes { return a.reclaimableBytes > b.reclaimableBytes }296 return (a.urls.first?.path ?? "") < (b.urls.first?.path ?? "")297 }298 progress?(DuplicateScanProgress(phase: .done, filesProcessed: walk.files.count, filesTotal: walk.files.count, bytesHashed: bytesHashed))299300 var notInspected = [301 L("Files are compared by content (SHA-256); names, dates and metadata are not compared."),302 L("Copies made by the system as clones share storage: removing one may free less space than announced. iOS does not let an app see this."),303 L("Symbolic links are not followed."),304 ]305 if options.minimumFileSize > 0 { notInspected.append(L("Files smaller than \(ORIXFormat.bytes(options.minimumFileSize)) were left out.")) }306 if options.skipHiddenFiles { notInspected.append(L("Hidden files were left out.")) }307 if options.skipPackages { notInspected.append(L("The content of packages (apps, libraries, document bundles) was left out.")) }308 if walk.truncated { notInspected.append(L("The scan stopped after \(walk.files.count) files; the rest of the folder was not examined.")) }309 return DuplicateReport(310 groups: groups, filesExamined: walk.files.count, bytesHashed: bytesHashed, hardLinksIgnored: hardLinks,311 truncated: walk.truncated, skipped: skipped, notInspected: notInspected, duration: Date().timeIntervalSince(start)312 )313 }314}315