Ejemplo n.º 1
0
    def on_query_completions(self, view, prefix, locations):
        if not GoBuffers.is_go_source(view): return
        if not golangconfig.setting_value("autocomplete")[0]: return

        gocodeFlag = ["-f=json", "-sock=none"] if golangconfig.setting_value(
            "gocode_client_mode")[0] else ["-f=json"]
        suggestionsJsonStr, stderr, rc = ToolRunner.run(
            view,
            "gocode",
            gocodeFlag + ["autocomplete",
                          view.file_name(),
                          str(locations[0])],
            stdin=Buffers.buffer_text(view))

        suggestionsJson = json.loads(suggestionsJsonStr)

        Logger.log("DEBUG: gocode output: " + suggestionsJsonStr)

        if rc != 0:
            Logger.status("no completions found: " + str(e))
            return []

        if len(suggestionsJson) > 0:
            return ([
                GotoolsSuggestions.build_suggestion(j)
                for j in suggestionsJson[1]
            ], sublime.INHIBIT_WORD_COMPLETIONS)
        else:
            return []
    def run(self):
        """
        Runs the "golang_build_terminal" command - invoked by Sublime Text via
        the command palette or sublime.Window.run_command()
        """

        working_dir = _determine_working_dir(self.window)
        if working_dir is None:
            return

        relevant_sources = set([
            'project file',
            'project file (os-specific)',
            'golang.sublime-settings',
            'golang.sublime-settings (os-specific)'
        ])

        env_overrides = {}
        for var_name in GO_ENV_VARS:
            value, source = golangconfig.setting_value(var_name, window=self.window)
            # Only set overrides that are not coming from the user's shell
            if source in relevant_sources:
                env_overrides[var_name] = value

        # Get the PATH from the shell environment and then prepend any custom
        # value so the user's terminal searches all locations
        value, source = golangconfig.setting_value('PATH', window=self.window)
        if source in relevant_sources:
            shell, env = shellenv.get_env()
            env_overrides['PATH'] = value + os.pathsep + env.get('PATH', '')

        newterm.launch_terminal(working_dir, env=env_overrides)
Ejemplo n.º 3
0
    def run(self):
        """
        Runs the "golang_build_terminal" command - invoked by Sublime Text via
        the command palette or sublime.Window.run_command()
        """

        working_dir = _determine_working_dir(self.window)
        if working_dir is None:
            return

        relevant_sources = set([
            'project file', 'project file (os-specific)',
            'golang.sublime-settings', 'golang.sublime-settings (os-specific)'
        ])

        env_overrides = {}
        for var_name in GO_ENV_VARS:
            value, source = golangconfig.setting_value(var_name,
                                                       window=self.window)
            # Only set overrides that are not coming from the user's shell
            if source in relevant_sources:
                env_overrides[var_name] = value

        # Get the PATH from the shell environment and then prepend any custom
        # value so the user's terminal searches all locations
        value, source = golangconfig.setting_value('PATH', window=self.window)
        if source in relevant_sources:
            shell, env = shellenv.get_env()
            env_overrides['PATH'] = value + os.pathsep + env.get('PATH', '')

        newterm.launch_terminal(working_dir, env=env_overrides)
Ejemplo n.º 4
0
    def run(self, edit, command=None):
        if not command:
            Logger.log("command is required")
            return

        filename, row, col, offset, offset_end = Buffers.location_at_cursor(
            self.view)
        if command == "freevars":
            pos = filename + ":#" + str(offset) + "," + "#" + str(offset_end)
        else:
            pos = filename + ":#" + str(offset)

        # Build up a package scope contaning all packages the user might have
        # configured.
        package_scope = []
        project_package = golangconfig.setting_value("project_package",
                                                     view=self.view)[0]
        if project_package:
            for p in golangconfig.setting_value("build_packages",
                                                view=self.view)[0]:
                package_scope.append(os.path.join(project_package, p))

        sublime.active_window().run_command("hide_panel",
                                            {"panel": "output.gotools_guru"})
        self.do_plain_guru(command, pos, package_scope)
Ejemplo n.º 5
0
  def run(self, edit):
    command = ""
    args = []
    if golangconfig.setting_value("format_backend")[0] == "gofmt":
      command = "gofmt"
      args = ["-e", "-s"]
    elif golangconfig.setting_value("format_backend")[0] in ["goimports", "both"] :
      command = "goimports"
      args = ["-e", "-srcdir=%s" % os.path.dirname(self.view.file_name())]

    stdout, stderr, rc = ToolRunner.run(self.view, command, args, stdin=Buffers.buffer_text(self.view))

    # Clear previous syntax error marks
    self.view.erase_regions("mark")

    if rc == 2:
      # Show syntax errors and bail
      self.show_syntax_errors(stderr)
      Logger.err = True
      return

    if rc != 0:
      # Ermmm...
      Logger.log("unknown gofmt error (" + str(rc) + ") stderr:\n" + stderr)
      return

    if golangconfig.setting_value("format_backend")[0] == "both":
      command = "gofmt"
      args = ["-e", "-s"]
      stdout, stderr, rc = ToolRunner.run(self.view, command, args, stdin=stdout.encode('utf-8'))

    # Clear previous syntax error marks
    self.view.erase_regions("mark")

    if rc == 2:
      # Show syntax errors and bail
      self.show_syntax_errors(stderr)
      Logger.err = True
      return

    if rc != 0:
      # Ermmm...
      Logger.log("unknown gofmt error (" + str(rc) + ") stderr:\n" + stderr)
      return

    # Everything's good, hide the syntax error panel
    self.view.window().run_command("hide_panel", {"panel": "output.gotools_syntax_errors"})

    # Remember the viewport position. When replacing the buffer, Sublime likes to jitter the
    # viewport around for some reason.
    self.prev_viewport_pos = self.view.viewport_position()

    # Replace the buffer with gofmt output.
    self.view.replace(edit, sublime.Region(0, self.view.size()), stdout)

    # Restore the viewport on the main GUI thread (which is the only way this works).
    sublime.set_timeout(self.restore_viewport, 0)

    Logger.err = False
