#!/usr/bin/env python3
"""Script to replace Golang lint exceptions by current errors.

Do not use this blindly! Typical use case would be merging upstream
in the case their changes are just about line numbers.
"""
import os
from pathlib import Path
import subprocess

BASE_DIR = Path(__file__).parent


TOOLCHAINS = (
    None,  # means there is currently a single lint exceptions file
    # example possible value to use if several exceptions file come
    # back upstream: 'go1.22.5'
)


def short_version(toolchain):
    if not toolchain.startswith('go'):
        raise ValueError("Not a valid Golang toolchain: %r" % toolchain)
    return toolchain[2:].rsplit('.', 1)[0]


def generate_exceptions(toolchain):
    env = dict(os.environ)
    if toolchain is None:
        print("Generating common lint exceptions file for all toolchains")
        file_name = 'lint_last_known_acceptable.txt'
    else:
        print(f"Generating lint exceptions file for toolchain {toolchain}")
        env['GOTOOLCHAIN'] = toolchain
        gov = short_version(toolchain)
        file_name = f'lint_last_known_acceptable_go{gov}.txt'

    env['GOFLAGS'] = '-buildvcs=false'
    env['GODEBUG'] = 'allowmultiplevcs=1'

    subp_opts = dict(env=env, cwd=BASE_DIR.parent)
    out = subprocess.check_output(('make', 'golangci'), **subp_opts)
    file_path = BASE_DIR / file_name
    file_path.write_bytes(out)
    print("Now running full `make verify`")
    subprocess.check_call(('make', 'verify'), **subp_opts)
    input("Press enter to display resulting diff against p1()")
    subprocess.run(('hg', 'di', '-r', 'p1()', file_path),
                    **subp_opts)


def main():
    for toolchain in TOOLCHAINS:
        generate_exceptions(toolchain)
        print("\n\n")


if __name__ == '__main__':
    main()



