| 1 |
###################################################################### |
| 2 |
# |
| 3 |
# File: test/static/test_licenses.py |
| 4 |
# |
| 5 |
# Copyright 2020 Backblaze Inc. All Rights Reserved. |
| 6 |
# |
| 7 |
# License https://www.backblaze.com/using_b2_code.html |
| 8 |
# |
| 9 |
###################################################################### |
| 10 |
from datetime import datetime |
| 11 |
from glob import glob |
| 12 |
from itertools import islice |
| 13 |
|
| 14 |
import pytest |
| 15 |
|
| 16 |
FIXER_CMD = "python test/static/test_licenses.py" |
| 17 |
LICENSE_HEADER_TMPL = """\ |
| 18 |
###################################################################### |
| 19 |
# |
| 20 |
# File: {path} |
| 21 |
# |
| 22 |
# Copyright {year} Backblaze Inc. All Rights Reserved. |
| 23 |
# |
| 24 |
# License https://www.backblaze.com/using_b2_code.html |
| 25 |
# |
| 26 |
###################################################################### |
| 27 |
""" |
| 28 |
|
| 29 |
|
| 30 |
def get_file_header_errors(file_path_glob: str) -> dict[str, str]: |
| 31 |
failed_files = {} |
| 32 |
for file in glob(file_path_glob, recursive=True): |
| 33 |
if file.startswith('build/'): |
| 34 |
# built files naturally have a different file path than source files |
| 35 |
continue |
| 36 |
with open(file) as fd: |
| 37 |
file = file.replace( |
| 38 |
'\\', '/' |
| 39 |
) # glob('**/*.py') on Windows returns "b2\console_tool.py" (wrong slash) |
| 40 |
head = ''.join(islice(fd, 9)) |
| 41 |
if 'All Rights Reserved' not in head: |
| 42 |
failed_files[file] = 'Missing "All Rights Reserved" in the header' |
| 43 |
elif file not in head: |
| 44 |
failed_files[file] = 'Wrong file name in the header' |
| 45 |
return failed_files |
| 46 |
|
| 47 |
|
| 48 |
def test_files_headers(): |
| 49 |
failed_files = get_file_header_errors('**/*.py') |
| 50 |
if failed_files: |
| 51 |
error_msg = '; '.join(f'{path}:{error}' for path, error in failed_files.items()) |
| 52 |
pytest.fail(f'Bad file headers in files (you may want to run {FIXER_CMD!r}): {error_msg}') |
| 53 |
|
| 54 |
|
| 55 |
def insert_header(file_path: str): |
| 56 |
with open(file_path, 'r+') as fd: |
| 57 |
content = fd.read() |
| 58 |
fd.seek(0) |
| 59 |
fd.write(LICENSE_HEADER_TMPL.format( |
| 60 |
path=file_path, |
| 61 |
year=datetime.now().year, |
| 62 |
)) |
| 63 |
fd.write(content) |
| 64 |
|
| 65 |
|
| 66 |
def _main(): |
| 67 |
failed_files = get_file_header_errors('**/*.py') |
| 68 |
for filepath in failed_files: |
| 69 |
insert_header(filepath) |
| 70 |
|
| 71 |
|
| 72 |
if __name__ == '__main__': |
| 73 |
_main() |