Пример #1
0
    def format_code(self, source, node_path, prettier_cli_path, prettier_options, view, provide_cursor=False):
        self._error_message = None

        cursor = None
        if provide_cursor:
            cursor = view.sel()[0].a
            prettier_options += ['--cursor-offset', str(cursor)]

        if is_str_none_or_empty(node_path):
            cmd = [prettier_cli_path] \
                + ['--stdin'] \
                + prettier_options
        else:
            cmd = [node_path] \
                + [prettier_cli_path] \
                + ['--stdin'] \
                + prettier_options

        try:
            format_debug_message('Prettier CLI Command', list_to_str(cmd), debug_enabled(view))

            proc = Popen(
                cmd, stdin=PIPE,
                stderr=PIPE,
                stdout=PIPE,
                env=get_proc_env(),
                shell=is_windows())

            stdout, stderr = proc.communicate(input=source.encode('utf-8'))
            if proc.returncode != 0:
                error_output = stderr.decode('utf-8')
                self.error_message = format_error_message(error_output, str(proc.returncode))

                # detect and scroll to 'Syntax Errors':
                _, _, error_line, error_col = self.has_syntax_error(error_output)
                if error_line != -1 and error_col != -1:
                    scroll_view_to(view, error_line, error_col)

                return None

            new_cursor = None
            if stderr:
                stderr_output = stderr.decode('utf-8')
                if provide_cursor:
                    stderr_lines = stderr_output.splitlines()
                    stderr_output, new_cursor = '\n'.join(stderr_lines[:-1]), stderr_lines[-1]

                # allow warnings to pass-through
                if stderr_output:
                    print(format_error_message(stderr_output, str(proc.returncode)))

            if provide_cursor:
                if not new_cursor and cursor is not None:
                    new_cursor = cursor
                return stdout.decode('utf-8'), int(new_cursor)

            return stdout.decode('utf-8')
        except OSError as ex:
            sublime.error_message('{0} - {1}'.format(PLUGIN_NAME, ex))
            raise
Пример #2
0
    def format_code(self, source, node_path, prettier_cli_path,
                    prettier_options, view):
        self._error_message = None

        if is_str_none_or_empty(node_path):
            cmd = [prettier_cli_path] \
                + ['--stdin'] \
                + prettier_options
        else:
            cmd = [node_path] \
                + [prettier_cli_path] \
                + ['--stdin'] \
                + prettier_options

        try:
            format_debug_message('Prettier CLI Command', list_to_str(cmd),
                                 debug_enabled(view))

            proc = Popen(cmd,
                         stdin=PIPE,
                         stderr=PIPE,
                         stdout=PIPE,
                         env=get_proc_env(),
                         shell=is_windows())

            stdout, stderr = proc.communicate(input=source.encode('utf-8'))
            if proc.returncode != 0:
                error_output = stderr.decode('utf-8')
                self.error_message = format_error_message(
                    error_output, str(proc.returncode))

                # detect and scroll to 'Syntax Errors':
                _, _, error_line, error_col = self.has_syntax_error(
                    error_output)
                if error_line != -1 and error_col != -1:
                    scroll_view_to(view, error_line, error_col)

                return None
            if stderr:
                # allow warnings to pass-through
                print(
                    format_error_message(stderr.decode('utf-8'),
                                         str(proc.returncode)))
            return stdout.decode('utf-8')
        except OSError as ex:
            sublime.error_message('{0} - {1}'.format(PLUGIN_NAME, ex))
            raise
Пример #3
0
    def format_code(self, source, node_path, prettier_cli_path, prettier_options, view):
        self._error_message = None

        if is_str_none_or_empty(node_path):
            cmd = [prettier_cli_path] \
                + ['--stdin'] \
                + prettier_options
        else:
            cmd = [node_path] \
                + [prettier_cli_path] \
                + ['--stdin'] \
                + prettier_options

        try:
            format_debug_message('Prettier CLI Command', list_to_str(cmd), debug_enabled(view))

            proc = Popen(
                cmd, stdin=PIPE,
                stderr=PIPE,
                stdout=PIPE,
                env=get_proc_env(),
                shell=is_windows())

            stdout, stderr = proc.communicate(input=source.encode('utf-8'))
            if proc.returncode != 0:
                error_output = stderr.decode('utf-8')
                self.error_message = format_error_message(error_output, str(proc.returncode))

                # detect and scroll to 'Syntax Errors':
                _, _, error_line, error_col = self.has_syntax_error(error_output)
                if error_line != -1 and error_col != -1:
                    scroll_view_to(view, error_line, error_col)

                return None
            if stderr:
                # allow warnings to pass-through
                print(format_error_message(stderr.decode('utf-8'), str(proc.returncode)))
            return stdout.decode('utf-8')
        except OSError as ex:
            sublime.error_message('{0} - {1}'.format(PLUGIN_NAME, ex))
            raise
Пример #4
0
    def parse_prettier_options(self, view, parsed_additional_cli_args,
                               prettier_config_path, has_custom_config_defined,
                               has_no_config_defined,
                               has_config_precedence_defined,
                               prettier_ignore_filepath, file_name):
        prettier_options = []

        #
        # Check for prettier config file:
        prettier_config_exists = not is_str_none_or_empty(prettier_config_path)
        if prettier_config_exists:
            if not has_custom_config_defined:
                # only add the '--config <path>' option if it's not
                # already specified as an additional cli arg:
                prettier_options.append('--config')
                prettier_options.append(prettier_config_path)

                # set config-precedence to 'cli-override' if
                # the key wasn't defined in additional_cli_args:
                if not has_config_precedence_defined:
                    prettier_options.append('--config-precedence')
                    prettier_options.append('cli-override')
        else:
            if not has_no_config_defined and not has_custom_config_defined:
                # only add the '--no-config' option if it's not
                # already specified as an additional cli arg:
                prettier_options.append('--no-config')

        #
        # Iterate over option map:
        for mapping in PRETTIER_OPTION_CLI_MAP:
            option_name = mapping['option']
            cli_option_name = mapping['cli']

            option_value = get_sub_setting(view, option_name)

            if option_name == 'parser':
                if self.is_typescript(view):
                    prettier_options.append(cli_option_name)
                    prettier_options.append('typescript')
                    continue
                elif self.is_package_or_composer_json(view):
                    prettier_options.append(cli_option_name)
                    prettier_options.append('json-stringify')
                    continue
                elif self.is_json(view):
                    prettier_options.append(cli_option_name)
                    prettier_options.append('json')
                    continue
                elif self.is_graphql(view):
                    prettier_options.append(cli_option_name)
                    prettier_options.append('graphql')
                    continue
                elif self.is_mdx(view):
                    prettier_options.append(cli_option_name)
                    prettier_options.append('mdx')
                    continue
                elif self.is_markdown(view):
                    prettier_options.append(cli_option_name)
                    prettier_options.append('markdown')
                    continue
                elif self.is_yaml(view):
                    prettier_options.append(cli_option_name)
                    prettier_options.append('yaml')
                    continue
                elif self.is_vue(view):
                    prettier_options.append(cli_option_name)
                    prettier_options.append('vue')
                    continue
                elif self.is_angular_html(view):
                    prettier_options.append(cli_option_name)
                    prettier_options.append('angular')
                    continue
                elif self.is_source_js(view) or self.is_es_module(view):
                    prettier_options.append(cli_option_name)
                    prettier_options.append('babel')
                    continue
                elif self.is_css(view):
                    prettier_options.append(cli_option_name)
                    prettier_options.append('css')
                    continue
                elif self.is_html(view):
                    prettier_options.append(cli_option_name)
                    prettier_options.append('html')
                    continue
                elif self.is_php(view):
                    prettier_options.append(cli_option_name)
                    prettier_options.append('php')
                    continue
                else:
                    # parser couldn't be detected... let Prettier try to infer it via --stdin-filepath:
                    continue

            if not prettier_config_exists and not has_custom_config_defined:
                # add the cli args or the respective defaults:
                if option_value is None or str(option_value) == '':
                    option_value = mapping['default']
                option_value = str(option_value).strip()

                # special handling for "tabWidth":
                if option_name == 'tabWidth':
                    has_additional_cli_for_tab_width = parsed_additional_cli_args.count(
                        '--tab-width') > 0
                    if not has_additional_cli_for_tab_width:
                        if self.disable_tab_width_auto_detection is False:
                            # set `tabWidth` from st "tab_size" setting (default behavior)
                            prettier_options.append(cli_option_name)
                            prettier_options.append(str(self.tab_size))
                        else:
                            if not has_additional_cli_for_tab_width:
                                prettier_options.append(cli_option_name)
                                prettier_options.append(option_value)
                    else:
                        if not has_additional_cli_for_tab_width:
                            prettier_options.append(cli_option_name)
                            prettier_options.append(option_value)
                    continue

                # handle bool types:
                if is_bool_str(option_value):
                    option_value = option_value.lower()

                # append the opt/val:
                prettier_options.append(cli_option_name)
                prettier_options.append(option_value)

        # set the `useTabs` option based on the current view:
        prettier_options.append('--use-tabs')
        prettier_options.append(str(self.use_tabs).lower())

        if prettier_ignore_filepath is not None:
            prettier_options.append('--ignore-path')
            prettier_options.append(prettier_ignore_filepath)

        # add the current file name to `--stdin-filepath`, only when
        # the current file being edited is NOT html, and in order
        # detect and format css/js selection(s) within html files:
        # if not self.is_html(view):
        prettier_options.append('--stdin-filepath')
        prettier_options.append(file_name)

        if debug_enabled(view):
            if not parsed_additional_cli_args.count('--loglevel') > 0:
                # set prettier's log level to debug, when the plug-in's debug setting is enabled:
                prettier_options.append('--loglevel')
                prettier_options.append('debug')

        # Append any additional specified arguments:
        prettier_options.extend(parsed_additional_cli_args)

        return prettier_options
