fix_gn_headers.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. #!/usr/bin/env python
  2. # Copyright 2017 The Chromium Authors. 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. """Fix header files missing in GN.
  6. This script takes the missing header files from check_gn_headers.py, and
  7. try to fix them by adding them to the GN files.
  8. Manual cleaning up is likely required afterwards.
  9. """
  10. from __future__ import print_function
  11. import argparse
  12. import os
  13. import re
  14. import subprocess
  15. import sys
  16. def GitGrep(pattern):
  17. p = subprocess.Popen(
  18. ['git', 'grep', '-En', pattern, '--', '*.gn', '*.gni'],
  19. stdout=subprocess.PIPE)
  20. out, _ = p.communicate()
  21. return out, p.returncode
  22. def ValidMatches(basename, cc, grep_lines):
  23. """Filter out 'git grep' matches with header files already."""
  24. matches = []
  25. for line in grep_lines:
  26. gnfile, linenr, contents = line.split(':')
  27. linenr = int(linenr)
  28. new = re.sub(cc, basename, contents)
  29. lines = open(gnfile).read().splitlines()
  30. assert contents in lines[linenr - 1]
  31. # Skip if it's already there. It could be before or after the match.
  32. if lines[linenr] == new:
  33. continue
  34. if lines[linenr - 2] == new:
  35. continue
  36. print(' ', gnfile, linenr, new)
  37. matches.append((gnfile, linenr, new))
  38. return matches
  39. def AddHeadersNextToCC(headers, skip_ambiguous=True):
  40. """Add header files next to the corresponding .cc files in GN files.
  41. When skip_ambiguous is True, skip if multiple .cc files are found.
  42. Returns unhandled headers.
  43. Manual cleaning up is likely required, especially if not skip_ambiguous.
  44. """
  45. edits = {}
  46. unhandled = []
  47. for filename in headers:
  48. filename = filename.strip()
  49. if not (filename.endswith('.h') or filename.endswith('.hh')):
  50. continue
  51. basename = os.path.basename(filename)
  52. print(filename)
  53. cc = r'\b' + os.path.splitext(basename)[0] + r'\.(cc|cpp|mm)\b'
  54. out, returncode = GitGrep('(/|")' + cc + '"')
  55. if returncode != 0 or not out:
  56. unhandled.append(filename)
  57. continue
  58. matches = ValidMatches(basename, cc, out.splitlines())
  59. if len(matches) == 0:
  60. continue
  61. if len(matches) > 1:
  62. print('\n[WARNING] Ambiguous matching for', filename)
  63. for i in enumerate(matches, 1):
  64. print('%d: %s' % (i[0], i[1]))
  65. print()
  66. if skip_ambiguous:
  67. continue
  68. picked = raw_input('Pick the matches ("2,3" for multiple): ')
  69. try:
  70. matches = [matches[int(i) - 1] for i in picked.split(',')]
  71. except (ValueError, IndexError):
  72. continue
  73. for match in matches:
  74. gnfile, linenr, new = match
  75. print(' ', gnfile, linenr, new)
  76. edits.setdefault(gnfile, {})[linenr] = new
  77. for gnfile in edits:
  78. lines = open(gnfile).read().splitlines()
  79. for l in sorted(edits[gnfile].keys(), reverse=True):
  80. lines.insert(l, edits[gnfile][l])
  81. open(gnfile, 'w').write('\n'.join(lines) + '\n')
  82. return unhandled
  83. def AddHeadersToSources(headers, skip_ambiguous=True):
  84. """Add header files to the sources list in the first GN file.
  85. The target GN file is the first one up the parent directories.
  86. This usually does the wrong thing for _test files if the test and the main
  87. target are in the same .gn file.
  88. When skip_ambiguous is True, skip if multiple sources arrays are found.
  89. "git cl format" afterwards is required. Manually cleaning up duplicated items
  90. is likely required.
  91. """
  92. for filename in headers:
  93. filename = filename.strip()
  94. print(filename)
  95. dirname = os.path.dirname(filename)
  96. while not os.path.exists(os.path.join(dirname, 'BUILD.gn')):
  97. dirname = os.path.dirname(dirname)
  98. rel = filename[len(dirname) + 1:]
  99. gnfile = os.path.join(dirname, 'BUILD.gn')
  100. lines = open(gnfile).read().splitlines()
  101. matched = [i for i, l in enumerate(lines) if ' sources = [' in l]
  102. if skip_ambiguous and len(matched) > 1:
  103. print('[WARNING] Multiple sources in', gnfile)
  104. continue
  105. if len(matched) < 1:
  106. continue
  107. print(' ', gnfile, rel)
  108. index = matched[0]
  109. lines.insert(index + 1, '"%s",' % rel)
  110. open(gnfile, 'w').write('\n'.join(lines) + '\n')
  111. def RemoveHeader(headers, skip_ambiguous=True):
  112. """Remove non-existing headers in GN files.
  113. When skip_ambiguous is True, skip if multiple matches are found.
  114. """
  115. edits = {}
  116. unhandled = []
  117. for filename in headers:
  118. filename = filename.strip()
  119. if not (filename.endswith('.h') or filename.endswith('.hh')):
  120. continue
  121. basename = os.path.basename(filename)
  122. print(filename)
  123. out, returncode = GitGrep('(/|")' + basename + '"')
  124. if returncode != 0 or not out:
  125. unhandled.append(filename)
  126. print(' Not found')
  127. continue
  128. grep_lines = out.splitlines()
  129. matches = []
  130. for line in grep_lines:
  131. gnfile, linenr, contents = line.split(':')
  132. print(' ', gnfile, linenr, contents)
  133. linenr = int(linenr)
  134. lines = open(gnfile).read().splitlines()
  135. assert contents in lines[linenr - 1]
  136. matches.append((gnfile, linenr, contents))
  137. if len(matches) == 0:
  138. continue
  139. if len(matches) > 1:
  140. print('\n[WARNING] Ambiguous matching for', filename)
  141. for i in enumerate(matches, 1):
  142. print('%d: %s' % (i[0], i[1]))
  143. print()
  144. if skip_ambiguous:
  145. continue
  146. picked = raw_input('Pick the matches ("2,3" for multiple): ')
  147. try:
  148. matches = [matches[int(i) - 1] for i in picked.split(',')]
  149. except (ValueError, IndexError):
  150. continue
  151. for match in matches:
  152. gnfile, linenr, contents = match
  153. print(' ', gnfile, linenr, contents)
  154. edits.setdefault(gnfile, set()).add(linenr)
  155. for gnfile in edits:
  156. lines = open(gnfile).read().splitlines()
  157. for l in sorted(edits[gnfile], reverse=True):
  158. lines.pop(l - 1)
  159. open(gnfile, 'w').write('\n'.join(lines) + '\n')
  160. return unhandled
  161. def main():
  162. parser = argparse.ArgumentParser()
  163. parser.add_argument('input_file', help="missing or non-existing headers, "
  164. "output of check_gn_headers.py")
  165. parser.add_argument('--prefix',
  166. help="only handle path name with this prefix")
  167. parser.add_argument('--remove', action='store_true',
  168. help="treat input_file as non-existing headers")
  169. args, _extras = parser.parse_known_args()
  170. headers = open(args.input_file).readlines()
  171. if args.prefix:
  172. headers = [i for i in headers if i.startswith(args.prefix)]
  173. if args.remove:
  174. RemoveHeader(headers, False)
  175. else:
  176. unhandled = AddHeadersNextToCC(headers)
  177. AddHeadersToSources(unhandled)
  178. if __name__ == '__main__':
  179. sys.exit(main())