Exemplo n.º 1
0
    def on_query_completions(self, view, prefix, locations):
        """Fired directly from Sublime Text 3 events systems
        """

        if not is_code(view, lang='go'):
            return

        if not go.ANAGONDA_PRESENT:
            if go.AVAILABLE:
                go.init()
            else:
                return

        if self.ready_from_defer is True:
            completion_flags = 0

            if get_settings(view, 'suppress_word_completions', False):
                completion_flags = sublime.INHIBIT_WORD_COMPLETIONS

            if get_settings(view, 'suppress_explicit_completions', False):
                completion_flags |= sublime.INHIBIT_EXPLICIT_COMPLETIONS

            cpl = self.completions
            self.completions = []
            self.ready_from_defer = False

            return (cpl, completion_flags)

        code = view.substr(sublime.Region(0, view.size()))
        row, col = view.rowcol(locations[0])
        data = {
            'vid':
            view.id(),
            'path':
            view.file_name(),
            'code':
            code,
            'offset':
            view.text_point(row, col),
            'add_params':
            get_settings(view, 'anaconda_go_add_completion_params', True),
            'go_env': {
                'GOROOT': go.GOROOT,
                'GOPATH': go.GOPATH,
                'CGO_ENABLED': go.CGO_ENABLED
            },
            'method':
            'autocomplete',
            'handler':
            'anaGonda'
        }
        Worker.execute(
            Callback(on_success=self._complete,
                     on_failure=self._on_failure,
                     on_timeout=self._on_timeout), **data)
Exemplo n.º 2
0
    def on_query_completions(self, view, prefix, locations):
        """Fired directly from Sublime Text 3 events systems
        """

        if not is_code(view, lang='go'):
            return

        if not go.ANAGONDA_PRESENT:
            if go.AVAILABLE:
                go.init()
            else:
                return

        if self.ready_from_defer is True:
            completion_flags = 0

            if get_settings(view, 'suppress_word_completions', False):
                completion_flags = sublime.INHIBIT_WORD_COMPLETIONS

            if get_settings(view, 'suppress_explicit_completions', False):
                completion_flags |= sublime.INHIBIT_EXPLICIT_COMPLETIONS

            cpl = self.completions
            self.completions = []
            self.ready_from_defer = False

            return (cpl, completion_flags)

        code = view.substr(sublime.Region(0, view.size()))
        row, col = view.rowcol(locations[0])
        data = {
            'vid': view.id(),
            'path': view.file_name(),
            'code': code,
            'offset': view.text_point(row, col),
            'add_params': get_settings(
                view, 'anaconda_go_add_completion_params', True),
            'go_env': {
                'GOROOT': go.GOROOT,
                'GOPATH': go.GOPATH,
                'CGO_ENABLED': go.CGO_ENABLED
            },
            'method': 'autocomplete',
            'handler': 'anaGonda'
        }
        Worker.execute(
            Callback(
                on_success=self._complete,
                on_failure=self._on_failure,
                on_timeout=self._on_timeout
            ),
            **data
        )
Exemplo n.º 3
0
 def run(self, operation='analyze') -> None:
     self.operation = operation
     try:
         view = self.window.active_view()
         self.view = view
         scope = get_settings(view, 'anaconda_go_guru_scope')
         data = {
             'vid': self.view.id(),
             'scope': scope if scope is not None else get_scope(view, go.GOPATH),  # noqa
             'code': view.substr(sublime.Region(0, view.size())),
             'offset': view.text_point(*view.rowcol(view.sel()[0].begin())),
             'path': view.file_name(),
             'buf': self.modified_buffer(view),
             'mode': self.operation,
             'go_env': {
                 'GOROOT': go.GOROOT,
                 'GOPATH': go.GOPATH,
                 'CGO_ENABLED': go.CGO_ENABLED
             },
             'method': 'analyze_symbol',
             'handler': 'anaGonda'
         }
         Worker().execute(
             Callback(
                 on_success=self.on_success,
                 on_failure=self._on_failure,
                 on_timeout=self._on_timeout
             ),
             **data
         )
     except Exception as err:
         print('anaconda_go: {}'.format(self.method.replace('_', '')))
         print(err)
Exemplo n.º 4
0
 def run(self) -> None:
     try:
         view = self.window.active_view()
         self.view = view
         data = {
             'vid': view.id(),
             'file_path': view.file_name(),
             'parse_comments': get_settings(
                 view, 'anaconda_go_motion_parse_comments', False
             ),
             'go_env': {
                 'GOROOT': go.GOROOT,
                 'GOPATH': go.GOPATH,
                 'CGO_ENABLED': go.CGO_ENABLED
             },
             'method': self.method,
             'handler': 'anaGonda'
         }
         Worker().execute(
             Callback(
                 on_success=ExplorerPanel(view).run,
                 on_failure=self._on_failure,
                 on_timeout=self._on_timeout
             ),
             **data
         )
     except Exception as err:
         print('anaconda_go: {}'.format(self.method.replace('_', ' ')))
         print(err)
