pretty_gyp.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. #!/usr/bin/env python
  2. # Copyright (c) 2012 Google Inc. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """Pretty-prints the contents of a GYP file."""
  6. from __future__ import print_function
  7. import sys
  8. import re
  9. # Regex to remove comments when we're counting braces.
  10. COMMENT_RE = re.compile(r'\s*#.*')
  11. # Regex to remove quoted strings when we're counting braces.
  12. # It takes into account quoted quotes, and makes sure that the quotes match.
  13. # NOTE: It does not handle quotes that span more than one line, or
  14. # cases where an escaped quote is preceded by an escaped backslash.
  15. QUOTE_RE_STR = r'(?P<q>[\'"])(.*?)(?<![^\\][\\])(?P=q)'
  16. QUOTE_RE = re.compile(QUOTE_RE_STR)
  17. def comment_replace(matchobj):
  18. return matchobj.group(1) + matchobj.group(2) + '#' * len(matchobj.group(3))
  19. def mask_comments(input):
  20. """Mask the quoted strings so we skip braces inside quoted strings."""
  21. search_re = re.compile(r'(.*?)(#)(.*)')
  22. return [search_re.sub(comment_replace, line) for line in input]
  23. def quote_replace(matchobj):
  24. return "%s%s%s%s" % (matchobj.group(1),
  25. matchobj.group(2),
  26. 'x'*len(matchobj.group(3)),
  27. matchobj.group(2))
  28. def mask_quotes(input):
  29. """Mask the quoted strings so we skip braces inside quoted strings."""
  30. search_re = re.compile(r'(.*?)' + QUOTE_RE_STR)
  31. return [search_re.sub(quote_replace, line) for line in input]
  32. def do_split(input, masked_input, search_re):
  33. output = []
  34. mask_output = []
  35. for (line, masked_line) in zip(input, masked_input):
  36. m = search_re.match(masked_line)
  37. while m:
  38. split = len(m.group(1))
  39. line = line[:split] + r'\n' + line[split:]
  40. masked_line = masked_line[:split] + r'\n' + masked_line[split:]
  41. m = search_re.match(masked_line)
  42. output.extend(line.split(r'\n'))
  43. mask_output.extend(masked_line.split(r'\n'))
  44. return (output, mask_output)
  45. def split_double_braces(input):
  46. """Masks out the quotes and comments, and then splits appropriate
  47. lines (lines that matche the double_*_brace re's above) before
  48. indenting them below.
  49. These are used to split lines which have multiple braces on them, so
  50. that the indentation looks prettier when all laid out (e.g. closing
  51. braces make a nice diagonal line).
  52. """
  53. double_open_brace_re = re.compile(r'(.*?[\[\{\(,])(\s*)([\[\{\(])')
  54. double_close_brace_re = re.compile(r'(.*?[\]\}\)],?)(\s*)([\]\}\)])')
  55. masked_input = mask_quotes(input)
  56. masked_input = mask_comments(masked_input)
  57. (output, mask_output) = do_split(input, masked_input, double_open_brace_re)
  58. (output, mask_output) = do_split(output, mask_output, double_close_brace_re)
  59. return output
  60. def count_braces(line):
  61. """keeps track of the number of braces on a given line and returns the result.
  62. It starts at zero and subtracts for closed braces, and adds for open braces.
  63. """
  64. open_braces = ['[', '(', '{']
  65. close_braces = [']', ')', '}']
  66. closing_prefix_re = re.compile(r'(.*?[^\s\]\}\)]+.*?)([\]\}\)],?)\s*$')
  67. cnt = 0
  68. stripline = COMMENT_RE.sub(r'', line)
  69. stripline = QUOTE_RE.sub(r"''", stripline)
  70. for char in stripline:
  71. for brace in open_braces:
  72. if char == brace:
  73. cnt += 1
  74. for brace in close_braces:
  75. if char == brace:
  76. cnt -= 1
  77. after = False
  78. if cnt > 0:
  79. after = True
  80. # This catches the special case of a closing brace having something
  81. # other than just whitespace ahead of it -- we don't want to
  82. # unindent that until after this line is printed so it stays with
  83. # the previous indentation level.
  84. if cnt < 0 and closing_prefix_re.match(stripline):
  85. after = True
  86. return (cnt, after)
  87. def prettyprint_input(lines):
  88. """Does the main work of indenting the input based on the brace counts."""
  89. indent = 0
  90. basic_offset = 2
  91. last_line = ""
  92. for line in lines:
  93. if COMMENT_RE.match(line):
  94. print(line)
  95. else:
  96. line = line.strip('\r\n\t ') # Otherwise doesn't strip \r on Unix.
  97. if len(line) > 0:
  98. (brace_diff, after) = count_braces(line)
  99. if brace_diff != 0:
  100. if after:
  101. print(" " * (basic_offset * indent) + line)
  102. indent += brace_diff
  103. else:
  104. indent += brace_diff
  105. print(" " * (basic_offset * indent) + line)
  106. else:
  107. print(" " * (basic_offset * indent) + line)
  108. else:
  109. print("")
  110. last_line = line
  111. def main():
  112. if len(sys.argv) > 1:
  113. data = open(sys.argv[1]).read().splitlines()
  114. else:
  115. data = sys.stdin.read().splitlines()
  116. # Split up the double braces.
  117. lines = split_double_braces(data)
  118. # Indent and print the output.
  119. prettyprint_input(lines)
  120. return 0
  121. if __name__ == '__main__':
  122. sys.exit(main())