Пример #5
0
    def format_code(self,
                    source,
                    node_path,
                    prettier_cli_path,
                    prettier_options,
                    view,
                    provide_cursor=False,
                    is_selection=False):

        self._error_message = None

        cursor = None
        if provide_cursor:
            cursor = view.sel()[0].a
            prettier_options += ['--cursor-offset', str(cursor)]

        if is_windows() and is_str_none_or_empty(
                node_path) and prettier_cli_path.endswith(".js"):
            # on windows, when a custom 'node_path' is not specified and 'prettier_cli_path' is
            # presumably a .js script (e.g: 'bin-prettier.js')...
            # automatically prepend the environment detected node[.exe|.cmd] path to
            # the generated command (see #146 --no-bin-links).
            cmd = [resolve_node_path(view.file_name())] \
                + [prettier_cli_path] \
                + ['--stdin'] \
                + prettier_options
        elif is_str_none_or_empty(node_path):
            cmd = [prettier_cli_path] \
                + ['--stdin'] \
                + prettier_options
        else:
            cmd = [node_path] \
                + [prettier_cli_path] \
                + ['--stdin'] \
                + prettier_options

        try:
            format_debug_message('Prettier CLI Command', list_to_str(cmd),
                                 debug_enabled(view))

            proc = Popen(cmd,
                         stdin=PIPE,
                         stderr=PIPE,
                         stdout=PIPE,
                         env=get_proc_env(),
                         shell=is_windows())

            stdout, stderr = proc.communicate(input=source.encode('utf-8'))
            if proc.returncode != 0:
                error_output = stderr.decode('utf-8')
                self.error_message = format_error_message(
                    error_output, str(proc.returncode))

                # detect and scroll to 'Syntax Errors' (if not formatting a selection):
                if not is_selection:
                    _, _, error_line, error_col = self.has_syntax_error(
                        error_output)
                    if error_line != -1 and error_col != -1:
                        scroll_view_to(view, error_line, error_col)

                return None

            new_cursor = None
            if stderr:
                stderr_output = stderr.decode('utf-8')
                if provide_cursor:
                    stderr_lines = stderr_output.splitlines()
                    stderr_output, new_cursor = '\n'.join(
                        stderr_lines[:-1]), stderr_lines[-1]

                # allow warnings to pass-through
                if stderr_output:
                    print(
                        format_error_message(stderr_output,
                                             str(proc.returncode)))

            if provide_cursor:
                if not new_cursor and cursor is not None:
                    new_cursor = cursor
                try:
                    new_cursor = int(new_cursor)
                except ValueError:
                    log_warn(
                        view,
                        'Adjusted cursor position could not be parsed (int).')
                    return stdout.decode('utf-8'), None
                return stdout.decode('utf-8'), new_cursor

            return stdout.decode('utf-8')
        except OSError as ex:
            sublime.error_message('{0} - {1}'.format(PLUGIN_NAME, ex))
            raise