Exemplo n.º 5
0
 def run(self) -> None:
     try:
         view = self.window.active_view()
         self.view = view
         data = {
             'vid':
             view.id(),
             'file_path':
             view.file_name(),
             'offset':
             view.sel()[0].begin(),
             'parse_comments':
             get_settings(view, 'anaconda_go_motion_parse_comments', False),
             'go_env': {
                 'GOROOT': go.GOROOT,
                 'GOPATH': go.GOPATH,
                 'CGO_ENABLED': go.CGO_ENABLED
             },
             'method':
             'enclosing',
             'handler':
             'anaGonda'
         }
         Worker().execute(
             Callback(on_success=self._on_success,
                      on_failure=self._on_failure,
                      on_timeout=self._on_timeout), **data)
     except Exception as err:
         print('anaconda_go: enclosing function error')
         print(err)
Exemplo n.º 6
0
 def run(self, operation='analyze') -> None:
     self.operation = operation
     try:
         view = self.window.active_view()
         self.view = view
         scope = get_settings(view, 'anaconda_go_guru_scope')
         data = {
             'vid': self.view.id(),
             'scope': scope if scope is not None else get_scope(
                 view, go.GOPATH),  # noqa
             'code': view.substr(sublime.Region(0, view.size())),
             'offset': view.text_point(*view.rowcol(view.sel()[0].begin())),
             'path': view.file_name(),
             'buf': self.modified_buffer(view),
             'mode': self.operation,
             'go_env': {
                 'GOROOT': go.GOROOT,
                 'GOPATH': go.GOPATH,
                 'CGO_ENABLED': go.CGO_ENABLED
             },
             'method': 'analyze_symbol',
             'handler': 'anaGonda'
         }
         Worker().execute(
             Callback(on_success=self.on_success,
                      on_failure=self._on_failure,
                      on_timeout=self._on_timeout), **data)
     except Exception as err:
         print('anaconda_go: {}'.format(self.method.replace('_', '')))
         print(err)
Exemplo n.º 7
0
def slow_linters(view=None, hook=None):
    """Run slow gometalinter linters
    """

    if view is None:
        view = active_view()

    if not get_settings(view, 'anaconda_go_linting', True):
        return

    if view.file_name() in anaconda_sublime.ANACONDA['DISABLED']:
        anaconda_sublime.erase_lint_marks(view)
        return

    settings = _get_settings(view)

    data = {
        'vid': view.id(),
        'code': view.substr(st3_sublime.Region(0, view.size())),
        'settings': settings,
        'filepath': view.file_name(),
        'method': 'slow_lint',
        'handler': 'anaGonda',
        'go_env': {
            'GOROOT': go.GOROOT,
            'GOPATH': go.GOPATH,
            'CGO_ENABLED': go.CGO_ENABLED
        }
    }

    callback = partial(anaconda_sublime.parse_results, **dict(code='go'))
    if hook is None:
        Worker().execute(Callback(on_success=callback), **data)
    else:
        Worker().execute(Callback(partial(hook, callback)), **data)
Exemplo n.º 8
0
 def run(self) -> None:
     try:
         view = self.window.active_view()
         self.view = view
         data = {
             'vid':
             view.id(),
             'file_path':
             view.file_name(),
             'parse_comments':
             get_settings(view, 'anaconda_go_motion_parse_comments', False),
             'go_env': {
                 'GOROOT': go.GOROOT,
                 'GOPATH': go.GOPATH,
                 'CGO_ENABLED': go.CGO_ENABLED
             },
             'method':
             self.method,
             'handler':
             'anaGonda'
         }
         Worker().execute(
             Callback(on_success=ExplorerPanel(view).run,
                      on_failure=self._on_failure,
                      on_timeout=self._on_timeout), **data)
     except Exception as err:
         print('anaconda_go: {}'.format(self.method.replace('_', ' ')))
         print(err)