Ejemplo n.º 6
0
    def run(self, edit):
        command = ""
        args = []
        if golangconfig.setting_value('format_backend')[0] == "gofmt":
            command = "gofmt"
            args = ["-e", "-s"]
        elif golangconfig.setting_value('format_backend')[0] in [
                "goimports", "both"
        ]:
            command = "goimports"
            args = ["-e"]

        stdout, stderr, rc = ToolRunner.run(self.view,
                                            command,
                                            args,
                                            stdin=Buffers.buffer_text(
                                                self.view))

        # Clear previous syntax error marks
        self.view.erase_regions("mark")

        if rc == 2:
            # Show syntax errors and bail
            self.show_syntax_errors(stderr)
            return

        if rc != 0:
            # Ermmm...
            Logger.log("unknown gofmt error (" + str(rc) + ") stderr:\n" +
                       stderr)
            self.phantom_set.update([])
            return

        if golangconfig.setting_value('format_backend')[0] == "both":
            command = "gofmt"
            args = ["-e", "-s"]
            stdout, stderr, rc = ToolRunner.run(self.view,
                                                command,
                                                args,
                                                stdin=stdout.encode('utf-8'))

        # Clear previous syntax error marks
        self.view.erase_regions("mark")

        if rc == 2:
            # Show syntax errors and bail
            self.show_syntax_errors(stderr)
            return

        if rc != 0:
            # Ermmm...
            Logger.log("unknown gofmt error (" + str(rc) + ") stderr:\n" +
                       stderr)
            self.phantom_set.update([])
            return

        # Everything's good, hide the syntax error panel
        self.phantom_set.update([])
Ejemplo n.º 7
0
    def run(self, edit, command=None):
        if not command:
            Logger.log("command is required")
            return

        filename, row, col, offset, offset_end = Buffers.location_at_cursor(
            self.view)
        pos = filename + ":#" + str(offset)

        # Build up a package scope contaning all packages the user might have
        # configured.
        # TODO: put into a utility
        package_scope = []
        project_pkg = golangconfig.setting_value('project_package')[0] or ""
        for p in golangconfig.setting_value('build_packages'):
            if p:
                package_scope.append(os.path.join(project_pkg, p))
        for p in golangconfig.setting_value('test_packages'):
            if p:
                package_scope.append(os.path.join(project_pkg, p))
        for p in golangconfig.setting_value('tagged_test_packages'):
            if p:
                package_scope.append(os.path.join(project_pkg, p))

        sublime.active_window().run_command("hide_panel",
                                            {"panel": "output.gotools_oracle"})

        if command == "callees":
            sublime.set_timeout_async(
                lambda: self.do_plain_oracle("callees", pos, package_scope), 0)
        if command == "callers":
            sublime.set_timeout_async(
                lambda: self.do_plain_oracle("callers", pos, package_scope), 0)
        if command == "callstack":
            sublime.set_timeout_async(
                lambda: self.do_plain_oracle("callstack", pos, package_scope),
                0)
        if command == "describe":
            sublime.set_timeout_async(
                lambda: self.do_plain_oracle("describe", pos, package_scope),
                0)
        if command == "freevars":
            pos = filename + ":#" + str(offset) + "," + "#" + str(offset_end)
            sublime.set_timeout_async(
                lambda: self.do_plain_oracle("freevars", pos, package_scope),
                0)
        if command == "implements":
            sublime.set_timeout_async(
                lambda: self.do_plain_oracle("implements", pos, package_scope),
                0)
        if command == "peers":
            sublime.set_timeout_async(
                lambda: self.do_plain_oracle("peers", pos, package_scope), 0)
        if command == "referrers":
            sublime.set_timeout_async(
                lambda: self.do_plain_oracle("referrers", pos, package_scope),
                0)
Ejemplo n.º 8
0
  def run(self, edit):
    command = ""
    args = []
    if golangconfig.setting_value("format_backend")[0] == "gofmt":
      command = "gofmt"
      args = ["-e", "-s"]
    elif golangconfig.setting_value("format_backend")[0] in ["goimports", "both"] :
      command = "goimports"
      args = ["-e"]

    stdout, stderr, rc = ToolRunner.run(self.view, command, args, stdin=Buffers.buffer_text(self.view))

    # Clear previous syntax error marks
    self.view.erase_regions("mark")

    if rc == 2:
      # Show syntax errors and bail
      self.show_syntax_errors(stderr)
      return

    if rc != 0:
      # Ermmm...
      Logger.log("unknown gofmt error (" + str(rc) + ") stderr:\n" + stderr)
      return

    if golangconfig.setting_value("format_backend")[0] == "both":
      command = "gofmt"
      args = ["-e", "-s"]
      stdout, stderr, rc = ToolRunner.run(self.view, command, args, stdin=stdout.encode('utf-8'))

    # Clear previous syntax error marks
    self.view.erase_regions("mark")

    if rc == 2:
      # Show syntax errors and bail
      self.show_syntax_errors(stderr)
      return

    if rc != 0:
      # Ermmm...
      Logger.log("unknown gofmt error (" + str(rc) + ") stderr:\n" + stderr)
      return

    # Everything's good, hide the syntax error panel
    self.view.window().run_command("hide_panel", {"panel": "output.gotools_syntax_errors"})

    # Remember the viewport position. When replacing the buffer, Sublime likes to jitter the
    # viewport around for some reason.
    self.prev_viewport_pos = self.view.viewport_position()

    # Replace the buffer with gofmt output.
    self.view.replace(edit, sublime.Region(0, self.view.size()), stdout)

    # Restore the viewport on the main GUI thread (which is the only way this works).
    sublime.set_timeout(self.restore_viewport, 0)
Ejemplo n.º 9
0
 def run(self, edit):
   if golangconfig.setting_value("lint_backend")[0] == "golint":
     self.run_golint()
   elif golangconfig.setting_value("lint_backend")[0] == "govet":
     self.run_govet()
   elif golangconfig.setting_value("lint_backend")[0] == "both":
     rc = self.run_govet()
     if rc != 1:
       self.run_golint()
   else:
     sublime.error_message("Must choose a linter: govet or golint or both")
     return
