source: cows/branches/cows-vis/add_license.py @ 4912

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/cows/branches/cows-vis/add_license.py@5265
Revision 4912, 2.2 KB checked in by spascoe, 11 years ago (diff)

Added LICENSE file and a short banner at the top of each python file.
Use add_license.py to add a license to new files.

NOTE: also contains a couple of files missed at last commit.

Line 
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
9Insert a copywrite notice at the top of any python files given as arguments.
10
11"""
12
13import datetime
14import os, re, sys
15
16license_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
26default_message = """
27See the LICENSE file in the source distribution of this software for
28the full license text.
29""".strip()
30
31def 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
87def main(argv=sys.argv):
88    for filename in argv[1:]:
89        add_license(filename)
90   
91   
92
93if __name__ == '__main__':
94    main()
Note: See TracBrowser for help on using the repository browser.