Skip to content

Instantly share code, notes, and snippets.

@rolandkakonyi
Forked from Hazer/named_colors_compat.py
Last active May 21, 2019 09:10
Show Gist options
  • Save rolandkakonyi/741a4510aa686f2693ee8a3d8de24cac to your computer and use it in GitHub Desktop.
Save rolandkakonyi/741a4510aa686f2693ee8a3d8de24cac to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, json, argparse
print os.getcwd()
parser = argparse.ArgumentParser(description='Convert color assets from storyboards and xibs')
parser.add_argument('--colorSpace', dest="color_space",
type=str,
default="calibratedRGB",
nargs='?',
help="Default colorSpace string (default: calibratedRGB)") #calibratedRGB
parser.add_argument('--assetRoot', dest="asset_root",
type=str,
default="",
nargs='?',
help="Path to search for .colorset files (default: current folder)") #calibratedRGB
colorDict = {}
def custom_color_space(space):
return 'colorSpace="custom" customColorSpace="{}"'.format(space)
args = parser.parse_args()
colorSpaceMap = {
'calibratedrgb': 'colorSpace="calibratedRGB"',
'srgb': custom_color_space("sRGB"),
'displayP3': custom_color_space("displayP3"),
'calibratedwhite': custom_color_space("calibratedWhite"),
'extended-srgb': custom_color_space("sRGB"),
}
defaultColorSpace = colorSpaceMap.get(args.color_space.lower())
searchRoot = args.asset_root
# read all colorset
for root, dirs, files in os.walk("./" + searchRoot):
for d in dirs:
if d.endswith(".colorset"):
colorK = d.split(".")[0]
#print "found " + colorK
for file in files:
if file == "Contents.json":
f = open(os.path.join(root, d, file))
jd = json.load(f)
color = jd["colors"][0]["color"]
rgb = color["components"]
colorSpace = color["color-space"]
if not colorSpace:
colorSpace = defaultColorSpace
else:
colorSpace = colorSpaceMap.get(colorSpace)
colorDict[colorK] = 'red="{}" green="{}" blue="{}" alpha="{}" {}'.format(rgb["red"], rgb["green"], rgb["blue"], rgb["alpha"], colorSpace)
print ""
import re
# replacing
for root, dirs, files in os.walk("./"):
for file in files:
if file.endswith((".storyboard", ".xib")):
path = os.path.join(root, file)
print "Replacing namedColors in " + path
f = open(path)
nf = f.read()
f.close()
for k, v in colorDict.items():
nf = re.sub(r"<namedColor name=\"{}\">.*\n( +)<color .*/>\n( +)</namedColor>".format(k), '<namedColor name="{}">\n\g<1><color {}/>\n\g<2></namedColor>'.format(k, v), nf)
#print "Replaced named color: " + k
f = open(path, 'w')
f.write(nf)
f.close()
@rolandkakonyi
Copy link
Author

Updated to keep named colors in the resources but update their values based on current color resources values (handy if you need to hot swap on build)

@ethi1989
Copy link

How can i add py to run, Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment