2022-07-25 23:45:44 +03:00
|
|
|
# Copyright (c) Microsoft Corporation.
|
|
|
|
# Licensed under the MIT License.
|
2022-07-08 19:28:41 +03:00
|
|
|
|
2022-07-21 21:04:53 +03:00
|
|
|
"""Ensure copyright header is at the top of Python scripts."""
|
|
|
|
|
2022-07-08 19:28:41 +03:00
|
|
|
import argparse
|
|
|
|
import sys
|
|
|
|
from pathlib import Path
|
|
|
|
from typing import List
|
|
|
|
|
|
|
|
COPYRIGHT = [
|
2022-07-25 23:45:44 +03:00
|
|
|
"# Copyright (c) Microsoft Corporation.",
|
|
|
|
"# Licensed under the MIT License."
|
2022-07-08 19:28:41 +03:00
|
|
|
]
|
2023-05-01 19:41:02 +03:00
|
|
|
COPYRIGHT_SET = set(COPYRIGHT)
|
|
|
|
HEADER_SIZE = 5
|
2022-07-08 19:28:41 +03:00
|
|
|
|
|
|
|
|
2022-07-21 21:04:53 +03:00
|
|
|
def _test(testpaths: List[Path], excludes: List[Path] = []) -> bool:
|
2022-07-08 19:28:41 +03:00
|
|
|
badfiles = []
|
|
|
|
for testpath in testpaths:
|
|
|
|
for file in testpath.rglob("*.py"):
|
|
|
|
# Skip ignored files
|
2023-05-01 20:53:02 +03:00
|
|
|
if any([p in excludes for p in file.parents]):
|
2022-07-08 19:28:41 +03:00
|
|
|
continue
|
|
|
|
|
2022-07-25 23:45:44 +03:00
|
|
|
# Ignore zero-length files
|
|
|
|
if file.stat().st_size == 0:
|
|
|
|
continue
|
|
|
|
|
2022-07-08 19:28:41 +03:00
|
|
|
with open(file, encoding="utf8") as f:
|
2023-05-01 19:41:02 +03:00
|
|
|
# Read top HEADER_SIZE lines of file
|
|
|
|
header = []
|
|
|
|
for _ in range(0, HEADER_SIZE):
|
|
|
|
line = f.readline()
|
|
|
|
if not line:
|
|
|
|
# Handle EOF
|
2022-07-08 19:28:41 +03:00
|
|
|
break
|
2023-05-01 19:41:02 +03:00
|
|
|
header.append(line.rstrip())
|
|
|
|
|
|
|
|
# Check for copyright header
|
|
|
|
if not COPYRIGHT_SET <= set(header):
|
|
|
|
badfiles.append(file)
|
2022-07-08 19:28:41 +03:00
|
|
|
|
|
|
|
if len(badfiles) > 0:
|
|
|
|
print("File(s) missing copyright header:")
|
|
|
|
for line in badfiles:
|
|
|
|
print(line)
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
# Handle command-line args
|
|
|
|
parser = argparse.ArgumentParser()
|
2022-07-20 21:45:32 +03:00
|
|
|
parser.add_argument("-i", "--input-directories", required=True, type=Path, nargs='+',
|
|
|
|
help="Directories to validate")
|
|
|
|
parser.add_argument("-e", "--excludes", default=[], type=Path, nargs='+',
|
|
|
|
help="Directories to exclude")
|
2022-07-08 19:28:41 +03:00
|
|
|
args = parser.parse_args()
|
|
|
|
|
2022-07-21 21:04:53 +03:00
|
|
|
success = _test(args.input_directories, args.excludes)
|
2022-07-08 19:28:41 +03:00
|
|
|
|
|
|
|
if not success:
|
|
|
|
sys.exit(1)
|