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 return FormatCode(source_code, style_config=options.style, lines=line_ranges) 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
def _init_options(self, options, cwd): from os import getcwd self.cwd = cwd or getcwd() # pep8radius specific options from pep8radius.main import parse_args self.options = options if options else parse_args(['']) self.verbose = self.options.verbose self.in_place = self.options.in_place self.diff = self.options.diff self.color = not self.options.no_color # autopep8 specific options self.options.verbose = max(0, self.options.verbose - 1) self.options.in_place = False self.options.diff = False
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