Skip to content

Commit

Permalink
Merge pull request #15 from max-mykhailenko/master
Browse files Browse the repository at this point in the history
Fix #13, prettify type output, format code with Black
  • Loading branch information
Pegase745 authored Nov 20, 2019
2 parents 329737b + 19cad92 commit 9fd21d1
Show file tree
Hide file tree
Showing 24 changed files with 671 additions and 637 deletions.
2 changes: 1 addition & 1 deletion FlowType.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@
def plugin_loaded():
"""Raise an error if Sublime Text < 3."""
if int(sublime.version()) < 3000:
raise RuntimeError('FlowType plugin works with Sublime Text 3 only.')
raise RuntimeError("FlowType plugin works with Sublime Text 3 only.")
16 changes: 8 additions & 8 deletions flowtype/commands/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@
from .suggest_annotations import FlowtypeSuggestAnnotations

__all__ = [
'FlowtypeViewType',
'FlowtypeCoverage',
'FlowtypeAddPragma',
'FlowtypeViewErrors',
'FlowtypeAutocomplete',
'FlowtypeCheckContents',
'FlowtypeGotoDefinition',
'FlowtypeSuggestAnnotations',
"FlowtypeViewType",
"FlowtypeCoverage",
"FlowtypeAddPragma",
"FlowtypeViewErrors",
"FlowtypeAutocomplete",
"FlowtypeCheckContents",
"FlowtypeGotoDefinition",
"FlowtypeSuggestAnnotations",
]
4 changes: 2 additions & 2 deletions flowtype/commands/add_pragma.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ class FlowtypeAddPragma(BaseCommand):
def is_enabled(self):
"""Enable the command only on Javascript files and has flow pragma."""
content = self.get_content()
no_pragma = '// @flow' not in content and '/* @flow */' not in content
no_pragma = "// @flow" not in content and "/* @flow */" not in content

return is_js_source(self.view) and no_pragma

def run(self, edit):
"""Run command."""
logger.logger.debug('Running add_pragma')
logger.logger.debug("Running add_pragma")

self.view.insert(edit, 0, "// @flow\n\n")
83 changes: 45 additions & 38 deletions flowtype/commands/autocomplete.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,19 @@

def build_content_snippet(suggestion):
"""Build snippet for function autocompletion."""
name = suggestion['name']
name = suggestion["name"]

if suggestion['func_details']:
paramText = ''
params = suggestion['func_details']['params']
if suggestion["func_details"]:
paramText = ""
params = suggestion["func_details"]["params"]

for param in params:
if not paramText:
paramText += param['name']
paramText += param["name"]
else:
paramText += ', ' + param['name']
paramText += ", " + param["name"]

return '{}({})'.format(name, paramText)
return "{}({})".format(name, paramText)
else:
return name

Expand All @@ -34,65 +34,72 @@ def get_cmd(self):
"""Construct cli command."""
try:
flow_bin = self.get_flow_bin()
logger.logger.debug('using flow-bin %s' % flow_bin)
logger.logger.debug("using flow-bin %s" % flow_bin)
except ValueError as e:
logger.logger.error('autocomplete %s' % e)
logger.logger.error("autocomplete %s" % e)
return

arguments = prepare_arguments(self.view)

cmd = [
flow_bin, 'autocomplete',
'--from', 'nuclide',
'--quiet', '--json',
flow_bin,
"autocomplete",
"--from",
"nuclide",
"--quiet",
"--json",
arguments.file_name,
str(arguments.row + 1), str(arguments.col + 1)
str(arguments.row + 1),
str(arguments.col + 1),
]

return cmd

def handle_process(self, returncode, stdout, error):
"""Handle the output from the threaded process."""
if type(error) is bytes:
error = error.decode('utf-8')
error = error.decode("utf-8")

if returncode != 0:
logger.logger.error('autocomplete %s' % error)
logger.logger.error("autocomplete %s" % error)
return

logger.logger.debug(stdout)

if len(stdout['result']) > 0:
for suggestion in stdout['result']:
FLOW_SUGGESTIONS.append(print_type_format(
suggestion['name'],
build_content_snippet(suggestion),
suggestion['type']
))

