Clean code for file type detection

This commit is contained in:
Christoph Hagen
2022-08-29 18:57:37 +02:00
parent 4c52232d24
commit 50519762a9
6 changed files with 47 additions and 54 deletions

View File

@ -261,7 +261,8 @@ final class FileSystem {
// Ensure that image file is supported
let ext = destinationUrl.pathExtension.lowercased()
guard MediaType.isProcessableImage(ext) else {
guard ImageType(fileExtension: ext) != nil else {
// TODO: This should never be reached, since extensions are checked before
log.add(info: "Copying image", source: image.source)
do {
let sourceUrl = input.appendingPathComponent(image.source)
@ -303,7 +304,7 @@ final class FileSystem {
}
let destinationExtension = destinationUrl.pathExtension.lowercased()
guard let type = MediaType.supportedImage(destinationExtension) else {
guard let type = ImageType(fileExtension: destinationExtension)?.fileType else {
log.add(error: "No image type for extension \(destinationExtension)",
source: destination)
return

View File

@ -0,0 +1,27 @@
import Foundation
import AppKit
enum ImageType: CaseIterable {
case jpg
case png
init?(fileExtension: String) {
switch fileExtension {
case "jpg", "jpeg":
self = .jpg
case "png":
self = .png
default:
return nil
}
}
var fileType: NSBitmapImageRep.FileType {
switch self {
case .jpg:
return .jpeg
case .png:
return .png
}
}
}

View File

@ -1,39 +0,0 @@
import Foundation
import AppKit
private let supportedImageExtensions: [String : NSBitmapImageRep.FileType] = [
"jpg" : .jpeg,
"jpeg" : .jpeg,
"png" : .png,
]
private let supportedVideoExtensions: Set<String> = [
"mp4", "mov", "m4v"
]
enum MediaType {
case image
case video
case file
case svg
init(fileExtension: String) {
if supportedImageExtensions[fileExtension] != nil {
self = .image
} else if supportedVideoExtensions.contains(fileExtension) {
self = .video
} else if fileExtension == "svg" {
self = .svg
} else {
self = .file
}
}
static func isProcessableImage(_ fileExtension: String) -> Bool {
supportedImage(fileExtension) != nil
}
static func supportedImage(_ fileExtension: String) -> NSBitmapImageRep.FileType? {
supportedImageExtensions[fileExtension]
}
}

View File

@ -1,6 +1,6 @@
import Foundation
enum VideoType: String {
enum VideoType: String, CaseIterable {
case mp4
case m4v