Exemplo n.º 9
0
    def _run(self) -> None:

        try:
            if get_settings(
                self.window.active_view(),
                    'anaconda_go_packages_cache_persistence', False):
                cache.load_package_cache()

            self.env = os.environ.copy()
            self.env.update({'GOROOT': go.GOROOT, 'GOPATH': go.GOPATH})
            gocmd = os.path.join(go.GOROOT, 'bin', 'go')
            golist = create_subprocess(
                shlex.split(gocmd + ' list -json all', posix=os.name != 'nt'),
                stdout=PIPE, stdin=PIPE, env=self.env
            )
            msg = 'Getting list of golang packages from the system...\n'
            self.print_to_panel(msg)
            out, err = golist.communicate()
            if err is not None and len(err) > 0:
                self.print_to_panel(err.decode('utf8'))
                self.pbar.terminate(status=self.pbar.Status.FAILURE)
                return

            self.process(out.decode('utf8'))
        except:
            print(traceback.print_exc())
Exemplo n.º 10
0
    def _run(self) -> None:

        try:
            if get_settings(self.window.active_view(),
                            'anaconda_go_packages_cache_persistence', False):
                cache.load_package_cache()

            self.env = os.environ.copy()
            self.env.update({'GOROOT': go.GOROOT, 'GOPATH': go.GOPATH})
            gocmd = os.path.join(go.GOROOT, 'bin', 'go')
            golist = create_subprocess(shlex.split(gocmd + ' list -json all',
                                                   posix=os.name != 'nt'),
                                       stdout=PIPE,
                                       stdin=PIPE,
                                       env=self.env)
            msg = 'Getting list of golang packages from the system...\n'
            self.print_to_panel(msg)
            out, err = golist.communicate()
            if err is not None and len(err) > 0:
                self.print_to_panel(err.decode('utf8'))
                self.pbar.terminate(status=self.pbar.Status.FAILURE)
                return

            self.process(out.decode('utf8'))
        except:
            print(traceback.print_exc())
Exemplo n.º 11
0
 def run(self) -> None:
     try:
         view = self.window.active_view()
         self.view = view
         data = {
             'vid': view.id(),
             'file_path': view.file_name(),
             'offset': view.sel()[0].begin(),
             'parse_comments': get_settings(
                 view, 'anaconda_go_motion_parse_comments', False
             ),
             'go_env': {
                 'GOROOT': go.GOROOT,
                 'GOPATH': go.GOPATH,
                 'CGO_ENABLED': go.CGO_ENABLED
             },
             'method': 'enclosing',
             'handler': 'anaGonda'
         }
         Worker().execute(
             Callback(
                 on_success=self._on_success,
                 on_failure=self._on_failure,
                 on_timeout=self._on_timeout
             ),
             **data
         )
     except Exception as err:
         print('anaconda_go: enclosing function error')
         print(err)
Exemplo n.º 12
0
    def run(self, edit: sublime.Edit) -> None:
        try:
            view = self.view
            scope = get_settings(view, 'anaconda_go_guru_scope')
            row, col = view.rowcol(view.sel()[0].begin())
            offset = view.text_point(row, col)
            code = view.substr(sublime.Region(0, view.size()))

            data = {
                'vid': view.id(),
                'scope': scope if scope is not None else get_scope(view, go.GOPATH),  # noqa
                'path': view.file_name(),
                'offset': offset,
                'modified_buffer': self._modified_buffer(view, code),
                'go_env': {
                    'GOROOT': go.GOROOT,
                    'GOPATH': go.GOPATH,
                    'CGO_ENABLED': go.CGO_ENABLED
                },
                'method': 'callstack',
                'handler': 'anaGonda'
            }
            Worker().execute(
                Callback(
                    on_success=self._on_success,
                    on_failure=self._on_failure,
                    on_timeout=self._on_timeout
                ),
                **data
            )
        except:
            print('anaconda_go: callers error')
            print(traceback.print_exc())
Exemplo n.º 13
0
    def run(self) -> None:
        try:
            view = self.window.active_view()
            self.view = view
            scope = get_settings(view, 'anaconda_go_guru_scope')
            row, col = view.rowcol(view.sel()[0].begin())
            offset = view.text_point(row, col)
            code = view.substr(sublime.Region(0, view.size()))

            data = {
                'vid': view.id(),
                'scope': scope if scope is not None else get_scope(view, go.GOPATH),  # noqa
                'path': view.file_name(),
                'offset': offset,
                'modified_buffer': self._modified_buffer(view, code),
                'go_env': {
                    'GOROOT': go.GOROOT,
                    'GOPATH': go.GOPATH,
                    'CGO_ENABLED': go.CGO_ENABLED
                },
                'method': 'implements',
                'handler': 'anaGonda'
            }
            Worker().execute(
                Callback(
                    on_success=self._on_success,
                    on_failure=self._on_failure,
                    on_timeout=self._on_timeout
                ), **data
            )
        except:
            print('anaconda_go: implements error')
            print(traceback.print_exc())
