summaryrefslogtreecommitdiff
path: root/venv/lib/python3.11/site-packages/jsbeautifier/cli/__init__.py
blob: 73f0c488fcf52d7e0f74a602df0ccc9a2493325d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
from __future__ import print_function
import sys
import os
import platform
import io
import getopt
import re
import string
import errno
import copy
import glob
from jsbeautifier.__version__ import __version__
from jsbeautifier.javascript.options import BeautifierOptions
from jsbeautifier.javascript.beautifier import Beautifier

#
# The MIT License (MIT)

# Copyright (c) 2007-2020 Einar Lielmanis, Liam Newman, and contributors.

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:

# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

__all__ = [
    "MissingInputStreamError",
    "process_file",
    "get_filepaths_from_params",
    "integrate_editorconfig_options",
    "write_beautified_output",
]


class MissingInputStreamError(Exception):
    pass


def set_file_editorconfig_opts(filename, js_options):
    from editorconfig import get_properties, EditorConfigError

    try:
        _ecoptions = get_properties(os.path.abspath(filename))

        if _ecoptions.get("indent_style") == "tab":
            js_options.indent_with_tabs = True
        elif _ecoptions.get("indent_style") == "space":
            js_options.indent_with_tabs = False

        if _ecoptions.get("indent_size"):
            js_options.indent_size = int(_ecoptions["indent_size"])

        if _ecoptions.get("max_line_length"):
            if _ecoptions.get("max_line_length") == "off":
                js_options.wrap_line_length = 0
            else:
                js_options.wrap_line_length = int(_ecoptions["max_line_length"])

        if _ecoptions.get("insert_final_newline") == "true":
            js_options.end_with_newline = True
        elif _ecoptions.get("insert_final_newline") == "false":
            js_options.end_with_newline = False

        if _ecoptions.get("end_of_line"):
            if _ecoptions["end_of_line"] == "cr":
                js_options.eol = "\r"
            elif _ecoptions["end_of_line"] == "lf":
                js_options.eol = "\n"
            elif _ecoptions["end_of_line"] == "crlf":
                js_options.eol = "\r\n"

    except EditorConfigError:
        # do not error on bad editor config
        print("Error loading EditorConfig.  Ignoring.", file=sys.stderr)


def process_file(file_name, opts, beautify_code):
    input_string = ""
    if file_name == "-":  # stdin
        if sys.stdin.isatty():
            raise MissingInputStreamError()

        stream = sys.stdin
        if platform.platform().lower().startswith("windows"):
            if sys.version_info.major >= 3:
                # for python 3 on windows this prevents conversion
                stream = io.TextIOWrapper(sys.stdin.buffer, newline="")
            elif platform.architecture()[0] == "32bit":
                # for python 2 x86 on windows this prevents conversion
                import msvcrt

                msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
            else:
                raise Exception(
                    "Pipe to stdin not supported on Windows with Python 2.x 64-bit."
                )

        input_string = stream.read()

        # if you pipe an empty string, that is a failure
        if input_string == "":
            raise MissingInputStreamError()
    else:
        stream = io.open(file_name, "rt", newline="", encoding="UTF-8")
        input_string = stream.read()

    return beautify_code(input_string, opts)


def mkdir_p(path):
    try:
        if path:
            os.makedirs(path)
    except OSError as exc:  # Python >2.5
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else:
            raise Exception()


def isFileDifferent(filepath, expected):
    try:
        return "".join(io.open(filepath, "rt", newline="").readlines()) != expected
    except BaseException:
        return True


def get_filepaths_from_params(filepath_params, replace):
    filepaths = []
    if not filepath_params or (len(filepath_params) == 1 and filepath_params[0] == "-"):
        # default to stdin
        filepath_params = []
        filepaths.append("-")

    for filepath_param in filepath_params:
        # ignore stdin setting if files are specified
        if "-" == filepath_param:
            continue

        # Check if each literal filepath exists
        if os.path.isfile(filepath_param):
            filepaths.append(filepath_param)
        elif "*" in filepath_param or "?" in filepath_param:
            # handle globs
            # empty result is okay
            if sys.version_info.major == 2 or (
                sys.version_info.major == 3 and sys.version_info.minor <= 4
            ):
                if "**" in filepath_param:
                    raise Exception("Recursive globs not supported on Python <= 3.4.")
                filepaths.extend(glob.glob(filepath_param))
            else:
                filepaths.extend(glob.glob(filepath_param, recursive=True))
        else:
            # not a glob and not a file
            raise OSError(errno.ENOENT, os.strerror(errno.ENOENT), filepath_param)

    if len(filepaths) > 1:
        replace = True
    elif filepaths and filepaths[0] == "-":
        replace = False

    # remove duplicates
    filepaths = set(filepaths)

    return filepaths, replace


def integrate_editorconfig_options(filepath, local_options, outfile, default_file_type):
    # Editorconfig used only on files, not stdin
    if getattr(local_options, "editorconfig"):
        editorconfig_filepath = filepath

        if editorconfig_filepath == "-":
            if outfile != "stdout":
                editorconfig_filepath = outfile
            else:
                fileType = default_file_type
                editorconfig_filepath = "stdin." + fileType

        # debug("EditorConfig is enabled for ", editorconfig_filepath);
        local_options = copy.copy(local_options)
        set_file_editorconfig_opts(editorconfig_filepath, local_options)

    return local_options


def write_beautified_output(pretty, local_options, outfile):
    if outfile == "stdout":
        stream = sys.stdout

        # python automatically converts newlines in text to "\r\n" when on windows
        # switch to binary to prevent this
        if platform.platform().lower().startswith("windows"):
            if sys.version_info.major >= 3:
                # for python 3 on windows this prevents conversion
                stream = io.TextIOWrapper(sys.stdout.buffer, newline="")
            elif platform.architecture()[0] == "32bit":
                # for python 2 x86 on windows this prevents conversion
                import msvcrt

                msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
            else:
                raise Exception(
                    "Pipe to stdout not supported on Windows with Python 2.x 64-bit."
                )

        stream.write(pretty)
    else:
        if isFileDifferent(outfile, pretty):
            mkdir_p(os.path.dirname(outfile))

            # python automatically converts newlines in text to "\r\n" when on windows
            # set newline to empty to prevent this
            with io.open(outfile, "wt", newline="", encoding="UTF-8") as f:
                if not local_options.keep_quiet:
                    print("beautified " + outfile, file=sys.stdout)

                try:
                    f.write(pretty)
                except TypeError:
                    # This is not pretty, but given how we did the version import
                    # it is the only way to do this without having setup.py
                    # fail on a missing six dependency.
                    six = __import__("six")
                    f.write(six.u(pretty))
        elif not local_options.keep_quiet:
            print("beautified " + outfile + " - unchanged", file=sys.stdout)