Repository: google/yapf
Pull request #125 (2015-04-22 21:03:01)

Fix edge case of python file which is blank lines.
Before this was just passed through (no diff was shown, nothing happened inplace).

See https://github.com/google/yapf/pull/120#issuecomment-95316601.


Patch:
diff --git a/yapf/__init__.py b/yapf/__init__.py
index 0d64ad4..f3c12de 100644
--- a/yapf/__init__.py
+++ b/yapf/__init__.py
@@ -72,7 +72,7 @@ def main(argv):
             'the default.'))
   parser.add_argument('--verify',
                       action='store_true',
-                      help='try to verify reformatted code for syntax errors')
+                      help='try to verify refomatted code for syntax errors')
   diff_inplace_group = parser.add_mutually_exclusive_group()
   diff_inplace_group.add_argument('-d', '--diff',
                                   action='store_true',
diff --git a/yapf/yapflib/file_resources.py b/yapf/yapflib/file_resources.py
index 63d6e56..519ad5a 100644
--- a/yapf/yapflib/file_resources.py
+++ b/yapf/yapflib/file_resources.py
@@ -39,8 +39,6 @@ def WriteReformattedCode(filename, reformatted_code, in_place, encoding):
     in_place: (bool) If True, then write the reformatted code to the file.
     encoding: (unicode) The encoding of the file.
   """
-  if not reformatted_code.strip():
-    return
   if in_place:
     with py3compat.open_with_encoding(filename, mode='w',
                                       encoding=encoding) as fd:
diff --git a/yapf/yapflib/reformatter.py b/yapf/yapflib/reformatter.py
index ad54b8f..e56b4ba 100644
--- a/yapf/yapflib/reformatter.py
+++ b/yapf/yapflib/reformatter.py
@@ -20,6 +20,7 @@ as a string.
   Reformat(): the main function exported by this module.
 """
 
+from __future__ import unicode_literals
 import collections
 import heapq
 import re
diff --git a/yapf/yapflib/style.py b/yapf/yapflib/style.py
index 83a24ac..baabe4e 100644
--- a/yapf/yapflib/style.py
+++ b/yapf/yapflib/style.py
@@ -215,12 +215,9 @@ def CreateStyleFromConfig(style_config):
 
 def _CreateConfigParserFromConfigString(config_string):
   """Given a config string from the command line, return a config parser."""
-  if config_string[0] != "{" or config_string[-1] != "}":
-    raise StyleConfigError(
-        "Invalid style dict syntax: '{}'.".format(config_string))
   config = py3compat.ConfigParser()
   config.add_section('style')
-  for key, value in re.findall(r'([a-zA-Z0-9_]+)\s*[:=]\s*([a-zA-Z0-9_]+)',
+  for key, value in re.findall(r'([a-zA-Z0-9_]*): *([a-zA-Z0-9_]+)',
                                config_string):
     config.set('style', key, value)
   return config
@@ -230,14 +227,14 @@ def _CreateConfigParserFromConfigFile(config_filename):
   """Read the file and return a ConfigParser object."""
   if not os.path.exists(config_filename):
     # Provide a more meaningful error here.
-    raise StyleConfigError(
-        '"{0}" is not a valid style or file path'.format(config_filename))
+    raise StyleConfigError('"{0}" is not a valid style or file path'.format(
+        config_filename))
   with open(config_filename) as style_file:
     config = py3compat.ConfigParser()
     config.read_file(style_file)
     if not config.has_section('style'):
-      raise StyleConfigError(
-          'Unable to find section [style] in {0}'.format(config_filename))
+      raise StyleConfigError('Unable to find section [style] in {0}'.format(
+          config_filename))
     return config
 
 
@@ -268,11 +265,7 @@ def _CreateStyleFromConfigParser(config):
     option = option.upper()
     if option not in _STYLE_OPTION_VALUE_CONVERTER:
       raise StyleConfigError('Unknown style option "{0}"'.format(option))
-    try:
-      base_style[option] = _STYLE_OPTION_VALUE_CONVERTER[option](value)
-    except ValueError:
-      raise StyleConfigError(
-          "'{}' is not a valid setting for {}.".format(value, option))
+    base_style[option] = _STYLE_OPTION_VALUE_CONVERTER[option](value)
   return base_style
 
 
diff --git a/yapf/yapflib/yapf_api.py b/yapf/yapflib/yapf_api.py
index 50b58fc..74b106a 100644
--- a/yapf/yapflib/yapf_api.py
+++ b/yapf/yapflib/yapf_api.py
@@ -110,8 +110,6 @@ def FormatCode(unformatted_source,
   blank_line_calculator.CalculateBlankLines(tree)
 
   uwlines = pytree_unwrapper.UnwrapPyTree(tree)
-  if not uwlines:
-    return ''
   for uwl in uwlines:
     uwl.CalculateFormattingInformation()
 


Test patch:
diff --git a/yapftests/style_test.py b/yapftests/style_test.py
index 62b5507..f11485f 100644
--- a/yapftests/style_test.py
+++ b/yapftests/style_test.py
@@ -196,24 +196,6 @@ class StyleFromCommandLine(unittest.TestCase):
     self.assertTrue(_LooksLikeYapfStyle(cfg))
     self.assertEqual(cfg['INDENT_WIDTH'], 2)
 
-  def testDefaultBasedOnStyleNotStrict(self):
-    cfg = style.CreateStyleFromConfig(
-        '{based_on_style : pep8'
-        ' ,indent_width=2'
-        ' blank_line_before_nested_class_or_def:True}')
-    self.assertTrue(_LooksLikeYapfStyle(cfg))
-    self.assertEqual(cfg['INDENT_WIDTH'], 2)
-
-  def testDefaultBasedOnStyleBadString(self):
-    self.assertRaisesRegexp(style.StyleConfigError, "Unknown style option",
-                            style.CreateStyleFromConfig,
-                            '{based_on_styl: pep8}')
-    self.assertRaisesRegexp(style.StyleConfigError, "not a valid",
-                            style.CreateStyleFromConfig, '{INDENT_WIDTH: FOUR}')
-    self.assertRaisesRegexp(style.StyleConfigError, "Invalid style dict",
-                            style.CreateStyleFromConfig,
-                            '{based_on_style: pep8')
-
 
 class StyleHelp(unittest.TestCase):
 
diff --git a/yapftests/yapf_test.py b/yapftests/yapf_test.py
index 5dc05b3..a5a664a 100644
--- a/yapftests/yapf_test.py
+++ b/yapftests/yapf_test.py
@@ -102,6 +102,23 @@ class CommandLineTest(unittest.TestCase):
 
     self.assertEqual(reformatted_code, expected_formatted_code)
 
+  def testInPlaceReformattingBlank(self):
+    unformatted_code = u"\n\n"
+    expected_formatted_code = u"\n"
+
+    with tempfile.NamedTemporaryFile(suffix='.py',
+                                     dir=self.test_tmpdir) as testfile:
+      testfile.write(unformatted_code.encode('UTF-8'))
+      testfile.seek(0)
+
+      p = subprocess.Popen(YAPF_BINARY + ['--in-place', testfile.name])
+      p.wait()
+
+      with io.open(testfile.name, mode='r', newline='') as fd:
+        reformatted_code = fd.read()
+
+    self.assertEqual(reformatted_code, expected_formatted_code)
+
   def testReadFromStdin(self):
     unformatted_code = textwrap.dedent(u"""\
         def foo():