Exemplo n.º 14
0
 def run(self) -> None:
     try:
         view = self.window.active_view()
         self.view = view
         scope = get_settings(view, 'anaconda_go_guru_scope')
         data = {
             'vid': view.id(),
             'scope': scope if scope is not None else get_scope(view, go.GOPATH),  # noqa
             'code': view.substr(sublime.Region(0, view.size())),
             'path': view.file_name(),
             'buf': self.modified_buffer(view),
             'go_env': {
                 'GOROOT': go.GOROOT,
                 'GOPATH': go.GOPATH,
                 'CGO_ENABLED': go.CGO_ENABLED
             },
             'method': 'get_package_decls',
             'handler': 'anaGonda'
         }
         Worker().execute(
             Callback(
                 on_success=ExplorerPanel(view).run,
                 on_failure=self._on_failure,
                 on_timeout=self._on_timeout
             ),
             **data
         )
     except Exception as err:
         print('anaconda_go: {}'.format(self.method.replace('_', ' ')))
         print(err)
Exemplo n.º 15
0
 def run(self) -> None:
     try:
         view = self.window.active_view()
         self.view = view
         scope = get_settings(view, 'anaconda_go_guru_scope')
         data = {
             'vid': view.id(),
             'scope': scope if scope is not None else get_scope(
                 view, go.GOPATH),  # noqa
             'code': view.substr(sublime.Region(0, view.size())),
             'path': view.file_name(),
             'buf': self.modified_buffer(view),
             'go_env': {
                 'GOROOT': go.GOROOT,
                 'GOPATH': go.GOPATH,
                 'CGO_ENABLED': go.CGO_ENABLED
             },
             'method': 'get_package_decls',
             'handler': 'anaGonda'
         }
         Worker().execute(
             Callback(on_success=ExplorerPanel(view).run,
                      on_failure=self._on_failure,
                      on_timeout=self._on_timeout), **data)
     except Exception as err:
         print('anaconda_go: {}'.format(self.method.replace('_', ' ')))
         print(err)
Exemplo n.º 16
0
    def get_formatter_cmd(self, name, path):
        formatter = self.get_binary(name)
        if not formatter:
            raise RuntimeError('{} not found...'.format(name))

        args = get_settings(self.view, 'anaconda_go_{}_args'.format(name), [])
        args = [formatter] + args + [path]

        return args
Exemplo n.º 17
0
    def get_formatter_cmd(self, name, path):
        formatter = self.get_binary(name)
        if not formatter:
            raise RuntimeError('{} not found...'.format(name))

        args = get_settings(self.view, 'anaconda_go_{}_args'.format(name), [])
        args = [formatter] + args + [path]

        return args
Exemplo n.º 18
0
    def _detect_in_configuration(self) -> bool:
        """Detect and validate Go parameters in configuration
        """

        view = active_view()

        goroot = get_settings(view, 'anaconda_go_GOROOT', '')
        gopath = get_settings(view, 'anaconda_go_GOPATH', '')
        gobin = get_settings(view, 'anaconda_go_GOBIN', '')
        if goroot and gopath:
            gobin = 'go' if os.name != 'nt' else 'go.exe'
            if os.path.exists(os.path.join(goroot, 'bin', gobin)):
                self.GOROOT = goroot
                self.GOPATH = gopath
                self.GOBIN = gobin
                self.CGO_ENABLED = "1"
                return True

        return False
Exemplo n.º 19
0
    def run(self, package: bool = False, callstack: bool = False) -> None:
        if package is True:
            self.run_for_packages()
            return

        try:
            view = self.window.active_view()
            self.view = view
            row, col = view.rowcol(view.sel()[0].begin())
            code = view.substr(sublime.Region(0, view.size()))
            data = {
                'vid':
                view.id(),
                'path':
                view.file_name(),
                'expr':
                get_symbol(code, row, col),
                'private':
                get_settings(view, 'anaconda_go_doc_private_symbols', False),
                'force':
                get_settings(view, 'anaconda_go_force_go_doc_usage', False),
                'offset':
                view.text_point(*view.rowcol(view.sel()[0].begin())),
                'buf':
                self.modified_buffer(view),
                'go_env': {
                    'GOROOT': go.GOROOT,
                    'GOPATH': go.GOPATH,
                    'CGO_ENABLED': go.CGO_ENABLED,
                    'GO_VERSION': self.go_version
                },
                'method':
                'doc',
                'handler':
                'anaGonda'
            }
            Worker().execute(
                Callback(on_success=self.on_success,
                         on_failure=self._on_failure,
                         on_timeout=self._on_timeout), **data)
        except Exception as err:
            print('anaconda_go: go doc error')
            print(traceback.print_exc())
