]>
Commit | Line | Data |
---|---|---|
53e6db90 DC |
1 | """Glue for the "yapf" library. |
2 | ||
3 | """ | |
4 | ||
5 | import os | |
6 | import sys | |
7 | ||
8 | from elpy.rpc import Fault | |
9 | ||
10 | YAPF_NOT_SUPPORTED = sys.version_info < (2, 7) or ( | |
11 | sys.version_info >= (3, 0) and sys.version_info < (3, 4)) | |
12 | ||
13 | try: | |
14 | if YAPF_NOT_SUPPORTED: | |
15 | yapf_api = None | |
16 | else: | |
17 | from yapf.yapflib import yapf_api | |
18 | from yapf.yapflib import file_resources | |
19 | except ImportError: # pragma: no cover | |
20 | yapf_api = None | |
21 | ||
22 | ||
23 | def fix_code(code, directory): | |
24 | """Formats Python code to conform to the PEP 8 style guide. | |
25 | ||
26 | """ | |
27 | if not yapf_api: | |
28 | raise Fault('yapf not installed', code=400) | |
29 | style_config = file_resources.GetDefaultStyleForDir(directory or os.getcwd()) | |
30 | try: | |
31 | reformatted_source, _ = yapf_api.FormatCode(code, | |
32 | filename='<stdin>', | |
33 | style_config=style_config, | |
34 | verify=False) | |
35 | return reformatted_source | |
36 | except Exception as e: | |
37 | raise Fault("Error during formatting: {}".format(e), | |
38 | code=400) |