self.view.run_command('auto_complete', {
'disable_auto_insert': True,
'api_completions_only': True,
'next_completion_if_showing': False,
'auto_complete_commit_on_tab': True,
})
if len(stdout["result"]) > 0:
for suggestion in stdout["result"]:
FLOW_SUGGESTIONS.append(
print_type_format(
suggestion["name"],
build_content_snippet(suggestion),
suggestion["type"],
)
)

self.view.run_command(
"auto_complete",
{
"disable_auto_insert": True,
"api_completions_only": True,
"next_completion_if_showing": False,
"auto_complete_commit_on_tab": True,
},
)
else:
if (not get_settings('suggest_autocomplete_on_edit', True)):
if not get_settings("suggest_autocomplete_on_edit", True):
self.view.set_status(
'flow_type_autocomplete',
'Flow: not enough type information to autocomplete')
"flow_type_autocomplete",
"Flow: not enough type information to autocomplete",
)

def run(self, view):
"""Execute `autocomplete` command."""
logger.logger.debug('Running autocomplete')
logger.logger.debug("Running autocomplete")

FLOW_SUGGESTIONS[:] = []

self.view.erase_status('flow_type_autocomplete')
self.view.erase_status("flow_type_autocomplete")

thread = ExecFlowCommand(
self.get_cmd(),
self.get_content()
)
thread = ExecFlowCommand(self.get_cmd(), self.get_content())
thread.start()
self.check_thread(thread)
20 changes: 9 additions & 11 deletions flowtype/commands/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ def get_project_root(self):
Search for a .flowconfig file and consider its location as the
project's root.
"""
file_path = self.active_window.extract_variables()['file_path']
return find_in_parent_folders('.flowconfig', file_path)
file_path = self.active_window.extract_variables()["file_path"]
return find_in_parent_folders(".flowconfig", file_path)

def get_flow_bin(self):
"""Return the flow binary to use."""
file_path = self.active_window.extract_variables()['file_path']
file_path = self.active_window.extract_variables()["file_path"]
return get_flow_bin(file_path)

def get_content(self):
Expand All @@ -27,11 +27,11 @@ def get_content(self):

def get_cmd(self):
"""Construct cli command."""
raise NotImplementedError('get_cmd method must be defined')
raise NotImplementedError("get_cmd method must be defined")

def handle_process(self, returncode, stdout, error):
"""Handle the output from the threaded process."""
raise NotImplementedError('handle_process method must be defined')
raise NotImplementedError("handle_process method must be defined")

def check_thread(self, thread, i=0, dir=1):
"""Check if the thread is still running."""
Expand All @@ -44,21 +44,19 @@ def check_thread(self, thread, i=0, dir=1):
i += dir

self.view.set_status(
'flow_loader',
'FlowType [%s=%s]' % (' ' * before, ' ' * after)
"flow_loader", "FlowType [%s=%s]" % (" " * before, " " * after)
)

if thread.is_alive():
return sublime.set_timeout(lambda: self.check_thread(
thread, i, dir), 100)
return sublime.set_timeout(lambda: self.check_thread(thread, i, dir), 100)

self.view.erase_status('flow_loader')
self.view.erase_status("flow_loader")
self.handle_process(thread.returncode, thread.stdout, thread.stderr)

def is_enabled(self):
"""Enable the command only on Javascript files and has flow pragma."""
content = self.get_content()
pragma = '// @flow' in content or '/* @flow */' in content
pragma = "// @flow" in content or "/* @flow */" in content

return is_js_source(self.view) and pragma

Expand Down
82 changes: 41 additions & 41 deletions flowtype/commands/check_contents.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,43 +16,46 @@ def get_cmd(self):
"""Construct cli command."""
try:
flow_bin = self.get_flow_bin()
logger.logger.debug('using flow-bin %s' % flow_bin)
logger.logger.debug("using flow-bin %s" % flow_bin)
except ValueError as e:
logger.logger.error('check_contents %s' % e)
logger.logger.error("check_contents %s" % e)
return

arguments = prepare_arguments(self.view)

cmd = [
flow_bin, 'check-contents',
'--from', 'nuclide',
'--quiet', '--json', arguments.file_name
flow_bin,
"check-contents",
"--from",
"nuclide",
"--quiet",
"--json",
arguments.file_name,
]

return cmd

def handle_process(self, returncode, stdout, error):
"""Handle the output from the threaded process."""
self.view.erase_regions('flow_type_highlights')
self.view.erase_regions("flow_type_highlights")

if type(error) is bytes:
error = error.decode('utf-8')
error = error.decode("utf-8")

if returncode != 0:
logger.logger.error('check_contents %s' % error)
logger.logger.error("check_contents %s" % error)
return

passed = stdout.get('passed', False)
errors = stdout.get('errors', [])
flow_version = stdout.get('flowVersion', '')
passed = stdout.get("passed", False)
errors = stdout.get("errors", [])
flow_version = stdout.get("flowVersion", "")

# No errors
if passed:
self.view.erase_status('flow_errors')
self.view.erase_status('flow_single_error')
self.view.set_status(
'flow_errors', 'Flow %s: no errors' % flow_version)
FLOWTYPE['LAST_ERROR_CHECK'] = time.time()
self.view.erase_status("flow_errors")
self.view.erase_status("flow_single_error")
self.view.set_status("flow_errors", "Flow %s: no errors" % flow_version)
FLOWTYPE["LAST_ERROR_CHECK"] = time.time()
return

# Errors
Expand All @@ -61,60 +64,57 @@ def handle_process(self, returncode, stdout, error):
for error in errors:
legend = []
full_description = []
messages = error.get('message', [])
messages = error.get("message", [])
operation = messages[0]

if operation:
row = int(operation['line']) - 1
col = int(operation['start']) - 1
endcol = int(operation['end'])
row = int(operation["line"]) - 1
col = int(operation["start"]) - 1
endcol = int(operation["end"])

start = self.view.text_point(row, col)
stop = self.view.text_point(row, endcol)

regions.append(sublime.Region(start, stop))

for message in messages:
legend.append(message['descr'])
legend.append(message["descr"])

full_description.append('{} {}'.format(
row + 1, operation['context']))
full_description.append(' '.join(legend))
full_description.append("{} {}".format(row + 1, operation["context"]))
full_description.append(" ".join(legend))

error_per_line[row + 1] = ' '.join(legend)
error_per_line[row + 1] = " ".join(legend)

self.view.add_regions(
'flow_type_highlights',
regions, 'string', 'dot',
sublime.DRAW_NO_FILL
"flow_type_highlights", regions, "string", "dot", sublime.DRAW_NO_FILL
)

cursor_position = self.view.sel()[0].begin()
row, col = self.view.rowcol(cursor_position)
error_description = error_per_line.get(row + 1, '')
error_description = error_per_line.get(row + 1, "")

self.view.erase_status('flow_errors')
self.view.erase_status('flow_single_error')
self.view.erase_status("flow_errors")
self.view.erase_status("flow_single_error")
if error_description:
self.view.set_status(
'flow_single_error',
'Flow error: {}'.format(error_description))
"flow_single_error", "Flow error: {}".format(error_description)
)
else:
self.view.set_status(
'flow_errors', 'Flow {}: {} error{}'.format(
flow_version, len(errors), 's' if len(errors) > 1 else ''))
"flow_errors",
"Flow {}: {} error{}".format(
flow_version, len(errors), "s" if len(errors) > 1 else ""
),
)

self.viewport_pos = self.view.viewport_position()
self.selection = list(self.view.sel())
FLOWTYPE['LAST_ERROR_CHECK'] = time.time()
FLOWTYPE["LAST_ERROR_CHECK"] = time.time()

def run(self, view):
"""Execute `check_contents` command."""
logger.logger.debug('Running check_contents')
logger.logger.debug("Running check_contents")

thread = ExecFlowCommand(
self.get_cmd(),
self.get_content()
)
thread = ExecFlowCommand(self.get_cmd(), self.get_content())
thread.start()
self.check_thread(thread)
Loading

0 comments on commit 9fd21d1

Please sign in to comment.