summaryrefslogtreecommitdiffstats
path: root/tools/pragmaonce/pragmaonce.py
blob: 15224c49edbf149c6a7781e961b8beafb5885b64 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# Copyright (c) 2010 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import re
import sys

# A tool to add "#pragma once" lines to files that don't have it yet.
# Intended usage:
#   find chrome -name '*.h' -exec python tools/pragmaonce/pragmaonce.py {} \;

# Some files have absurdly long comments at the top
NUM_LINES_TO_SCAN_FOR_GUARD = 250

def main(filename):
  f = open(filename)
  lines = f.readlines()
  f.close()

  index = -1
  for i in xrange(min(NUM_LINES_TO_SCAN_FOR_GUARD, len(lines) - 1)):
    m1 = re.match(r'^#ifndef ([A-Z_0-9]+)$', lines[i])
    m2 = re.match(r'^#define ([A-Z_0-9]+)$', lines[i + 1])
    if m1 and m2:
      if m1.group(1) != m2.group(1):
        print 'Skipping', filename, \
              ': Broken include guard (%s, %s)' % (m1.group(1), m2.group(1))
      index = i + 2
      break

  if index == -1:
    print 'Skipping', filename, ': no include guard found'
    return

  if index < len(lines) and re.match(r'#pragma once', lines[index]):
    # The pragma is already there.
    return

  lines.insert(index, "#pragma once\n")

  f = open(filename, 'w')
  f.write(''.join(lines))
  f.close()

if __name__ == '__main__':
  if len(sys.argv) != 2:
    print >>sys.stderr, "Usage: %s inputfile" % sys.argv[0]
    sys.exit(1)
  main(sys.argv[1])