UltiSnips/utils/get_tm_snippets.py

162 lines
3.9 KiB
Python
Raw Normal View History

#!/usr/bin/env python
# encoding: utf-8
import urllib
import re
from xml.etree import ElementTree
from xml.parsers.expat import ExpatError
import htmlentitydefs
import os
import glob
_UNESCAPE = re.compile(ur'&\w+?;', re.UNICODE)
2015-01-20 15:26:03 -05:00
def unescape(s):
if s is None:
2015-01-20 15:26:03 -05:00
return ''
def fixup(m):
ent = m.group(0)[1:-1]
return unichr(htmlentitydefs.name2codepoint[ent])
try:
2015-01-20 15:26:03 -05:00
return _UNESCAPE.sub(fixup, s)
except:
2015-01-20 15:26:03 -05:00
print 'unescape failed: %s' % repr(s)
raise
2015-01-20 15:26:03 -05:00
class UnknownVariable(Exception):
pass
2015-01-20 15:26:03 -05:00
class UnsupportedVariableExpression(Exception):
pass
2015-01-20 15:26:03 -05:00
def replace_vars(m):
2015-01-20 15:26:03 -05:00
"""Replace vars in 'content' portion.
:m: match object
2015-01-20 15:26:03 -05:00
:returns: string
"""
var = m.group(1)
default = m.group(2)
if not re.match(r'\w+$', var):
raise UnsupportedVariableExpression(var)
translate_vars = {
2015-01-20 15:26:03 -05:00
'TM_PHP_OPEN_TAG_WITH_ECHO': 'g:UltiSnipsOpenTagWithEcho',
'TM_PHP_OPEN_TAG': 'g:UltiSnipsOpenTag',
'PHPDOC_AUTHOR': 'g:snips_author',
}
# TODO: TM_SELECTED_TEXT/([\t ]*).*/$1/m
if var in translate_vars:
newvar = translate_vars[var]
else:
# TODO: this could be autogenerated
raise UnknownVariable(var)
return "`!v exists('%s') ? %s : '%s'`" % (newvar, newvar, default)
2015-01-20 15:26:03 -05:00
def parse_content(c):
try:
data = ElementTree.fromstring(c)[0]
rv = {}
2015-01-20 15:26:03 -05:00
for k, v in zip(data[::2], data[1::2]):
rv[k.text] = unescape(v.text)
2015-01-20 15:26:03 -05:00
if re.search(r'\$\{\D', rv['content']):
rv['content'] = re.sub(
r'\$\{([^\d}][^}:]*)(?::([^}]*))?\}',
replace_vars,
rv['content'])
return rv
except (ExpatError, ElementTree.ParseError) as detail:
2015-01-20 15:26:03 -05:00
print ' Syntax Error: %s' % (detail,)
print c
return None
except UnknownVariable as detail:
2015-01-20 15:26:03 -05:00
print ' Unknown variable: %s' % (detail,)
return None
except UnsupportedVariableExpression as detail:
2015-01-20 15:26:03 -05:00
print ' Unsupported variable expression: %s' % (detail,)
return None
2015-01-20 15:26:03 -05:00
def fetch_snippets_from_svn(name):
2015-01-20 15:26:03 -05:00
base_url = 'http://svn.textmate.org/trunk/Bundles/' + name + '.tmbundle/'
snippet_idx = base_url + 'Snippets/'
idx_list = urllib.urlopen(snippet_idx).read()
rv = []
2015-01-20 15:26:03 -05:00
for link in re.findall('<li>(.*?)</li>', idx_list):
m = re.match(r'<a\s*href="(.*)"\s*>(.*)</a>', link)
link, name = m.groups()
2015-01-20 15:26:03 -05:00
if name == '..':
continue
2015-01-20 15:26:03 -05:00
name = unescape(name.rsplit('.', 1)[0]) # remove Extension
print "Fetching data for Snippet '%s'" % name
content = urllib.urlopen(snippet_idx + link).read()
cont = parse_content(content)
if cont:
rv.append((name, cont))
return rv
2015-01-20 15:26:03 -05:00
def fetch_snippets_from_dir(path):
2015-01-20 15:26:03 -05:00
"""Fetch snippets from a given path."""
rv = []
for filename in glob.glob(os.path.join(path, '*.tmSnippet')):
2015-01-20 15:26:03 -05:00
print 'Reading file %s' % filename
f = open(filename)
content = f.read()
cont = parse_content(content)
if cont:
name = os.path.splitext(os.path.basename(filename))[0]
rv.append((name, cont))
return rv
2015-01-20 15:26:03 -05:00
def write_snippets(snip_descr, f):
for name, d in snip_descr:
2015-01-20 15:26:03 -05:00
if 'tabTrigger' not in d:
continue
2015-01-20 15:26:03 -05:00
if 'content' not in d or d['content'] is None:
print 'SKIP: %s (no content)' % (d,)
continue
2015-01-20 15:26:03 -05:00
f.write('snippet %s "%s"\n' % (d['tabTrigger'], name))
f.write(d['content'].encode('utf-8') + '\n')
f.write('endsnippet\n\n')
if __name__ == '__main__':
import sys
bundle = sys.argv[1]
if os.path.isdir(bundle):
name = sys.argv[2]
rv = fetch_snippets_from_dir(bundle)
else:
rv = fetch_snippets_from_svn(bundle)
name = bundle.lower()
2015-01-20 15:26:03 -05:00
write_snippets(rv, open('tm_' + name + '.snippets', 'w'))