"Fossies" - the Fresh Open Source Software Archive

Member "js-beautify-1.14.0/python/jsbeautifier/cli/__init__.py" (14 Jun 2021, 8722 Bytes) of package /linux/www/js-beautify-1.14.0.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. See also the latest Fossies "Diffs" side-by-side code changes report for "__init__.py": 1.13.13_vs_1.14.0.

    1 from __future__ import print_function
    2 import sys
    3 import os
    4 import platform
    5 import io
    6 import getopt
    7 import re
    8 import string
    9 import errno
   10 import copy
   11 import glob
   12 from jsbeautifier.__version__ import __version__
   13 from jsbeautifier.javascript.options import BeautifierOptions
   14 from jsbeautifier.javascript.beautifier import Beautifier
   15 
   16 #
   17 # The MIT License (MIT)
   18 
   19 # Copyright (c) 2007-2020 Einar Lielmanis, Liam Newman, and contributors.
   20 
   21 # Permission is hereby granted, free of charge, to any person
   22 # obtaining a copy of this software and associated documentation files
   23 # (the "Software"), to deal in the Software without restriction,
   24 # including without limitation the rights to use, copy, modify, merge,
   25 # publish, distribute, sublicense, and/or sell copies of the Software,
   26 # and to permit persons to whom the Software is furnished to do so,
   27 # subject to the following conditions:
   28 
   29 # The above copyright notice and this permission notice shall be
   30 # included in all copies or substantial portions of the Software.
   31 
   32 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
   33 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
   34 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
   35 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
   36 # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
   37 # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   38 # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
   39 # SOFTWARE.
   40 
   41 __all__ = [
   42     "MissingInputStreamError",
   43     "process_file",
   44     "get_filepaths_from_params",
   45     "integrate_editorconfig_options",
   46     "write_beautified_output",
   47 ]
   48 
   49 
   50 class MissingInputStreamError(Exception):
   51     pass
   52 
   53 
   54 def set_file_editorconfig_opts(filename, js_options):
   55     from editorconfig import get_properties, EditorConfigError
   56 
   57     try:
   58         _ecoptions = get_properties(os.path.abspath(filename))
   59 
   60         if _ecoptions.get("indent_style") == "tab":
   61             js_options.indent_with_tabs = True
   62         elif _ecoptions.get("indent_style") == "space":
   63             js_options.indent_with_tabs = False
   64 
   65         if _ecoptions.get("indent_size"):
   66             js_options.indent_size = int(_ecoptions["indent_size"])
   67 
   68         if _ecoptions.get("max_line_length"):
   69             if _ecoptions.get("max_line_length") == "off":
   70                 js_options.wrap_line_length = 0
   71             else:
   72                 js_options.wrap_line_length = int(_ecoptions["max_line_length"])
   73 
   74         if _ecoptions.get("insert_final_newline") == "true":
   75             js_options.end_with_newline = True
   76         elif _ecoptions.get("insert_final_newline") == "false":
   77             js_options.end_with_newline = False
   78 
   79         if _ecoptions.get("end_of_line"):
   80             if _ecoptions["end_of_line"] == "cr":
   81                 js_options.eol = "\r"
   82             elif _ecoptions["end_of_line"] == "lf":
   83                 js_options.eol = "\n"
   84             elif _ecoptions["end_of_line"] == "crlf":
   85                 js_options.eol = "\r\n"
   86 
   87     except EditorConfigError:
   88         # do not error on bad editor config
   89         print("Error loading EditorConfig.  Ignoring.", file=sys.stderr)
   90 
   91 
   92 def process_file(file_name, opts, beautify_code):
   93     input_string = ""
   94     if file_name == "-":  # stdin
   95         if sys.stdin.isatty():
   96             raise MissingInputStreamError()
   97 
   98         stream = sys.stdin
   99         if platform.platform().lower().startswith("windows"):
  100             if sys.version_info.major >= 3:
  101                 # for python 3 on windows this prevents conversion
  102                 stream = io.TextIOWrapper(sys.stdin.buffer, newline="")
  103             elif platform.architecture()[0] == "32bit":
  104                 # for python 2 x86 on windows this prevents conversion
  105                 import msvcrt
  106 
  107                 msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
  108             else:
  109                 raise Exception(
  110                     "Pipe to stdin not supported on Windows with Python 2.x 64-bit."
  111                 )
  112 
  113         input_string = stream.read()
  114 
  115         # if you pipe an empty string, that is a failure
  116         if input_string == "":
  117             raise MissingInputStreamError()
  118     else:
  119         stream = io.open(file_name, "rt", newline="", encoding="UTF-8")
  120         input_string = stream.read()
  121 
  122     return beautify_code(input_string, opts)
  123 
  124 
  125 def mkdir_p(path):
  126     try:
  127         if path:
  128             os.makedirs(path)
  129     except OSError as exc:  # Python >2.5
  130         if exc.errno == errno.EEXIST and os.path.isdir(path):
  131             pass
  132         else:
  133             raise Exception()
  134 
  135 
  136 def isFileDifferent(filepath, expected):
  137     try:
  138         return "".join(io.open(filepath, "rt", newline="").readlines()) != expected
  139     except BaseException:
  140         return True
  141 
  142 
  143 def get_filepaths_from_params(filepath_params, replace):
  144     filepaths = []
  145     if not filepath_params or (len(filepath_params) == 1 and filepath_params[0] == "-"):
  146         # default to stdin
  147         filepath_params = []
  148         filepaths.append("-")
  149 
  150     for filepath_param in filepath_params:
  151         # ignore stdin setting if files are specified
  152         if "-" == filepath_param:
  153             continue
  154 
  155         # Check if each literal filepath exists
  156         if os.path.isfile(filepath_param):
  157             filepaths.append(filepath_param)
  158         elif "*" in filepath_param or "?" in filepath_param:
  159             # handle globs
  160             # empty result is okay
  161             if sys.version_info.major == 2 or (
  162                 sys.version_info.major == 3 and sys.version_info.minor <= 4
  163             ):
  164                 if "**" in filepath_param:
  165                     raise Exception("Recursive globs not supported on Python <= 3.4.")
  166                 filepaths.extend(glob.glob(filepath_param))
  167             else:
  168                 filepaths.extend(glob.glob(filepath_param, recursive=True))
  169         else:
  170             # not a glob and not a file
  171             raise OSError(errno.ENOENT, os.strerror(errno.ENOENT), filepath_param)
  172 
  173     if len(filepaths) > 1:
  174         replace = True
  175     elif filepaths and filepaths[0] == "-":
  176         replace = False
  177 
  178     # remove duplicates
  179     filepaths = set(filepaths)
  180 
  181     return filepaths, replace
  182 
  183 
  184 def integrate_editorconfig_options(filepath, local_options, outfile, default_file_type):
  185     # Editorconfig used only on files, not stdin
  186     if getattr(local_options, "editorconfig"):
  187         editorconfig_filepath = filepath
  188 
  189         if editorconfig_filepath == "-":
  190             if outfile != "stdout":
  191                 editorconfig_filepath = outfile
  192             else:
  193                 fileType = default_file_type
  194                 editorconfig_filepath = "stdin." + fileType
  195 
  196         # debug("EditorConfig is enabled for ", editorconfig_filepath);
  197         local_options = copy.copy(local_options)
  198         set_file_editorconfig_opts(editorconfig_filepath, local_options)
  199 
  200     return local_options
  201 
  202 
  203 def write_beautified_output(pretty, local_options, outfile):
  204     if outfile == "stdout":
  205         stream = sys.stdout
  206 
  207         # python automatically converts newlines in text to "\r\n" when on windows
  208         # switch to binary to prevent this
  209         if platform.platform().lower().startswith("windows"):
  210             if sys.version_info.major >= 3:
  211                 # for python 3 on windows this prevents conversion
  212                 stream = io.TextIOWrapper(sys.stdout.buffer, newline="")
  213             elif platform.architecture()[0] == "32bit":
  214                 # for python 2 x86 on windows this prevents conversion
  215                 import msvcrt
  216 
  217                 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  218             else:
  219                 raise Exception(
  220                     "Pipe to stdout not supported on Windows with Python 2.x 64-bit."
  221                 )
  222 
  223         stream.write(pretty)
  224     else:
  225         if isFileDifferent(outfile, pretty):
  226             mkdir_p(os.path.dirname(outfile))
  227 
  228             # python automatically converts newlines in text to "\r\n" when on windows
  229             # set newline to empty to prevent this
  230             with io.open(outfile, "wt", newline="", encoding="UTF-8") as f:
  231                 if not local_options.keep_quiet:
  232                     print("beautified " + outfile, file=sys.stdout)
  233 
  234                 try:
  235                     f.write(pretty)
  236                 except TypeError:
  237                     # This is not pretty, but given how we did the version import
  238                     # it is the only way to do this without having setup.py
  239                     # fail on a missing six dependency.
  240                     six = __import__("six")
  241                     f.write(six.u(pretty))
  242         elif not local_options.keep_quiet:
  243             print("beautified " + outfile + " - unchanged", file=sys.stdout)