Пример #6
0
    def format_code(
        self,
        source,
        node_path,
        prettier_cli_path,
        prettier_options,
        vid,
        region=None,
        provide_cursor=False,
        save=False,
    ):
        view = sublime.View(vid)
        if not view.is_valid():
            return

        self._error_message = None

        cursor = None
        if provide_cursor:
            cursor = view.sel()[0].a
            prettier_options += ["--cursor-offset", str(cursor)]

        if is_str_none_or_empty(node_path):
            cmd = [prettier_cli_path] + ["--stdin"] + prettier_options
        else:
            cmd = [node_path] + [prettier_cli_path] + ["--stdin"
                                                       ] + prettier_options

        try:
            format_debug_message("Prettier CLI Command", list_to_str(cmd),
                                 debug_enabled(view))

            proc = Popen(
                cmd,
                stdin=PIPE,
                stderr=PIPE,
                stdout=PIPE,
                env=get_proc_env(),
                shell=is_windows(),
            )

            stdout, stderr = proc.communicate(input=source.encode("utf-8"))
            if proc.returncode != 0:
                error_output = stderr.decode("utf-8")
                self.error_message = format_error_message(
                    error_output, str(proc.returncode))

                # detect and scroll to 'Syntax Errors':
                _, _, error_line, error_col = self.has_syntax_error(
                    error_output)
                if error_line != -1 and error_col != -1:
                    scroll_view_to(view, error_line, error_col)

                format_console_error(self.error_message)
                return show_status_bar_error()

            new_cursor = None
            if stderr:
                stderr_output = stderr.decode("utf-8")
                if provide_cursor:
                    stderr_lines = stderr_output.splitlines()
                    stderr_output, new_cursor = (
                        "\n".join(stderr_lines[:-1]),
                        stderr_lines[-1],
                    )

                # allow warnings to pass-through
                if stderr_output:
                    print(
                        format_error_message(stderr_output,
                                             str(proc.returncode)))

            if provide_cursor:
                if not new_cursor and cursor is not None:
                    new_cursor = cursor
                view.run_command(
                    "js_prettier_replace",
                    {
                        "code": stdout.decode("utf-8"),
                        "cursor": int(new_cursor),
                        "region": region,
                        "save": save,
                    },
                )
            else:
                view.run_command(
                    "js_prettier_replace",
                    {
                        "code": stdout.decode("utf-8"),
                        "region": region,
                        "save": save
                    },
                )
        except OSError as ex:
            sublime.error_message("{0} - {1}".format(PLUGIN_NAME, ex))
            raise