Small code refactoring to re-use code blocks + readme slight change

This commit is contained in:
Nikolajus 2014-06-05 09:58:00 +02:00 committed by Nikolajus Krauklis
parent 9399ae5a22
commit f5265b40a7
2 changed files with 89 additions and 72 deletions

View File

@ -29,7 +29,9 @@ if sys.platform != 'win32' and '/usr/local/bin' not in os.environ['PATH']:
try: try:
# checking if ./jq tool is available so we can use it # checking if ./jq tool is available so we can use it
s = subprocess.Popen(["jq", "--version"], stderr=subprocess.PIPE, stdout=subprocess.PIPE) s = subprocess.Popen(["jq", "--version"],
stderr=subprocess.PIPE,
stdout=subprocess.PIPE)
out, err = s.communicate() out, err = s.communicate()
jq_version = err.decode("utf-8").replace("jq version ", "").strip() jq_version = err.decode("utf-8").replace("jq version ", "").strip()
jq_exits = True jq_exits = True
@ -42,9 +44,54 @@ except OSError:
s = sublime.load_settings("Pretty JSON.sublime-settings") s = sublime.load_settings("Pretty JSON.sublime-settings")
class PrettyJsonCommand(sublime_plugin.TextCommand): class PrettyJsonBaseCommand(sublime_plugin.TextCommand):
json_error_matcher = re.compile(r"line (\d+) column (\d+) \(char (\d+)\)") json_error_matcher = re.compile(r"line (\d+) column (\d+) \(char (\d+)\)")
@staticmethod
def json_loads(selection):
return json.loads(selection,
object_pairs_hook=OrderedDict,
parse_float=decimal.Decimal)
@staticmethod
def json_dumps(obj):
return json.dumps(obj,
indent=s.get("indent", 2),
ensure_ascii=s.get("ensure_ascii", False),
sort_keys=s.get("sort_keys", False),
separators=(',', ': '),
use_decimal=True)
@staticmethod
def json_dumps_minified(obj):
return json.dumps(obj,
ensure_ascii=s.get("ensure_ascii", False),
sort_keys=s.get("sort_keys", False),
separators=(',', ':'),
use_decimal=True)
def highlight_error(self, message):
m = self.json_error_matcher.search(message)
if m:
line = int(m.group(1)) - 1
regions = [self.view.full_line(self.view.text_point(line, 0)), ]
self.view.add_regions('json_errors', regions, 'invalid', 'dot',
sublime.DRAW_OUTLINED)
self.view.set_status('json_errors', message)
def show_exception(self):
exc = sys.exc_info()[1]
sublime.status_message(str(exc))
self.highlight_error(str(exc))
def change_syntax(self):
""" Changes syntax to JSON if its in plain text """
if "Plain text" in self.view.settings().get('syntax'):
self.view.set_syntax_file("Packages/JavaScript/JSON.tmLanguage")
class PrettyJsonCommand(PrettyJsonBaseCommand):
""" Pretty Print JSON """ """ Pretty Print JSON """
def run(self, edit): def run(self, edit):
self.view.erase_regions('json_errors') self.view.erase_regions('json_errors')
@ -60,46 +107,20 @@ class PrettyJsonCommand(sublime_plugin.TextCommand):
selection = region selection = region
try: try:
obj = json.loads(self.view.substr(selection), obj = self.json_loads(self.view.substr(selection))
object_pairs_hook=OrderedDict, self.view.replace(edit, selection, self.json_dumps(obj))
parse_float=decimal.Decimal)
self.view.replace(edit, selection, json.dumps(obj,
indent=s.get("indent", 2),
ensure_ascii=s.get("ensure_ascii", False),
sort_keys=s.get("sort_keys", False),
separators=(',', ': '),
use_decimal=True))
if selected_entire_file: if selected_entire_file:
self.change_syntax() self.change_syntax()
except Exception: except Exception:
exc = sys.exc_info()[1] self.show_exception()
sublime.status_message(str(exc))
self.highlight_error(str(exc))
def highlight_error(self, message):
m = self.json_error_matcher.search(message)
if m:
line = int(m.group(1)) - 1
regions = [self.view.full_line(self.view.text_point(line, 0)), ]
self.view.add_regions('json_errors', regions, 'invalid', 'dot', sublime.DRAW_OUTLINED)
self.view.set_status('json_errors', message)
def change_syntax(self):
""" Changes syntax to JSON if its in plain text """
if "Plain text" in self.view.settings().get('syntax'):
self.view.set_syntax_file("Packages/JavaScript/JSON.tmLanguage")
class UnPrettyJsonCommand(PrettyJsonCommand): class UnPrettyJsonCommand(PrettyJsonBaseCommand):
"""
Compress/minify JSON """ Compress/minify JSON - it makes json as one-liner """
it makes json as one-liner
"""
def run(self, edit): def run(self, edit):
""" overwriting base class run function to remove intent """
self.view.erase_regions('json_errors') self.view.erase_regions('json_errors')
for region in self.view.sel(): for region in self.view.sel():
@ -113,23 +134,14 @@ class UnPrettyJsonCommand(PrettyJsonCommand):
selection = region selection = region
try: try:
obj = json.loads(self.view.substr(selection), obj = self.json_loads(self.view.substr(selection))
object_pairs_hook=OrderedDict, self.view.replace(edit, selection, self.json_dumps_minified(obj))
parse_float=decimal.Decimal)
self.view.replace(edit, selection, json.dumps(obj,
ensure_ascii=s.get("ensure_ascii", False),
sort_keys=s.get("sort_keys", False),
separators=(',', ':'),
use_decimal=True))
if selected_entire_file: if selected_entire_file:
self.change_syntax() self.change_syntax()
except Exception: except Exception:
exc = sys.exc_info()[1] self.show_exception()
self.highlight_error(str(exc))
sublime.status_message(str(exc))
class JqPrettyJson(sublime_plugin.WindowCommand): class JqPrettyJson(sublime_plugin.WindowCommand):
@ -138,14 +150,13 @@ class JqPrettyJson(sublime_plugin.WindowCommand):
""" """
def run(self): def run(self):
if jq_exits: if jq_exits:
self.window.show_input_panel("Enter ./jq filter expression", ".", self.done, None, None) self.window.show_input_panel("Enter ./jq filter expression", ".",
self.done, None, None)
else: else:
sublime.status_message("./jq tool is not available on your system. http://stedolan.github.io/jq") sublime.status_message('./jq tool is not available on your system. http://stedolan.github.io/jq')
def get_content(self): def get_content(self):
""" """ returns content of active view or selected region """
returns content of active view or selected region
"""
view = self.window.active_view() view = self.window.active_view()
selection = "" selection = ""
for region in view.sel(): for region in view.sel():
@ -158,7 +169,11 @@ class JqPrettyJson(sublime_plugin.WindowCommand):
def done(self, query): def done(self, query):
try: try:
p = subprocess.Popen(["jq", query], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) p = subprocess.Popen(["jq", query],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
raw_json = self.get_content() raw_json = self.get_content()
if SUBLIME_MAJOR_VERSION < 3: if SUBLIME_MAJOR_VERSION < 3:
@ -176,7 +191,7 @@ class JqPrettyJson(sublime_plugin.WindowCommand):
sublime.status_message(str(exc)) sublime.status_message(str(exc))
class JsonToXml(PrettyJsonCommand): class JsonToXml(PrettyJsonBaseCommand):
""" """
converts Json to XML converts Json to XML
""" """
@ -211,7 +226,8 @@ class JsonToXml(PrettyJsonCommand):
xml_string += rtn xml_string += rtn
# for some reason python 2.6 shipped with ST2 does not have pyexpat # for some reason python 2.6 shipped with ST2
# does not have pyexpat
if SUBLIME_MAJOR_VERSION >= 3: if SUBLIME_MAJOR_VERSION >= 3:
xml_string = minidom.parseString(xml_string).toprettyxml(encoding="UTF-8") xml_string = minidom.parseString(xml_string).toprettyxml(encoding="UTF-8")
@ -224,11 +240,10 @@ class JsonToXml(PrettyJsonCommand):
self.change_syntax() self.change_syntax()
except Exception: except Exception:
exc = sys.exc_info()[1] self.show_exception()
self.highlight_error(str(exc))
sublime.status_message(str(exc))
def indent_for_26(self, elem, level=0): def indent_for_26(self, elem, level=0):
""" intent of ElementTree in case it's py26 without minidom/pyexpat """
i = "\n" + level*" " i = "\n" + level*" "
if len(elem): if len(elem):
if not elem.text or not elem.text.strip(): if not elem.text or not elem.text.strip():
@ -243,22 +258,24 @@ class JsonToXml(PrettyJsonCommand):
if level and (not elem.tail or not elem.tail.strip()): if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i elem.tail = i
def traverse(self, el, ha): def traverse(self, element, json_dict):
if type(ha) is dict and ha.keys(): """ recursive traverse through dict and build xml tree """
for i in ha.keys(): if type(json_dict) is dict and json_dict.keys():
for i in json_dict.keys():
e = ElementTree.Element(i) e = ElementTree.Element(i)
el.append(self.traverse(e, ha[i])) element.append(self.traverse(e, json_dict[i]))
elif type(ha) is list: elif type(json_dict) is list:
e_items = ElementTree.Element('items') e_items = ElementTree.Element('items')
for i in ha: for i in json_dict:
e_items.append(self.traverse(ElementTree.Element('item'), i)) e_items.append(self.traverse(ElementTree.Element('item'), i))
el.append(e_items) element.append(e_items)
else: else:
el.set('value', str(ha)) element.set('value', str(json_dict))
return el return element
def change_syntax(self): def change_syntax(self):
""" change syntax to xml """
self.view.set_syntax_file("Packages/XML/XML.tmLanguage") self.view.set_syntax_file("Packages/XML/XML.tmLanguage")

View File

@ -4,22 +4,22 @@ Prettify/Minify/Query JSON plugin for Sublime Text 2 & 3
## Installation ## Installation
Install this sublime text package via [Package Control](https://sublime.wbond.net) Install this sublime text 2/3 package via [Package Control](https://sublime.wbond.net)
### or manual installation ### or manually install
- `cd <Packages directory>` - `cd <Packages directory>`
- `git clone https://github.com/dzhibas/SublimePrettyJson.git` - `git clone https://github.com/dzhibas/SublimePrettyJson.git`
## Usage ## Usage
To prettify JSON, make selection of json and press keys: To prettify JSON, make selection of json (or else it will try to use full view buffer) and press keys:
- Linux: <kbd>ctrl+alt+j</kbd> - Linux: <kbd>ctrl+alt+j</kbd>
- Windows: <kbd>ctrl+alt+j</kbd> - Windows: <kbd>ctrl+alt+j</kbd>
- OS X: <kbd>cmd+ctrl+j</kbd> - OS X: <kbd>cmd+ctrl+j</kbd>
or through Command Palette <kbd>Ctrl+Shift+P</kbd> find "Pretty JSON: Format (Pretty Print) JSON" or through Command Palette <kbd>Ctrl+Shift+P</kbd> find "Pretty JSON: Format (Pretty Print) JSON" (you can search for part of it like 'pretty format')
If selection is empty and configuration entry **use_entire_file_if_no_selection** is true, tries to prettify whole file If selection is empty and configuration entry **use_entire_file_if_no_selection** is true, tries to prettify whole file
@ -27,11 +27,11 @@ If JSON is not valid it will be displayed in status bar of Sublime Text
### Compress / Minify JSON ### Compress / Minify JSON
Using Command Palette <kbd>Ctrl+Shift+P</kbd> find "Pretty JSON: Minify (compress) JSON" this will make selection or full buffer as single line JSON which later you can use in command lines (curl/httpie) or somewhere else... Using Command Palette <kbd>Ctrl+Shift+P</kbd> find "Pretty JSON: Minify (compress) JSON" (you can search for part of it like 'json minify') this will make selection or full buffer as single line JSON which later you can use in command lines (curl/httpie) or somewhere else...
### Convert JSON to XML ### Convert JSON to XML
Using Command Palette <kbd>Ctrl+Shift+P</kbd> search fo "Pretty JSON: JSON 2 XML" this will convert your selected JSON of full buffer to XML and replace syntax and buffer to XML output Using Command Palette <kbd>Ctrl+Shift+P</kbd> search fo "Pretty JSON: JSON 2 XML" (you can search for part of it like '2XML') this will convert your selected JSON of full buffer to XML and replace syntax and buffer to XML output
## ./jQ query/filter usage ## ./jQ query/filter usage