Add experimental support for python in 'git cl format'
Based on yapf (https://github.com/google/yapf) this
formatter currently only works with --full. It defaults
to pep8 style and projects that use a different style
can add .style.yapf to the top level.
Review URL: https://codereview.chromium.org/1156743008
git-svn-id: svn://svn.chromium.org/chrome/trunk/tools/depot_tools@295547 0039d316-1c4b-4281-b951-d872f2087c98
diff --git a/git_cl.py b/git_cl.py
index ce36541..26f04fd 100755
--- a/git_cl.py
+++ b/git_cl.py
@@ -3183,12 +3183,14 @@
@subcommand.usage('[files or directories to diff]')
def CMDformat(parser, args):
- """Runs clang-format on the diff."""
+ """Runs auto-formatting tools (clang-format etc.) on the diff."""
CLANG_EXTS = ['.cc', '.cpp', '.h', '.mm', '.proto', '.java']
parser.add_option('--full', action='store_true',
help='Reformat the full content of all touched files')
parser.add_option('--dry-run', action='store_true',
help='Don\'t modify any file on disk.')
+ parser.add_option('--python', action='store_true',
+ help='Format python code with yapf (experimental).')
parser.add_option('--diff', action='store_true',
help='Print diff to stdout rather than modifying files.')
opts, args = parser.parse_args(args)
@@ -3216,12 +3218,12 @@
if opts.full:
# Only list the names of modified files.
- clang_diff_type = '--name-only'
+ diff_type = '--name-only'
else:
# Only generate context-less patches.
- clang_diff_type = '-U0'
+ diff_type = '-U0'
- diff_cmd = BuildGitDiffCmd(clang_diff_type, upstream_commit, args, CLANG_EXTS)
+ diff_cmd = BuildGitDiffCmd(diff_type, upstream_commit, args, CLANG_EXTS)
diff_output = RunGit(diff_cmd)
top_dir = os.path.normpath(
@@ -3267,6 +3269,29 @@
if opts.dry_run and len(stdout) > 0:
return_value = 2
+ # Similar code to above, but using yapf on .py files rather than clang-format
+ # on C/C++ files
+ if opts.python:
+ diff_cmd = BuildGitDiffCmd(diff_type, upstream_commit, args, ['.py'])
+ diff_output = RunGit(diff_cmd)
+ yapf_tool = gclient_utils.FindExecutable('yapf')
+ if yapf_tool is None:
+ DieWithError('yapf not found in PATH')
+
+ if opts.full:
+ files = diff_output.splitlines()
+ if files:
+ cmd = [yapf_tool]
+ if not opts.dry_run and not opts.diff:
+ cmd.append('-i')
+ stdout = RunCommand(cmd + files, cwd=top_dir)
+ if opts.diff:
+ sys.stdout.write(stdout)
+ else:
+ # TODO(sbc): yapf --lines mode still has some issues.
+ # https://github.com/google/yapf/issues/154
+ DieWithError('--python currently only works with --full')
+
# Build a diff command that only operates on dart files. dart's formatter
# does not have the nice property of only operating on modified chunks, so
# hard code full.