import Foundation
/// Removes the last file extension from a filename or path.
///
/// Examples:
/// - "document.pdf" -> "document"
/// - "archive.tar.gz" -> "archive.tar"
/// - "photo.jpg" -> "photo"
/// - "README" -> "README"
/// - "/tmp/file.txt" -> "/tmp/file"
/// - ".gitignore" -> ".gitignore"
///
/// - Parameter path: A filename or full path.
/// - Returns: The filename/path without its last extension.
/// - Throws: `FilePathError.emptyPath` if the path is empty.
func removeFileExtension(from path: String) throws -> String {
guard !path.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
throw FilePathError.emptyPath
}
let url = URL(fileURLWithPath: path)
// Remove only the last extension.
let pathWithoutExtension = url.deletingPathExtension().path
return pathWithoutExtension
}
/// Errors related to file path validation.
enum FilePathError: Error {
case emptyPath
}
// Example usage
do {
print(try removeFileExtension(from: "document.pdf"))
print(try removeFileExtension(from: "archive.tar.gz"))
print(try removeFileExtension(from: ".gitignore"))
print(try removeFileExtension(from: "/tmp/file.txt"))
print(try removeFileExtension(from: "C:\\Temp\\a.txt"))
print(try removeFileExtension(from: "README"))
} catch {
print("Error: \(error)")
}
/*
run:
document
archive.tar
.gitignore
/tmp/file
README
*/