コード例 #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 []
コード例 #2
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)
コード例 #3
0
ファイル: golang_build.py プロジェクト: nuance/sublime-build
    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)
コード例 #4
0
ファイル: gotools_guru.py プロジェクト: ottob/gotools-sublime
    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)
コード例 #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
コード例 #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([])
コード例 #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)
コード例 #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)
コード例 #9
0
ファイル: gotools_lint.py プロジェクト: ottob/gotools-sublime
 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
コード例 #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
コード例 #11
0
ファイル: gotools_goto_def.py プロジェクト: nuance/GoTools
  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)
コード例 #12
0
ファイル: gotools_format.py プロジェクト: nuance/GoTools
    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([])
コード例 #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)
コード例 #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)
コード例 #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())
コード例 #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())
コード例 #17
0
ファイル: gotools_oracle.py プロジェクト: nuance/GoTools
    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)
コード例 #18
0
ファイル: tests.py プロジェクト: jduhamel/sublime-config
 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())
コード例 #19
0
ファイル: tests.py プロジェクト: jduhamel/sublime-config
 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())
コード例 #20
0
ファイル: golang_build.py プロジェクト: codexns/golang-build
    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)
コード例 #21
0
ファイル: gotools_guru.py プロジェクト: ottob/gotools-sublime
  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)
コード例 #22
0
ファイル: tests.py プロジェクト: gavinong10/sublime3_packages
 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())
コード例 #23
0
ファイル: gotools_goto_def.py プロジェクト: nuance/GoTools
  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]
コード例 #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)
コード例 #25
0
ファイル: tests.py プロジェクト: jduhamel/sublime-config
 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())
コード例 #26
0
ファイル: tests.py プロジェクト: jduhamel/sublime-config
 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())
コード例 #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())
コード例 #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)
コード例 #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())
コード例 #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 []
コード例 #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)
コード例 #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]
コード例 #33
0
ファイル: golang_build.py プロジェクト: nuance/sublime-build
    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)
コード例 #34
0
 def log(msg):
     if golangconfig.setting_value('debug_enabled')[0]:
         print("GoTools: DEBUG: {0}".format(msg))
コード例 #35
0
ファイル: golang_build.py プロジェクト: SjB/sublime-build
    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)
コード例 #36
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)
コード例 #37
0
 def do_test():
     golangconfig.setting_value(b'GOPATH', mock_context.view,
                                mock_context.window)
コード例 #38
0
 def do_test():
     golangconfig.setting_value('GOPATH', True, mock_context.window)
コード例 #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')
コード例 #40
0
ファイル: tests.py プロジェクト: jduhamel/sublime-config
 def do_test():
     golangconfig.setting_value('GOPATH', True, mock_context.window)
コード例 #41
0
ファイル: tests.py プロジェクト: jduhamel/sublime-config
 def do_test():
     golangconfig.setting_value('GOPATH', mock_context.view, True)
コード例 #42
0
ファイル: tests.py プロジェクト: jduhamel/sublime-config
 def do_test():
     golangconfig.setting_value(b'GOPATH', mock_context.view, mock_context.window)
コード例 #43
0
ファイル: tests.py プロジェクト: jduhamel/sublime-config
 def do_test():
     golangconfig.setting_value(CustomString('GOPATH'), mock_context.view, mock_context.window)
コード例 #44
0
ファイル: tests.py プロジェクト: jduhamel/sublime-config
    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())
コード例 #45
0
ファイル: golang_build.py プロジェクト: codexns/golang-build
    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)
コード例 #46
0
 def log(msg):
   if golangconfig.setting_value('debug_enabled')[0]:
     print("GoTools: DEBUG: {0}".format(msg))
コード例 #47
0
ファイル: gotools_lint.py プロジェクト: ottob/gotools-sublime
 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')
コード例 #48
0
 def do_test():
     golangconfig.setting_value(CustomString('GOPATH'),
                                mock_context.view,
                                mock_context.window)
コード例 #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')
コード例 #50
0
 def do_test():
     golangconfig.setting_value('GOPATH', mock_context.view, True)