Skip to content
Open
Show file tree
Hide file tree
Changes from 3 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
27 changes: 27 additions & 0 deletions Sources/LocalLLMClientCore/LLMSession.swift
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,33 @@ public extension LLMSession {
public func downloadModel(onProgress: @Sendable @escaping (Double) async -> Void = { _ in }) async throws {
try await downloader.download(onProgress: onProgress)
}

public static func pruneModels(in url: URL = FileDownloader.defaultRootDestination, excluding: [Model] = []) throws {
guard let enumerator = FileManager.default.enumerator(at: url, includingPropertiesForKeys: [.isDirectoryKey], options: [.skipsPackageDescendants]) else { return }

let excludingNormalized: Set<URL> = Set(excluding.compactMap { model -> URL? in
if let model = model as? LLMSession.DownloadModel {
return model.modelPath.resolvingSymlinksInPath().standardizedFileURL
}
if let model = model as? LLMSession.LocalModel {
return model.modelPath.resolvingSymlinksInPath().standardizedFileURL
}
return nil
})

for case let fileURL as URL in enumerator {
if excludingNormalized.contains(fileURL.resolvingSymlinksInPath().standardizedFileURL) {
enumerator.skipDescendants()
continue
}

if (try fileURL.resourceValues(forKeys: [.isDirectoryKey])).isDirectory == false {
try FileManager.default.removeItem(at: fileURL)
}
}

try url.removeEmptyFolders()
}
}

struct LocalModel: Model {
Expand Down
13 changes: 13 additions & 0 deletions Sources/LocalLLMClientUtility/URL+.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,17 @@ package extension URL {
return url
#endif
}

func removeEmptyFolders() throws {
guard isFileURL else { return }

let contents = try FileManager.default.contentsOfDirectory(at: self, includingPropertiesForKeys: [.isDirectoryKey])
let subdirectories = try contents.filter { try $0.resourceValues(forKeys: [.isDirectoryKey]).isDirectory ?? false }

for subdirectory in subdirectories { try subdirectory.removeEmptyFolders() }

guard try FileManager.default.contentsOfDirectory(at: self, includingPropertiesForKeys: nil).isEmpty else { return }

try FileManager.default.removeItem(at: self)
}
}