Last active
October 16, 2024 01:42
-
-
Save samhenrigold/c4c3e472c77dda72853b9f1cf2e361f3 to your computer and use it in GitHub Desktop.
Convert `assetutil` colors to colorset directories
This file contains 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
import json | |
import os | |
def convert_color_space(space): | |
if space == "extended gray": | |
return "extended-gray" | |
elif space == "p3": | |
return "display-p3" | |
else: | |
return space | |
def create_color_component(components, colorspace): | |
if colorspace == "extended-gray": | |
return { | |
"white": f"{components[0]:.3f}", | |
"alpha": f"{components[1]:.3f}" | |
} | |
else: | |
return { | |
"red": f"{components[0]:.3f}", | |
"green": f"{components[1]:.3f}", | |
"blue": f"{components[2]:.3f}", | |
"alpha": f"{components[3]:.3f}" | |
} | |
def create_color_entry(color_data): | |
return { | |
"color": { | |
"color-space": convert_color_space(color_data["Colorspace"]), | |
"components": create_color_component(color_data["Color components"], convert_color_space(color_data["Colorspace"])) | |
}, | |
"idiom": color_data["Idiom"] | |
} | |
def create_colorset(colors): | |
colorset = { | |
"colors": [], | |
"info": { | |
"author": "xcode", | |
"version": 1 | |
} | |
} | |
for color in colors: | |
entry = create_color_entry(color) | |
if "Appearance" in color: | |
if color["Appearance"] == "UIAppearanceDark": | |
entry["appearances"] = [{"appearance": "luminosity", "value": "dark"}] | |
elif color["Appearance"] == "UIAppearanceLight": | |
entry["appearances"] = [{"appearance": "luminosity", "value": "light"}] | |
colorset["colors"].append(entry) | |
return colorset | |
def process_colors(input_json): | |
with open(input_json, 'r') as f: | |
data = json.load(f) | |
colors_by_name = {} | |
for color in data: | |
name = color["Name"] | |
if name not in colors_by_name: | |
colors_by_name[name] = [] | |
colors_by_name[name].append(color) | |
for name, colors in colors_by_name.items(): | |
colorset_dir = f"{name}.colorset" | |
os.makedirs(colorset_dir, exist_ok=True) | |
colorset = create_colorset(colors) | |
with open(os.path.join(colorset_dir, "Contents.json"), 'w') as f: | |
json.dump(colorset, f, indent=2) | |
print(f"Created {len(colors_by_name)} .colorset directories.") | |
# Usage | |
input_json = "/Users/shg/Desktop/colors/colors.json" | |
process_colors(input_json) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment