def _ody_get_settings(self, cmd_id):
        """Set settings.

        Parameters
        ----------
        cmd_id : str
            Command ID.

        Returns
        -------
        None
            Halt execution.
        """
        if cmd_id is None or get_settings(cmd_id).get("disabled", False):
            return False

        settings_exec_map = get_settings(cmd_id).get("exec_map", {}).get(
            sublime.platform(), [])

        for _map in settings_exec_map:
            if "cmd" not in _map or _map.get("is_visible", "auto") is False:
                continue

            cmd = utils.substitute_variables(utils.get_view_context(None),
                                             _map["cmd"])

            if cmd_utils.can_exec(cmd) or cmd_utils.which(cmd):
                return misc_utils.merge_dict(self._ody_get_defaults(), _map)

        return False
Exemplo n.º 2
0
    def _ody_get_cmd_settings(self, cmd_id):
        """Set settings.

        Parameters
        ----------
        cmd_id : str
            Command ID.

        Returns
        -------
        bool
            Halt execution.
        dict
            Command definition of an existent command.
        """
        if cmd_id is None or get_settings(cmd_id).get("disabled", False):
            return False

        settings_exec_map = utils.substitute_variables(
            utils.get_view_context(self.view),
            get_settings(cmd_id).get("exec_map",
                                     {}).get(sublime.platform(), []))

        for _map in settings_exec_map:
            if "cmd" not in _map or not _map["cmd"]:
                continue

            # NOTE: The cmd_utils.can_exec is to not require the command to exist in PATH.
            # Let's see how it goes.
            if cmd_utils.can_exec(_map["cmd"]) or cmd_utils.which(_map["cmd"]):
                return misc_utils.merge_dict(self._ody_cmd_get_defaults(),
                                             _map)

        return False
Exemplo n.º 3
0
    def _ody_get_stylesheets(self):
        stylesheets = substitute_variables(get_view_context(self.view),
                                           settings.get("preview_stylesheets"))

        return "\n".join(
            [_stylesheet_link_template.format(href=s)
             for s in stylesheets]) if stylesheets else ""
Exemplo n.º 4
0
    def __init__(self, view, settings):
        """Prepare to call daemon.

        :type settings: dict

        Parameters
        ----------
        settings : TYPE
            Description
        """
        view_context = utils.get_view_context(view)
        python_virtualenv = settings.get("python_virtualenv").get(
            sublime.platform(), "")
        python_interpreter = settings.get("python_interpreter").get(
            sublime.platform(), "")

        if python_virtualenv:
            logger.debug("Jedi Environment: {0}".format(python_virtualenv))
            self.env = environment.create_environment(
                utils.substitute_variables(view_context, python_virtualenv),
                safe=False)
        elif python_interpreter:
            logger.debug("Jedi Environment: {0}".format(python_interpreter))
            self.env = environment.create_environment(
                utils.substitute_variables(view_context, python_interpreter),
                safe=False)
        else:
            self.env = jedi.get_default_environment()

        self.sys_path = self.env.get_sys_path()
        # prepare the extra packages if any
        extra_packages = settings.get("python_package_paths").get(
            sublime.platform(), [])

        if extra_packages:
            logger.debug("Jedi Extra Packages: {0}".format(extra_packages))
            self.sys_path = utils.substitute_variables(
                view_context, extra_packages) + self.sys_path
Exemplo n.º 5
0
    def run(self, edit):
        file_path = get_file_path(self.view)
        text = self.view.substr(sublime.Region(
            0, self.view.size())).encode("utf-8")

        if not text or not file_path:
            sublime.status_message("No content to preview")
            return

        html_file_id = "%d-%d" % (self.view.window().id(), self.view.id())
        html_file_path = os.path.join(get_system_tempdir(), plugin_name,
                                      html_file_id + ".html")

        cmd = [rst_to_html, html_file_path]
        stylesheets = substitute_variables(get_view_context(self.view),
                                           settings.get("preview_stylesheets"))

        if stylesheets:
            for css in stylesheets:
                cmd.append("--extra-css")
                cmd.append(css)

        if html_file_id not in Storage.open_previews:
            Storage.open_previews = html_file_id
            cmd.append("--open-in-browser")
        else:
            sublime.status_message("Reload web page")

        with cmd_utils.popen(cmd,
                             logger=logger,
                             bufsize=160 * len(text),
                             cwd=os.path.dirname(rst_to_html)) as proc:
            stdout, stderr = proc.communicate(text)

        if stderr:
            logger.error(
                "%s Error:\n%s" %
                (self.__class__.__name__, str(stderr.decode("utf-8")).strip()))
    def run(self, **kwargs):
        """Action to perform when this Sublime Text command is executed.

        Parameters
        ----------
        **kwargs
            Keyword arguments.

        Returns
        -------
        None
            Halt execution.
        """
        cmd_id = kwargs.get("cmd_id")
        cmd_settings = self._ody_get_settings(cmd_id)

        if not cmd_settings or not cmd_settings["cmd"]:
            title = "%s: No command set or found." % self.name()
            msg = "# cmd_id: %s" % str(cmd_id)
            display_message_in_panel(self.window, title=title, body=msg)
            return

        cmd = [
            utils.substitute_variables(utils.get_view_context(None),
                                       cmd_settings["cmd"])
        ]
        args = cmd_settings["args"]
        report_stdout = cmd_settings["report_stdout"]
        pass_path_to_cmd = cmd_settings["pass_path_to_cmd"]
        allow_multiple = cmd_settings["allow_multiple"]
        path_type = cmd_settings["path_type"]
        exec_once = cmd_settings["exec_once"]
        working_directory = cmd_settings["working_directory"] if \
            os.path.isdir(cmd_settings["working_directory"]) else \
            None
        self._ody_stdout_storage = []

        if path_type == "folder":
            selected_paths = kwargs.get("dirs", [])
        elif path_type == "file":
            selected_paths = kwargs.get("files", [])
        else:
            selected_paths = kwargs.get("paths", [])

        if selected_paths:
            # exec_func = ThreadCall if report_stdout else Process
            threads = []
            # NOTE: Make a copy of original. It doesn't matter if a change in the original modifies the copy,
            # what matters is that a change in the copy doesn't change the original.
            command = cmd[:]
            command.extend(args)

            for path in selected_paths:
                # Build a single command with all selected paths to run once.
                if exec_once and allow_multiple and pass_path_to_cmd:
                    if isinstance(pass_path_to_cmd, str):
                        command.append(pass_path_to_cmd + path)
                    else:
                        command.append(path)
                else:  # Run command for each selected path.
                    arguments = utils.substitute_variables(
                        utils.get_view_context(
                            None,
                            additional_context={"selected_sidebar_path":
                                                path}), args)

                    if pass_path_to_cmd is True:
                        arguments.append(path)

                    if report_stdout:
                        thread = ThreadCall(cmd=cmd + arguments,
                                            cwd=working_directory)
                        threads.append(thread)
                        thread.start()

                        self._ody_handle_threads(
                            threads, lambda process, last_error: self.
                            _ody_handle_output(process, last_error))
                    else:
                        proc = Process(target=self._ody_proc_exec,
                                       args=(cmd + arguments, ),
                                       kwargs={
                                           "cmd_id":
                                           str(cmd_id),
                                           "cmd_settings":
                                           cmd_settings,
                                           "cwd":
                                           path if os.path.isdir(path) else
                                           os.path.dirname(path)
                                       })
                        proc.start()

            if exec_once and command:
                if report_stdout:
                    thread = ThreadCall(cmd=command, cwd=working_directory)
                    threads.append(thread)
                    thread.start()

                    self._ody_handle_threads(
                        threads,
                        lambda process, last_error: self._ody_handle_output(
                            process, last_error))
                else:
                    proc = Process(target=self._ody_proc_exec,
                                   args=(command, ),
                                   kwargs={
                                       "cmd_id": str(cmd_id),
                                       "cmd_settings": cmd_settings,
                                       "cwd": working_directory
                                   })

                    proc.start()
        else:
            sublime.status_message("No valid path/s selected.")