Ejemplo n.º 10
0
 def run(self, edit):
     if golangconfig.setting_value("lint_backend")[0] == "golint":
         self.run_golint()
     elif golangconfig.setting_value("lint_backend")[0] == "govet":
         self.run_govet()
     elif golangconfig.setting_value("lint_backend")[0] == "both":
         rc = self.run_govet()
         if rc != 1:
             self.run_golint()
     else:
         sublime.error_message(
             "Must choose a linter: govet or golint or both")
         return
Ejemplo n.º 11
0
  def run(self, edit, event=None):
    # Find and store the current filename and byte offset at the
    # cursor or mouse event location.
    if event:
      filename, row, col, offset = Buffers.location_for_event(self.view, event)
    else:
      filename, row, col, offset, offset_end = Buffers.location_at_cursor(self.view)

    backend = golangconfig.setting_value('goto_def_backend')[0] or "godef"
    try:
      if backend == "oracle":
        file, row, col = self.get_oracle_location(filename, offset)
      elif backend == "godef":
        file, row, col = self.get_godef_location(filename, offset)
      else:
        Logger.log("Invalid godef backend '" + backend + "' (supported: godef, oracle)")
        Logger.status("Invalid godef configuration; see console log for details")
        return
    except Exception as e:
     Logger.status(str(e))
     return
    
    if not os.path.isfile(file):
      Logger.log("WARN: file indicated by godef not found: " + file)
      Logger.status("godef failed: Please enable debugging and check console log")
      return
    
    Logger.log("opening definition at " + file + ":" + str(row) + ":" + str(col))
    w = self.view.window()
    new_view = w.open_file(file + ':' + str(row) + ':' + str(col), sublime.ENCODED_POSITION)
    group, index = w.get_view_index(new_view)
    if group != -1:
        w.focus_group(group)
Ejemplo n.º 12
0
    def run(self, edit):
        command = ""
        args = []
        if golangconfig.setting_value('format_backend')[0] == "gofmt":
            command = "gofmt"
            args = ["-e", "-s"]
        elif golangconfig.setting_value('format_backend')[0] in ["goimports", "both"]:
            command = "goimports"
            args = ["-e"]

        stdout, stderr, rc = ToolRunner.run(self.view, command, args, stdin=Buffers.buffer_text(self.view))

        # Clear previous syntax error marks
        self.view.erase_regions("mark")

        if rc == 2:
            # Show syntax errors and bail
            self.show_syntax_errors(stderr)
            return

        if rc != 0:
            # Ermmm...
            Logger.log("unknown gofmt error (" + str(rc) + ") stderr:\n" + stderr)
            self.phantom_set.update([])
            return

        if golangconfig.setting_value('format_backend')[0] == "both":
            command = "gofmt"
            args = ["-e", "-s"]
            stdout, stderr, rc = ToolRunner.run(self.view, command, args, stdin=stdout.encode('utf-8'))

        # Clear previous syntax error marks
        self.view.erase_regions("mark")

        if rc == 2:
            # Show syntax errors and bail
            self.show_syntax_errors(stderr)
            return

        if rc != 0:
            # Ermmm...
            Logger.log("unknown gofmt error (" + str(rc) + ") stderr:\n" + stderr)
            self.phantom_set.update([])
            return

        # Everything's good, hide the syntax error panel
        self.phantom_set.update([])
Ejemplo n.º 13
0
    def run(self, url=None, flags=None):
        """
        Runs the "golang_build_get" command - invoked by Sublime Text via the
        command palette or sublime.Window.run_command()

        :param url:
            A unicode string of the URL to download, instead of prompting the
            user

        :param flags:
            A list of unicode strings of flags to send to the command-line go
            tool. Execute "go help" on the command line to learn about available
            flags.
        """

        if _yeild_to_running_build(self.window):
            return

        working_dir = _determine_working_dir(self.window)
        if working_dir is None:
            return

        go_bin, env = _get_config(
            'go',
            set(['GOPATH']),
            GO_ENV_VARS - set(['GOPATH']),
            view=self.window.active_view(),
            window=self.window,
        )
        if (go_bin, env) == (None, None):
            return

        if flags is None:
            flags, _ = golangconfig.setting_value(
                'get:flags',
                view=self.window.active_view(),
                window=self.window)

        def on_done(get_url):
            """
            Processes the user's input and launches the "go get" command

            :param get_url:
                A unicode string of the URL to get
            """

            args = [go_bin, 'get', '-v']
            if flags and isinstance(flags, list):
                args.extend(flags)
            args.append(get_url)
            proc = _run_process('get', self.window, args, working_dir, env)
            _set_proc(self.window, proc)

        if url is not None:
            on_done(url)
            return

        self.window.show_input_panel('go get', '', on_done, None, None)
Ejemplo n.º 14
0
    def run(self, edit, command=None):
        if not command:
            Logger.log("command is required")
            return

        filename, row, col, offset, offset_end = Buffers.location_at_cursor(
            self.view)
        if command == "freevars":
            pos = filename + ":#" + str(offset) + "," + "#" + str(offset_end)
        else:
            pos = filename + ":#" + str(offset)

        # Build up a package scope contaning all packages the user might have
        # configured.
        package_scope = []
        project_package = golangconfig.setting_value("project_package",
                                                     view=self.view)[0]
        if project_package:
            if not golangconfig.setting_value("build_packages")[0]:
                package_scope.append(project_package)
            else:
                for p in golangconfig.setting_value("build_packages",
                                                    view=self.view)[0]:
                    package_scope.append(os.path.join(project_package, p))

        # add local package to guru scope
        if golangconfig.setting_value("guru_use_current_package")[0]:
            current_file_path = os.path.realpath(
                os.path.dirname(self.view.file_name()))
            toolpath, env = golangconfig.subprocess_info('guru',
                                                         ['GOPATH', 'PATH'],
                                                         view=self.view)
            GOPATH = os.path.realpath(env["GOPATH"])
            GOPATH = os.path.join(GOPATH, "src")
            local_package = os.path.relpath(current_file_path, GOPATH)
            if sublime.platform() == 'windows':
                local_package = local_package.replace('\\', '/')
            Logger.status("GOPATH: " + GOPATH)
            Logger.status("local_package: " + local_package)
            package_scope.append(local_package)

        sublime.active_window().run_command("hide_panel",
                                            {"panel": "output.gotools_guru"})
        self.do_plain_guru(command, pos, package_scope)
