1 | """ |
---|
2 | # BSD Licence |
---|
3 | # Copyright (c) 2009, Science & Technology Facilities Council (STFC) |
---|
4 | # All rights reserved. |
---|
5 | # |
---|
6 | # See the LICENSE file in the source distribution of this software for |
---|
7 | # the full license text. |
---|
8 | |
---|
9 | Insert a copywrite notice at the top of any python files given as arguments. |
---|
10 | |
---|
11 | """ |
---|
12 | |
---|
13 | import datetime |
---|
14 | import os, re, sys |
---|
15 | |
---|
16 | license_text = """ |
---|
17 | # BSD Licence |
---|
18 | # Copyright (c) %(year)s, Science & Technology Facilities Council (STFC) |
---|
19 | # All rights reserved. |
---|
20 | # |
---|
21 | %(msg)s |
---|
22 | |
---|
23 | """.lstrip() |
---|
24 | |
---|
25 | |
---|
26 | default_message = """ |
---|
27 | See the LICENSE file in the source distribution of this software for |
---|
28 | the full license text. |
---|
29 | """.strip() |
---|
30 | |
---|
31 | def add_license(filename, year=None, msg=None): |
---|
32 | """ |
---|
33 | Add a license to a file |
---|
34 | |
---|
35 | """ |
---|
36 | |
---|
37 | ext = os.path.splitext(filename)[1][1:] |
---|
38 | #!TODO: Add xml when fixme below complete |
---|
39 | if ext not in ['py']: |
---|
40 | raise ValueError('Extension %s not supported' % ext) |
---|
41 | |
---|
42 | if year is None: |
---|
43 | year = datetime.datetime.now().year |
---|
44 | if msg is None: |
---|
45 | msg = default_message |
---|
46 | |
---|
47 | msg = '\n'.join('# %s'%x for x in msg.split('\n')) |
---|
48 | |
---|
49 | license = license_text % dict(msg=msg, year=year) |
---|
50 | |
---|
51 | fh_in = open(filename) |
---|
52 | fh_out = open('%s.tmp' % filename, 'w') |
---|
53 | |
---|
54 | if ext == 'py': |
---|
55 | line = fh_in.readline() |
---|
56 | if line[:2] == '#!': |
---|
57 | fh_out.write(line) |
---|
58 | line = fh_in.readline() |
---|
59 | fh_out.write(license) |
---|
60 | else: |
---|
61 | fh_out.write(license) |
---|
62 | fh_out.write(line) |
---|
63 | |
---|
64 | #!FIXME: This bit is broken because it doesn't look for <!DOCTYPE!> |
---|
65 | # declarations |
---|
66 | elif ext == 'xml': |
---|
67 | line = fh_in.readline() |
---|
68 | if re.match(r'<\?xml', line): |
---|
69 | fh_out.write(line) |
---|
70 | line = fh_in.readline() |
---|
71 | |
---|
72 | fh_out.write('<!--\n') |
---|
73 | fh_out.write(license) |
---|
74 | fh_out.write('-->\n') |
---|
75 | |
---|
76 | |
---|
77 | for line in fh_in: |
---|
78 | fh_out.write(line) |
---|
79 | |
---|
80 | fh_in.close() |
---|
81 | fh_out.close() |
---|
82 | os.system('mv %s %s.orig' % (filename, filename)) |
---|
83 | os.system('mv %s.tmp %s' % (filename, filename)) |
---|
84 | print 'Added license to %s, original is %s.orig' % (filename, filename) |
---|
85 | |
---|
86 | |
---|
87 | def main(argv=sys.argv): |
---|
88 | for filename in argv[1:]: |
---|
89 | add_license(filename) |
---|
90 | |
---|
91 | |
---|
92 | |
---|
93 | if __name__ == '__main__': |
---|
94 | main() |
---|