Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sublime 2 Package - Property Extractor
[
{ "keys": ["alt+t"], "command": "extractor_command"}
]
[
{ "keys": ["alt+t"], "command": "extractor_command"}
]
[
{ "keys": ["alt+t"], "command": "extractor_command"}
]
[
{
"caption": "Extract Property",
"command": "extractor_command"
}
]
# -*- coding: utf-8 -*-
import sublime, sublime_plugin
import os, re, md5, json
translit_table={
u'Á': u'A', u'É': u'E', u'Í': u'I', u'Ó': u'O', u'Ú': u'U',
u'á': u'a', u'é': u'e', u'í': u'i', u'ó': u'o', u'ú': u'u',
u'Ñ': u'N', u'ñ': u'n'
}
def error(msg): sublime.error_message(msg)
def log(msg): sublime.status_message(msg)
def transliterate(word):
transliterated = ''
for char in word:
transchar = ''
if char in translit_table:
transchar = translit_table[char]
else:
transchar = char
transliterated += transchar
return transliterated
class ExtractorCommandCommand(sublime_plugin.TextCommand):
def run(self, edit):
self.edit = edit
self.region = self.view.sel()[0]
if self.region.empty():
error("Select a region")
return
os.path.basename(self.view.file_name())
filename, file_extension = os.path.splitext(self.view.file_name())
matches = re.search(r"\.([a-z]{2})(_[A-Z]{2})?$", filename)
if matches:
self.locale = matches.group(1)
filename = filename.replace(matches.group(0), '')
else:
self.locale = 'en'
self.properties = filename + '.json'
self.string = self.view.substr(self.region)
key_name = transliterate(self.string).encode('utf-8', 'replace')
key_name = re.sub(r"\W+", '_', key_name)
key_name = re.sub(r"_+", '_', key_name)
key_name = key_name
if len(key_name) > 30:
hash = md5.md5(key_name).hexdigest()[0:5]
key_name = key_name[0:30] + '_' + hash
key_name = key_name.upper()
self.view.window().show_input_panel("Key name: ", key_name, self.persist, None, None)
def persist(self, key_name):
self.dict = {}
if os.path.exists(self.properties):
with open(self.properties) as f:
lines = f.readlines()
raw = "\n".join(line for line in lines)
self.dict = json.loads(raw)
if not self.locale in self.dict: self.dict[self.locale] = {}
self.dict[self.locale][key_name] = self.string
replacement = "<%- t(" + json.dumps(key_name) + ") %>"
self.view.replace(self.edit, self.region, replacement)
with open(self.properties, 'w') as f:
f.write(json.dumps(self.dict, ensure_ascii=False).encode('utf-8', 'replace'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment