Exemple #1
0
  def testSetGlobalStyle(self):
    try:
      style.SetGlobalStyle(style.CreateChromiumStyle())
      unformatted_code = textwrap.dedent(u"""\
          for i in range(5):
           print('bar')
          """)
      expected_formatted_code = textwrap.dedent(u"""\
          for i in range(5):
            print('bar')
          """)
      uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
      self.assertCodeEqual(expected_formatted_code,
                           reformatter.Reformat(uwlines))
    finally:
      style.SetGlobalStyle(style.CreatePEP8Style())
      style.DEFAULT_STYLE = self.current_style

    unformatted_code = textwrap.dedent(u"""\
        for i in range(5):
         print('bar')
        """)
    expected_formatted_code = textwrap.dedent(u"""\
        for i in range(5):
            print('bar')
        """)
    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
  def testNoSplitBeforeFirstArgumentStyle2(self):
    try:
      pep8_no_split_before_first = style.CreatePEP8Style()
      pep8_no_split_before_first['SPLIT_BEFORE_FIRST_ARGUMENT'] = False
      pep8_no_split_before_first['SPLIT_BEFORE_NAMED_ASSIGNS'] = True
      style.SetGlobalStyle(pep8_no_split_before_first)
      formatted_code = textwrap.dedent("""\
          # Examples Issue#556
          i_take_a_lot_of_params(arg1,
                                 param1=very_long_expression1(),
                                 param2=very_long_expression2(),
                                 param3=very_long_expression3(),
                                 param4=very_long_expression4())

          # Examples Issue#590
          plt.plot(numpy.linspace(0, 1, 10),
                   numpy.linspace(0, 1, 10),
                   marker="x",
                   color="r")

          plt.plot(veryverylongvariablename,
                   veryverylongvariablename,
                   marker="x",
                   color="r")
          """)
      uwlines = yapf_test_helper.ParseAndUnwrap(formatted_code)
      self.assertCodeEqual(formatted_code, reformatter.Reformat(uwlines))
    finally:
      style.SetGlobalStyle(style.CreatePEP8Style())
      style.DEFAULT_STYLE = self.current_style
 def testSplittingBeforeLogicalOperator(self):
     try:
         style.SetGlobalStyle(
             style.CreateStyleFromConfig(
                 '{based_on_style: pep8, split_before_logical_operator: True}'
             ))
         unformatted_code = textwrap.dedent("""\
       def foo():
           return bool(update.message.new_chat_member or update.message.left_chat_member or
                       update.message.new_chat_title or update.message.new_chat_photo or
                       update.message.delete_chat_photo or update.message.group_chat_created or
                       update.message.supergroup_chat_created or update.message.channel_chat_created
                       or update.message.migrate_to_chat_id or update.message.migrate_from_chat_id or
                       update.message.pinned_message)
       """)
         expected_formatted_code = textwrap.dedent("""\
       def foo():
           return bool(
               update.message.new_chat_member or update.message.left_chat_member
               or update.message.new_chat_title or update.message.new_chat_photo
               or update.message.delete_chat_photo
               or update.message.group_chat_created
               or update.message.supergroup_chat_created
               or update.message.channel_chat_created
               or update.message.migrate_to_chat_id
               or update.message.migrate_from_chat_id
               or update.message.pinned_message)
       """)
         uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
         self.assertCodeEqual(expected_formatted_code,
                              reformatter.Reformat(uwlines))
     finally:
         style.SetGlobalStyle(style.CreatePEP8Style())
 def testB19372573(self):
     code = textwrap.dedent("""\
     def f():
         if a: return 42
         while True:
             if b: continue
             if c: break
         return 0
     """)
     uwlines = yapf_test_helper.ParseAndUnwrap(code)
     try:
         style.SetGlobalStyle(style.CreatePEP8Style())
         self.assertCodeEqual(code, reformatter.Reformat(uwlines))
     finally:
         style.SetGlobalStyle(style.CreateChromiumStyle())
    def testAwait(self):
        style.SetGlobalStyle(
            style.CreateStyleFromConfig('{space_inside_brackets: True}'))
        unformatted_code = textwrap.dedent("""\
      import asyncio
      import time

      @print_args
      async def slow_operation():
        await asyncio.sleep(1)
        # print("Slow operation {} complete".format(n))
        async def main():
          start = time.time()
          if (await get_html()):
            pass
      """)
        expected_formatted_code = textwrap.dedent("""\
      import asyncio
      import time


      @print_args
      async def slow_operation():
          await asyncio.sleep( 1 )

          # print("Slow operation {} complete".format(n))
          async def main():
              start = time.time()
              if ( await get_html() ):
                  pass
      """)
        uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
        self.assertCodeEqual(expected_formatted_code,
                             reformatter.Reformat(uwlines))
    def test_warn_location(self):
        style.SetGlobalStyle(
            style.CreateStyleFromConfig(
                f'{{based_on_style: pep8, '
                f'check_var_naming_style: snake_case, '
                f'column_limit: 30}}'))

        input_source = textwrap.dedent("""\
            if left > right or right > left: pass
            SomeVariable = 0

            def fn():
                ''' fn
                description
                '''
                pass

            OtherVar = fn()
        """)
        FormatCode(input_source)

        # one line added becaus the `if` statement was wrapped
        self.assertWarnMessage(warns.Warnings.VAR_NAMING_STYLE,
            pattern='.*SomeVariable', lineno=3)

        # two more line added as the style requires two blank lines
        # around top-level functions
        self.assertWarnMessage(warns.Warnings.VAR_NAMING_STYLE,
            pattern='.*OtherVar', lineno=13)
