Python yapf.yapflib.yapf_api.FormatCode() Examples
The following are 18
code examples of yapf.yapflib.yapf_api.FormatCode().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
yapf.yapflib.yapf_api
, or try the search function
.
Example #1
Source File: gen_classes.py From zenpy with GNU General Public License v3.0 | 6 votes |
def process_specification_directory(glob_pattern, outfile_name, namespace, write_baseclass=True,): with open(os.path.join(options.out_path, outfile_name), 'w+') as out_file: paths = [p for p in glob.glob(os.path.join(options.spec_path, glob_pattern))] classes = list() func = functools.partial(process_file, namespace) with Pool() as pool: classes.extend(pool.map(func, paths)) print("Formatting...") formatted_code = FormatCode("\n".join(sorted(classes)))[0] if write_baseclass: header = BASE_CLASS else: header = "from zenpy.lib.api_objects import BaseObject\nimport dateutil.parser" out_file.write("\n\n\n".join((header, formatted_code)))
Example #2
Source File: core.py From poetry-setup with Apache License 2.0 | 6 votes |
def get_setup(self): # render template with self.setup_path.open(encoding='utf-8') as f: document = f.read() template = Environment().from_string(document) document = template.render( package=self.package, format_vcs=self._format_vcs, ) # format by yapf style = CreateGoogleStyle() document, _changed = FormatCode(document, style_config=style) # remove empty strings while '\n\n' in document: document = document.replace('\n\n', '\n') # format by autopep8 document = fix_code(document) return document
Example #3
Source File: formatters.py From ciocheck with MIT License | 6 votes |
def format_string(cls, old_contents): """Format file for use with task queue.""" # cmd_root is assigned to formatter inside format_task... ugly! style_config = os.path.join(cls.cmd_root, cls.config_file) # It might be tempting to use the "inplace" option to FormatFile, but # it doesn't do an atomic replace, which is dangerous, so don't use # it unless you submit a fix to yapf. (new_contents, changed) = FormatCode( old_contents, style_config=style_config) if platform.system() == 'Windows': # yapf screws up line endings on windows new_contents = new_contents.replace("\r\n", "\n") if len(old_contents) == 0: # Windows yapf seems to force a newline? I dunno new_contents = "" return old_contents, new_contents, 'utf-8'
Example #4
Source File: yapf_test.py From yapf with Apache License 2.0 | 5 votes |
def _Check(self, unformatted_code, expected_formatted_code): formatted_code, _ = yapf_api.FormatCode( unformatted_code, style_config='yapf') self.assertCodeEqual(expected_formatted_code, formatted_code)
Example #5
Source File: radius.py From pep8radius with MIT License | 5 votes |
def fix_code(source_code, line_ranges, options=None, verbose=0): '''Apply autopep8 over the line_ranges, returns the corrected code. Note: though this is not checked for line_ranges should not overlap. Example ------- >>> code = "def f( x ):\\n if True:\\n return 2*x" >>> print(fix_code(code, [(1, 1), (3, 3)])) def f(x): if True: return 2 * x ''' if options is None: from pep8radius.main import parse_args options = parse_args() if getattr(options, "yapf", False): from yapf.yapflib.yapf_api import FormatCode result = FormatCode(source_code, style_config=options.style, lines=line_ranges) # yapf<0.3 returns diff as str, >=0.3 returns a tuple of (diff, changed) return result[0] if isinstance(result, tuple) else result line_ranges = reversed(line_ranges) # Apply line fixes "up" the file (i.e. in reverse) so that # fixes do not affect changes we're yet to make. partial = source_code for start, end in line_ranges: partial = fix_line_range(partial, start, end, options) _maybe_print('.', end='', max_=1, verbose=verbose) _maybe_print('', max_=1, verbose=verbose) fixed = partial return fixed
Example #6
Source File: lab_black.py From nb_black with MIT License | 5 votes |
def _format_code(code): return FormatCode(code, style_config="facebook")[0]
Example #7
Source File: yapf_test.py From yapf with Apache License 2.0 | 5 votes |
def _Check(self, unformatted_code, expected_formatted_code): formatted_code, _ = yapf_api.FormatCode( unformatted_code, style_config=style.SetGlobalStyle(self._OwnStyle())) self.assertEqual(expected_formatted_code, formatted_code)
Example #8
Source File: yapf_test.py From yapf with Apache License 2.0 | 5 votes |
def _Check(self, unformatted_code, expected_formatted_code): formatted_code, _ = yapf_api.FormatCode( unformatted_code, style_config=style.SetGlobalStyle(self._OwnStyle())) self.assertCodeEqual(expected_formatted_code, formatted_code)
Example #9
Source File: yapf_test.py From yapf with Apache License 2.0 | 5 votes |
def _Check(self, unformatted_code, expected_formatted_code): formatted_code, _ = yapf_api.FormatCode( unformatted_code, style_config=style.SetGlobalStyle(self._OwnStyle())) self.assertEqual(expected_formatted_code, formatted_code)
Example #10
Source File: yapf_test.py From yapf with Apache License 2.0 | 5 votes |
def testBadCode(self): code = 'x = """hello\n' self.assertRaises(tokenize.TokenError, yapf_api.FormatCode, code)
Example #11
Source File: blank_line_calculator_test.py From yapf with Apache License 2.0 | 5 votes |
def testLinesRangeRemoveSome(self): unformatted_code = textwrap.dedent(u"""\ def A(): pass def B(): # 7 pass # 8 def C(): pass """) expected_formatted_code = textwrap.dedent(u"""\ def A(): pass def B(): # 7 pass # 8 def C(): pass """) code, changed = yapf_api.FormatCode(unformatted_code, lines=[(6, 9)]) self.assertCodeEqual(expected_formatted_code, code) self.assertTrue(changed)
Example #12
Source File: blank_line_calculator_test.py From yapf with Apache License 2.0 | 5 votes |
def testLinesRangeRemove(self): unformatted_code = textwrap.dedent(u"""\ def A(): pass def B(): # 6 pass # 7 def C(): pass """) expected_formatted_code = textwrap.dedent(u"""\ def A(): pass def B(): # 6 pass # 7 def C(): pass """) code, changed = yapf_api.FormatCode(unformatted_code, lines=[(5, 9)]) self.assertCodeEqual(expected_formatted_code, code) self.assertTrue(changed)
Example #13
Source File: blank_line_calculator_test.py From yapf with Apache License 2.0 | 5 votes |
def testLinesRangeBoundaryNotOutside(self): unformatted_code = textwrap.dedent(u"""\ def A(): pass def B(): # 6 pass # 7 def C(): pass """) expected_formatted_code = textwrap.dedent(u"""\ def A(): pass def B(): # 6 pass # 7 def C(): pass """) code, changed = yapf_api.FormatCode(unformatted_code, lines=[(6, 7)]) self.assertCodeEqual(expected_formatted_code, code) self.assertFalse(changed)
Example #14
Source File: blank_line_calculator_test.py From yapf with Apache License 2.0 | 5 votes |
def testLinesOnRangeBoundary(self): unformatted_code = textwrap.dedent(u"""\ def A(): pass def B(): # 4 pass # 5 def C(): pass def D(): # 9 pass # 10 def E(): pass """) expected_formatted_code = textwrap.dedent(u"""\ def A(): pass def B(): # 4 pass # 5 def C(): pass def D(): # 9 pass # 10 def E(): pass """) code, changed = yapf_api.FormatCode( unformatted_code, lines=[(4, 5), (9, 10)]) self.assertCodeEqual(expected_formatted_code, code) self.assertTrue(changed)
Example #15
Source File: ext2md.py From chaostoolkit-documentation with Apache License 2.0 | 5 votes |
def exported_function_info(mod, mod_name, func_name) -> Dict[str, Any]: func = getattr(mod, func_name) sig = inspect.signature(func) activity_type = "" mod_lastname = mod_name.rsplit(".", 1)[1] if mod_lastname == "actions": activity_type = "action" elif mod_lastname == "probes": activity_type = "probe" elif mod_lastname == "tolerances": activity_type = "tolerance" args = build_signature_info(sig) return_type = build_return_type_info(sig) as_json = called_without_args_info( args, mod_name, func_name, activity_type) s = '' try: s = FormatCode("def {}{}:pass".format(func_name, str(sig)))[0] except Exception: print('Failed to format {} in {}'.format(func_name, mod_name)) d = inspect.getdoc(func) or "" d = d.replace(" ", "") d = d.replace("Parameters", "").replace("--------", "") d = d.replace("Examples", "").replace("----------", "") return { "type": activity_type, "module": mod_name, "name": func_name, "doc": d, "return": return_type, "signature": s, "arguments": args, "as_json": json.dumps(as_json, indent=2), "as_yaml": yaml.dump(as_json, default_flow_style=False) }
Example #16
Source File: generator.py From fake-bpy-module with MIT License | 5 votes |
def format(self, style_config: str): self._code_data = FormatCode(self._code_data, style_config=style_config)[0]
Example #17
Source File: events.py From olympe with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _format_olympe_dsl(code): try: return FormatCode(code, style_config=_olympe_dsl_style)[0] except Exception: # Fallback, return unformatted olympe dsl code return code
Example #18
Source File: formatters.py From jupyterlab_code_formatter with MIT License | 5 votes |
def format_code(self, code: str, notebook: bool, **options) -> str: from yapf.yapflib.yapf_api import FormatCode return FormatCode(code, **options)[0]