Ejemplo n.º 15
0
 def test_setting_value_gopath_not_string(self):
     shell = '/bin/bash'
     env = {'GOPATH': 1}
     with GolangConfigMock(shell, env, None, None,
                           {'debug': True}) as mock_context:
         self.assertEquals(
             (None, None),
             golangconfig.setting_value('GOPATH', mock_context.view,
                                        mock_context.window))
         self.assertTrue('is not a string' in sys.stdout.getvalue())
Ejemplo n.º 16
0
    def setting_value_gopath(self, shell, env, view_settings, window_settings,
                             sublime_settings, setting, result):

        with GolangConfigMock(shell, env, view_settings, window_settings,
                              sublime_settings) as mock_context:
            self.assertEquals(
                result,
                golangconfig.setting_value(setting, mock_context.view,
                                           mock_context.window))
            self.assertEqual('', sys.stdout.getvalue())
Ejemplo n.º 17
0
    def run(self, edit, command=None):
        if not command:
            Logger.log("command is required")
            return

        filename, row, col, offset, offset_end = Buffers.location_at_cursor(self.view)
        pos = filename + ":#" + str(offset)

        # Build up a package scope contaning all packages the user might have
        # configured.
        # TODO: put into a utility
        package_scope = []
        project_pkg = golangconfig.setting_value('project_package')[0] or ""
        for p in golangconfig.setting_value('build_packages'):
            if p:
                package_scope.append(os.path.join(project_pkg, p))
        for p in golangconfig.setting_value('test_packages'):
            if p:
                package_scope.append(os.path.join(project_pkg, p))
        for p in golangconfig.setting_value('tagged_test_packages'):
            if p:
                package_scope.append(os.path.join(project_pkg, p))

        sublime.active_window().run_command("hide_panel", {"panel": "output.gotools_oracle"})

        if command == "callees":
            sublime.set_timeout_async(lambda: self.do_plain_oracle("callees", pos, package_scope), 0)
        if command == "callers":
            sublime.set_timeout_async(lambda: self.do_plain_oracle("callers", pos, package_scope), 0)
        if command == "callstack":
            sublime.set_timeout_async(lambda: self.do_plain_oracle("callstack", pos, package_scope), 0)
        if command == "describe":
            sublime.set_timeout_async(lambda: self.do_plain_oracle("describe", pos, package_scope), 0)
        if command == "freevars":
            pos = filename + ":#" + str(offset) + "," + "#" + str(offset_end)
            sublime.set_timeout_async(lambda: self.do_plain_oracle("freevars", pos, package_scope), 0)
        if command == "implements":
            sublime.set_timeout_async(lambda: self.do_plain_oracle("implements", pos, package_scope), 0)
        if command == "peers":
            sublime.set_timeout_async(lambda: self.do_plain_oracle("peers", pos, package_scope), 0)
        if command == "referrers":
            sublime.set_timeout_async(lambda: self.do_plain_oracle("referrers", pos, package_scope), 0)
Ejemplo n.º 18
0
 def test_setting_value_gopath_not_existing(self):
     shell = '/bin/bash'
     env = {
         'GOPATH': os.path.join(os.path.expanduser('~'), 'hdjsahkjzhkjzhiashs7hdsuybyusbguycas')
     }
     with GolangConfigMock(shell, env, None, None, {'debug': True}) as mock_context:
         self.assertEquals(
             (None, None),
             golangconfig.setting_value('GOPATH', mock_context.view, mock_context.window)
         )
         self.assertTrue('does not exist on the filesystem' in sys.stdout.getvalue())
Ejemplo n.º 19
0
 def test_setting_value_gopath_not_string(self):
     shell = '/bin/bash'
     env = {
         'GOPATH': 1
     }
     with GolangConfigMock(shell, env, None, None, {'debug': True}) as mock_context:
         self.assertEquals(
             (None, None),
             golangconfig.setting_value('GOPATH', mock_context.view, mock_context.window)
         )
         self.assertTrue('is not a string' in sys.stdout.getvalue())
Ejemplo n.º 20
0
    def run(self, url=None, flags=None):
        """
        Runs the "golang_build_get" command - invoked by Sublime Text via the
        command palette or sublime.Window.run_command()

        :param url:
            A unicode string of the URL to download, instead of prompting the
            user

        :param flags:
            A list of unicode strings of flags to send to the command-line go
            tool. Execute "go help" on the command line to learn about available
            flags.
        """

        if _yield_to_running_build(self.window):
            return

        working_dir = _determine_working_dir(self.window)
        if working_dir is None:
            return

        go_bin, env = _get_config(
            "go", set(["GOPATH"]), GO_ENV_VARS - set(["GOPATH"]), view=self.window.active_view(), window=self.window
        )
        if (go_bin, env) == (None, None):
            return

        if flags is None:
            flags, _ = golangconfig.setting_value("get:flags", view=self.window.active_view(), window=self.window)

        if flags is None:
            flags = ["-v"]

        def on_done(get_url):
            """
            Processes the user's input and launches the "go get" command

            :param get_url:
                A unicode string of the URL to get
            """

            args = [go_bin, "get"]
            if flags and isinstance(flags, list):
                args.extend(flags)
            args.append(get_url)
            proc = _run_process("get", self.window, args, working_dir, env)
            _set_proc(self.window, proc)

        if url is not None:
            on_done(url)
            return

        self.window.show_input_panel("go get", "", on_done, None, None)
