#!/usr/bin/env python
#
# Copyright (C) 2025 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# Much of this implementation was borrowed from
# https://github.com/google/perfetto/blob/main/python/tools/code_format_python.py
#

import os
import subprocess
import sys

ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
YAPF_BIN = os.path.join(ROOT_DIR, '.venv', 'bin', 'yapf')

def get_python_files():
    cmd = ['git', 'ls-files']
    files = subprocess.check_output(cmd, text=True).splitlines()
    return [f for f in files if f.endswith('.py')]

if __name__ == '__main__':
    if not os.path.exists(YAPF_BIN):
        err = f'Cannot find {YAPF_BIN}\nRun tools/build_deps'
        print(err, file=sys.stderr)
        exit(127)

    cmd = [YAPF_BIN, '--parallel', '-i'] + get_python_files()
    try:
      subprocess.check_call(cmd)
    except subprocess.CalledProcessError as ex:
      print('`%s` returned %d' % (' '.join(cmd)[:128], ex.returncode))
      exit(ex.returncode)

