1#!/usr/bin/env python3
2#
3# Copyright 2018 The Hafnium Authors.
4#
5# Use of this source code is governed by a BSD-style
6# license that can be found in the LICENSE file or at
7# https://opensource.org/licenses/BSD-3-Clause.
8
9"""Add license header to source files.
10
11If the file doesn't have the license header, add it with the appropriate comment
12style.
13"""
14
15import argparse
16import datetime
17import re
18import sys
19
20
21bsd = """{comment} Copyright {year} The Hafnium Authors.
22{comment}
23{comment} Use of this source code is governed by a BSD-style
24{comment} license that can be found in the LICENSE file or at
25{comment} https://opensource.org/licenses/BSD-3-Clause."""
26
27def Main():
28    parser = argparse.ArgumentParser()
29    parser.add_argument("file")
30    parser.add_argument("--style", choices=["c", "hash"], required=True)
31    args = parser.parse_args()
32    header = "/*\n" if args.style == "c" else ""
33    year = str(datetime.datetime.now().year)
34    header += bsd.format(comment=" *" if args.style == "c" else "#", year=year)
35    header += "\n */" if args.style == "c" else ""
36    header += "\n\n"
37    header_regex = re.escape(header).replace(year, r"\d\d\d\d")
38    with open(args.file, "rb") as f:
39        try:
40            contents = f.read().decode('utf-8', 'strict')
41        except Exception as ex:
42            print("Failed reading: " + args.file +
43                " (" + ex.__class__.__name__ + ")")
44            return
45        if re.search(header_regex, contents):
46            return
47    with open(args.file, "w") as f:
48        f.write(header)
49        f.write(contents)
50
51if __name__ == "__main__":
52    sys.exit(Main())
53