Ejemplo n.º 21
0
  def run(self, edit, command=None):
    if not command:
      Logger.log("command is required")
      return

    filename, row, col, offset, offset_end = Buffers.location_at_cursor(self.view)
    if command == "freevars":
      pos = filename+":#"+str(offset)+","+"#"+str(offset_end)
    else:
      pos = filename+":#"+str(offset)

    # Build up a package scope contaning all packages the user might have
    # configured.
    package_scope = []
    project_package = golangconfig.setting_value("project_package", view=self.view)[0]
    if project_package:
      for p in golangconfig.setting_value("build_packages", view=self.view)[0]:
        package_scope.append(os.path.join(project_package, p))

    sublime.active_window().run_command("hide_panel", {"panel": "output.gotools_guru"})
    self.do_plain_guru(command, pos, package_scope)
Ejemplo n.º 22
0
 def test_setting_value_multiple_gopath(self):
     shell = '/bin/bash'
     env = {'GOPATH': '{tempdir}bin%s{tempdir}usr/bin' % os.pathsep}
     with GolangConfigMock(shell, env, None, None,
                           {'debug': True}) as mock_context:
         mock_context.replace_tempdir_env()
         mock_context.make_dirs(['bin', 'usr/bin'])
         self.assertEquals(
             (env['GOPATH'], shell),
             golangconfig.setting_value('GOPATH', mock_context.view,
                                        mock_context.window))
         self.assertEqual('', sys.stdout.getvalue())
Ejemplo n.º 23
0
  def get_oracle_location(self, filename, offset):
    args = ["-pos="+filename+":#"+str(offset), "-format=json", "definition"]

    # Build up a package scope contaning all packages the user might have
    # configured.
    # TODO: put into a utility
    package_scope = []
    for p in golangconfig.setting_value('build_packages')[0]:
      package_scope.append(os.path.join(golangconfig.setting_value('project_package')[0], p))
    for p in golangconfig.setting_value('test_packages')[0]:
      package_scope.append(os.path.join(golangconfig.setting_value('project_package')[0], p))
    for p in golangconfig.setting_value('tagged_test_packages')[0]:
      package_scope.append(os.path.join(golangconfig.setting_value('project_package')[0], p))

    if len(package_scope) > 0:
      args = args + package_scope

    location, err, rc = ToolRunner.run(self.view, "oracle", args)
    if rc != 0:
      raise Exception("no definition found")

    Logger.log("oracle output:\n" + location.rstrip())

    # cut anything prior to the first path separator
    location = json.loads(location.rstrip())['definition']['objpos'].rsplit(":", 2)

    if len(location) != 3:
      raise Exception("no definition found")

    file = location[0]
    row = int(location[1])
    col = int(location[2])

    return [file, row, col]
Ejemplo n.º 24
0
    def run(self, task='build', flags=None):
        """
        Runs the "golang_build" command - invoked by Sublime Text via the
        command palette or sublime.Window.run_command()

        :param task:
            A unicode string of "build", "test", "install", "clean"
            or "cross_compile"

        :param flags:
            A list of unicode strings of flags to send to the command-line go
            tool. The "cross_compile" task executes the "build" command with
            the GOOS and GOARCH environment variables set, meaning that
            flags for "build" should be used with it. Execute "go help" on the
            command line to learn about available flags.
        """

        if _yield_to_running_build(self.window):
            return

        working_dir = _determine_working_dir(self.window)
        if working_dir is None:
            return

        go_bin, env = _get_config(
            'go',
            set(['GOPATH']),
            GO_ENV_VARS - set(['GOPATH']),
            view=self.window.active_view(),
            window=self.window,
        )
        if (go_bin, env) == (None, None):
            return

        if flags is None:
            flags, _ = golangconfig.setting_value(
                '%s:flags' % task,
                view=self.window.active_view(),
                window=self.window)

        if flags is None:
            flags = ['-v']

        if task == 'cross_compile':
            _task_cross_compile(self, go_bin, flags, working_dir, env)
            return

        args = [go_bin, task]
        if flags and isinstance(flags, list):
            args.extend(flags)
        proc = _run_process(task, self.window, args, working_dir, env)
        _set_proc(self.window, proc)
Ejemplo n.º 25
0
 def test_setting_value_multiple_gopath_one_not_existing(self):
     shell = '/bin/bash'
     env = {
         'GOPATH': '{tempdir}bin%s{tempdir}usr/bin' % os.pathsep
     }
     with GolangConfigMock(shell, env, None, None, {'debug': True}) as mock_context:
         mock_context.replace_tempdir_env()
         mock_context.make_dirs(['usr/bin'])
         self.assertEquals(
             (None, None),
             golangconfig.setting_value('GOPATH', mock_context.view, mock_context.window)
         )
         self.assertTrue('one of the values for GOPATH' in sys.stdout.getvalue())
Ejemplo n.º 26
0
 def test_setting_value_multiple_gopath(self):
     shell = '/bin/bash'
     env = {
         'GOPATH': '{tempdir}bin%s{tempdir}usr/bin' % os.pathsep
     }
     with GolangConfigMock(shell, env, None, None, {'debug': True}) as mock_context:
         mock_context.replace_tempdir_env()
         mock_context.make_dirs(['bin', 'usr/bin'])
         self.assertEquals(
             (env['GOPATH'], shell),
             golangconfig.setting_value('GOPATH', mock_context.view, mock_context.window)
         )
         self.assertEqual('', sys.stdout.getvalue())
Ejemplo n.º 27
0
 def test_setting_value_multiple_gopath_one_not_existing(self):
     shell = '/bin/bash'
     env = {'GOPATH': '{tempdir}bin%s{tempdir}usr/bin' % os.pathsep}
     with GolangConfigMock(shell, env, None, None,
                           {'debug': True}) as mock_context:
         mock_context.replace_tempdir_env()
         mock_context.make_dirs(['usr/bin'])
         self.assertEquals(
             (None, None),
             golangconfig.setting_value('GOPATH', mock_context.view,
                                        mock_context.window))
         self.assertTrue(
             'one of the values for GOPATH' in sys.stdout.getvalue())
