Skip to content

Instantly share code, notes, and snippets.

@nkrisc nkrisc/format.py
Created Feb 28, 2019

Embed
What would you like to do?
Format the names of all symbols in a Sketch file to be all lowercase
import os
import zipfile
import tempfile
import sys
import json
zipname = sys.argv[1]
def format_symbol_name(name):
return name.lower()
def update_file(zipname):
# generate a temp file
tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
os.close(tmpfd)
# read the sketch file as a zip file
with zipfile.ZipFile(zipname, 'r') as zin:
with zipfile.ZipFile(tmpname, 'w') as zout:
zout.comment = zin.comment # preserve the comment
# track how many layer names were changed
updated = 0
for item in zin.infolist():
data = zin.read(item.filename)
# find pages and update symbol names
if item.filename.startswith('pages') and item.filename.endswith('.json'):
parsed_json = json.loads(data)
for layer in parsed_json['layers']:
# only modify symbol masters
if layer['_class'] == 'symbolMaster':
before_name = layer['name']
formatted_name = format_symbol_name(layer['name'])
layer['name'] = formatted_name
if before_name != formatted_name: updated += 1
data = json.dumps(parsed_json)
#write back to temp archive
zout.writestr(item, data)
print '%d symbol names updated.' % updated
# replace with the temp archive
os.remove(zipname)
os.rename(tmpname, zipname)
update_file(zipname)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.