Update generation

- Move to global objects for files and validation
- Only write changed files
- Check images for changes before scaling
- Simplify code
This commit is contained in:
Christoph Hagen
2022-08-26 17:40:51 +02:00
parent 91d5bcb66d
commit 80d3c08a93
54 changed files with 1344 additions and 2419 deletions

View File

@ -0,0 +1,9 @@
import Foundation
extension Data {
func createFolderAndWrite(to url: URL) throws {
try url.ensureParentFolderExistence()
try write(to: url)
}
}

View File

@ -0,0 +1,15 @@
import Foundation
import AppKit
extension NSImage {
func scaledDown(to size: NSSize) -> NSImage {
guard self.size.width > size.width else {
return self
}
return NSImage(size: size, flipped: false) { (resizedRect) -> Bool in
self.draw(in: resizedRect)
return true
}
}
}

View File

@ -0,0 +1,28 @@
import Foundation
extension NSSize {
func scaledDown(to desiredWidth: CGFloat) -> NSSize {
if width == desiredWidth {
return self
}
if width < desiredWidth {
// Don't scale larger
return self
}
let height = height * desiredWidth / width
return NSSize(width: desiredWidth, height: height)
}
}
extension NSSize {
var ratio: CGFloat {
guard height != 0 else {
return 0
}
return width / height
}
}

View File

@ -32,8 +32,16 @@ extension String {
components(separatedBy: separator).last!
}
/**
Insert the new content before the last occurence of the specified separator.
If the separator does not appear in the string, then the new content is simply appended.
*/
func insert(_ content: String, beforeLast separator: String) -> String {
let parts = components(separatedBy: separator)
guard parts.count > 1 else {
return self + content
}
return parts.dropLast().joined(separator: separator) + content + separator + parts.last!
}
@ -53,3 +61,10 @@ extension Substring {
.components(separatedBy: end).first!
}
}
extension String {
func createFolderAndWrite(to url: URL) throws {
try data(using: .utf8)!.createFolderAndWrite(to: url)
}
}

View File

@ -0,0 +1,38 @@
import Foundation
extension URL {
func ensureParentFolderExistence() throws {
try deletingLastPathComponent().ensureFolderExistence()
}
func ensureFolderExistence() throws {
guard !exists else {
return
}
try FileManager.default.createDirectory(at: self, withIntermediateDirectories: true)
}
var isDirectory: Bool {
(try? resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true
}
var exists: Bool {
FileManager.default.fileExists(atPath: path)
}
/**
Delete the file at the url.
*/
func delete() throws {
try FileManager.default.removeItem(at: self)
}
func copy(to url: URL) throws {
if url.exists {
try url.delete()
}
try url.ensureParentFolderExistence()
try FileManager.default.copyItem(at: self, to: url)
}
}