Skip to content

Instantly share code, notes, and snippets.

@antmd
Created July 13, 2013 22:24
Show Gist options
  • Save antmd/5992445 to your computer and use it in GitHub Desktop.
Save antmd/5992445 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
__author__ = 'ant'
"""
Generate a C-function to convert an enum value into an NSString, and put it on the clipboard
Note, only handles NS_ENUM style enums at the moment.
"""
import sys
import re
import AppKit
import Foundation
from string import Template
indent = " "
def pbcopy(s):
board = AppKit.NSPasteboard.generalPasteboard()
board.declareTypes_owner_([AppKit.NSStringPboardType], None)
newStr = Foundation.NSString.stringWithString_(s)
newData = \
newStr.nsstring().dataUsingEncoding_(Foundation.NSUTF8StringEncoding)
board.setData_forType_(newData, AppKit.NSStringPboardType)
# Normailse stdin input: remove all newlines, condense contiguous whitespace to single space
# TODO: strip block comments while reading file
body = ' '.join([ line.rstrip("\n") for line in sys.stdin.readlines() ] )
# Strip c-style comments
body = re.sub(r'/\*.*?\*/',
r' ',
body)
body = re.sub(r'\s+',
r' ',
body)
# Process file
# ============
enumName = None
# NS_ENUM
# -------
enumMatch = re.search(r'NS_ENUM\s?\(\s?\w+\s?,\s?(\w+)\s?\)\s?\{([ A-z0-9_,]*)\}',body)
if enumMatch:
enumName = enumMatch.group(1)
enumMembers = enumMatch.group(2).replace(' ','').split(',')
if enumName:
output = "NSString* stringFrom{enumName}({enumName} value)\n{{".format( enumName = enumName[0].upper() + enumName[1:] )
output += "\n{indent}switch (value) {{".format(indent=indent)
template = Template(r'{indent}case $member: return @"$member"; break;'.format(indent = indent))
for member in enumMembers:
output += "\n" + template.substitute(member = member)
output += '\n{indent}default: return @"ERROR: Unknown {enumName} value."; break;'.format(indent=indent, enumName=enumName)
output += '\n{indent}}}'.format(indent=indent)
output += '\n}\n'
pbcopy(output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment