Repository: google/yapf
Pull request #72 (2015-04-06 18:35:20)

Improve handling of filenames on the command line
Don't call GetCommandLineFiles unless there are positional
arguments (args.files), and only pass the positional parameters
(otherwise GetCommandLineFiles ends up processing all the args
as well).

Prior to this change if you run 'yapf -i foo.c' it will give you
the unhelpful error:
'cannot use --in_place or --diff flags when reading from stdin'

Add a unit test for this case. Would add here but would prefer
to use 'mock' and don't see a dependency on 'mock' yet.

Also, give a useful error message when positional paramters
are specified but not arguments were given.

googlebot: Thanks for your pull request.  It looks like this may be your first contribution to a Google open source project, in which case you'll need to sign a Contributor License Agreement (CLA).

:memo: **Please visit <https://cla.developers.google.com/> to sign.**

Once you've signed, please reply here (e.g. `I signed it!`) and we'll verify.  Thanks.

---

- If you've already signed a CLA, it's possible we don't have your GitHub username or you're using a different email address.  Check [your existing CLA data](https://cla.developers.google.com/clas) and verify that your [email is set on your git commits](https://help.github.com/articles/setting-your-email-in-git/).
- If you signed the CLA as a corporation, please let us know the company's name.

<!-- need_sender_cla -->
coveralls: 
[![Coverage Status](https://coveralls.io/builds/2274860/badge)](https://coveralls.io/builds/2274860)

Coverage increased (+1.36%) to 92.29% when pulling **97b28b8d1b23da559074c77434dc98387044767a on sbc100:fix_input_file** into **6cd1669be306dd590926a2837ef7904968c54249 on google:master**.

coveralls: 
[![Coverage Status](https://coveralls.io/builds/2274860/badge)](https://coveralls.io/builds/2274860)

Coverage increased (+1.36%) to 92.29% when pulling **97b28b8d1b23da559074c77434dc98387044767a on sbc100:fix_input_file** into **6cd1669be306dd590926a2837ef7904968c54249 on google:master**.

coveralls: 
[![Coverage Status](https://coveralls.io/builds/2275668/badge)](https://coveralls.io/builds/2275668)

Coverage increased (+1.36%) to 92.29% when pulling **af4bd674696e94e83a359a649da38fba05deba09 on sbc100:fix_input_file** into **6cd1669be306dd590926a2837ef7904968c54249 on google:master**.

coveralls: 
[![Coverage Status](https://coveralls.io/builds/2275685/badge)](https://coveralls.io/builds/2275685)

Coverage increased (+1.36%) to 92.29% when pulling **daac2db445309eb1e79df9c5b9703e111056ebd3 on sbc100:fix_input_file** into **6cd1669be306dd590926a2837ef7904968c54249 on google:master**.

sbc100: My google and github accounts should be linked already.

gwelymernans: Odd. Could you go to https://cla.developers.google.com/  and see if the CLA is listed? If you can't find it, you may have to resign. :-(
sbc100: Its my fault.. i should have used my @google.com address.  Will upload a new version of PR shortly.

Patch:
diff --git a/.gitignore b/.gitignore
index 5909460..b8038e4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -24,7 +24,5 @@
 #==============================================================================#
 # Directories to ignore (do not add trailing '/'s, they skip symlinks).
 #==============================================================================#
+# The build directory.
 build
-dist
-.tox
-yapf.egg-info
diff --git a/CONTRIBUTORS b/CONTRIBUTORS
index bf60fc6..7d31575 100644
--- a/CONTRIBUTORS
+++ b/CONTRIBUTORS
@@ -11,3 +11,4 @@
 
 Bill Wendling <morbo@google.com>
 Eli Bendersky <eliben@google.com>
+Sam Clegg <sbc@google.com>
diff --git a/HACKING.rst b/HACKING.rst
deleted file mode 100644
index 214c2b3..0000000
--- a/HACKING.rst
+++ /dev/null
@@ -1,17 +0,0 @@
-Releasing a new version
------------------------
-
-* Run tests: python setup.py test
-  [don't forget to run with Python 2.7 and 3.4]
-
-* Bump version in yapf/__init__.py
-
-* Build source distribution: python setup.py sdist
-
-* Check it looks OK, install it onto a virtualenv, run tests, run yapf as a tool
-
-* Push to PyPI: python setup.py sdist upload
-
-* Commit the version bump; add tag with git tag v<VERSION_NUM>; git push --tags
-
-TODO: figure out a way to make tox work to make virtualenv testing easier.
diff --git a/README.rst b/README.rst
index a39f70c..4c817ba 100644
--- a/README.rst
+++ b/README.rst
@@ -42,18 +42,15 @@ some of the drudgery of maintaining your code.
 Installation
 ============
 
-To install YAPF from PyPI::
-
-    $ pip install yapf
-
-YAPF is still considered in "alpha" stage, and the released version may change
-often; therefore, the best way to keep up-to-date with the latest development
-is to clone this repository.
-
-Note that if you intend to use YAPF as a command-line tool rather than as a
-library, installation is not necessary. YAPF supports being run as a directory
-by the Python interpreter. If you cloned/unzipped YAPF into ``DIR``, it's
-possible to run::
+We consider YAPF to be "alpha" quality at this time. Therefore, we don't yet
+support official releases to PyPI and the most stable and correct version is
+at the tip of the ``master`` branch in this repository. We plan to make a
+first beta release (including to PyPI) in the next few weeks.
+
+If you intend to use YAPF as a command-line tool rather than as a library,
+installation is not necessary. YAPF supports being run as a directory by the
+Python interpreter. If you cloned/unzipped yapf into ``DIR``, it's possible to
+run::
 
     $ PYTHONPATH=DIR python DIR/yapf [options] ...
 
diff --git a/plugins/yapf.vim b/plugins/yapf.vim
index cdbb048..3b43104 100644
--- a/plugins/yapf.vim
+++ b/plugins/yapf.vim
@@ -23,7 +23,7 @@
 function! yapf#YAPF() range
   " Determine range to format.
   let l:line_ranges = a:firstline . '-' . a:lastline
-  let l:cmd = 'yapf --lines=' . l:line_ranges
+  let l:cmd = 'env PYTHONPATH=<path_to_srcdir>/yapf <path_to_python>/python -m yapf --lines=' . l:line_ranges
 
   " Call YAPF with the current buffer
   let l:formatted_text = system(l:cmd, join(getline(1, '$'), "\n") . "\n")
diff --git a/setup.py b/setup.py
index f667b21..db16843 100644
--- a/setup.py
+++ b/setup.py
@@ -47,7 +47,7 @@ with codecs.open('README.rst', 'r', 'utf-8') as fd:
       author='Google Inc.',
       maintainer='Bill Wendling',
       maintainer_email='morbo@google.com',
-      packages=['yapf', 'yapf.yapflib', 'yapftests'],
+      packages=['yapf', 'yapf.yapflib'],
       classifiers=[
           'Development Status :: 3 - Alpha',
           'Environment :: Console',
diff --git a/yapf/__init__.py b/yapf/__init__.py
index db12f01..0ebd17b 100644
--- a/yapf/__init__.py
+++ b/yapf/__init__.py
@@ -34,7 +34,11 @@ from yapf.yapflib import file_resources
 from yapf.yapflib import py3compat
 from yapf.yapflib import yapf_api
 
-__version__ = '0.1.4'
+__version__ = '0.1'
+
+
+class YapfError(Exception):
+  pass
 
 
 def main(argv):
@@ -48,37 +52,32 @@ def main(argv):
     0 if there were no errors, non-zero otherwise.
   """
   parser = argparse.ArgumentParser(description='Formatter for Python code.')
-  parser.add_argument('--version',
-                      action='store_true',
-                      help='print version number and exit')
   parser.add_argument(
-      '--style',
-      action='store',
-      default='pep8',
+      '--version', action='store_true',
+      help='print version number and exit')
+  parser.add_argument(
+      '--style', action='store', default='pep8',
       help=('specify formatting style: either a style name (for example "pep8" '
             'or "google"), or the name of a file with style settings. pep8 is '
             'the default.'))
-  parser.add_argument('--verify',
-                      action='store_true',
-                      help='try to verify refomatted code for syntax errors')
+  parser.add_argument(
+      '--verify', action='store_true',
+      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',
-                                  help='print the diff for the fixed source')
-  diff_inplace_group.add_argument('-i', '--in-place',
-                                  action='store_true',
-                                  help='make changes to files in place')
+  diff_inplace_group.add_argument(
+      '-d', '--diff', action='store_true',
+      help='print the diff for the fixed source')
+  diff_inplace_group.add_argument(
+      '-i', '--in-place', action='store_true',
+      help='make changes to files in place')
 
   lines_recursive_group = parser.add_mutually_exclusive_group()
   lines_recursive_group.add_argument(
-      '-l', '--lines',
-      metavar='START-END',
-      action='append',
-      default=None,
+      '-l', '--lines', metavar='START-END', action='append', default=None,
       help='range of lines to reformat, one-based')
-  lines_recursive_group.add_argument('-r', '--recursive',
-                                     action='store_true',
-                                     help='run recursively over directories')
+  lines_recursive_group.add_argument(
+      '-r', '--recursive', action='store_true',
+      help='run recursively over directories')
 
   parser.add_argument('files', nargs='*')
   args = parser.parse_args(argv[1:])
@@ -91,8 +90,7 @@ def main(argv):
     parser.error('cannot use -l/--lines with more than one file')
 
   lines = _GetLines(args.lines) if args.lines is not None else None
-  files = file_resources.GetCommandLineFiles(argv[1:], args.recursive)
-  if not files:
+  if not args.files:
     # No arguments specified. Read code from stdin.
     if args.in_place or args.diff:
       parser.error('cannot use --in_place or --diff flags when reading '
@@ -116,19 +114,16 @@ def main(argv):
         verify=args.verify))
     return 0
 
-  FormatFiles(files, lines,
-              style_config=args.style,
-              in_place=args.in_place,
-              print_diff=args.diff,
-              verify=args.verify)
+  files = file_resources.GetCommandLineFiles(args.files, args.recursive)
+  if not files:
+    raise YapfError('Input filenames did not match any python files')
+  FormatFiles(files, lines, style_config=args.style, in_place=args.in_place,
+              print_diff=args.diff, verify=args.verify)
   return 0
 
 
-def FormatFiles(filenames, lines,
-                style_config=None,
-                in_place=False,
-                print_diff=False,
-                verify=True):
+def FormatFiles(filenames, lines, style_config=None, in_place=False,
+                print_diff=False, verify=True):
   """Format a list of files.
 
   Arguments:
@@ -145,11 +140,9 @@ def FormatFiles(filenames, lines,
   """
   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)
+    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)
 
diff --git a/yapf/yapflib/file_resources.py b/yapf/yapflib/file_resources.py
index 076dfd8..ccec3a8 100644
--- a/yapf/yapflib/file_resources.py
+++ b/yapf/yapflib/file_resources.py
@@ -26,7 +26,7 @@ from yapf.yapflib import py3compat
 
 def GetCommandLineFiles(command_line_file_list, recursive):
   """Return the list of files specified on the command line."""
-  return _FindFiles(command_line_file_list, recursive)
+  return _FindPythonFiles(command_line_file_list, recursive)
 
 
 def WriteReformattedCode(filename, reformatted_code, in_place):
@@ -49,7 +49,7 @@ def WriteReformattedCode(filename, reformatted_code, in_place):
     sys.stdout.write(py3compat.EncodeForStdout(reformatted_code))
 
 
-def _FindFiles(filenames, recursive):
+def _FindPythonFiles(filenames, recursive):
   """Find all Python files."""
   python_files = []
   for filename in filenames:
diff --git a/yapf/yapflib/split_penalty.py b/yapf/yapflib/split_penalty.py
index dca1b0b..603dc81 100644
--- a/yapf/yapflib/split_penalty.py
+++ b/yapf/yapflib/split_penalty.py
@@ -366,7 +366,7 @@ def _AllowBuilderStyleCalls(node):
     if child.value == '.':
       if prev_child.lineno != child.lineno:
         pytree_utils.SetNodeAnnotation(
-            child, pytree_utils.Annotation.SPLIT_PENALTY, 0)
+            child, pytree_utils.Annotation.SPLIT_PENALTY, None)
     prev_child = child
 
 


Test patch:
diff --git a/yapftests/main_test.py b/yapftests/main_test.py
new file mode 100644
index 0000000..2a19bd6
--- /dev/null
+++ b/yapftests/main_test.py
@@ -0,0 +1,26 @@
+# -*- coding: utf-8 -*-
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tests for yapf.__init__.main."""
+
+import unittest
+import yapf
+
+
+class MainTest(unittest.TestCase):
+
+  def testNoPythonFilesMatched(self):
+    with self.assertRaisesRegexp(yapf.YapfError,
+                                 'did not match any python files'):
+      yapf.main(['yapf', 'foo.c'])