]>
crepu.dev Git - config.git/blob - djavu-asus/elpa/elpy-20230803.1455/elpy/blackutil.py
1 """Glue for the "black" library.
7 from elpy
.rpc
import Fault
8 # in case pkg_resources is not properly installed
9 # (see https://github.com/jorgenschaefer/elpy/issues/1674).
11 from pkg_resources
import parse_version
12 except ImportError: # pragma: no cover
13 def parse_version(*arg
, **kwargs
):
14 raise Fault("`pkg_resources` could not be imported, "
15 "please reinstall Elpy RPC virtualenv with"
16 " `M-x elpy-rpc-reinstall-virtualenv`", code
=400)
26 BLACK_NOT_SUPPORTED
= sys
.version_info
< (3, 6)
29 if BLACK_NOT_SUPPORTED
: # pragma: no cover
33 current_version
= parse_version(black
.__version
__)
34 if current_version
>= parse_version("21.5b1"):
35 from black
.files
import find_pyproject_toml
36 elif current_version
>= parse_version("20.8b0"):
37 from black
import find_pyproject_toml
39 find_pyproject_toml
= None
41 except ImportError: # pragma: no cover
45 def fix_code(code
, directory
):
46 """Formats Python code to conform to the PEP 8 style guide.
50 raise Fault("black not installed", code
=400)
51 # Get black config from pyproject.toml
52 line_length
= black
.DEFAULT_LINE_LENGTH
53 string_normalization
= True
54 if find_pyproject_toml
:
55 pyproject_path
= find_pyproject_toml((directory
,))
57 pyproject_path
= os
.path
.join(directory
, "pyproject.toml")
58 if toml
and pyproject_path
and os
.path
.exists(pyproject_path
):
59 pyproject_config
= toml
.load(pyproject_path
)
60 black_config
= pyproject_config
.get("tool", {}).get("black", {})
61 if "line-length" in black_config
:
62 line_length
= black_config
["line-length"]
63 if "skip-string-normalization" in black_config
:
64 string_normalization
= not black_config
["skip-string-normalization"]
66 if parse_version(black
.__version
__) < parse_version("19.0"):
67 reformatted_source
= black
.format_file_contents(
68 src_contents
=code
, line_length
=line_length
, fast
=False)
71 line_length
=line_length
,
72 string_normalization
=string_normalization
)
73 reformatted_source
= black
.format_file_contents(
74 src_contents
=code
, fast
=False, mode
=fm
)
75 return reformatted_source
76 except black
.NothingChanged
:
78 except Exception as e
:
79 raise Fault("Error during formatting: {}".format(e
), code
=400)