コード例 #1
0
ファイル: yapf_test.py プロジェクト: xiangjian123/yapf
    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)
コード例 #2
0
  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)
コード例 #3
0
ファイル: yapf_test.py プロジェクト: yashbathia/yapf
  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)
コード例 #4
0
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
コード例 #5
0
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
コード例 #6
0
ファイル: __init__.py プロジェクト: zofuthan/yapf
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)
コード例 #7
0
ファイル: __init__.py プロジェクト: wilsenock220/pitches
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
コード例 #8
0
 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)
コード例 #9
0
 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)
コード例 #10
0
 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)
コード例 #11
0
 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)
コード例 #12
0
ファイル: yapf_test.py プロジェクト: xiangjian123/yapf
    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)
コード例 #13
0
    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)
コード例 #14
0
 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)
コード例 #15
0
 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)
コード例 #16
0
 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)
コード例 #17
0
  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)
コード例 #18
0
 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)
コード例 #19
0
  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)
コード例 #20
0
  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)
コード例 #21
0
ファイル: __init__.py プロジェクト: yuvrajm/yapf
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
コード例 #22
0
ファイル: yapf_test.py プロジェクト: BrianOmbega/To-Do-list
 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)
コード例 #23
0
    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)
コード例 #24
0
  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)
コード例 #25
0
  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)
コード例 #26
0
ファイル: yapf_test.py プロジェクト: xiangjian123/yapf
    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)
コード例 #27
0
ファイル: yapf_test.py プロジェクト: xiangjian123/yapf
    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)
コード例 #28
0
    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)
コード例 #29
0
  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)
コード例 #30
0
  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)