implementation: Prettify files that considered as JSON files #85

Author https://github.com/zcold
This commit is contained in:
TheSecEng 2020-04-14 16:35:59 -04:00
parent 6f190adf62
commit 1c7917875f
No known key found for this signature in database
GPG Key ID: A7C3BA459E8C5C4E
2 changed files with 41 additions and 37 deletions

View File

@ -12,18 +12,10 @@ import sublime_plugin
from . import simplejson as json from . import simplejson as json
from .simplejson import OrderedDict from .simplejson import OrderedDict
try:
basestring
except NameError:
basestring = str
SUBLIME_MAJOR_VERSION = int(sublime.version()) / 1000 SUBLIME_MAJOR_VERSION = int(sublime.version()) / 1000
xml_syntax = "Packages/XML/XML.tmLanguage" xml_syntax = "Packages/XML/XML.tmLanguage"
json_syntax = "Packages/JSON/JSON.tmLanguage" json_syntax = "Packages/JSON/JSON.tmLanguage"
if SUBLIME_MAJOR_VERSION < 4:
json_syntax = "Packages/JavaScript/JSON.tmLanguage"
jq_exists = False jq_exists = False
@ -165,10 +157,9 @@ class PrettyJsonBaseCommand:
self.view.show(regions[0]) self.view.show(regions[0])
self.view.set_status("json_errors", message) self.view.set_status("json_errors", message)
def show_exception(self): def show_exception(self, msg):
exc = sys.exc_info()[1] sublime.status_message("[Error]: {}".format(msg))
sublime.status_message(str(exc)) self.highlight_error("{}".format(msg))
self.highlight_error(str(exc))
def syntax_to_json(self): def syntax_to_json(self):
""" Changes syntax to JSON if its in plain text """ """ Changes syntax to JSON if its in plain text """
@ -191,8 +182,8 @@ class PrettyJsonValidate(PrettyJsonBaseCommand, sublime_plugin.TextCommand):
try: try:
self.json_loads(self.view.substr(selection)) self.json_loads(self.view.substr(selection))
sublime.status_message("JSON is Valid") sublime.status_message("JSON is Valid")
except Exception: except Exception as ex:
self.show_exception() self.show_exception(msg=ex)
sublime.message_dialog("Invalid JSON") sublime.message_dialog("Invalid JSON")
@ -221,21 +212,28 @@ class PrettyJsonCommand(PrettyJsonBaseCommand, sublime_plugin.TextCommand):
if selected_entire_file: if selected_entire_file:
self.syntax_to_json() self.syntax_to_json()
except Exception: except Exception as ex:
amount_of_single_quotes = re.findall(r"(\'[^\']+\'?)", selection_text) try:
amount_of_double_quotes = re.findall(r"(\"[^\"]+\"?)", selection_text) amount_of_single_quotes = re.findall(
r"(\'[^\']+\'?)", selection_text
if len(amount_of_single_quotes) >= len(amount_of_double_quotes): )
selection_text_modified = re.sub( amount_of_double_quotes = re.findall(
r"(?:\'([^\']+)\'?)", r'"\1"', selection_text r"(\"[^\"]+\"?)", selection_text
) )
obj = self.json_loads(selection_text_modified)
self.view.replace(edit, selection, self.json_dumps(obj))
if selected_entire_file: if len(amount_of_single_quotes) >= len(amount_of_double_quotes):
self.syntax_to_json() selection_text_modified = re.sub(
else: r"(?:\'([^\']+)\'?)", r'"\1"', selection_text
self.show_exception() )
obj = self.json_loads(selection_text_modified)
self.view.replace(edit, selection, self.json_dumps(obj))
if selected_entire_file:
self.syntax_to_json()
else:
self.show_exception(msg=ex)
except Exception as ex:
self.show_exception(msg=ex)
class PrettyJsonAndSortCommand(PrettyJsonCommand, sublime_plugin.TextCommand): class PrettyJsonAndSortCommand(PrettyJsonCommand, sublime_plugin.TextCommand):
@ -272,8 +270,8 @@ class UnPrettyJsonCommand(PrettyJsonBaseCommand, sublime_plugin.TextCommand):
if selected_entire_file: if selected_entire_file:
self.syntax_to_xml() self.syntax_to_xml()
except Exception: except Exception as ex:
self.show_exception() self.show_exception(msg=ex)
class JqPrettyJson(sublime_plugin.WindowCommand): class JqPrettyJson(sublime_plugin.WindowCommand):
@ -295,7 +293,7 @@ class JqPrettyJson(sublime_plugin.WindowCommand):
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 = str()
for region in view.sel(): for region in view.sel():
# If no selection, use the entire file as the selection # If no selection, use the entire file as the selection
if region.empty(): if region.empty():
@ -384,8 +382,8 @@ class JsonToXml(PrettyJsonBaseCommand, sublime_plugin.TextCommand):
if selected_entire_file: if selected_entire_file:
self.syntax_to_xml() self.syntax_to_xml()
except Exception: except Exception as ex:
self.show_exception() self.show_exception(msg=ex)
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 """ """ intent of ElementTree in case it's py26 without minidom/pyexpat """
@ -440,8 +438,8 @@ class PrettyJsonGotoSymbolCommand(PrettyJsonBaseCommand, sublime_plugin.TextComm
json_data = self.json_loads(content) json_data = self.json_loads(content)
self.generate_items(json_data, "") self.generate_items(json_data, "")
sublime.active_window().show_quick_panel(self.items, self.goto) sublime.active_window().show_quick_panel(self.items, self.goto)
except Exception: except Exception as ex:
self.show_exception() self.show_exception(msg=ex)
def generate_items(self, json_data, root_key): def generate_items(self, json_data, root_key):
if isinstance(json_data, OrderedDict): if isinstance(json_data, OrderedDict):
@ -452,7 +450,7 @@ class PrettyJsonGotoSymbolCommand(PrettyJsonBaseCommand, sublime_plugin.TextComm
self.generate_items(json_data[key], new_key_name) self.generate_items(json_data[key], new_key_name)
elif isinstance(json_data, list): elif isinstance(json_data, list):
for index, item in enumerate(json_data): for index, item in enumerate(json_data):
if isinstance(item, basestring): if isinstance(item, str):
self.items.append("%s" % root_key + "." + item) self.items.append("%s" % root_key + "." + item)
self.goto_items.append('"%s"' % item) self.goto_items.append('"%s"' % item)

View File

@ -14,7 +14,10 @@ class PrettyJsonLintListener(sublime_plugin.EventListener, PrettyJsonBaseCommand
def on_post_save(self, view): def on_post_save(self, view):
# will work only in json syntax and once validate_on_save setting is true # will work only in json syntax and once validate_on_save setting is true
validate = s.get("validate_on_save", True) validate = s.get("validate_on_save", True)
if validate and "JSON" in view.settings().get("syntax"): as_json = s.get("as_json", ["JSON"])
if validate and any(
syntax in view.settings().get("syntax") for syntax in as_json
):
self.view = view self.view = view
self.view.erase_regions("json_errors") self.view.erase_regions("json_errors")
@ -31,5 +34,8 @@ class PrettyJsonLintListener(sublime_plugin.EventListener, PrettyJsonBaseCommand
class PrettyJsonAutoPrettyOnSaveListener(sublime_plugin.EventListener): class PrettyJsonAutoPrettyOnSaveListener(sublime_plugin.EventListener):
def on_pre_save(self, view): def on_pre_save(self, view):
auto_pretty = s.get("pretty_on_save", False) auto_pretty = s.get("pretty_on_save", False)
if auto_pretty and "JSON" in view.settings().get("syntax"): as_json = s.get("as_json", ["JSON"])
if auto_pretty and any(
syntax in view.settings().get("syntax") for syntax in as_json
):
sublime.active_window().run_command("pretty_json") sublime.active_window().run_command("pretty_json")