Repository: google/yapf
Pull request #430 (2017-07-28 22:27:27)

Fix formatting of vim code block.
The example code is omitted from the rendered output without the blank line.


Patch:
diff --git a/CHANGELOG b/CHANGELOG
index d7a465c..3a3ba8f 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -2,17 +2,9 @@
 # All notable changes to this project will be documented in this file.
 # This project adheres to [Semantic Versioning](http://semver.org/).
 
-## [0.17.0] Unreleased
-### Added
-- Option `NO_SPACES_AROUND_SELECTED_BINARY_OPERATORS` prevents adding spaces
-  around selected binary operators, in accordance with the current style guide.
+## [0.16.4] Unreleased
 ### Changed
 - Adjust blank lines on formatting boundaries when using the `--lines` option.
-- Return 1 if a diff changed the code. This is in line with how GNU diff acts.
-### Fixed
-- Corrected how `DEDENT_CLOSING_BRACKETS` and `COALESCE_BRACKETS` interacted.
-- Fix return value to return a boolean.
-- Correct vim plugin not to clobber edited code if yapf returns an error.
 
 ## [0.16.3] 2017-07-13
 ### Changed
diff --git a/README.rst b/README.rst
index 3ccf989..a05a072 100644
--- a/README.rst
+++ b/README.rst
@@ -399,19 +399,6 @@ Knobs
 ``SPACES_AROUND_POWER_OPERATOR``
     Set to ``True`` to prefer using spaces around ``**``.
 
-``NO_SPACES_AROUND_SELECTED_BINARY_OPERATORS``
-    Do not include spaces around selected binary operators. For example:
-
-    .. code-block:: python
-
-        1 + 2 * 3 - 4 / 5
-
-    will be formatted as follows when configured with a value ``"*,/"``:
-
-    .. code-block:: python
-
-        1 + 2*3 - 4/5
-
 ``SPACES_AROUND_DEFAULT_OR_NAMED_ASSIGN``
     Set to ``True`` to prefer spaces around the assignment operator for default
     or keyword arguments.
diff --git a/plugins/README.rst b/plugins/README.rst
index 6d458f7..7f24a9b 100644
--- a/plugins/README.rst
+++ b/plugins/README.rst
@@ -15,6 +15,7 @@ The ``vim`` plugin allows you to reformat a range of code. Place it into the
 ``.vim/autoload`` directory or use a plugin manager like Plug or Vundle:
 
 .. code-block:: vim
+
      " Plug
      Plug 'google/yapf', { 'rtp': 'plugins/vim', 'for': 'python' }
 
diff --git a/plugins/vim/autoload/yapf.vim b/plugins/vim/autoload/yapf.vim
index b5e94dc..82f9991 100644
--- a/plugins/vim/autoload/yapf.vim
+++ b/plugins/vim/autoload/yapf.vim
@@ -33,23 +33,11 @@ function! yapf#YAPF() range
   let l:cmd = 'yapf --lines=' . l:line_ranges
 
   " Call YAPF with the current buffer
-  if exists('*systemlist')
-    let l:formatted_text = systemlist(l:cmd, join(getline(1, '$'), "\n") . "\n")
-  else
-    let l:formatted_text =
-        \ split(system(l:cmd, join(getline(1, '$'), "\n") . "\n"), "\n")
-  endif
-
-  if v:shell_error
-    echohl ErrorMsg
-    echomsg printf('"%s" returned error: %s', l:cmd, l:formatted_text[-1])
-    echohl None
-    return
-  endif
+  let l:formatted_text = system(l:cmd, join(getline(1, '$'), "\n") . "\n")
 
   " Update the buffer.
   execute '1,' . string(line('$')) . 'delete'
-  call setline(1, l:formatted_text)
+  call setline(1, split(l:formatted_text, "\n"))
 
   " Reset cursor to first line of the formatted range.
   call cursor(a:firstline, 1)
diff --git a/yapf/__init__.py b/yapf/__init__.py
index 8d74b18..a89582f 100644
--- a/yapf/__init__.py
+++ b/yapf/__init__.py
@@ -177,7 +177,7 @@ def main(argv):
   if not files:
     raise errors.YapfError('Input filenames did not match any python files')
 
-  changed = FormatFiles(
+  FormatFiles(
       files,
       lines,
       style_config=args.style,
@@ -186,7 +186,7 @@ def main(argv):
       print_diff=args.diff,
       verify=args.verify,
       parallel=args.parallel)
-  return 1 if changed and args.diff else 0
+  return 0
 
 
 def FormatFiles(filenames,
diff --git a/yapf/yapflib/format_decision_state.py b/yapf/yapflib/format_decision_state.py
index b7b5997..3c17dc4 100644
--- a/yapf/yapflib/format_decision_state.py
+++ b/yapf/yapflib/format_decision_state.py
@@ -502,7 +502,11 @@ class FormatDecisionState(object):
       self.stack[-1].closing_scope_indent = max(
           0, self.stack[-1].indent - style.Get('CONTINUATION_INDENT_WIDTH'))
 
-      self.stack[-1].split_before_closing_bracket = True
+      split_before_closing_bracket = True
+      if style.Get('COALESCE_BRACKETS'):
+        split_before_closing_bracket = False
+
+      self.stack[-1].split_before_closing_bracket = split_before_closing_bracket
 
     # Calculate the split penalty.
     penalty = current.split_penalty
diff --git a/yapf/yapflib/reformatter.py b/yapf/yapflib/reformatter.py
index 990b9e4..2f0cc43 100644
--- a/yapf/yapflib/reformatter.py
+++ b/yapf/yapflib/reformatter.py
@@ -68,8 +68,8 @@ def Reformat(uwlines, verify=False, lines=None):
       if prev_uwline and prev_uwline.disable:
         # Keep the vertical spacing between a disabled and enabled formatting
         # region.
-        _RetainRequiredVerticalSpacingBetweenTokens(uwline.first,
-                                                    prev_uwline.last, lines)
+        _RetainRequiredVerticalSpacingBetweenTokens(
+            uwline.first, prev_uwline.last, lines)
       if any(tok.is_comment for tok in uwline.tokens):
         _RetainVerticalSpacingBeforeComments(uwline)
 
@@ -134,7 +134,7 @@ def _RetainRequiredVerticalSpacingBetweenTokens(cur_tok, prev_tok, lines):
     cur_lineno = cur_tok.lineno
 
   if prev_tok.value.endswith('\\'):
-    prev_lineno += prev_tok.value.count('\n')
+    prev_lineno = prev_lineno + prev_tok.value.count('\n')
 
   required_newlines = cur_lineno - prev_lineno
 
diff --git a/yapf/yapflib/style.py b/yapf/yapflib/style.py
index e8840e4..762b05a 100644
--- a/yapf/yapflib/style.py
+++ b/yapf/yapflib/style.py
@@ -136,16 +136,6 @@ _STYLE_HELP = dict(
       etc."""),
     SPACES_AROUND_POWER_OPERATOR=textwrap.dedent("""\
       Use spaces around the power operator."""),
-    NO_SPACES_AROUND_SELECTED_BINARY_OPERATORS=textwrap.dedent("""\
-      Do not include spaces around selected binary operators. For example:
-
-        1 + 2 * 3 - 4 / 5
-
-      will be formatted as follows when configured with a value "*,/":
-
-        1 + 2*3 - 4/5
-
-      """),
     SPACES_AROUND_DEFAULT_OR_NAMED_ASSIGN=textwrap.dedent("""\
       Use spaces around default or named assigns."""),
     SPACES_BEFORE_COMMENT=textwrap.dedent("""\
@@ -226,7 +216,6 @@ def CreatePEP8Style():
       JOIN_MULTIPLE_LINES=True,
       SPACE_BETWEEN_ENDING_COMMA_AND_CLOSING_BRACKET=True,
       SPACES_AROUND_POWER_OPERATOR=False,
-      NO_SPACES_AROUND_SELECTED_BINARY_OPERATORS=set(),
       SPACES_AROUND_DEFAULT_OR_NAMED_ASSIGN=False,
       SPACES_BEFORE_COMMENT=2,
       SPLIT_ARGUMENTS_WHEN_COMMA_TERMINATED=False,
@@ -311,11 +300,6 @@ def _StringListConverter(s):
   return [part.strip() for part in s.split(',')]
 
 
-def _StringSetConverter(s):
-  """Option value converter for a comma-separated set of strings."""
-  return set(part.strip() for part in s.split(','))
-
-
 def _BoolConverter(s):
   """Option value converter for a boolean."""
   return py3compat.CONFIGPARSER_BOOLEAN_STATES[s.lower()]
@@ -345,7 +329,6 @@ _STYLE_OPTION_VALUE_CONVERTER = dict(
     INDENT_WIDTH=int,
     JOIN_MULTIPLE_LINES=_BoolConverter,
     SPACE_BETWEEN_ENDING_COMMA_AND_CLOSING_BRACKET=_BoolConverter,
-    NO_SPACES_AROUND_SELECTED_BINARY_OPERATORS=_StringSetConverter,
     SPACES_AROUND_POWER_OPERATOR=_BoolConverter,
     SPACES_AROUND_DEFAULT_OR_NAMED_ASSIGN=_BoolConverter,
     SPACES_BEFORE_COMMENT=int,
diff --git a/yapf/yapflib/unwrapped_line.py b/yapf/yapflib/unwrapped_line.py
index 3124cd5..e68f48e 100644
--- a/yapf/yapflib/unwrapped_line.py
+++ b/yapf/yapflib/unwrapped_line.py
@@ -253,9 +253,8 @@ def _SpaceRequiredBetween(left, right):
     if lval == '**' or rval == '**':
       # Space around the "power" operator.
       return style.Get('SPACES_AROUND_POWER_OPERATOR')
-    # Enforce spaces around binary operators except the blacklisted ones.
-    blacklist = style.Get('NO_SPACES_AROUND_SELECTED_BINARY_OPERATORS')
-    return lval not in blacklist and rval not in blacklist
+    # Enforce spaces around binary operators.
+    return True
   if (_IsUnaryOperator(left) and lval != 'not' and
       (right.is_name or right.is_number or rval == '(')):
     # The previous token was a unary op. No space is desired between it and
@@ -332,9 +331,9 @@ def _SpaceRequiredBetween(left, right):
 
 def _MustBreakBefore(prev_token, cur_token):
   """Return True if a line break is required before the current token."""
-  if prev_token.is_comment or (prev_token.previous_token and
-                               prev_token.is_pseudo_paren and
-                               prev_token.previous_token.is_comment):
+  if prev_token.is_comment or (
+      prev_token.previous_token and prev_token.is_pseudo_paren and
+      prev_token.previous_token.is_comment):
     # Must break if the previous token was a comment.
     return True
   if (cur_token.is_string and prev_token.is_string and
diff --git a/yapf/yapflib/yapf_api.py b/yapf/yapflib/yapf_api.py
index 47e790e..cb10e8b 100644
--- a/yapf/yapflib/yapf_api.py
+++ b/yapf/yapflib/yapf_api.py
@@ -152,7 +152,7 @@ def FormatCode(unformatted_source,
       unformatted_source, reformatted_source, filename=filename)
 
   if print_diff:
-    return code_diff, code_diff.strip() != ''
+    return code_diff, code_diff != ''
 
   return reformatted_source, True
 


Test patch:
diff --git a/yapftests/reformatter_basic_test.py b/yapftests/reformatter_basic_test.py
index 0ce8da8..1361219 100644
--- a/yapftests/reformatter_basic_test.py
+++ b/yapftests/reformatter_basic_test.py
@@ -2266,26 +2266,23 @@ xxxxxxxxxxx, yyyyyyyyyyyy, vvvvvvvvv)
           style.CreateStyleFromConfig(
               '{based_on_style: chromium, coalesce_brackets: True}'))
       unformatted_code = textwrap.dedent("""\
-          date_time_values = (
-              {
-                  u'year': year,
-                  u'month': month,
-                  u'day_of_month': day_of_month,
-                  u'hours': hours,
-                  u'minutes': minutes,
-                  u'seconds': seconds
-              }
-          )
+          date_time_values = {
+              u'year': year,
+              u'month': month,
+              u'day_of_month': day_of_month,
+              u'hours': hours,
+              u'minutes': minutes,
+              u'seconds': seconds
+          }
           """)
       expected_formatted_code = textwrap.dedent("""\
-          date_time_values = ({
+          date_time_values = {
               u'year': year,
               u'month': month,
               u'day_of_month': day_of_month,
               u'hours': hours,
               u'minutes': minutes,
-              u'seconds': seconds
-          })
+              u'seconds': seconds}
           """)
       uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
       self.assertCodeEqual(expected_formatted_code,
diff --git a/yapftests/reformatter_style_config_test.py b/yapftests/reformatter_style_config_test.py
index dae8e46..5a04930 100644
--- a/yapftests/reformatter_style_config_test.py
+++ b/yapftests/reformatter_style_config_test.py
@@ -57,25 +57,5 @@ class TestsForStyleConfig(yapf_test_helper.YAPFTest):
     self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
 
 
-  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
-
-
 if __name__ == '__main__':
   unittest.main()
diff --git a/yapftests/yapf_test.py b/yapftests/yapf_test.py
index 7fe7e90..0ec093a 100644
--- a/yapftests/yapf_test.py
+++ b/yapftests/yapf_test.py
@@ -492,10 +492,7 @@ class CommandLineTest(unittest.TestCase):
         suffix='.py', dirname=self.test_tmpdir) as (out, _):
       with utils.TempFileContents(
           self.test_tmpdir, unformatted_code, suffix='.py') as filepath:
-        try:
-          subprocess.check_call(YAPF_BINARY + ['--diff', filepath], stdout=out)
-        except subprocess.CalledProcessError as e:
-          self.assertEqual(e.returncode, 1)  # Indicates the text changed.
+        subprocess.check_call(YAPF_BINARY + ['--diff', filepath], stdout=out)
 
   def testReformattingSpecificLines(self):
     unformatted_code = textwrap.dedent("""\
@@ -1017,22 +1014,20 @@ class CommandLineTest(unittest.TestCase):
 
   def testCoalesceBrackets(self):
     unformatted_code = textwrap.dedent("""\
-       some_long_function_name_foo(
-           {
-               'first_argument_of_the_thing': id,
-               'second_argument_of_the_thing': "some thing"
-           }
-       )""")
+       some_long_function_name_foo({
+           'first_argument_of_the_thing': id,
+           'second_argument_of_the_thing': "some thing"}
+           )""")
     expected_formatted_code = textwrap.dedent("""\
        some_long_function_name_foo({
            'first_argument_of_the_thing': id,
-           'second_argument_of_the_thing': "some thing"
-       })
+           'second_argument_of_the_thing': "some thing"})
        """)
     with utils.NamedTempFile(dirname=self.test_tmpdir, mode='w') as (f, name):
       f.write(
           textwrap.dedent(u'''\
           [style]
+          based_on_style = facebook
           column_limit=82
           coalesce_brackets = True
           '''))