Exemplo n.º 20
0
    def _detect_in_configuration(self) -> bool:
        """Detect and validate Go parameters in configuration
        """

        view = active_view()

        goroot = get_settings(view, 'anaconda_go_GOROOT', '')
        gopath = get_settings(view, 'anaconda_go_GOPATH', '')
        gobin = get_settings(view, 'anaconda_go_GOBIN', '')
        if goroot and gopath:
            gobin = 'go' if os.name != 'nt' else 'go.exe'
            if os.path.exists(os.path.join(goroot, 'bin', gobin)):
                self.GOROOT = goroot
                self.GOPATH = gopath
                self.GOBIN = gobin
                self.CGO_ENABLED = "1"
                return True

        return False
Exemplo n.º 21
0
    def run(self, edit, path=None):

        if path is None:
            path = self.view.file_name()
        code = self.view.substr(sublime.Region(0, self.view.size()))
        try:
            self.view.set_read_only(True)
            use_goimports = get_settings(self.view, 'anaconda_go_format_with_goimports', True)
            if use_goimports:
                self.format('goimports', code, path, edit)

            self.view.set_read_only(True)
            use_gofmt = get_settings(self.view, 'anaconda_go_format_with_gofmt', False)
            if use_gofmt:
                self.format('gofmt', code, path, edit)
        except Exception:
            self.view.set_read_only(False)
            raise
        finally:
            self.view.set_read_only(False)
Exemplo n.º 22
0
def run_linter(view=None, hook=None):
    """Wrapper to run the right linter
    """

    if not go.ANAGONDA_PRESENT:
        return

    if get_settings(view, 'anaconda_go_fast_linters_only', False):
        fast_linters(view, hook)
    else:
        all_linters(view, hook)
Exemplo n.º 23
0
    def on_pre_save(self, view: sublime_plugin.sublime.View) -> None:
        """Called just before the file is going to be saved
        """

        if time.time() - self._last_save < 2:
            return

        auto_format = get_settings(view, 'anaconda_go_auto_format', False)
        if auto_format and is_code(view, lang='go'):
            view.run_command('anaconda_go_format')

        self._last_save = time.time()
Exemplo n.º 24
0
    def run(self, package: bool=False, callstack: bool=False) -> None:
        if package is True:
            self.run_for_packages()
            return

        try:
            view = self.window.active_view()
            self.view = view
            row, col = view.rowcol(view.sel()[0].begin())
            code = view.substr(sublime.Region(0, view.size()))
            data = {
                'vid': view.id(),
                'path': view.file_name(),
                'expr': get_symbol(code, row, col),
                'private': get_settings(
                    view, 'anaconda_go_doc_private_symbols', False),
                'force': get_settings(
                    view, 'anaconda_go_force_go_doc_usage', False),
                'offset': view.text_point(*view.rowcol(view.sel()[0].begin())),
                'buf': self.modified_buffer(view),
                'go_env': {
                    'GOROOT': go.GOROOT,
                    'GOPATH': go.GOPATH,
                    'CGO_ENABLED': go.CGO_ENABLED,
                    'GO_VERSION': self.go_version
                },
                'method': 'doc',
                'handler': 'anaGonda'
            }
            Worker().execute(
                Callback(
                    on_success=self.on_success,
                    on_failure=self._on_failure,
                    on_timeout=self._on_timeout
                ),
                **data
            )
        except Exception as err:
            print('anaconda_go: go doc error')
            print(traceback.print_exc())
Exemplo n.º 25
0
    def run(self, edit, path=None):

        if path is None:
            path = self.view.file_name()
        code = self.view.substr(sublime.Region(0, self.view.size()))
        try:
            self.view.set_read_only(True)
            use_goimports = get_settings(self.view,
                                         'anaconda_go_format_with_goimports',
                                         True)
            if use_goimports:
                self.format('goimports', code, path, edit)

            self.view.set_read_only(True)
            use_gofmt = get_settings(self.view,
                                     'anaconda_go_format_with_gofmt', False)
            if use_gofmt:
                self.format('gofmt', code, path, edit)
        except Exception:
            self.view.set_read_only(False)
            raise
        finally:
            self.view.set_read_only(False)
Exemplo n.º 26
0
    def update_buffer(self, edit):
        """Update and reload the buffer
        """

        results = self.data.get('result')
        view = get_window_view(self.data['vid'])
        if results is not None and results != '' and self.code != results:
            region = sublime.Region(0, view.size())
            view.replace(edit, region, results)
            if get_settings(view, 'anaconda_go_auto_format'):
                view.run_command('save')
                # sublime.set_timeout(lambda: view.run_command('save'), 0)

        self.data = None
        self.code = None
