Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / tools / gn / bin / gn-format.py
blobc835753eefbdb894a02254994195e18dc9a3a1ff
1 # Copyright 2014 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
5 # Based on clang-format.py.
7 # This file is a minimal gn format vim-integration. To install:
8 # - Change 'binary' if gn is not on the path (see below).
9 # - Add to your .vimrc:
11 # map <F1> :pyf <path-to-this-file>/gn-format.py<CR>
13 # gn format currently formats only a complete file so visual ranges, etc. won't
14 # be used. It operates on the current, potentially unsaved buffer and does not
15 # create or save any files. To revert a formatting, just undo.
17 import difflib
18 import subprocess
19 import sys
20 import vim
22 # Change this to the full path if gn is not on the path.
23 binary = 'gn'
25 def main():
26 # Get the current text.
27 buf = vim.current.buffer
28 text = '\n'.join(buf)
30 # Avoid flashing an ugly cmd prompt on Windows when invoking gn.
31 startupinfo = None
32 if sys.platform.startswith('win32'):
33 startupinfo = subprocess.STARTUPINFO()
34 startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
35 startupinfo.wShowWindow = subprocess.SW_HIDE
37 # Call formatter.
38 p = subprocess.Popen([binary, 'format', '--stdin'],
39 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
40 stdin=subprocess.PIPE, startupinfo=startupinfo,
41 universal_newlines=True)
42 stdout, stderr = p.communicate(input=text)
43 if p.returncode != 0:
44 print 'Formatting failed, please report to gn-dev@chromium.org.'
45 print stdout, stderr
46 else:
47 # Otherwise, replace current buffer.
48 lines = stdout.split('\n')
49 # Last line should have trailing \n, but we don't want to insert a blank
50 # line at the end of the buffer, so remove that.
51 if lines[-1] == '':
52 lines = lines[:-1]
53 sequence = difflib.SequenceMatcher(None, vim.current.buffer, lines)
54 for op in reversed(sequence.get_opcodes()):
55 if op[0] is not 'equal':
56 vim.current.buffer[op[1]:op[2]] = lines[op[3]:op[4]]
58 main()