implement: type hinting

implement: .gitattributes
implement: .python-verison
implement: f'strings

fix: libs -> lib
fix: Sublime Menus
This commit is contained in:
TheSecEng 2020-04-15 19:09:43 -04:00
parent a9fab727fd
commit 623e810569
No known key found for this signature in database
GPG Key ID: A7C3BA459E8C5C4E
17 changed files with 76 additions and 111 deletions

1
.gitattributes vendored Normal file
View File

@ -0,0 +1 @@
/tests export-ignore

1
.python-version Normal file
View File

@ -0,0 +1 @@
3.8

View File

@ -12,7 +12,7 @@
"command": "un_pretty_json"
},
{
"caption": "Pretty JSON: JSON 2 XML",
"caption": "Pretty JSON: json2xml",
"command": "json_to_xml"
},
{
@ -24,17 +24,11 @@
"command": "pretty_json_validate"
},
{
"caption": "Preferences: Pretty JSON Settings - User",
"command": "open_file", "args":
{
"file": "${packages}/User/Pretty JSON.sublime-settings"
}
},
{
"caption": "Preferences: Pretty JSON Settings - Default",
"command": "open_file", "args":
{
"file": "${packages}/Pretty JSON/Pretty JSON.sublime-settings"
"caption": "Preferences: Pretty JSON Settings",
"command": "edit_settings",
"args": {
"base_file": "${packages}/Pretty JSON/Pretty JSON.sublime-settings",
"default": "{\n\t$0\n}\n"
}
}
]

View File

@ -1,5 +1,5 @@
[
{
{
"mnemonic": "n",
"caption": "Preferences",
"id": "preferences",
@ -13,26 +13,17 @@
"caption": "Pretty JSON",
"children": [
{
"caption": "Settings Default",
"args": {
"file": "${packages}/Pretty JSON/Pretty JSON.sublime-settings"
},
"command": "open_file"
},
"caption": "Settings",
"command": "edit_settings",
"args":
{
"caption": "Settings User",
"args": {
"file": "${packages}/User/Pretty JSON.sublime-settings"
},
"command": "open_file"
"base_file": "${packages}/Pretty JSON/Pretty JSON.sublime-settings",
"default": "{\n\t$0\n}\n",
}
},
{
"caption": "-"
}
]
}
]
}
]
}
]
}]
}]
}]
}]

View File

@ -9,5 +9,9 @@
"max_arrays_line_length": 120,
"pretty_on_save": false,
"validate_on_save": true,
"reindent_block": false
"reindent_block": false,
// Name or Path to jq binary
// Example: /usr/bin/local/jq
// Example: jq
"jq_binary": "jq"
}

View File

