blob: 9fa0dc78d5bc98889ae1008cb1e3eda2a1acb16c [file] [log] [blame]
David Brazdil6c63a262019-12-23 13:23:46 +00001#!/usr/bin/env python3
Andrew Scull18834872018-10-12 11:48:09 +01002#
Andrew Walbran692b3252019-03-07 15:51:31 +00003# Copyright 2018 The Hafnium Authors.
Andrew Scull18834872018-10-12 11:48:09 +01004#
Andrew Walbrane959ec12020-06-17 15:01:09 +01005# 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.
Andrew Scull18834872018-10-12 11:48:09 +01008
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
Andrew Walbran928d8c12019-01-11 04:29:39 +000016import datetime
17import re
Andrew Scull18834872018-10-12 11:48:09 +010018import sys
19
20
Andrew Walbrane959ec12020-06-17 15:01:09 +010021bsd = """{comment} Copyright {year} The Hafnium Authors.
Andrew Scull18834872018-10-12 11:48:09 +010022{comment}
Andrew Walbrane959ec12020-06-17 15:01:09 +010023{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."""
Andrew Scull18834872018-10-12 11:48:09 +010026
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 ""
Andrew Walbran928d8c12019-01-11 04:29:39 +000033 year = str(datetime.datetime.now().year)
Andrew Walbrane959ec12020-06-17 15:01:09 +010034 header += bsd.format(comment=" *" if args.style == "c" else "#", year=year)
Andrew Scull18834872018-10-12 11:48:09 +010035 header += "\n */" if args.style == "c" else ""
36 header += "\n\n"
Andrew Walbran928d8c12019-01-11 04:29:39 +000037 header_regex = re.escape(header).replace(year, r"\d\d\d\d")
Olivier Deprez830702b2021-01-18 10:23:39 +010038 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
Andrew Walbran928d8c12019-01-11 04:29:39 +000045 if re.search(header_regex, contents):
Andrew Scull18834872018-10-12 11:48:09 +010046 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())