pretty_gyp.py 4.6 KB

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