@ -2,14 +2,15 @@ import decimal
import os
import re
import subprocess
import shutil
import sys
from xml.etree import ElementTree
import sublime
import sublime_plugin
from .libs import simplejson as json
from .libs.simplejson import OrderedDict
from .lib import simplejson as json
from .lib.simplejson import OrderedDict
SUBLIME_MAJOR_VERSION = int(sublime.version()) / 1000
@ -20,34 +21,20 @@ json_syntax = 'Packages/JSON/JSON.tmLanguage'
jq_exists = False
jq_init = False
''' for OSX we need to manually add brew bin path so jq can be found '''
if sys.platform != 'win32' and '/usr/local/bin' not in os.environ['PATH']:
os.environ['PATH'] += os.pathsep + '/usr/local/bin'
''' defer jq presence check until the user tries to use it, include Package "Fix Mac Path" to resolve
all homebrew issues (https://github.com/int3h/SublimeFixMacPath) '''
jq_path = str()
def check_jq():
global jq_exists
global jq_init
global jq_init, jq_exists, jq_path
if not jq_init:
jq_init = True
jq_test = s.get('jq_binary', 'jq')
try:
# checking if ./jq tool is available so we can use it
s = subprocess.Popen(
['jq', '--version'],
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
)
out, err = s.communicate()
jq_path = shutil.which(jq_test)
jq_exists = True
except OSError:
os_exception = sys.exc_info()[1]
print(str(os_exception))
except OSError as ex:
print(str(ex))
jq_exists = False
@ -58,14 +45,13 @@ class PrettyJsonBaseCommand:
force_sorting = False
@staticmethod
def json_loads(selection):
def json_loads(selection: str) -> dict:
return json.loads(
selection, object_pairs_hook=OrderedDict, parse_float=decimal.Decimal
)
@staticmethod
def json_dumps(obj, minified=False):
def json_dumps(obj, minified: bool = False) -> str:
sort_keys = s.get('sort_keys', False)
if PrettyJsonBaseCommand.force_sorting:
sort_keys = True
@ -102,7 +88,7 @@ class PrettyJsonBaseCommand:
return output_json
def reindent(self, text, selection):
def reindent(self, text: str, selection: str):
current_line = self.view.line(selection.begin())
text_before_sel = sublime.Region(current_line.begin(), selection.begin())
@ -122,14 +108,14 @@ class PrettyJsonBaseCommand:
return '\n'.join(lines)
def show_exception(self, region, msg):
sublime.status_message('[Error]: {}'.format(msg))
def show_exception(self, region: sublime.Region, msg):
sublime.status_message(f'[Error]: {msg}')
if region is None:
sublime.message_dialog(msg)
return
self.highlight_error(region=region, message='{}'.format(msg))
self.highlight_error(region=region, message=f'{msg}')
def highlight_error(self, region, message):
def highlight_error(self, region: sublime.Region, message: str):
self.phantom_set = sublime.PhantomSet(self.view, 'json_errors')
char_match = self.json_char_matcher.search(message)
@ -155,21 +141,19 @@ class PrettyJsonBaseCommand:
# Description: Taken from https://github.com/sublimelsp/LSP/blob/master/plugin/diagnostics.py
# - Thanks to the LSP Team
def create_phantom_html(self, content: str, severity: str) -> str:
stylesheet = sublime.load_resource('Packages/SublimePrettyJson/phantom.css')
return '''<body id=inline-error>
<style>{}</style>
<div class="{}-arrow"></div>
<div class="{} container">
stylesheet = sublime.load_resource('Packages/Pretty JSON/phantom.css')
return f'''<body id=inline-error>
<style>{stylesheet}</style>
<div class="{severity}-arrow"></div>
<div class="{severity} container">
<div class="toolbar">
<a href="hide">×</a>
</div>
<div class="content">{}</div>
<div class="content">{content}</div>
</div>
</body>'''.format(
stylesheet, severity, severity, content
)
</body>'''
def navigation(self, href):
def navigation(self, href: str):
self.clear_phantoms()
def clear_phantoms(self):
@ -180,7 +164,7 @@ class PrettyJsonBaseCommand:
self.phantom_set.update(self.phantoms)
def syntax_to_json(self):
' Changes syntax to JSON if its in plain text '
''' Changes syntax to JSON if its in plain text '''
if 'Plain text' in self.view.settings().get('syntax'):
self.view.set_syntax_file(json_syntax)
@ -335,10 +319,10 @@ class JqPrettyJson(sublime_plugin.WindowCommand):
selection = region
return view.substr(selection)
def done(self, query):
def done(self, query: str):
try:
p = subprocess.Popen(
["jq", query],
[jq_path, query],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
@ -424,7 +408,7 @@ class JsonToXml(PrettyJsonBaseCommand, sublime_plugin.TextCommand):
class JqPrettyJsonOut(sublime_plugin.TextCommand):
def run(self, edit, jq_output=str()):
def run(self, edit, jq_output: str = str()):
self.view.insert(edit, 0, jq_output)

View File

@ -1,30 +1,20 @@
import sublime
import sublime_plugin
try:
# python 3 / Sublime Text 3
from .PrettyJson import PrettyJsonBaseCommand
except ValueError:
from PrettyJson import PrettyJsonBaseCommand
from .PrettyJson import PrettyJsonBaseCommand
s = sublime.load_settings("Pretty JSON.sublime-settings")
class PrettyJsonLintListener(sublime_plugin.EventListener, PrettyJsonBaseCommand):
def on_post_save(self, view):
# will work only in json syntax and once validate_on_save setting is true
validate = s.get("validate_on_save", True)
as_json = s.get("as_json", ["JSON"])
validate = s.get('validate_on_save', True)
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.erase_regions("json_errors")
self.view.erase_status("json_errors")
json_content = self.view.substr(sublime.Region(0, view.size()))
PrettyJsonBaseCommand.clear_phantoms(self)
json_content = self.view.substr(sublime.Region(0, self.view.size()))
try:
self.json_loads(json_content)
except Exception as ex:
@ -33,9 +23,9 @@ class PrettyJsonLintListener(sublime_plugin.EventListener, PrettyJsonBaseCommand
class PrettyJsonAutoPrettyOnSaveListener(sublime_plugin.EventListener):
def on_pre_save(self, view):
auto_pretty = s.get("pretty_on_save", False)
as_json = s.get("as_json", ["JSON"])
auto_pretty = s.get('pretty_on_save', False)
as_json = s.get('as_json', ['JSON'])
if auto_pretty and any(
syntax in view.settings().get("syntax") for syntax in as_json
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')

View File

@ -2,7 +2,7 @@ import sys
import os
# parent folder holds libraries which needs to be included
sys.path.append(os.path.realpath('..'))
sys.path.append(os.path.realpath('../lib'))
import simplejson as json
from simplejson import OrderedDict