Exemplo n.º 27
0
def _get_settings(view):
    return {
        'linters': get_settings(view, 'anaconda_go_linters', []),
        'lint_test': get_settings(
            view, 'anaconda_go_lint_test', False),
        'exclude_regexps': get_settings(
            view, 'anaconda_go_exclude_regexps', []),
        'max_line_length': get_settings(
            view, 'anaconda_go_max_line_length', 120),
        'gocyclo_threshold': get_settings(
            view, 'anaconda_go_gocyclo_threshold', 10),
        'golint_min_confidence': get_settings(
            view, 'anaconda_go_golint_min_confidence', 0.80),
        'goconst_min_occurrences': get_settings(
            view, 'anaconda_go_goconst_min_occurrences', 3),
        'min_const_length': get_settings(
            view, 'anaconda_go_min_const_length', 3),
        'dupl_threshold': get_settings(
            view, 'anaconda_go_dupl_threshold', 50),
        'path': os.path.dirname(view.file_name())
    }
    def on_pre_save(self, view: sublime_plugin.sublime.View) -> None:
        """Called just before the file is going to be saved
        """

        if time.time() - self._last_save < 2:
            return

        auto_format = get_settings(view, 'anaconda_go_auto_format', False)
        if auto_format and is_code(view, lang='go'):
            filename = os.path.join(tempfile.gettempdir(), view.file_name())
            buf = view.substr(sublime.Region(0, view.size()))
            self._save_tmp_buffer(buf, filename)
            view.run_command('anaconda_go_format_sync',
                             args={"path": filename})
            self._remove_tmp_buffer(filename)

        AnacondaGoAutoFormatEventListener._last_save = time.time()
Exemplo n.º 29
0
    def on_pre_save(self, view: sublime_plugin.sublime.View) -> None:
        """Called just before the file is going to be saved
        """

        if time.time() - self._last_save < 2:
            return

        auto_format = get_settings(view, 'anaconda_go_auto_format', False)
        if auto_format and is_code(view, lang='go'):
            filename = os.path.join(tempfile.gettempdir(), view.file_name())
            buf = view.substr(sublime.Region(0, view.size()))
            self._save_tmp_buffer(buf, filename)
            view.run_command(
                'anaconda_go_format_sync', args={"path": filename}
            )
            self._remove_tmp_buffer(filename)

        AnacondaGoAutoFormatEventListener._last_save = time.time()
Exemplo n.º 30
0
    def _on_select(self, index: int) -> None:
        """Called when a package is selected from the quick panel
        """

        if index == -1:
            return

        package = self._packages[index]
        try:
            view = self.window.active_view()
            self.view = view
            data = {
                'vid':
                view.id(),
                'path':
                view.file_name(),
                'expr':
                package,
                'private':
                get_settings(view, 'anaconda_go_doc_private_symbols', False),
                'force':
                True,
                'offset':
                0,
                'buf':
                '',
                'go_env': {
                    'GOROOT': go.GOROOT,
                    'GOPATH': go.GOPATH,
                    'CGO_ENABLED': go.CGO_ENABLED,
                    'GO_VERSION': self.go_version
                },
                'method':
                'doc',
                'handler':
                'anaGonda'
            }
            Worker().execute(
                Callback(on_success=self.on_success,
                         on_failure=self._on_failure,
                         on_timeout=self._on_timeout), **data)
        except Exception as err:
            print('anaconda_go: go doc error')
            print(traceback.print_exc())
Exemplo n.º 31
0
 def run(self, standalone=False) -> None:
     panel = self.window.create_output_panel('browse')
     panel.settings().set('wrap_width', 120)
     panel.settings().set("scroll_past_end", False)
     panel.assign_syntax('Packages/Text/Plain text.tmLanguage')
     self.output = panel
     self.window.create_output_panel('browse')
     if standalone or get_settings(
             self.window.active_view(), 'anaconda_go_verbose', True):
         self.window.run_command('show_panel', {'panel': 'output.browse'})
     sublime.set_timeout_async(lambda: self._run(), 0)
     messages = {
         'start': 'Building packages navigation cache...',
         'end': 'done!',
         'fail': 'The package navigation cache could not be build!',
         'timeout': ''
     }
     self.pbar = ProgressBar(messages)
     self.pbar.start()
