# SPDX-FileCopyrightText: Stone Tickle <lattis@mochiro.moe>
# SPDX-License-Identifier: GPL-3.0-only

fs = import('fs')

func file_list(source_root str) -> list[str]
    l = ['meson.build', 'meson_options.txt']

    foreach dir : ['doc', 'src', 'tests']
        l += fs.glob(source_root / f'@dir@/**/meson.build')
        l += fs.glob(source_root / f'@dir@/**/*.meson')
        l += fs.glob(source_root / f'@dir@/**/meson_options.txt')
    endforeach

    return l
endfunc

muon = argv[1]
source_root = argv[2]

fail_fast = 'f' in argv # TODO make this a proper argument

files = []
exclude = ['badnum.meson', 'line_continuation.meson']

foreach f : file_list(source_root)
    basename = fs.name(f)
    if basename in exclude or 'tests/fmt/editorconfig' in f or 'tests/fmt/cases' in f
        continue
    endif

    files += f
endforeach

failing_len = 0
passing_len = 0
files_len = files.length()

diff = find_program('diff', required: false)

foreach f : files
    path = source_root / f
    res = run_command(muon, 'fmt', '-eq', path, check: false)
    if res.returncode() == 0
        passing_len += 1
    else
        failing_len += 1

        print(f'\033[31mfailing\033[0m: @path@\n')
        if diff.found()
            tmp_file = '/tmp/muon_fmt_diff_tmp'
            fs.write(tmp_file, run_command(muon, 'fmt', path).stdout())
            print(run_command(diff, path, tmp_file).stdout())
        endif

        if fail_fast
            break
        endif
    endif
endforeach

print(f'@passing_len@/@files_len@ passed\n')

if failing_len > 0
    error('errors encountered')
endif