def _ParseAndUnwrap(code, dumptree=False):
    """Produces unwrapped lines from the given code.

  Parses the code into a tree, performs comment splicing and runs the
  unwrapper.

  Arguments:
    code: code to parse as a string
    dumptree: if True, the parsed pytree (after comment splicing) is dumped
      to stderr. Useful for debugging.

  Returns:
    List of unwrapped lines.
  """
    style.SetGlobalStyle(style.CreateGoogleStyle())
    tree = pytree_utils.ParseCodeToTree(code)
    comment_splicer.SpliceComments(tree)
    subtype_assigner.AssignSubtypes(tree)
    split_penalty.ComputeSplitPenalties(tree)
    blank_line_calculator.CalculateBlankLines(tree)

    if dumptree:
        pytree_visitor.DumpPyTree(tree, target_stream=sys.stderr)

    uwlines = pytree_unwrapper.UnwrapPyTree(tree)
    for uwl in uwlines:
        uwl.CalculateFormattingInformation()

    return uwlines
Exemple #8
0
 def testNoSpacesAroundPowerOparator(self):
   try:
     style.SetGlobalStyle(
         style.CreateStyleFromConfig(
             '{based_on_style: pep8, SPACES_AROUND_POWER_OPERATOR: True}'))
     unformatted_code = textwrap.dedent("""\
         a**b
         """)
     expected_formatted_code = textwrap.dedent("""\
         a ** b
         """)
     uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
     self.assertCodeEqual(expected_formatted_code,
                          reformatter.Reformat(uwlines))
   finally:
     style.SetGlobalStyle(style.CreatePEP8Style())
    def test_pseudo_parens(self):
        #
        # Check the second branch in `reformatter._FormatFinalLines()`.
        #
        # Ensure that `reformatted_lines` are correcly formed when
        # when the following conditions hold:
        #
        #    if tok.is_pseudo_paren:
        #        if (not tok.next_token.whitespace_prefix.startswith('\n') and
        #            not tok.next_token.whitespace_prefix.startswith(' ')):
        #          if (tok.previous_token.value == ':' or
        #              tok.next_token.value not in ',}])'):
        #              ...
        #

        style.SetGlobalStyle(
            style.CreateStyleFromConfig(
                f'{{based_on_style: pep8, '
                f'indent_dictionary_value: true}}'))

        input_text = textwrap.dedent("""\
            {'a':1}
        """)

        # should not raise any exception
        FormatCode(input_text, lines=[(10,10)])[0]
 def testSpacesAroundDefaultOrNamedAssign(self):
     try:
         style.SetGlobalStyle(
             style.CreateStyleFromConfig(
                 '{based_on_style: pep8, '
                 'SPACES_AROUND_DEFAULT_OR_NAMED_ASSIGN: True}'))
         unformatted_code = textwrap.dedent("""\
       f(a=5)
       """)
         expected_formatted_code = textwrap.dedent("""\
       f(a = 5)
       """)
         uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
         self.assertCodeEqual(expected_formatted_code,
                              reformatter.Reformat(uwlines))
     finally:
         style.SetGlobalStyle(style.CreatePEP8Style())
Exemple #11
0
def FormatCode(unformatted_source,
               filename='<unknown>',
               style_config=None,
               lines=None,
               print_diff=False,
               verify=False):
    """Format a string of Python code.

  This provides an alternative entry point to YAPF.

  Arguments:
    unformatted_source: (unicode) The code to format.
    filename: (unicode) The name of the file being reformatted.
    remaining arguments: see comment at the top of this module.

  Returns:
    Tuple of (reformatted_source, changed). reformatted_source conforms to the
    desired formatting style. changed is True if the source changed.
  """
    _CheckPythonVersion()
    style.SetGlobalStyle(style.CreateStyleFromConfig(style_config))
    if not unformatted_source.endswith('\n'):
        unformatted_source += '\n'

    try:
        tree = pytree_utils.ParseCodeToTree(unformatted_source)
    except parse.ParseError as e:
        e.msg = filename + ': ' + e.msg
        raise

    # Run passes on the tree, modifying it in place.
    comment_splicer.SpliceComments(tree)
    continuation_splicer.SpliceContinuations(tree)
    subtype_assigner.AssignSubtypes(tree)
    identify_container.IdentifyContainers(tree)
    split_penalty.ComputeSplitPenalties(tree)
    blank_line_calculator.CalculateBlankLines(tree)

    uwlines = pytree_unwrapper.UnwrapPyTree(tree)
    for uwl in uwlines:
        uwl.CalculateFormattingInformation()

    lines = _LineRangesToSet(lines)
    _MarkLinesToFormat(uwlines, lines)
    reformatted_source = reformatter.Reformat(_SplitSemicolons(uwlines),
                                              verify, lines)

    if unformatted_source == reformatted_source:
        return '' if print_diff else reformatted_source, False

    code_diff = _GetUnifiedDiff(unformatted_source,
                                reformatted_source,
                                filename=filename)

    if print_diff:
        return code_diff, code_diff.strip() != ''  # pylint: disable=g-explicit-bool-comparison

    return reformatted_source, True
    def testB20016122(self):
        try:
            style.SetGlobalStyle(
                style.CreateStyleFromConfig(
                    '{based_on_style: pep8, split_penalty_import_names: 35}'))
            unformatted_code = textwrap.dedent("""\
          from a_very_long_or_indented_module_name_yada_yada import (long_argument_1,
                                                                     long_argument_2)
          """)
            expected_formatted_code = textwrap.dedent("""\
          from a_very_long_or_indented_module_name_yada_yada import (
              long_argument_1, long_argument_2)
          """)
            uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
            self.assertCodeEqual(expected_formatted_code,
                                 reformatter.Reformat(uwlines))
        finally:
            style.SetGlobalStyle(style.CreatePEP8Style())

        try:
            style.SetGlobalStyle(
                style.CreateStyleFromConfig(
                    '{based_on_style: chromium, '
                    'split_before_logical_operator: True}'))
            code = textwrap.dedent("""\
          class foo():

            def __eq__(self, other):
              return (isinstance(other, type(self))
                      and self.xxxxxxxxxxx == other.xxxxxxxxxxx
                      and self.xxxxxxxx == other.xxxxxxxx
                      and self.aaaaaaaaaaaa == other.aaaaaaaaaaaa
                      and self.bbbbbbbbbbb == other.bbbbbbbbbbb
                      and self.ccccccccccccccccc == other.ccccccccccccccccc
                      and self.ddddddddddddddddddddddd == other.ddddddddddddddddddddddd
                      and self.eeeeeeeeeeee == other.eeeeeeeeeeee
                      and self.ffffffffffffff == other.time_completed
                      and self.gggggg == other.gggggg and self.hhh == other.hhh
                      and len(self.iiiiiiii) == len(other.iiiiiiii)
                      and all(jjjjjjj in other.iiiiiiii for jjjjjjj in self.iiiiiiii))
          """)
            uwlines = yapf_test_helper.ParseAndUnwrap(code)
            self.assertCodeEqual(code, reformatter.Reformat(uwlines))
        finally:
            style.SetGlobalStyle(style.CreateChromiumStyle())
    def testSpaceBetweenColonAndElipses(self):
        style.SetGlobalStyle(style.CreatePEP8Style())
        code = textwrap.dedent("""\
      class MyClass(ABC):

          place: ...
    """)
        llines = yapf_test_helper.ParseAndUnwrap(code)
        self.assertCodeEqual(code, reformatter.Reformat(llines, verify=False))
Exemple #14
0
 def __setup(self, enable):
     style.SetGlobalStyle(
         style.CreateStyleFromConfig(
             f'{{based_on_style: pep8, '
             f'should_have_encoding_header: {enable}}}'))
     input_source = textwrap.dedent("""\
                def foo():
                    pass
             """)
     FormatCode(input_source)
Exemple #15
0
    def testOperatorStyle(self):
        try:
            sympy_style = style.CreatePEP8Style()
            sympy_style['NO_SPACES_AROUND_SELECTED_BINARY_OPERATORS'] = \
              style._StringSetConverter('*,/')
            style.SetGlobalStyle(sympy_style)
            unformatted_code = textwrap.dedent("""\
          a = 1+2 * 3 - 4 / 5
          """)
            expected_formatted_code = textwrap.dedent("""\
          a = 1 + 2*3 - 4/5
          """)

            uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
            self.assertCodeEqual(expected_formatted_code,
                                 reformatter.Reformat(uwlines))
        finally:
            style.SetGlobalStyle(style.CreatePEP8Style())
            style.DEFAULT_STYLE = self.current_style
Exemple #16
0
  def testOperatorPrecedenceStyle(self):
    try:
      pep8_with_precedence = style.CreatePEP8Style()
      pep8_with_precedence['ARITHMETIC_PRECEDENCE_INDICATION'] = True
      style.SetGlobalStyle(pep8_with_precedence)
      unformatted_code = textwrap.dedent("""\
          1+2
          (1 + 2) * (3 - (4 / 5))
          a = 1 * 2 + 3 / 4
          b = 1 / 2 - 3 * 4
          c = (1 + 2) * (3 - 4)
          d = (1 - 2) / (3 + 4)
          e = 1 * 2 - 3
          f = 1 + 2 + 3 + 4
          g = 1 * 2 * 3 * 4
          h = 1 + 2 - 3 + 4
          i = 1 * 2 / 3 * 4
          j = (1 * 2 - 3) + 4
          k = (1 * 2 * 3) + (4 * 5 * 6 * 7 * 8)
          """)
      expected_formatted_code = textwrap.dedent("""\
          1 + 2
          (1+2) * (3 - (4/5))
          a = 1*2 + 3/4
          b = 1/2 - 3*4
          c = (1+2) * (3-4)
          d = (1-2) / (3+4)
          e = 1*2 - 3
          f = 1 + 2 + 3 + 4
          g = 1 * 2 * 3 * 4
          h = 1 + 2 - 3 + 4
          i = 1 * 2 / 3 * 4
          j = (1*2 - 3) + 4
          k = (1*2*3) + (4*5*6*7*8)
          """)

      uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
      self.assertCodeEqual(expected_formatted_code,
                           reformatter.Reformat(uwlines))
    finally:
      style.SetGlobalStyle(style.CreatePEP8Style())
      style.DEFAULT_STYLE = self.current_style
    def testSpaceBetweenDictColonAndElipses(self):
        style.SetGlobalStyle(style.CreatePEP8Style())
        unformatted_code = textwrap.dedent("""\
      {0:"...", 1:...}
    """)
        expected_formatted_code = textwrap.dedent("""\
      {0: "...", 1: ...}
    """)

        llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
        self.assertCodeEqual(expected_formatted_code,
                             reformatter.Reformat(llines))
    def testSplitBeforeArithmeticOperators(self):
        try:
            style.SetGlobalStyle(
                style.CreateStyleFromConfig(
                    '{based_on_style: pep8, split_before_arithmetic_operator: true}'
                ))

            unformatted_code = """\
def _():
    raise ValueError('This is a long message that ends with an argument: ' + str(42))
"""
            expected_formatted_code = """\
def _():
    raise ValueError('This is a long message that ends with an argument: '
                     + str(42))
"""
            uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
            self.assertCodeEqual(expected_formatted_code,
                                 reformatter.Reformat(uwlines))
        finally:
            style.SetGlobalStyle(style.CreatePEP8Style())
Exemple #19
0
 def testSplittingBeforeFirstArgument(self):
   try:
     style.SetGlobalStyle(
         style.CreateStyleFromConfig(
             '{based_on_style: pep8, split_before_first_argument: True}'))
     unformatted_code = textwrap.dedent("""\
         a_very_long_function_name(long_argument_name_1=1, long_argument_name_2=2,
                                   long_argument_name_3=3, long_argument_name_4=4)
         """)
     expected_formatted_code = textwrap.dedent("""\
         a_very_long_function_name(
             long_argument_name_1=1,
             long_argument_name_2=2,
             long_argument_name_3=3,
             long_argument_name_4=4)
         """)
     uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
     self.assertCodeEqual(expected_formatted_code,
                          reformatter.Reformat(uwlines))
   finally:
     style.SetGlobalStyle(style.CreatePEP8Style())
    def testNoBlankLineBeforeNestedFuncOrClass(self):
        try:
            style.SetGlobalStyle(
                style.CreateStyleFromConfig(
                    '{based_on_style: pep8, '
                    'blank_line_before_nested_class_or_def: false}'))

            unformatted_code = '''\
def normal_function():
    """Return the nested function."""

    def nested_function():
        """Do nothing just nest within."""

        @nested(klass)
        class nested_class():
            pass

        pass

    return nested_function
'''
            expected_formatted_code = '''\
def normal_function():
    """Return the nested function."""
    def nested_function():
        """Do nothing just nest within."""
        @nested(klass)
        class nested_class():
            pass

        pass

    return nested_function
'''
            uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
            self.assertCodeEqual(expected_formatted_code,
                                 reformatter.Reformat(uwlines))
        finally:
            style.SetGlobalStyle(style.CreatePEP8Style())
  def testNoSplitBeforeFirstArgumentStyle1(self):
    try:
      pep8_no_split_before_first = style.CreatePEP8Style()
      pep8_no_split_before_first['SPLIT_BEFORE_FIRST_ARGUMENT'] = False
      pep8_no_split_before_first['SPLIT_BEFORE_NAMED_ASSIGNS'] = False
      style.SetGlobalStyle(pep8_no_split_before_first)
      formatted_code = textwrap.dedent("""\
          # Example from in-code MustSplit comments
          foo = outer_function_call(fitting_inner_function_call(inner_arg1, inner_arg2),
                                    outer_arg1, outer_arg2)

          foo = outer_function_call(
              not_fitting_inner_function_call(inner_arg1, inner_arg2), outer_arg1,
              outer_arg2)

          # Examples Issue#424
          a_super_long_version_of_print(argument1, argument2, argument3, argument4,
                                        argument5, argument6, argument7)

          CREDS_FILE = os.path.join(os.path.expanduser('~'),
                                    'apis/super-secret-admin-creds.json')

          # Examples Issue#556
          i_take_a_lot_of_params(arg1, param1=very_long_expression1(),
                                 param2=very_long_expression2(),
                                 param3=very_long_expression3(),
                                 param4=very_long_expression4())

          # Examples Issue#590
          plt.plot(numpy.linspace(0, 1, 10), numpy.linspace(0, 1, 10), marker="x",
                   color="r")

          plt.plot(veryverylongvariablename, veryverylongvariablename, marker="x",
                   color="r")
          """)
      uwlines = yapf_test_helper.ParseAndUnwrap(formatted_code)
      self.assertCodeEqual(formatted_code, reformatter.Reformat(uwlines))
    finally:
      style.SetGlobalStyle(style.CreatePEP8Style())
      style.DEFAULT_STYLE = self.current_style
Exemple #22
0
def FormatCode(unformatted_source,
               filename='<unknown>',
               style_config=None,
               lines=None,
               print_diff=False):
  """Format a string of Python code.

  This provides an alternative entry point to YAPF.

  Arguments:
    unformatted_source: (unicode) The code to format.
    filename: (unicode) The name of the file being reformatted.
    style_config, lines, print_diff: see comment at the top of this module.

  Returns:
    The code reformatted to conform to the desired formatting style.
  """
  style.SetGlobalStyle(style.CreateStyleFromConfig(style_config))
  tree = pytree_utils.ParseCodeToTree(unformatted_source.rstrip() + '\n')

  # Run passes on the tree, modifying it in place.
  comment_splicer.SpliceComments(tree)
  subtype_assigner.AssignSubtypes(tree)
  split_penalty.ComputeSplitPenalties(tree)
  blank_line_calculator.CalculateBlankLines(tree)

  uwlines = pytree_unwrapper.UnwrapPyTree(tree)
  if not uwlines:
    return ''
  for uwl in uwlines:
    uwl.CalculateFormattingInformation()

  if lines is not None:
    reformatted_source = _FormatLineSnippets(unformatted_source, uwlines, lines)
  else:
    lines = _LinesToFormat(uwlines)
    if lines:
      reformatted_source = _FormatLineSnippets(unformatted_source, uwlines,
                                               lines)
    else:
      reformatted_source = reformatter.Reformat(uwlines)

  if unformatted_source == reformatted_source:
    return '' if print_diff else reformatted_source

  code_diff = _GetUnifiedDiff(unformatted_source, reformatted_source,
                              filename=filename)

  if print_diff:
    return code_diff

  return reformatted_source
    def __check_test(self, positive_case, formatted_code, option):
        style.SetGlobalStyle(
            style.CreateStyleFromConfig(f"{{based_on_style: pep8 "
                                        f"{option}: "
                                        f"{positive_case}}}"))
        unformatted_code = textwrap.dedent("""\
                        #!/usr/bin/python3 someopt
                        # -*- coding: utf-8 -*-
                        import some_module
                        # some comment                       
                        """)

        self.assertCodeEqual(formatted_code, FormatCode(unformatted_code)[0])
Exemple #24
0
    def __setup(self, enable):
        style.SetGlobalStyle(
            style.CreateStyleFromConfig(
                f'{{based_on_style: pep8, '
                f'should_not_have_wildcard_imports: {enable}}}'))

        unformatted_code = textwrap.dedent("""\
                        #!/usr/bin/env python
                        # -*- coding: utf-8 -*-
                        import some_module
                        # some comment                       
                        from module import *
                        """)
        FormatCode(unformatted_code)
    def __check_test(self, pos_case, formatted_code):
        style.SetGlobalStyle(
            style.CreateStyleFromConfig(f"{{based_on_style: pep8 "
                                        f"format_last_quote_doc_string:"
                                        f"  {pos_case}}}"))
        unformatted_code = textwrap.dedent("""\
                        # -*- coding: utf-8 -*-
                        \'\'\'
                        Function: all logic that is related with fixing style of docstring statements
                        Copyright Information: Huawei Technologies Co., Ltd. All Rights Reserved © 2010-2019
                        Change History: 2019-12-12 18:11 Created\'\'\'
                        """)

        self.assertCodeEqual(formatted_code, FormatCode(unformatted_code)[0])
