1+ # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
2+ #
3+ # Licensed under the Apache License, Version 2.0 (the "License");
4+ # you may not use this file except in compliance with the License.
5+ # You may obtain a copy of the License at
6+ #
7+ # http://www.apache.org/licenses/LICENSE-2.0
8+ #
9+ # Unless required by applicable law or agreed to in writing, software
10+ # distributed under the License is distributed on an "AS IS" BASIS,
11+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+ # See the License for the specific language governing permissions and
13+ # limitations under the License.
14+
115from __future__ import absolute_import
216from __future__ import print_function
317from __future__ import unicode_literals
418
519import argparse
6- import io, re
7- import sys, os
8- import subprocess
9- import platform
20+ import io
21+ import re
22+ import sys
23+ import os
24+ import datetime
1025
11- COPYRIGHT = '''
12- Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
26+ COPYRIGHT = '''Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
1327
1428Licensed under the Apache License, Version 2.0 (the "License");
1529you may not use this file except in compliance with the License.
@@ -21,74 +35,80 @@ Unless required by applicable law or agreed to in writing, software
2135distributed under the License is distributed on an "AS IS" BASIS,
2236WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2337See the License for the specific language governing permissions and
24- limitations under the License.
25- '''
38+ limitations under the License.'''
2639
27- LANG_COMMENT_MARK = None
40+ def _generate_copyright(comment_mark):
41+ copyright=COPYRIGHT.split(os.linesep)
42+ header = copyright[0].rstrip()
2843
29- NEW_LINE_MARK = None
44+ p = re.search('(\d{4})', header).group(0)
45+ now = datetime.datetime.now()
3046
31- COPYRIGHT_HEADER = None
47+ header = header.replace(p,str(now.year))
3248
33- if platform.system() == "Windows":
34- NEW_LINE_MARK = "\r\n"
35- else:
36- NEW_LINE_MARK = '\n'
37- COPYRIGHT_HEADER = COPYRIGHT.split(NEW_LINE_MARK)[1]
38- p = re.search('(\d{4})', COPYRIGHT_HEADER).group(0)
39- process = subprocess.Popen(["date", "+%Y"], stdout=subprocess.PIPE)
40- date, err = process.communicate()
41- date = date.decode("utf-8").rstrip("\n")
42- COPYRIGHT_HEADER = COPYRIGHT_HEADER.replace(p, date)
49+ ans=[comment_mark + " " + header + os.linesep]
50+ for idx, line in enumerate(copyright[1:]):
51+ ans.append(comment_mark + " " + line.rstrip() + os.linesep)
4352
53+ return ans
4454
45- def generate_copyright(template, lang='C'):
46- if lang == 'Python':
47- LANG_COMMENT_MARK = '#'
48- else:
49- LANG_COMMENT_MARK = "//"
50-
51- lines = template.split(NEW_LINE_MARK)
52- BLANK = " "
53- ans = LANG_COMMENT_MARK + BLANK + COPYRIGHT_HEADER + NEW_LINE_MARK
54- for lino, line in enumerate(lines):
55- if lino == 0 or lino == 1 or lino == len(lines) - 1: continue
56- if len(line) == 0:
57- BLANK = ""
58- else:
59- BLANK = " "
60- ans += LANG_COMMENT_MARK + BLANK + line + NEW_LINE_MARK
61-
62- return ans + "\n"
63-
64-
65- def lang_type(filename):
66- if filename.endswith(".py"):
67- return "Python"
68- elif filename.endswith(".h"):
69- return "C"
70- elif filename.endswith(".c"):
71- return "C"
72- elif filename.endswith(".hpp"):
73- return "C"
74- elif filename.endswith(".cc"):
75- return "C"
76- elif filename.endswith(".cpp"):
77- return "C"
78- elif filename.endswith(".cu"):
79- return "C"
80- elif filename.endswith(".cuh"):
81- return "C"
82- elif filename.endswith(".go"):
83- return "C"
84- elif filename.endswith(".proto"):
85- return "C"
55+ def _get_comment_mark(path):
56+ lang_type=re.compile(r"\.(py|sh)$")
57+ if lang_type.search(path) is not None:
58+ return "#"
59+
60+ lang_type=re.compile(r"\.(h|c|hpp|cc|cpp|cu|go|cuh|proto)$")
61+ if lang_type.search(path) is not None:
62+ return "//"
63+
64+ return None
65+
66+
67+ RE_ENCODE = re.compile(r"^[ \t\v]*#.*?coding[:=]", re.IGNORECASE)
68+ RE_COPYRIGHT = re.compile(r".*Copyright \(c\) \d{4}", re.IGNORECASE)
69+ RE_SHEBANG = re.compile(r"^[ \t\v]*#[ \t]?\!")
70+
71+ def _check_copyright(path):
72+ head=[]
73+ try:
74+ with open(path) as f:
75+ head = [next(f) for x in range(4)]
76+ except StopIteration:
77+ pass
78+
79+ for idx, line in enumerate(head):
80+ if RE_COPYRIGHT.search(line) is not None:
81+ return True
82+
83+ return False
84+
85+ def generate_copyright(path, comment_mark):
86+ original_contents = io.open(path, encoding="utf-8").readlines()
87+ head = original_contents[0:4]
88+
89+ insert_line_no=0
90+ for i, line in enumerate(head):
91+ if RE_ENCODE.search(line) or RE_SHEBANG.search(line):
92+ insert_line_no=i+1
93+
94+ copyright = _generate_copyright(comment_mark)
95+ if insert_line_no == 0:
96+ new_contents = copyright
97+ if len(original_contents) > 0 and len(original_contents[0].strip()) != 0:
98+ new_contents.append(os.linesep)
99+ new_contents.extend(original_contents)
86100 else:
87- print("Unsupported filetype %s", filename)
88- exit(0)
101+ new_contents=original_contents[0:insert_line_no]
102+ new_contents.append(os.linesep)
103+ new_contents.extend(copyright)
104+ if len(original_contents) > insert_line_no and len(original_contents[insert_line_no].strip()) != 0:
105+ new_contents.append(os.linesep)
106+ new_contents.extend(original_contents[insert_line_no:])
107+ new_contents="".join(new_contents)
89108
109+ with io.open(path, 'w') as output_file:
110+ output_file.write(new_contents)
90111
91- PYTHON_ENCODE = re.compile("^[ \t\v]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)")
92112
93113
94114def main(argv=None):
@@ -98,23 +118,16 @@ def main(argv=None):
98118 args = parser.parse_args(argv)
99119
100120 retv = 0
101- for filename in args.filenames:
102- fd = io.open(filename, encoding="utf-8")
103- first_line = fd.readline()
104- second_line = fd.readline()
105- if "COPYRIGHT (C)" in first_line.upper(): continue
106- if first_line.startswith("#!") or PYTHON_ENCODE.match(
107- second_line) != None or PYTHON_ENCODE.match(first_line) != None:
121+ for path in args.filenames:
122+ comment_mark = _get_comment_mark(path)
123+ if comment_mark is None:
124+ print("warning:Unsupported file", path, file=sys.stderr)
108125 continue
109- original_contents = io.open(filename, encoding="utf-8").read()
110- new_contents = generate_copyright(
111- COPYRIGHT, lang_type(filename)) + original_contents
112- print('Auto Insert Copyright Header {}'.format(filename))
113- retv = 1
114- with io.open(filename, 'w') as output_file:
115- output_file.write(new_contents)
116-
117- return retv
126+
127+ if _check_copyright(path):
128+ continue
129+
130+ generate_copyright(path, comment_mark)
118131
119132
120133if __name__ == '__main__':
0 commit comments