Ejemplo n.º 28
0
  def run(self, edit, command=None):
    if not command:
      Logger.log("command is required")
      return

    filename, row, col, offset, offset_end = Buffers.location_at_cursor(self.view)
    if command == "freevars":
      pos = filename+":#"+str(offset)+","+"#"+str(offset_end)
    else:
      pos = filename+":#"+str(offset)

    # Build up a package scope contaning all packages the user might have
    # configured.
    package_scope = []
    project_package = golangconfig.setting_value("project_package", view=self.view)[0]
    if project_package:
      if not golangconfig.setting_value("build_packages")[0]:
        package_scope.append(project_package)
      else:
        for p in golangconfig.setting_value("build_packages", view=self.view)[0]:
          package_scope.append(os.path.join(project_package, p))

    # add local package to guru scope
    if golangconfig.setting_value("guru_use_current_package")[0]:
        current_file_path = os.path.realpath(os.path.dirname(self.view.file_name()))
        toolpath, env = golangconfig.subprocess_info('guru', ['GOPATH', 'PATH'], view=self.view)
        GOPATH = os.path.realpath(env["GOPATH"])
        GOPATH = os.path.join(GOPATH,"src")
        local_package = os.path.relpath(current_file_path, GOPATH)
        if sublime.platform() == 'windows':
            local_package = local_package.replace('\\', '/')
        Logger.status("GOPATH: "+GOPATH)
        Logger.status("local_package: "+local_package)
        package_scope.append(local_package)

    sublime.active_window().run_command("hide_panel", {"panel": "output.gotools_guru"})
    self.do_plain_guru(command, pos, package_scope)
Ejemplo n.º 29
0
 def test_setting_value_gopath_not_existing(self):
     shell = '/bin/bash'
     env = {
         'GOPATH':
         os.path.join(os.path.expanduser('~'),
                      'hdjsahkjzhkjzhiashs7hdsuybyusbguycas')
     }
     with GolangConfigMock(shell, env, None, None,
                           {'debug': True}) as mock_context:
         self.assertEquals(
             (None, None),
             golangconfig.setting_value('GOPATH', mock_context.view,
                                        mock_context.window))
         self.assertTrue(
             'does not exist on the filesystem' in sys.stdout.getvalue())
Ejemplo n.º 30
0
  def on_query_completions(self, view, prefix, locations):
    if not GoBuffers.is_go_source(view): return
    if not golangconfig.setting_value("autocomplete")[0]: return

    suggestionsJsonStr, stderr, rc = ToolRunner.run(view, "gocode", ["-f=json", "autocomplete", view.file_name(), str(locations[0])], stdin=Buffers.buffer_text(view))

    suggestionsJson = json.loads(suggestionsJsonStr)

    Logger.log("DEBUG: gocode output: " + suggestionsJsonStr)

    if rc != 0:
      Logger.status("no completions found: " + str(e))
      return []

    if len(suggestionsJson) > 0:
      return ([GotoolsSuggestions.build_suggestion(j) for j in suggestionsJson[1]], sublime.INHIBIT_WORD_COMPLETIONS)
    else:
      return []
Ejemplo n.º 31
0
    def run(self, edit, event=None):
        # Find and store the current filename and byte offset at the
        # cursor or mouse event location.
        if event:
            filename, row, col, offset = Buffers.location_for_event(
                self.view, event)
        else:
            filename, row, col, offset, offset_end = Buffers.location_at_cursor(
                self.view)

        backend = golangconfig.setting_value('goto_def_backend')[0] or "godef"
        try:
            if backend == "oracle":
                file, row, col = self.get_oracle_location(filename, offset)
            elif backend == "godef":
                file, row, col = self.get_godef_location(filename, offset)
            else:
                Logger.log("Invalid godef backend '" + backend +
                           "' (supported: godef, oracle)")
                Logger.status(
                    "Invalid godef configuration; see console log for details")
                return
        except Exception as e:
            Logger.status(str(e))
            return

        if not os.path.isfile(file):
            Logger.log("WARN: file indicated by godef not found: " + file)
            Logger.status(
                "godef failed: Please enable debugging and check console log")
            return

        Logger.log("opening definition at " + file + ":" + str(row) + ":" +
                   str(col))
        w = self.view.window()
        new_view = w.open_file(file + ':' + str(row) + ':' + str(col),
                               sublime.ENCODED_POSITION)
        group, index = w.get_view_index(new_view)
        if group != -1:
            w.focus_group(group)
Ejemplo n.º 32
0
    def get_oracle_location(self, filename, offset):
        args = [
            "-pos=" + filename + ":#" + str(offset), "-format=json",
            "definition"
        ]

        # Build up a package scope contaning all packages the user might have
        # configured.
        # TODO: put into a utility
        package_scope = []
        for p in golangconfig.setting_value('build_packages')[0]:
            package_scope.append(
                os.path.join(
                    golangconfig.setting_value('project_package')[0], p))
        for p in golangconfig.setting_value('test_packages')[0]:
            package_scope.append(
                os.path.join(
                    golangconfig.setting_value('project_package')[0], p))
        for p in golangconfig.setting_value('tagged_test_packages')[0]:
            package_scope.append(
                os.path.join(
                    golangconfig.setting_value('project_package')[0], p))

        if len(package_scope) > 0:
            args = args + package_scope

        location, err, rc = ToolRunner.run(self.view, "oracle", args)
        if rc != 0:
            raise Exception("no definition found")

        Logger.log("oracle output:\n" + location.rstrip())

        # cut anything prior to the first path separator
        location = json.loads(
            location.rstrip())['definition']['objpos'].rsplit(":", 2)

        if len(location) != 3:
            raise Exception("no definition found")

        file = location[0]
        row = int(location[1])
        col = int(location[2])

        return [file, row, col]
Ejemplo n.º 33
0
    def run(self, task='build', flags=None):
        """
        Runs the "golang_build" command - invoked by Sublime Text via the
        command palette or sublime.Window.run_command()

        :param task:
            A unicode string of "build", "test", "benchmark", "install", "clean"
            or "cross_compile"

        :param flags:
            A list of unicode strings of flags to send to the command-line go
            tool. The "cross_compile" task executes the "build" command with
            the GOOS and GOARCH environment variables set, meaning that
            flags for "build" should be used with it. Execute "go help" on the
            command line to learn about available flags.
        """

        if _yield_to_running_build(self.window):
            return

        working_dir = _determine_working_dir(self.window)
        if working_dir is None:
            return

        go_bin, env = _get_config(
            'go',
            set(['GOPATH']),
            GO_ENV_VARS - set(['GOPATH']),
            view=self.window.active_view(),
            window=self.window,
        )
        if (go_bin, env) == (None, None):
            return

        if flags is None:
            flags, _ = golangconfig.setting_value(
                '%s:flags' % task,
                view=self.window.active_view(),
                window=self.window)

        if flags is None:
            flags = ['-v']

        if task == 'run':
            # Allow the user to set a file path into the flags settings,
            # thus requiring that the flags be checked to ensure a second
            # filename is not added
            found_filename = False

            # Allow users to call "run" with a src-relative file path. Because
            # of that, flags may be rewritten since the "go run" does not
            # accept such file paths.
            use_new_flags = False
            new_flags = []

            gopaths = env['GOPATH'].split(os.pathsep)

            for flag in flags:
                if flag.endswith('.go'):
                    absolute_path = flag
                    if os.path.isfile(absolute_path):
                        found_filename = True
                        break

                    # If the file path is src-relative, rewrite the flag
                    for gopath in gopaths:
                        gopath_relative = os.path.join(gopath, 'src', flag)
                        if os.path.isfile(gopath_relative):
                            found_filename = True
                            flag = gopath_relative
                            use_new_flags = True
                            break
                new_flags.append(flag)

            if use_new_flags:
                flags = new_flags

            if not found_filename:
                flags.append(self.window.active_view().file_name())

        if task == 'cross_compile':
            _task_cross_compile(self, go_bin, flags, working_dir, env)
            return

        if task == 'benchmark':
            # Switch back to the real Go command-line arg
            task = 'test'

            # Allow user to set a regexp for the benchmarks to run
            found_bench_flag = False

            # Need to match '-bench=xyz', ['-bench','xyz'], ['-bench','.']
            # Don't match '-benchmem' or '-benchtime'
            # Remember user can't specify spaces in flags
            for flag in flags:
                if flag == '-bench' or flag.startswith('-bench='):
                    found_bench_flag = True

            # Otherwise default to running all benchmarks
            if not found_bench_flag:
                flags.append('-bench=.')

        args = [go_bin, task]
        if flags and isinstance(flags, list):
            args.extend(flags)
        proc = _run_process(task, self.window, args, working_dir, env)
        _set_proc(self.window, proc)
Ejemplo n.º 34
0
 def log(msg):
     if golangconfig.setting_value('debug_enabled')[0]:
         print("GoTools: DEBUG: {0}".format(msg))
Ejemplo n.º 35
0
    def run(self, task='build', flags=None):
        """
        Runs the "golang_build" command - invoked by Sublime Text via the
        command palette or sublime.Window.run_command()

        :param task:
            A unicode string of "build", "test", "install", "clean"
            or "cross_compile"

        :param flags:
            A list of unicode strings of flags to send to the command-line go
            tool. The "cross_compile" task executes the "build" command with
            the GOOS and GOARCH environment variables set, meaning that
            flags for "build" should be used with it. Execute "go help" on the
            command line to learn about available flags.
        """

        if _yield_to_running_build(self.window):
            return

        working_dir = _determine_working_dir(self.window)
        if working_dir is None:
            return

        go_bin, env = _get_config(
            'go',
            set(['GOPATH']),
            GO_ENV_VARS - set(['GOPATH']),
            view=self.window.active_view(),
            window=self.window,
        )
        if (go_bin, env) == (None, None):
            return

        if flags is None:
            flags, _ = golangconfig.setting_value(
                '%s:flags' % task,
                view=self.window.active_view(),
                window=self.window
            )

        if flags is None:
            flags = ['-v']

        if task == 'cross_compile':
            _task_cross_compile(
                self,
                go_bin,
                flags,
                working_dir,
                env
            )
            return

        args = [go_bin, task]
        if flags and isinstance(flags, list):
            args.extend(flags)
        proc = _run_process(
            task,
            self.window,
            args,
            working_dir,
            env
        )
        _set_proc(self.window, proc)
    def run(self, task='build', flags=None):
        """
        Runs the "golang_build" command - invoked by Sublime Text via the
        command palette or sublime.Window.run_command()

        :param task:
            A unicode string of "build", "test", "benchmark", "install", "clean"
            or "cross_compile"

        :param flags:
            A list of unicode strings of flags to send to the command-line go
            tool. The "cross_compile" task executes the "build" command with
            the GOOS and GOARCH environment variables set, meaning that
            flags for "build" should be used with it. Execute "go help" on the
            command line to learn about available flags.
        """

        if _yield_to_running_build(self.window):
            return

        working_dir = _determine_working_dir(self.window)
        if working_dir is None:
            return

        go_bin, env = _get_config(
            'go',
            set(['GOPATH']),
            GO_ENV_VARS - set(['GOPATH']),
            view=self.window.active_view(),
            window=self.window,
        )
        if (go_bin, env) == (None, None):
            return

        if flags is None:
            flags, _ = golangconfig.setting_value(
                '%s:flags' % task,
                view=self.window.active_view(),
                window=self.window
            )

        if flags is None:
            flags = ['-v']

        if task == 'run':
            # Allow the user to set a file path into the flags settings,
            # thus requiring that the flags be checked to ensure a second
            # filename is not added
            found_filename = False

            # Allow users to call "run" with a src-relative file path. Because
            # of that, flags may be rewritten since the "go run" does not
            # accept such file paths.
            use_new_flags = False
            new_flags = []

            gopaths = env['GOPATH'].split(os.pathsep)

            for flag in flags:
                if flag.endswith('.go'):
                    absolute_path = flag
                    if os.path.isfile(absolute_path):
                        found_filename = True
                        break

                    # If the file path is src-relative, rewrite the flag
                    for gopath in gopaths:
                        gopath_relative = os.path.join(gopath, 'src', flag)
                        if os.path.isfile(gopath_relative):
                            found_filename = True
                            flag = gopath_relative
                            use_new_flags = True
                            break
                new_flags.append(flag)

            if use_new_flags:
                flags = new_flags

            if not found_filename:
                flags.append(self.window.active_view().file_name())

        if task == 'cross_compile':
            _task_cross_compile(
                self,
                go_bin,
                flags,
                working_dir,
                env
            )
            return

        if task == 'benchmark':
            # Switch back to the real Go command-line arg
            task = 'test'

            # Allow user to set a regexp for the benchmarks to run
            found_bench_flag = False

            # Need to match '-bench=xyz', ['-bench','xyz'], ['-bench','.']
            # Don't match '-benchmem' or '-benchtime'
            # Remember user can't specify spaces in flags
            for flag in flags:
                if flag == '-bench' or flag.startswith('-bench='):
                    found_bench_flag = True

            # Otherwise default to running all benchmarks
            if not found_bench_flag:
                flags.append('-bench=.')

        args = [go_bin, task]
        if flags and isinstance(flags, list):
            args.extend(flags)
        proc = _run_process(
            task,
            self.window,
            args,
            working_dir,
            env
        )
        _set_proc(self.window, proc)
