Created
September 4, 2023 10:01
-
-
Save tkafka/12f6a0232af8b781713239530d85724e to your computer and use it in GitHub Desktop.
Embeds a binary data from file into a Swift class static variable (with cached decode)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Embeds a binary data from file as a static variable (with cached decode) | |
# Made by chatgpt: https://chat.openai.com/share/0d05b3a8-d25c-4226-876a-62868d3c0e88 | |
# Check if a valid number of arguments are provided (must be multiple of 2) | |
if [ $(($# % 2)) -ne 0 ] || [ "$#" -eq 0 ]; then | |
echo "Usage: $0 <property_name1> <binary_file1> [<property_name2> <binary_file2> ...]" | |
exit 1 | |
fi | |
# Initialize the Swift code for the class | |
swift_code="import Foundation\n\npublic class EmbeddedResource {\n private static var cachedData: [String: Data] = [:]\n" | |
# Loop through the tuples to add each property | |
while [ "$#" -gt 0 ]; do | |
property_name="$1" | |
binary_file="$2" | |
# Check if the file exists | |
if [ ! -f "$binary_file" ]; then | |
echo "File $binary_file not found!" | |
exit 1 | |
fi | |
# Convert the binary file to Base64 | |
base64_string=$(base64 -i "$binary_file" | tr -d '\n') | |
# Split the Base64 string into multiple lines | |
split_base64_string=$(echo "$base64_string" | sed -r 's/(.{64})/\1\\n/g') | |
# Add to the Swift code | |
swift_code+="\n public static var $property_name: Data {\n if let cached = cachedData[\"$property_name\"] {" | |
swift_code+="\n return cached\n }\n\n let base64String = \"\"\"\n$split_base64_string\n\"\"\"" | |
swift_code+="\n guard let data = Data(base64Encoded: base64String, options: [.ignoreUnknownCharacters]) else {\n fatalError(\"Failed to decode embedded resource: $property_name.\")" | |
swift_code+="\n }\n\n cachedData[\"$property_name\"] = data\n return data\n }\n" | |
# Log | |
echo "Embedded $property_name from $binary_file." | |
# Remove processed arguments | |
shift 2 | |
done | |
# Close the class definition | |
swift_code+="\n}" | |
# Generate the Swift file | |
echo -e "$swift_code" >GeneratedResource.swift | |
echo "Swift file GeneratedResource.swift has been generated." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment