#!/usr/bin/env python3.5
# -*- mode: python -*-
# Copyright 2016 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

"""Find imports that occur before `__all__`, if the latter is present.

Exits non-zero if any are found.
"""

import argparse
import sys
import tokenize


def find_early_imports(filepath):
    has_early_import = has_all_declaration = False
    with open(filepath, "rb") as fd:
        for token in tokenize.tokenize(fd.readline):
            if token.type == tokenize.NAME:
                if token.string in {"import", "from"}:
                    if not has_all_declaration:
                        has_early_import = True
                elif token.string == "__all__":
                    has_all_declaration = True
                    if not has_early_import:
                        break  # Short-circuit.
                else:
                    pass  # Keep looking.
    return has_all_declaration and has_early_import


argument_parser = argparse.ArgumentParser(
    formatter_class=argparse.RawDescriptionHelpFormatter,
    description=__doc__)
argument_parser.add_argument(
    "filenames", nargs="+", metavar="FILENAME")


if __name__ == '__main__':
    options = argument_parser.parse_args()

    has_early_imports = False
    for filename in options.filenames:
        if find_early_imports(filename):
            if has_early_imports:
                print(filename)
            else:
                has_early_imports = True
                print("Early imports found:", file=sys.stderr)
                print(filename)

    raise SystemExit(
        1 if has_early_imports else 0)