Exemplo n.º 32
0
 def run(self, standalone=False) -> None:
     panel = self.window.create_output_panel('browse')
     panel.settings().set('wrap_width', 120)
     panel.settings().set("scroll_past_end", False)
     panel.assign_syntax('Packages/Text/Plain text.tmLanguage')
     self.output = panel
     self.window.create_output_panel('browse')
     if standalone or get_settings(self.window.active_view(),
                                   'anaconda_go_verbose', True):
         self.window.run_command('show_panel', {'panel': 'output.browse'})
     sublime.set_timeout_async(lambda: self._run(), 0)
     messages = {
         'start': 'Building packages navigation cache...',
         'end': 'done!',
         'fail': 'The package navigation cache could not be build!',
         'timeout': ''
     }
     self.pbar = ProgressBar(messages)
     self.pbar.start()
Exemplo n.º 33
0
    def _on_success(self, data):
        """Process result and normalize it for anaconda's goto
        """

        if get_settings(self.view, 'anaconda_go_print_callstack', True):
            # print the callstack in a doc panel
            panel = panels.DocPanel(self.view)
            panel.show()
            panel.print(self._pretiffy(data))

        callstack = []
        for result in data['result'].get('callers', []):
            f, l, c = result['pos'].split(':')
            callstack.append({
                'title': result['caller'],
                'location': 'File: {} Line: {} Column: {}'.format(f, l, c),
                'position': result['pos']
            })

        ExplorerPanel(self.view, callstack).show([])
Exemplo n.º 34
0
    def _on_select(self, index: int) -> None:
        """Called when a package is selected from the quick panel
        """

        if index == -1:
            return

        package = self._packages[index]
        try:
            view = self.window.active_view()
            self.view = view
            data = {
                'vid': view.id(),
                'path': view.file_name(),
                'expr': package,
                'private': get_settings(
                    view, 'anaconda_go_doc_private_symbols', False),
                'force': True,
                'offset': 0,
                'buf': '',
                'go_env': {
                    'GOROOT': go.GOROOT,
                    'GOPATH': go.GOPATH,
                    'CGO_ENABLED': go.CGO_ENABLED,
                    'GO_VERSION': self.go_version
                },
                'method': 'doc',
                'handler': 'anaGonda'
            }
            Worker().execute(
                Callback(
                    on_success=self.on_success,
                    on_failure=self._on_failure,
                    on_timeout=self._on_timeout
                ),
                **data
            )
        except Exception as err:
            print('anaconda_go: go doc error')
            print(traceback.print_exc())
Exemplo n.º 35
0
    def run(self) -> None:
        try:
            view = self.window.active_view()
            self.view = view
            row, col = view.rowcol(view.sel()[0].begin())
            offset = view.text_point(row, col)

            code = view.substr(sublime.Region(0, view.size()))
            data = {
                'vid': view.id(),
                'code': code,
                'path': view.file_name(),
                'settings': {
                    'offset': offset,
                    'expr': get_symbol(code, row, col),
                    'modified_buffer': self._modified_buffer(view, code),
                    'guru_usage': get_settings(
                        view, 'anaconda_go_guru_usage', 'always'
                    )
                },
                'go_env': {
                    'GOROOT': go.GOROOT,
                    'GOPATH': go.GOPATH,
                    'CGO_ENABLED': go.CGO_ENABLED
                },
                'method': 'goto',
                'handler': 'anaGonda'
            }
            Worker().execute(
                Callback(
                    on_success=self._on_success,
                    on_failure=self._on_failure,
                    on_timeout=self._on_timeout
                ),
                **data
            )
        except Exception as err:
            print('anaconda_go: goto error')
            print(traceback.print_exc())
Exemplo n.º 36
0
    def run(self) -> None:
        try:
            view = self.window.active_view()
            self.view = view
            row, col = view.rowcol(view.sel()[0].begin())
            offset = view.text_point(row, col)

            code = view.substr(sublime.Region(0, view.size()))
            data = {
                'vid': view.id(),
                'code': code,
                'path': view.file_name(),
                'settings': {
                    'offset':
                    offset,
                    'expr':
                    get_symbol(code, row, col),
                    'modified_buffer':
                    self._modified_buffer(view, code),
                    'guru_usage':
                    get_settings(view, 'anaconda_go_guru_usage', 'always')
                },
                'go_env': {
                    'GOROOT': go.GOROOT,
                    'GOPATH': go.GOPATH,
                    'CGO_ENABLED': go.CGO_ENABLED
                },
                'method': 'goto',
                'handler': 'anaGonda'
            }
            Worker().execute(
                Callback(on_success=self._on_success,
                         on_failure=self._on_failure,
                         on_timeout=self._on_timeout), **data)
        except Exception as err:
            print('anaconda_go: goto error')
            print(traceback.print_exc())
