def testFormatFileLinesSelection(self): unformatted_code = textwrap.dedent(u"""\ if a: b if f: g if h: i """) expected_formatted_code_lines1and2 = textwrap.dedent(u"""\ if a: b if f: g if h: i """) expected_formatted_code_lines3 = textwrap.dedent(u"""\ if a: b if f: g if h: i """) with utils.TempFileContents(self.test_tmpdir, unformatted_code) as filepath: formatted_code, _, _ = yapf_api.FormatFile(filepath, style_config='pep8', lines=[(1, 2)]) self.assertCodeEqual(expected_formatted_code_lines1and2, formatted_code) formatted_code, _, _ = yapf_api.FormatFile(filepath, style_config='pep8', lines=[(3, 3)]) self.assertCodeEqual(expected_formatted_code_lines3, formatted_code)
def testFormatFileLinesSelection(self): unformatted_code = textwrap.dedent(u"""\ if a: b if f: g if h: i """) file1 = self._MakeTempFileWithContents('testfile1.py', unformatted_code) expected_formatted_code_lines1and2 = textwrap.dedent(u"""\ if a: b if f: g if h: i """) formatted_code = yapf_api.FormatFile( file1, style_config='pep8', lines=[(1, 2)])[0] self.assertCodeEqual(expected_formatted_code_lines1and2, formatted_code) expected_formatted_code_lines3 = textwrap.dedent(u"""\ if a: b if f: g if h: i """) formatted_code = yapf_api.FormatFile( file1, style_config='pep8', lines=[(3, 3)])[0] self.assertCodeEqual(expected_formatted_code_lines3, formatted_code)
def testDisablePartOfMultilineComment(self): unformatted_code = textwrap.dedent(u"""\ if a: b # This is a multiline comment that disables YAPF. # yapf: disable if f: g # yapf: enable # This is a multiline comment that enables YAPF. if h: i """) file1 = self._MakeTempFileWithContents('testfile1.py', unformatted_code) expected_formatted_code = textwrap.dedent(u"""\ if a: b # This is a multiline comment that disables YAPF. # yapf: disable if f: g # yapf: enable # This is a multiline comment that enables YAPF. if h: i """) formatted_code = yapf_api.FormatFile(file1, style_config='pep8')[0] self.assertCodeEqual(expected_formatted_code, formatted_code)
def _FormatFile(filename, lines, style_config=None, no_local_style=False, in_place=False, print_diff=False, verify=True): logging.info('Reformatting %s', filename) if style_config is None and not no_local_style: style_config = ( file_resources.GetDefaultStyleForDir(os.path.dirname(filename))) try: reformatted_code, encoding, has_change = yapf_api.FormatFile( filename, in_place=in_place, style_config=style_config, lines=lines, print_diff=print_diff, verify=verify, logger=logging.warning) if not in_place and reformatted_code: file_resources.WriteReformattedCode(filename, reformatted_code, in_place, encoding) return has_change except SyntaxError as e: e.filename = filename raise
def _FormatFile(filename, lines, style_config=None, no_local_style=False, in_place=False, print_diff=False, verify=False, quiet=False, verbose=False): """Format an individual file.""" if verbose and not quiet: print('Reformatting %s' % filename) if style_config is None and not no_local_style: style_config = file_resources.GetDefaultStyleForDir( os.path.dirname(filename)) try: reformatted_code, encoding, has_change = yapf_api.FormatFile( filename, in_place=in_place, style_config=style_config, lines=lines, print_diff=print_diff, verify=verify, logger=logging.warning) except errors.YapfError: raise except Exception as e: raise errors.YapfError(errors.FormatErrorMsg(e)) if not in_place and not quiet and reformatted_code: file_resources.WriteReformattedCode(filename, reformatted_code, encoding, in_place) return has_change
def FormatFiles(filenames, lines, style_config=None, in_place=False, print_diff=False, verify=True): """Format a list of files. Arguments: filenames: (list of unicode) A list of files to reformat. lines: (list of tuples of integers) A list of tuples of lines, [start, end], that we want to format. The lines are 1-based indexed. This argument overrides the 'args.lines'. It can be used by third-party code (e.g., IDEs) when reformatting a snippet of code. style_config: (string) Style name or file path. in_place: (bool) Modify the files in place. print_diff: (bool) Instead of returning the reformatted source, return a diff that turns the formatted source into reformatter source. verify: (bool) True if reformatted code should be verified for syntax. """ for filename in filenames: logging.info('Reformatting %s', filename) reformatted_code = yapf_api.FormatFile(filename, style_config=style_config, lines=lines, print_diff=print_diff, verify=verify) if reformatted_code is not None: file_resources.WriteReformattedCode(filename, reformatted_code, in_place)
def _FormatFile(filename, lines, style_config=None, no_local_style=False, in_place=False, print_diff=False, verify=False, verbose=False): """Format an individual file.""" if verbose: print('Reformatting %s' % filename) if style_config is None and not no_local_style: style_config = file_resources.GetDefaultStyleForDir( os.path.dirname(filename)) try: reformatted_code, encoding, has_change = yapf_api.FormatFile( filename, in_place=in_place, style_config=style_config, lines=lines, print_diff=print_diff, verify=verify, logger=logging.warning) if not in_place and reformatted_code: file_resources.WriteReformattedCode(filename, reformatted_code, encoding, in_place) return has_change except tokenize.TokenError as e: raise errors.YapfError('%s:%s:%s' % (filename, e.args[1][0], e.args[0])) except SyntaxError as e: e.filename = filename raise
def testDisabledSemiColonSeparatedStatements(self): code = textwrap.dedent(u"""\ # yapf: disable if True: a ; b """) with utils.TempFileContents(self.test_tmpdir, code) as filepath: formatted_code, _, _ = yapf_api.FormatFile(filepath, style_config='pep8') self.assertCodeEqual(code, formatted_code)
def testFormatFileDiff(self): unformatted_code = textwrap.dedent(u"""\ if True: pass """) file1 = self._MakeTempFileWithContents('testfile1.py', unformatted_code) diff = yapf_api.FormatFile(file1, print_diff=True)[0] self.assertTrue(u'+ pass' in diff)
def testFormatFileDiff(self): unformatted_code = textwrap.dedent(u"""\ if True: pass """) with utils.TempFileContents(self.test_tmpdir, unformatted_code) as filepath: diff, _, _ = yapf_api.FormatFile(filepath, print_diff=True) self.assertTrue(u'+ pass' in diff)
def testDisabledSemiColonSeparatedStatements(self): code = textwrap.dedent("""\ # yapf: disable if True: a ; b """) file1 = self._MakeTempFileWithContents('testfile1.py', code) formatted_code = yapf_api.FormatFile(file1, style_config='pep8')[0] self.assertCodeEqual(code, formatted_code)
def testDisablePartOfMultilineComment(self): unformatted_code = textwrap.dedent(u"""\ if a: b # This is a multiline comment that disables YAPF. # yapf: disable if f: g # yapf: enable # This is a multiline comment that enables YAPF. if h: i """) expected_formatted_code = textwrap.dedent(u"""\ if a: b # This is a multiline comment that disables YAPF. # yapf: disable if f: g # yapf: enable # This is a multiline comment that enables YAPF. if h: i """) with utils.TempFileContents(self.test_tmpdir, unformatted_code) as filepath: formatted_code, _, _ = yapf_api.FormatFile(filepath, style_config='pep8') self.assertCodeEqual(expected_formatted_code, formatted_code) code = textwrap.dedent(u"""\ def foo_function(): # some comment # yapf: disable foo( bar, baz ) # yapf: enable """) with utils.TempFileContents(self.test_tmpdir, code) as filepath: formatted_code, _, _ = yapf_api.FormatFile(filepath, style_config='pep8') self.assertCodeEqual(code, formatted_code)
def testDisablePartOfMultilineComment(self): unformatted_code = textwrap.dedent("""\ if a: b # This is a multiline comment that disables YAPF. # yapf: disable if f: g # yapf: enable # This is a multiline comment that enables YAPF. if h: i """) f = self._MakeTempFileWithContents('testfile1.py', unformatted_code) expected_formatted_code = textwrap.dedent("""\ if a: b # This is a multiline comment that disables YAPF. # yapf: disable if f: g # yapf: enable # This is a multiline comment that enables YAPF. if h: i """) formatted_code, _, _ = yapf_api.FormatFile(f, style_config='pep8') self.assertCodeEqual(expected_formatted_code, formatted_code) code = textwrap.dedent("""\ def foo_function(): # some comment # yapf: disable foo( bar, baz ) # yapf: enable """) f = self._MakeTempFileWithContents('testfile1.py', code) formatted_code, _, _ = yapf_api.FormatFile(f, style_config='pep8') self.assertCodeEqual(code, formatted_code)
def testDisabledHorizontalFormattingOnNewLine(self): code = textwrap.dedent(u"""\ # yapf: disable a = [ 1] # yapf: enable """) with utils.TempFileContents(self.test_tmpdir, code) as filepath: formatted_code, _, _ = yapf_api.FormatFile(filepath, style_config='pep8') self.assertCodeEqual(code, formatted_code)
def testDisabledHorizontalFormattingOnNewLine(self): code = textwrap.dedent("""\ # yapf: disable a = [ 1] # yapf: enable """) file1 = self._MakeTempFileWithContents('testfile1.py', code) formatted_code = yapf_api.FormatFile(file1, style_config='pep8')[0] self.assertCodeEqual(code, formatted_code)
def testCommentsUnformatted(self): code = textwrap.dedent(u"""\ foo = [# A list of things # bork 'one', # quark 'two'] # yapf: disable """) with utils.TempFileContents(self.test_tmpdir, code) as filepath: formatted_code, _, _ = yapf_api.FormatFile(filepath, style_config='pep8') self.assertCodeEqual(code, formatted_code)
def testFormatFile(self): unformatted_code = textwrap.dedent(u"""\ if True: pass """) expected_formatted_code_pep8 = textwrap.dedent(u"""\ if True: pass """) expected_formatted_code_chromium = textwrap.dedent(u"""\ if True: pass """) with utils.TempFileContents(self.test_tmpdir, unformatted_code) as filepath: formatted_code, _, _ = yapf_api.FormatFile(filepath, style_config='pep8') self.assertCodeEqual(expected_formatted_code_pep8, formatted_code) formatted_code, _, _ = yapf_api.FormatFile( filepath, style_config='chromium') self.assertCodeEqual(expected_formatted_code_chromium, formatted_code)
def testCommentsUnformatted(self): code = textwrap.dedent("""\ foo = [# A list of things # bork 'one', # quark 'two'] # yapf: disable """) file1 = self._MakeTempFileWithContents('testfile1.py', code) formatted_code = yapf_api.FormatFile(file1, style_config='pep8')[0] self.assertCodeEqual(code, formatted_code)
def testFormatFileInPlace(self): unformatted_code = 'True==False\n' formatted_code = 'True == False\n' file1 = self._MakeTempFileWithContents('testfile1.py', unformatted_code) result, _, _ = yapf_api.FormatFile(file1, in_place=True) self.assertEqual(result, None) with open(file1) as f: self.assertCodeEqual(formatted_code, f.read()) self.assertRaises( ValueError, yapf_api.FormatFile, file1, in_place=True, print_diff=True)
def testFormatFile(self): unformatted_code = textwrap.dedent(u"""\ if True: pass """) file1 = self._MakeTempFileWithContents('testfile1.py', unformatted_code) expected_formatted_code_pep8 = textwrap.dedent(u"""\ if True: pass """) expected_formatted_code_chromium = textwrap.dedent(u"""\ if True: pass """) formatted_code = yapf_api.FormatFile(file1, style_config='pep8')[0] self.assertCodeEqual(expected_formatted_code_pep8, formatted_code) formatted_code = yapf_api.FormatFile(file1, style_config='chromium')[0] self.assertCodeEqual(expected_formatted_code_chromium, formatted_code)
def FormatFiles(filenames, lines, style_config=None, no_local_style=False, in_place=False, print_diff=False, verify=True): """Format a list of files. Arguments: filenames: (list of unicode) A list of files to reformat. lines: (list of tuples of integers) A list of tuples of lines, [start, end], that we want to format. The lines are 1-based indexed. This argument overrides the 'args.lines'. It can be used by third-party code (e.g., IDEs) when reformatting a snippet of code. style_config: (string) Style name or file path. no_local_style: (string) If style_config is None don't search for directory-local style configuration. in_place: (bool) Modify the files in place. print_diff: (bool) Instead of returning the reformatted source, return a diff that turns the formatted source into reformatter source. verify: (bool) True if reformatted code should be verified for syntax. Returns: True if the source code changed in any of the files being formatted. """ changed = False for filename in filenames: logging.info('Reformatting %s', filename) if style_config is None and not no_local_style: style_config = ( file_resources.GetDefaultStyleForDir(os.path.dirname(filename))) try: reformatted_code, encoding, has_change = yapf_api.FormatFile( filename, in_place=in_place, style_config=style_config, lines=lines, print_diff=print_diff, verify=verify, logger=logging.warning) if has_change and reformatted_code is not None: file_resources.WriteReformattedCode(filename, reformatted_code, in_place, encoding) changed |= has_change except SyntaxError as e: e.filename = filename raise return changed
def testSemicolonStatementsDisabled(self): unformatted_code = textwrap.dedent(u"""\ def f(): x = y + 42 ; z = n * 42 # yapf: disable if True: a += 1 ; b += 1; c += 1 """) expected_formatted_code = textwrap.dedent(u"""\ def f(): x = y + 42 ; z = n * 42 # yapf: disable if True: a += 1 b += 1 c += 1 """) with utils.TempFileContents(self.test_tmpdir, unformatted_code) as filepath: formatted_code, _, _ = yapf_api.FormatFile(filepath, style_config='pep8') self.assertCodeEqual(expected_formatted_code, formatted_code)
def testDisabledWithPrecedingText(self): code = textwrap.dedent("""\ # TODO(fix formatting): yapf: disable A = [ { "aaaaaaaaaaaaaaaaaaa": ''' bbbbbbbbbbb: "ccccccccccc" dddddddddddddd: 1 eeeeeeee: 0 ffffffffff: "ggggggg" ''', }, ] """) f = self._MakeTempFileWithContents('testfile1.py', code) formatted_code, _, _ = yapf_api.FormatFile(f, style_config='chromium') self.assertCodeEqual(code, formatted_code)
def testDisabledMultilineStringInDictionary(self): code = textwrap.dedent("""\ # yapf: disable A = [ { "aaaaaaaaaaaaaaaaaaa": ''' bbbbbbbbbbb: "ccccccccccc" dddddddddddddd: 1 eeeeeeee: 0 ffffffffff: "ggggggg" ''', }, ] """) file1 = self._MakeTempFileWithContents('testfile1.py', code) formatted_code = yapf_api.FormatFile(file1, style_config='chromium')[0] self.assertCodeEqual(code, formatted_code)
def testFormatFileInPlace(self): unformatted_code = u'True==False\n' formatted_code = u'True == False\n' with utils.TempFileContents(self.test_tmpdir, unformatted_code) as filepath: result, _, _ = yapf_api.FormatFile(filepath, in_place=True) self.assertEqual(result, None) with open(filepath) as fd: if sys.version_info[0] <= 2: self.assertCodeEqual(formatted_code, fd.read().decode('ascii')) else: self.assertCodeEqual(formatted_code, fd.read()) self.assertRaises( ValueError, yapf_api.FormatFile, filepath, in_place=True, print_diff=True)
def testDisabledWithPrecedingText(self): code = textwrap.dedent(u"""\ # TODO(fix formatting): yapf: disable A = [ { "aaaaaaaaaaaaaaaaaaa": ''' bbbbbbbbbbb: "ccccccccccc" dddddddddddddd: 1 eeeeeeee: 0 ffffffffff: "ggggggg" ''', }, ] """) with utils.TempFileContents(self.test_tmpdir, code) as filepath: formatted_code, _, _ = yapf_api.FormatFile(filepath, style_config='chromium') self.assertCodeEqual(code, formatted_code)
def testDisabledMultilineStringInDictionary(self): code = textwrap.dedent(u"""\ # yapf: disable A = [ { "aaaaaaaaaaaaaaaaaaa": ''' bbbbbbbbbbb: "ccccccccccc" dddddddddddddd: 1 eeeeeeee: 0 ffffffffff: "ggggggg" ''', }, ] """) with utils.TempFileContents(self.test_tmpdir, code) as filepath: formatted_code, _, _ = yapf_api.FormatFile(filepath, style_config='chromium') self.assertCodeEqual(code, formatted_code)
def test(self): for test_path, expected_path in self.__get_test_sets(): test_name = os.path.basename(test_path) with self.subTest(msg=test_name): test = yapf_api.FormatFile(test_path)[0] test = test.replace(WINDOWS_EOL, UNIX_EOL) expected = self.__read_source(expected_path) # test checks warnings (stderr) if self.WARN in test_name: expected_warn = re.sub('filename.*,', '', expected) real_warn = re.sub('filename.*,', '', sys.stderr.get) self.assertCodeEqual(expected_warn, real_warn) # test checks fixes if self.INCORRECT in test_name: self.assertCodeEqual(expected, test)
def testDisableLinesPattern(self): unformatted_code = textwrap.dedent(u"""\ if a: b # yapf: disable if f: g if h: i """) expected_formatted_code = textwrap.dedent(u"""\ if a: b # yapf: disable if f: g if h: i """) with utils.TempFileContents(self.test_tmpdir, unformatted_code) as filepath: formatted_code, _, _ = yapf_api.FormatFile(filepath, style_config='pep8') self.assertCodeEqual(expected_formatted_code, formatted_code)
def testDisableLinesPattern(self): unformatted_code = textwrap.dedent(u"""\ if a: b # yapf: disable if f: g if h: i """) file1 = self._MakeTempFileWithContents('testfile1.py', unformatted_code) expected_formatted_code = textwrap.dedent(u"""\ if a: b # yapf: disable if f: g if h: i """) formatted_code = yapf_api.FormatFile(file1, style_config='pep8')[0] self.assertCodeEqual(expected_formatted_code, formatted_code)