pretty_gyp.py 4.9 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" % (
  25. matchobj.group(1),
  26. matchobj.group(2),
  27. "x" * len(matchobj.group(3)),
  28. matchobj.group(2),
  29. )
  30. def mask_quotes(input):
  31. """Mask the quoted strings so we skip braces inside quoted strings."""
  32. search_re = re.compile(r"(.*?)" + QUOTE_RE_STR)
  33. return [search_re.sub(quote_replace, line) for line in input]
  34. def do_split(input, masked_input, search_re):
  35. output = []
  36. mask_output = []
  37. for (line, masked_line) in zip(input, masked_input):
  38. m = search_re.match(masked_line)
  39. while m:
  40. split = len(m.group(1))
  41. line = line[:split] + r"\n" + line[split:]
  42. masked_line = masked_line[:split] + r"\n" + masked_line[split:]
  43. m = search_re.match(masked_line)
  44. output.extend(line.split(r"\n"))
  45. mask_output.extend(masked_line.split(r"\n"))
  46. return (output, mask_output)
  47. def split_double_braces(input):
  48. """Masks out the quotes and comments, and then splits appropriate
  49. lines (lines that matche the double_*_brace re's above) before
  50. indenting them below.
  51. These are used to split lines which have multiple braces on them, so
  52. that the indentation looks prettier when all laid out (e.g. closing
  53. braces make a nice diagonal line).
  54. """
  55. double_open_brace_re = re.compile(r"(.*?[\[\{\(,])(\s*)([\[\{\(])")
  56. double_close_brace_re = re.compile(r"(.*?[\]\}\)],?)(\s*)([\]\}\)])")
  57. masked_input = mask_quotes(input)
  58. masked_input = mask_comments(masked_input)
  59. (output, mask_output) = do_split(input, masked_input, double_open_brace_re)
  60. (output, mask_output) = do_split(output, mask_output, double_close_brace_re)
  61. return output
  62. def count_braces(line):
  63. """keeps track of the number of braces on a given line and returns the result.
  64. It starts at zero and subtracts for closed braces, and adds for open braces.
  65. """
  66. open_braces = ["[", "(", "{"]
  67. close_braces = ["]", ")", "}"]
  68. closing_prefix_re = re.compile(r"(.*?[^\s\]\}\)]+.*?)([\]\}\)],?)\s*$")
  69. cnt = 0
  70. stripline = COMMENT_RE.sub(r"", line)
  71. stripline = QUOTE_RE.sub(r"''", stripline)
  72. for char in stripline:
  73. for brace in open_braces:
  74. if char == brace:
  75. cnt += 1
  76. for brace in close_braces:
  77. if char == brace:
  78. cnt -= 1
  79. after = False
  80. if cnt > 0:
  81. after = True
  82. # This catches the special case of a closing brace having something
  83. # other than just whitespace ahead of it -- we don't want to
  84. # unindent that until after this line is printed so it stays with
  85. # the previous indentation level.
  86. if cnt < 0 and closing_prefix_re.match(stripline):
  87. after = True
  88. return (cnt, after)
  89. def prettyprint_input(lines):
  90. """Does the main work of indenting the input based on the brace counts."""
  91. indent = 0
  92. basic_offset = 2
  93. for line in lines:
  94. if COMMENT_RE.match(line):
  95. print(line)
  96. else:
  97. line = line.strip("\r\n\t ") # Otherwise doesn't strip \r on Unix.
  98. if len(line) > 0:
  99. (brace_diff, after) = count_braces(line)
  100. if brace_diff != 0:
  101. if after:
  102. print(" " * (basic_offset * indent) + line)
  103. indent += brace_diff
  104. else:
  105. indent += brace_diff
  106. print(" " * (basic_offset * indent) + line)
  107. else:
  108. print(" " * (basic_offset * indent) + line)
  109. else:
  110. print("")
  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())