pretty_gyp.py 4.9 KB

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