|
| 1 | +import re |
| 2 | + |
| 3 | +import click |
| 4 | +from dateutil.utils import today |
| 5 | +from glob import glob |
| 6 | +from os.path import dirname, join, abspath |
| 7 | + |
| 8 | + |
| 9 | +# path to the the pytest_cases folder |
| 10 | +root = abspath(join(dirname(__file__), '../pytest_cases')) |
| 11 | +default_tmpl = abspath(join(dirname(__file__), 'headers.tmpl')) |
| 12 | + |
| 13 | + |
| 14 | +@click.command() |
| 15 | +@click.option('-s', '--single', 'single', is_flag=True) |
| 16 | +@click.option('-r', '--remove', 'action', flag_value='remove') |
| 17 | +@click.option('-i', '--inject', 'action', flag_value='inject', default=True) |
| 18 | +def check_all_headers(path=root, headers_template=default_tmpl, action='inject', single=False): |
| 19 | + """ |
| 20 | +
|
| 21 | + :param path: |
| 22 | + :param headers_template: |
| 23 | + :param remove: |
| 24 | + :return: |
| 25 | + """ |
| 26 | + headers_tmpl = "" |
| 27 | + with open(headers_template) as f: |
| 28 | + for line in f.readlines(): |
| 29 | + headers_tmpl += "# %s" % line if line != "\n" else "#\n" |
| 30 | + |
| 31 | + # note: the year now disappeared, everything is redirected to the LICENSE file at the root |
| 32 | + headers_regex = re.compile(re.escape(headers_tmpl).replace("\\{", "{").replace("\\}", "}").format(year=".*")) |
| 33 | + headers = headers_tmpl.format(year=today().year) |
| 34 | + |
| 35 | + # rel_root = relpath(abspath(root), getcwd()) |
| 36 | + for f in glob("%s/**/*.py" % path, recursive=True): |
| 37 | + # skip meta tests |
| 38 | + if "meta" in f: |
| 39 | + print("skipping file %s" % f) |
| 40 | + continue |
| 41 | + |
| 42 | + # read file |
| 43 | + with open(f, mode="rt") as contents: |
| 44 | + src = contents.read() |
| 45 | + |
| 46 | + # skip empty files |
| 47 | + if src.strip() == "": |
| 48 | + print("skipping file %s as it is empty" % f) |
| 49 | + continue |
| 50 | + |
| 51 | + if action == 'inject': |
| 52 | + if src.startswith(headers): |
| 53 | + continue |
| 54 | + match = headers_regex.match(src) |
| 55 | + if match: |
| 56 | + # different year. remove the existing header and re-apply |
| 57 | + src = src[match.end():] |
| 58 | + new_contents = headers + src |
| 59 | + elif action == 'remove': |
| 60 | + if src.startswith(headers): |
| 61 | + new_contents = src[len(headers):] |
| 62 | + else: |
| 63 | + match = headers_regex.match(src) |
| 64 | + if match: |
| 65 | + new_contents = src[match.end():] |
| 66 | + else: |
| 67 | + continue |
| 68 | + else: |
| 69 | + raise ValueError("invalid action: %s" % action) |
| 70 | + |
| 71 | + with open(f, mode="wt") as contents: |
| 72 | + contents.write(new_contents) |
| 73 | + |
| 74 | + if single: |
| 75 | + print("single file modded '%s' - exiting" % f) |
| 76 | + break |
| 77 | + |
| 78 | + |
| 79 | +if __name__ == '__main__': |
| 80 | + check_all_headers() |
0 commit comments