#!/usr/bin/env python3

import configparser
import os
import re
import sys

import gitignorefile


DEFAULT_EXCLUDES = "/(\\.direnv|\\.eggs|\\.git|\\.hg|\\.mypy_cache|\\.nox|\\.tox|\\.venv|venv|\\.svn|_build|buck-out|build|dist|__pypackages__)/"
DEFAULT_INCLUDES = "(\\.pyi?|\\.ipynb)$"

show_names = "names" in sys.argv


def get_parents():
    path = os.path.abspath(os.getcwd())
    while True:
        yield path

        parent = os.path.dirname(path)
        if os.path.samefile(path, parent):
            return

        else:
            path = parent


def filter_value(value):
    assert value.startswith('"') and value.endswith('"')
    return value[1:-1]


for parent in get_parents():
    path = os.path.join(parent, "pyproject.toml")
    if os.path.isfile(path):
        break

else:
    assert False, "Could not find `pyproject.toml`."

config = configparser.ConfigParser()
config.read(path)
exclude = filter_value(config.get("tool.black", "exclude", fallback=f'"{DEFAULT_EXCLUDES}"'))
include = filter_value(config.get("tool.black", "include", fallback=f'"{DEFAULT_INCLUDES}"'))
gi = gitignorefile.Cache()

loc = 0

for root, directories, names in os.walk(parent):
    for name in names:
        if name != ".git":
            path = os.path.join(root, name)
            if not gi(path):
                re_path = path[len(parent) :].replace("\\", "/")
                if re.search(include, re_path) and not re.search(exclude, re_path):
                    if show_names:
                        print(os.path.relpath(path))

                    else:
                        with open(path) as f:
                            loc += len(f.read().splitlines())

if not show_names:
    print(loc)