Ejemplo n.º 37
0
 def do_test():
     golangconfig.setting_value(b'GOPATH', mock_context.view,
                                mock_context.window)
Ejemplo n.º 38
0
 def do_test():
     golangconfig.setting_value('GOPATH', True, mock_context.window)
Ejemplo n.º 39
0
 def on_pre_save(self, view):
   if not GoBuffers.is_go_source(view): return
   if not golangconfig.setting_value("format_on_save")[0]: return
   view.run_command('gotools_format')
Ejemplo n.º 40
0
 def do_test():
     golangconfig.setting_value('GOPATH', True, mock_context.window)
Ejemplo n.º 41
0
 def do_test():
     golangconfig.setting_value('GOPATH', mock_context.view, True)
Ejemplo n.º 42
0
 def do_test():
     golangconfig.setting_value(b'GOPATH', mock_context.view, mock_context.window)
Ejemplo n.º 43
0
 def do_test():
     golangconfig.setting_value(CustomString('GOPATH'), mock_context.view, mock_context.window)
Ejemplo n.º 44
0
    def setting_value_gopath(self, shell, env, view_settings, window_settings, sublime_settings, setting, result):

        with GolangConfigMock(shell, env, view_settings, window_settings, sublime_settings) as mock_context:
            self.assertEquals(result, golangconfig.setting_value(setting, mock_context.view, mock_context.window))
            self.assertEqual('', sys.stdout.getvalue())
Ejemplo n.º 45
0
    def run(self, task="build", flags=None):
        """
        Runs the "golang_build" command - invoked by Sublime Text via the
        command palette or sublime.Window.run_command()

        :param task:
            A unicode string of "build", "test", "install", "clean"
            or "cross_compile"

        :param flags:
            A list of unicode strings of flags to send to the command-line go
            tool. The "cross_compile" task executes the "build" command with
            the GOOS and GOARCH environment variables set, meaning that
            flags for "build" should be used with it. Execute "go help" on the
            command line to learn about available flags.
        """

        if _yield_to_running_build(self.window):
            return

        working_dir = _determine_working_dir(self.window)
        if working_dir is None:
            return

        go_bin, env = _get_config(
            "go", set(["GOPATH"]), GO_ENV_VARS - set(["GOPATH"]), view=self.window.active_view(), window=self.window
        )
        if (go_bin, env) == (None, None):
            return

        if flags is None:
            flags, _ = golangconfig.setting_value("%s:flags" % task, view=self.window.active_view(), window=self.window)

        if flags is None:
            flags = ["-v"]

        if task == "run":
            # Allow the user to set a file path into the flags settings,
            # thus requiring that the flags be checked to ensure a second
            # filename is not added
            found_filename = False

            # Allow users to call "run" with a src-relative file path. Because
            # of that, flags may be rewritten since the "go run" does not
            # accept such file paths.
            use_new_flags = False
            new_flags = []

            gopaths = env["GOPATH"].split(os.pathsep)

            for flag in flags:
                if flag.endswith(".go"):
                    absolute_path = flag
                    if os.path.isfile(absolute_path):
                        found_filename = True
                        break

                    # If the file path is src-relative, rewrite the flag
                    for gopath in gopaths:
                        gopath_relative = os.path.join(gopath, "src", flag)
                        if os.path.isfile(gopath_relative):
                            found_filename = True
                            flag = gopath_relative
                            use_new_flags = True
                            break
                new_flags.append(flag)

            if use_new_flags:
                flags = new_flags

            if not found_filename:
                flags.append(self.window.active_view().file_name())

        if task == "cross_compile":
            _task_cross_compile(self, go_bin, flags, working_dir, env)
            return

        args = [go_bin, task]
        if flags and isinstance(flags, list):
            args.extend(flags)
        proc = _run_process(task, self.window, args, working_dir, env)
        _set_proc(self.window, proc)
Ejemplo n.º 46
0
 def log(msg):
   if golangconfig.setting_value('debug_enabled')[0]:
     print("GoTools: DEBUG: {0}".format(msg))
Ejemplo n.º 47
0
 def on_post_save(self, view):
   if not GoBuffers.is_go_source(view): return
   if not golangconfig.setting_value("lint_on_save")[0]: return
   view.run_command('gotools_lint')
Ejemplo n.º 48
0
 def do_test():
     golangconfig.setting_value(CustomString('GOPATH'),
                                mock_context.view,
                                mock_context.window)
Ejemplo n.º 49
0
 def on_post_save(self, view):
     if not GoBuffers.is_go_source(view): return
     if not golangconfig.setting_value("lint_on_save")[0]: return
     if Logger.err: return
     view.run_command('gotools_lint')
Ejemplo n.º 50
0
 def do_test():
     golangconfig.setting_value('GOPATH', mock_context.view, True)