Exemplo n.º 37
0
    def process(self, data: str) -> None:
        """Process the output from go list (that is not valid JSON btw)
        """

        gurucmd = os.path.join(go.GOPATH, 'bin', 'guru')
        json_data = json.loads('[' + data.replace('}\n{', '},\n{') + ']')
        for package in json_data:
            self.print_to_panel('{} -> '.format(package['ImportPath']))
            if cache.package_in_cache(package):
                self.print_to_panel('already in cache, nothing to do\n')
                continue

            try:
                fname = os.path.join(package['Dir'], package['GoFiles'][0])
                args = []
                kwargs = {}
                if os.name == 'posix':
                    args = 'grep -b "package {}" {}'.format(
                        package['Name'], fname
                    )
                else:
                    startupinfo = subprocess.STARTUPINFO()
                    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
                    kwargs['startupinfo'] = startupinfo
                    args = shlex.split(
                        'findstr /O /R /C:"package {}" {}'.format(
                            package['Name'], fname
                        ), posix=False
                    )

                grep = check_output(args, shell=True, **kwargs)
            except Exception as error:
                self.print_to_panel(str(error))
                continue

            try:
                offset = int(grep.decode().split(':')[0]) + len('package ') + 1
            except Exception as e:
                print('while parsing grep/findstr output for {}: {}\t{}'.format(  # noqa
                    ' '.join(args), e, grep.decode())
                )
                continue
            args = shlex.split('{} -json -scope {} describe {}:#{}'.format(
                gurucmd, package['ImportPath'], fname, offset)
            )
            guru = create_subprocess(
                args, stdout=PIPE, stderr=PIPE, env=self.env)
            out, err = guru.communicate()
            if err is not None and len(err) > 0:
                self.print_to_panel(err.decode('utf8'))
                continue

            self.print_to_panel('Done\n')
            package['Guru'] = json.loads(out.decode('utf8'))
            cache.append(package)

        self.pbar.terminate()
        if get_settings(
                self.window.active_view(),
                'anaconda_go_packages_cache_persistence', False):
            cache.persist_package_cache()

        self.print_to_panel(
            '\nPackages browse cache loaded, set the option '
            '"anaconda_go_verbose" as "false" in the configuration '
            'if you do not want to see this panel everytime that you '
            'start your Sublime Text 3\n\n'
            'Note: you can generate this cache at any time using the '
            'Command Palette'
        )
Exemplo n.º 38
0
    def process(self, data: str) -> None:
        """Process the output from go list (that is not valid JSON btw)
        """

        gurucmd = os.path.join(go.GOPATH, 'bin', 'guru')
        json_data = json.loads('[' + data.replace('}\n{', '},\n{') + ']')
        for package in json_data:
            self.print_to_panel('{} -> '.format(package['ImportPath']))
            if cache.package_in_cache(package):
                self.print_to_panel('already in cache, nothing to do\n')
                continue

            try:
                fname = os.path.join(package['Dir'], package['GoFiles'][0])
                args = []
                kwargs = {}
                if os.name == 'posix':
                    args = 'grep -b "package {}" {}'.format(
                        package['Name'], fname)
                else:
                    startupinfo = subprocess.STARTUPINFO()
                    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
                    kwargs['startupinfo'] = startupinfo
                    args = shlex.split(
                        'findstr /O /R /C:"package {}" {}'.format(
                            package['Name'], fname),
                        posix=False)

                grep = check_output(args, shell=True, **kwargs)
            except Exception as error:
                self.print_to_panel(str(error))
                continue

            try:
                offset = int(grep.decode().split(':')[0]) + len('package ') + 1
            except Exception as e:
                print('while parsing grep/findstr output for {}: {}\t{}'.
                      format(  # noqa
                          ' '.join(args), e, grep.decode()))
                continue
            args = shlex.split('{} -json -scope {} describe {}:#{}'.format(
                gurucmd, package['ImportPath'], fname, offset))
            guru = create_subprocess(args,
                                     stdout=PIPE,
                                     stderr=PIPE,
                                     env=self.env)
            out, err = guru.communicate()
            if err is not None and len(err) > 0:
                self.print_to_panel(err.decode('utf8'))
                continue

            self.print_to_panel('Done\n')
            package['Guru'] = json.loads(out.decode('utf8'))
            cache.append(package)

        self.pbar.terminate()
        if get_settings(self.window.active_view(),
                        'anaconda_go_packages_cache_persistence', False):
            cache.persist_package_cache()

        self.print_to_panel(
            '\nPackages browse cache loaded, set the option '
            '"anaconda_go_verbose" as "false" in the configuration '
            'if you do not want to see this panel everytime that you '
            'start your Sublime Text 3\n\n'
            'Note: you can generate this cache at any time using the '
            'Command Palette')