Exemple #26
0
    def setUpClass(cls):
        # We could as well pass `style_config='huawei'` to `FormatFile()`
        # but configuring via `setUpClass()` is the way used in other tests
        # (such as "reformatter_facebook_test").
        # Besides, even if we did passed `style_config`, `FormatFile()`
        # would call the very same `style.SetGlobalStyle()` inside itself
        # anyway.
        #
        style.SetGlobalStyle(style.CreateHuaweiStyle())

        # resources' filenames do not fit any sound module naming rules
        # (it starts with a number), disable this option here
        #
        style.Set('CHECK_MODULE_NAMING_STYLE', False)
Exemple #27
0
def FormatCode(unformatted_source,
               filename='<unknown>',
               style_config=None,
               lines=None,
               print_diff=False,
               verify=True):
    """Format a string of Python code.

  This provides an alternative entry point to YAPF.

  Arguments:
    unformatted_source: (unicode) The code to format.
    filename: (unicode) The name of the file being reformatted.
    remaining arguments: see comment at the top of this module.

  Returns:
    The code reformatted to conform to the desired formatting style.
  """
    _CheckPythonVersion()
    style.SetGlobalStyle(style.CreateStyleFromConfig(style_config))
    if not unformatted_source.endswith('\n'):
        unformatted_source += '\n'
    tree = pytree_utils.ParseCodeToTree(unformatted_source)

    # Run passes on the tree, modifying it in place.
    comment_splicer.SpliceComments(tree)
    continuation_splicer.SpliceContinuations(tree)
    subtype_assigner.AssignSubtypes(tree)
    split_penalty.ComputeSplitPenalties(tree)
    blank_line_calculator.CalculateBlankLines(tree)

    uwlines = pytree_unwrapper.UnwrapPyTree(tree)
    for uwl in uwlines:
        uwl.CalculateFormattingInformation()

    _MarkLinesToFormat(uwlines, lines)
    reformatted_source = reformatter.Reformat(uwlines, verify)

    if unformatted_source == reformatted_source:
        return '' if print_diff else reformatted_source

    code_diff = _GetUnifiedDiff(unformatted_source,
                                reformatted_source,
                                filename=filename)

    if print_diff:
        return code_diff

    return reformatted_source
Exemple #28
0
def print_help(args):
    """Prints the help menu."""

    if args.style is None and not args.no_local_style:
        args.style = file_resources.GetDefaultStyleForDir(os.getcwd())
    style.SetGlobalStyle(style.CreateStyleFromConfig(args.style))
    print('[style]')
    for option, docstring in sorted(style.Help().items()):
        for line in docstring.splitlines():
            print('#', line and ' ' or '', line, sep='')
        option_value = style.Get(option)
        if isinstance(option_value, set) or isinstance(option_value, list):
            option_value = ', '.join(map(str, option_value))
        print(option.lower(), '=', option_value, sep='')
        print()
    def __check_test(self, pos_case, formatted_code):
        style.SetGlobalStyle(
            style.CreateStyleFromConfig(f"{{based_on_style: pep8 "
                                        f"blank_lines_after_indented_blocks: "
                                        f"{pos_case}}}"))
        unformatted_code = textwrap.dedent("""\
                        def f():
                            if True:
                                print("#1")
                            print("#2")
                        print("#3")
                        """)

        uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
        self.assertCodeEqual(formatted_code, reformatter.Reformat(uwlines))
Exemple #30
0
 def testDefault(self):
     style.SetGlobalStyle(style.CreatePEP8Style())
     expected_formatted_code = textwrap.dedent("""\
   a = list1[:]
   b = list2[slice_start:]
   c = list3[slice_start:slice_end]
   d = list4[slice_start:slice_end:]
   e = list5[slice_start:slice_end:slice_step]
   a1 = list1[:]
   b1 = list2[1:]
   c1 = list3[1:20]
   d1 = list4[1:20:]
   e1 = list5[1:20:3]
 """)
     uwlines = yapf_test_helper.ParseAndUnwrap(self.unformatted_code)
     self.assertCodeEqual(expected_formatted_code,
                          reformatter.Reformat(uwlines))