1#!/usr/bin/env python
2# Copyright 2014 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
6"""Create files with copyright boilerplate and header include guards.
7
8Usage: tools/boilerplate.py path/to/file.{h,cc}
9"""
10
11from datetime import date
12import os
13import os.path
14import sys
15
16LINES = [
17    'Copyright %d The Chromium Authors. All rights reserved.' %
18        date.today().year,
19    'Use of this source code is governed by a BSD-style license that can be',
20    'found in the LICENSE file.'
21]
22
23EXTENSIONS_TO_COMMENTS = {
24    'h': '//',
25    'cc': '//',
26    'mm': '//',
27    'js': '//',
28    'py': '#'
29}
30
31def _GetHeader(filename):
32  _, ext = os.path.splitext(filename)
33  ext = ext[1:]
34  comment = EXTENSIONS_TO_COMMENTS[ext] + ' '
35  return '\n'.join([comment + line for line in LINES])
36
37
38def _CppHeader(filename):
39  guard = filename.replace('/', '_').replace('.', '_').upper() + '_'
40  return '\n'.join([
41    '',
42    '#ifndef ' + guard,
43    '#define ' + guard,
44    '',
45    '#endif  // ' + guard,
46    ''
47  ])
48
49
50def _CppImplementation(filename):
51  base, _ = os.path.splitext(filename)
52  include = '#include "' + base + '.h"'
53  return '\n'.join(['', include])
54
55
56def _CreateFile(filename):
57  contents = _GetHeader(filename) + '\n'
58
59  if filename.endswith('.h'):
60    contents += _CppHeader(filename)
61  elif filename.endswith('.cc') or filename.endswith('.mm'):
62    contents += _CppImplementation(filename)
63
64  fd = open(filename, 'w')
65  fd.write(contents)
66  fd.close()
67
68
69def Main():
70  files = sys.argv[1:]
71  if len(files) < 1:
72    print >> sys.stderr, 'Usage: boilerplate.py path/to/file.h path/to/file.cc'
73    return 1
74
75  # Perform checks first so that the entire operation is atomic.
76  for f in files:
77    _, ext = os.path.splitext(f)
78    if not ext[1:] in EXTENSIONS_TO_COMMENTS:
79      print >> sys.stderr, 'Unknown file type for %s' % f
80      return 2
81
82    if os.path.exists(f):
83      print >> sys.stderr, 'A file at path %s already exists' % f
84      return 2
85
86  for f in files:
87    _CreateFile(f)
88
89
90if __name__ == '__main__':
91  sys.exit(Main())
92