blob: 74a2a4d10e13413e0a32d180bce534214d9a614c [file] [log] [blame]
[email protected]fb9d58c2014-03-20 17:43:101#!/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': '//',
sdefresne5feb0b42016-03-15 11:03:4028 'py': '#',
29 'gn': '#',
30 'gni': '#',
[email protected]fb9d58c2014-03-20 17:43:1031}
32
33def _GetHeader(filename):
34 _, ext = os.path.splitext(filename)
35 ext = ext[1:]
36 comment = EXTENSIONS_TO_COMMENTS[ext] + ' '
37 return '\n'.join([comment + line for line in LINES])
38
39
40def _CppHeader(filename):
rohitrao786f94382016-11-16 02:47:1541 guard = filename.upper() + '_'
marq070cc782016-11-15 16:19:2542 for char in '/.+':
43 guard = guard.replace(char, '_')
[email protected]fb9d58c2014-03-20 17:43:1044 return '\n'.join([
45 '',
46 '#ifndef ' + guard,
47 '#define ' + guard,
48 '',
49 '#endif // ' + guard,
50 ''
51 ])
52
53
54def _CppImplementation(filename):
55 base, _ = os.path.splitext(filename)
56 include = '#include "' + base + '.h"'
57 return '\n'.join(['', include])
58
59
kkhorimotocc826ad2016-02-11 20:17:4660def _ObjCppImplementation(filename):
61 base, _ = os.path.splitext(filename)
62 include = '#import "' + base + '.h"'
63 return '\n'.join(['', include])
64
65
[email protected]fb9d58c2014-03-20 17:43:1066def _CreateFile(filename):
67 contents = _GetHeader(filename) + '\n'
68
69 if filename.endswith('.h'):
70 contents += _CppHeader(filename)
kkhorimotocc826ad2016-02-11 20:17:4671 elif filename.endswith('.cc'):
[email protected]fb9d58c2014-03-20 17:43:1072 contents += _CppImplementation(filename)
kkhorimotocc826ad2016-02-11 20:17:4673 elif filename.endswith('.mm'):
74 contents += _ObjCppImplementation(filename)
[email protected]fb9d58c2014-03-20 17:43:1075
76 fd = open(filename, 'w')
77 fd.write(contents)
78 fd.close()
79
80
81def Main():
82 files = sys.argv[1:]
83 if len(files) < 1:
84 print >> sys.stderr, 'Usage: boilerplate.py path/to/file.h path/to/file.cc'
85 return 1
86
87 # Perform checks first so that the entire operation is atomic.
88 for f in files:
89 _, ext = os.path.splitext(f)
90 if not ext[1:] in EXTENSIONS_TO_COMMENTS:
91 print >> sys.stderr, 'Unknown file type for %s' % f
92 return 2
93
94 if os.path.exists(f):
95 print >> sys.stderr, 'A file at path %s already exists' % f
96 return 2
97
98 for f in files:
99 _CreateFile(f)
100
101
102if __name__ == '__main__':
103 sys.exit(Main())