New general-purpose function to clean up various Munki directories

This commit is contained in:
Greg Neagle
2024-08-18 17:49:12 -07:00
parent 1691110eb2
commit ab3c6fdc59
2 changed files with 36 additions and 0 deletions
@@ -0,0 +1,8 @@
//
// catalogs.swift
// munki
//
// Created by Greg Neagle on 8/16/24.
//
import Foundation
@@ -148,3 +148,31 @@ func getAbsolutePath(_ path: String) -> String {
let composedPath = (cwd as NSString).appendingPathComponent(path)
return ((composedPath as NSString).standardizingPath as NSString).resolvingSymlinksInPath
}
func cleanUpDir(_ dirPath: String, keep keepList: [String]) {
// Remove items in dirPath that aren't in the keepList
if !pathIsDirectory(dirPath) {
return
}
let filemanager = FileManager.default
let dirEnum = filemanager.enumerator(atPath: dirPath)
var foundDirectories = [String]()
while let file = dirEnum?.nextObject() as? String {
let fullPath = (dirPath as NSString).appendingPathComponent(file)
if pathIsDirectory(fullPath) {
foundDirectories.append(fullPath)
continue
}
if !keepList.contains(file) {
try? filemanager.removeItem(atPath: fullPath)
}
}
// clean up any empty directories
for directory in foundDirectories.reversed() {
if let contents = try? filemanager.contentsOfDirectory(atPath: directory),
contents.isEmpty
{
try? filemanager.removeItem(atPath: directory)
}
}
}