Exemple #1
0
def main():
    arguments = create_parser()
    if arguments.get('show_version'):
        print(INTRO)
        return

    if 'settings_path' in arguments:
        sp = arguments['settings_path']
        arguments['settings_path'] = os.path.abspath(sp) if os.path.isdir(
            sp) else os.path.dirname(os.path.abspath(sp))

    file_names = arguments.pop('files', [])
    if file_names == ['-']:
        SortImports(file_contents=sys.stdin.read(),
                    write_to_stdout=True,
                    **arguments)
    else:
        if not file_names:
            file_names = ['.']
            arguments['recursive'] = True
            if not arguments.get('apply', False):
                arguments['ask_to_apply'] = True
        config = from_path(os.path.abspath(file_names[0])
                           or os.getcwd()).copy()
        config.update(arguments)
        wrong_sorted_files = False
        skipped = []
        if arguments.get('recursive', False):
            file_names = iter_source_code(file_names, config, skipped)
        num_skipped = 0
        if config['verbose'] or config.get('show_logo', False):
            print(INTRO)
        for file_name in file_names:
            try:
                sort_attempt = SortImports(file_name, **arguments)
                incorrectly_sorted = sort_attempt.incorrectly_sorted
                if arguments.get('check', False) and incorrectly_sorted:
                    wrong_sorted_files = True
                if sort_attempt.skipped:
                    num_skipped += 1
            except IOError as e:
                print("WARNING: Unable to parse file {0} due to {1}".format(
                    file_name, e))
        if wrong_sorted_files:
            exit(1)

        num_skipped += len(skipped)
        if num_skipped and not arguments.get('quiet', False):
            if config['verbose']:
                for was_skipped in skipped:
                    print(
                        "WARNING: {0} was skipped as it's listed in 'skip' setting"
                        " or matches a glob in 'skip_glob' setting".format(
                            was_skipped))
            print("Skipped {0} files".format(num_skipped))
Exemple #2
0
def isort(check):  # sorting headers -the imports
    """
    Run isort on all the files in app and tests directory
    """
    exit_code = 0
    config = from_path(os.getcwd()).copy()
    config["check"] = check
    file_names = iter_source_code(["app", "tests", "manage.py"], config, [])
    for file_name in file_names:
        sort_attempt = sort_imports(file_name, **config)
        if sort_attempt:
            if sort_attempt.incorrectly_sorted:
                exit_code = 1
    raise sys.exit(exit_code)
Exemple #3
0
def main():
    arguments = create_parser()
    if arguments.get('show_version'):
        print(INTRO)
        return

    if 'settings_path' in arguments:
        sp = arguments['settings_path']
        arguments['settings_path'] = os.path.abspath(sp) if os.path.isdir(sp) else os.path.dirname(os.path.abspath(sp))

    file_names = arguments.pop('files', [])
    if file_names == ['-']:
        SortImports(file_contents=sys.stdin.read(), write_to_stdout=True, **arguments)
    else:
        if not file_names:
            file_names = ['.']
            arguments['recursive'] = True
            if not arguments.get('apply', False):
                arguments['ask_to_apply'] = True
        config = from_path(os.path.abspath(file_names[0]) or os.getcwd()).copy()
        config.update(arguments)
        wrong_sorted_files = False
        skipped = []
        if arguments.get('recursive', False):
            file_names = iter_source_code(file_names, config, skipped)
        num_skipped = 0
        if config['verbose'] or config.get('show_logo', False):
            print(INTRO)
        for file_name in file_names:
            try:
                sort_attempt = SortImports(file_name, **arguments)
                incorrectly_sorted = sort_attempt.incorrectly_sorted
                if arguments.get('check', False) and incorrectly_sorted:
                    wrong_sorted_files = True
                if sort_attempt.skipped:
                    num_skipped += 1
            except IOError as e:
                print("WARNING: Unable to parse file {0} due to {1}".format(file_name, e))
        if wrong_sorted_files:
            exit(1)

        num_skipped += len(skipped)
        if num_skipped and not arguments.get('quiet', False):
            if config['verbose']:
                for was_skipped in skipped:
                    print("WARNING: {0} was skipped as it's listed in 'skip' setting"
                        " or matches a glob in 'skip_glob' setting".format(was_skipped))
            print("Skipped {0} files".format(num_skipped))
Exemple #4
0
def main(argv=None):
    arguments = parse_args(argv)
    if arguments.get('show_version'):
        print(INTRO)
        return

    if arguments.get('ambiguous_r_flag'):
        print(
            'ERROR: Deprecated -r flag set. This flag has been replaced with -rm to remove ambiguity between it and '
            '-rc for recursive')
        sys.exit(1)

    arguments['check_skip'] = False
    if 'settings_path' in arguments:
        sp = arguments['settings_path']
        arguments['settings_path'] = os.path.abspath(sp) if os.path.isdir(
            sp) else os.path.dirname(os.path.abspath(sp))
        if not os.path.isdir(arguments['settings_path']):
            print("WARNING: settings_path dir does not exist: {0}".format(
                arguments['settings_path']))

    if 'virtual_env' in arguments:
        venv = arguments['virtual_env']
        arguments['virtual_env'] = os.path.abspath(venv)
        if not os.path.isdir(arguments['virtual_env']):
            print("WARNING: virtual_env dir does not exist: {0}".format(
                arguments['virtual_env']))

    file_names = arguments.pop('files', [])
    if file_names == ['-']:
        try:
            # python 3
            file_ = sys.stdin.buffer
        except AttributeError:
            # python 2
            file_ = sys.stdin
        SortImports(file_=file_, write_to_stdout=True, **arguments)
    else:
        if not file_names:
            file_names = ['.']
            arguments['recursive'] = True
            if not arguments.get('apply', False):
                arguments['ask_to_apply'] = True
        config = from_path(os.path.abspath(file_names[0])
                           or os.getcwd()).copy()
        config.update(arguments)
        wrong_sorted_files = False
        skipped = []
        if arguments.get('recursive', False):
            file_names = iter_source_code(file_names, config, skipped)
        num_skipped = 0
        if config['verbose'] or config.get('show_logo', False):
            print(INTRO)

        jobs = arguments.get('jobs')
        if jobs:
            import multiprocessing
            executor = multiprocessing.Pool(jobs)
            attempt_iterator = executor.imap(
                functools.partial(sort_imports, **arguments), file_names)
        else:
            attempt_iterator = (sort_imports(file_name, **arguments)
                                for file_name in file_names)

        for sort_attempt in attempt_iterator:
            if not sort_attempt:
                continue
            incorrectly_sorted = sort_attempt.incorrectly_sorted
            if arguments.get('check', False) and incorrectly_sorted:
                wrong_sorted_files = True
            if sort_attempt.skipped:
                num_skipped += 1

        if wrong_sorted_files:
            sys.exit(1)

        num_skipped += len(skipped)
        if num_skipped and not arguments.get('quiet', False):
            if config['verbose']:
                for was_skipped in skipped:
                    print(
                        "WARNING: {0} was skipped as it's listed in 'skip' setting"
                        " or matches a glob in 'skip_glob' setting".format(
                            was_skipped))
            print("Skipped {0} files".format(num_skipped))
Exemple #5
0
 def finalize_options(self):
     "Get options from config files."
     self.arguments = {}
     computed_settings = from_path(os.getcwd())
     for key, value in computed_settings.items():
         self.arguments[key] = value
Exemple #6
0
 def finalize_options(self):
     "Get options from config files."
     self.arguments = {}
     computed_settings = from_path(os.getcwd())
     for (key, value) in itemsview(computed_settings):
         self.arguments[key] = value
#! /usr/bin/env python
Exemple #8
0
def main():
    arguments = create_parser()
    if arguments.get("show_version"):
        print(INTRO)
        return

    if "settings_path" in arguments:
        sp = arguments["settings_path"]
        arguments["settings_path"] = (os.path.abspath(sp) if
                                      os.path.isdir(sp) else os.path.dirname(
                                          os.path.abspath(sp)))
        if not os.path.isdir(arguments["settings_path"]):
            print("WARNING: settings_path dir does not exist: {0}".format(
                arguments["settings_path"]))

    if "virtual_env" in arguments:
        venv = arguments["virtual_env"]
        arguments["virtual_env"] = os.path.abspath(venv)
        if not os.path.isdir(arguments["virtual_env"]):
            print("WARNING: virtual_env dir does not exist: {0}".format(
                arguments["virtual_env"]))

    file_names = arguments.pop("files", [])
    if file_names == ["-"]:
        SortImports(file_contents=sys.stdin.read(),
                    write_to_stdout=True,
                    **arguments)
    else:
        if not file_names:
            file_names = ["."]
            arguments["recursive"] = True
            if not arguments.get("apply", False):
                arguments["ask_to_apply"] = True
        config = from_path(os.path.abspath(file_names[0])
                           or os.getcwd()).copy()
        config.update(arguments)
        wrong_sorted_files = False
        skipped = []
        if arguments.get("recursive", False):
            file_names = iter_source_code(file_names, config, skipped)
        num_skipped = 0
        if config["verbose"] or config.get("show_logo", False):
            print(INTRO)
        jobs = arguments.get("jobs")
        if jobs:
            executor = ProcessPoolExecutor(max_workers=jobs)

            for sort_attempt in executor.map(
                    functools.partial(sort_imports, **arguments), file_names):
                if not sort_attempt:
                    continue
                incorrectly_sorted = sort_attempt.incorrectly_sorted
                if arguments.get("check", False) and incorrectly_sorted:
                    wrong_sorted_files = True
                if sort_attempt.skipped:
                    num_skipped += 1
        else:
            for file_name in file_names:
                try:
                    sort_attempt = SortImports(file_name, **arguments)
                    incorrectly_sorted = sort_attempt.incorrectly_sorted
                    if arguments.get("check", False) and incorrectly_sorted:
                        wrong_sorted_files = True
                    if sort_attempt.skipped:
                        num_skipped += 1
                except IOError as e:
                    print(
                        "WARNING: Unable to parse file {0} due to {1}".format(
                            file_name, e))
        if wrong_sorted_files:
            exit(1)

        num_skipped += len(skipped)
        if num_skipped and not arguments.get("quiet", False):
            if config["verbose"]:
                for was_skipped in skipped:
                    print(
                        "WARNING: {0} was skipped as it's listed in 'skip' setting"
                        " or matches a glob in 'skip_glob' setting".format(
                            was_skipped))
            print("Skipped {0} files".format(num_skipped))
Exemple #9
0
def main(argv=None):
    arguments = parse_args(argv)
    if arguments.get('show_version'):
        print(INTRO)
        return

    if arguments.get('ambiguous_r_flag'):
        print('ERROR: Deprecated -r flag set. This flag has been replaced with -rm to remove ambiguity between it and '
              '-rc for recursive')
        sys.exit(1)

    arguments['check_skip'] = False
    if 'settings_path' in arguments:
        sp = arguments['settings_path']
        arguments['settings_path'] = os.path.abspath(sp) if os.path.isdir(sp) else os.path.dirname(os.path.abspath(sp))
        if not os.path.isdir(arguments['settings_path']):
            print("WARNING: settings_path dir does not exist: {0}".format(arguments['settings_path']))

    if 'virtual_env' in arguments:
        venv = arguments['virtual_env']
        arguments['virtual_env'] = os.path.abspath(venv)
        if not os.path.isdir(arguments['virtual_env']):
            print("WARNING: virtual_env dir does not exist: {0}".format(arguments['virtual_env']))

    file_names = arguments.pop('files', [])
    if file_names == ['-']:
        try:
            # python 3
            file_ = sys.stdin.buffer
        except AttributeError:
            # python 2
            file_ = sys.stdin
        SortImports(file_=file_, write_to_stdout=True, **arguments)
    else:
        if not file_names:
            file_names = ['.']
            arguments['recursive'] = True
            if not arguments.get('apply', False):
                arguments['ask_to_apply'] = True

        config = from_path(arguments.get('settings_path', '') or os.path.abspath(file_names[0]) or os.getcwd()).copy()
        config.update(arguments)
        wrong_sorted_files = False
        skipped = []

        if config.get('filter_files'):
            filtered_files = []
            for file_name in file_names:
                if should_skip(file_name, config):
                    skipped.append(file_name)
                else:
                    filtered_files.append(file_name)
            file_names = filtered_files

        if arguments.get('recursive', False):
            file_names = iter_source_code(file_names, config, skipped)
        num_skipped = 0
        if config['verbose'] or config.get('show_logo', False):
            print(INTRO)

        jobs = arguments.get('jobs')
        if jobs:
            import multiprocessing
            executor = multiprocessing.Pool(jobs)
            attempt_iterator = executor.imap(functools.partial(sort_imports, **arguments), file_names)
        else:
            attempt_iterator = (sort_imports(file_name, **arguments) for file_name in file_names)

        for sort_attempt in attempt_iterator:
            if not sort_attempt:
                continue
            incorrectly_sorted = sort_attempt.incorrectly_sorted
            if arguments.get('check', False) and incorrectly_sorted:
                wrong_sorted_files = True
            if sort_attempt.skipped:
                num_skipped += 1

        if wrong_sorted_files:
            sys.exit(1)

        num_skipped += len(skipped)
        if num_skipped and not arguments.get('quiet', False):
            if config['verbose']:
                for was_skipped in skipped:
                    print("WARNING: {0} was skipped as it's listed in 'skip' setting"
                        " or matches a glob in 'skip_glob' setting".format(was_skipped))
            print("Skipped {0} files".format(num_skipped))
Exemple #10
0
def main(argv: Optional[Sequence[str]] = None) -> None:
    arguments = parse_args(argv)
    if arguments.get("show_version"):
        print(INTRO)
        return

    if arguments.get("ambiguous_r_flag"):
        print(
            "ERROR: Deprecated -r flag set. This flag has been replaced with -rm to remove ambiguity between it and "
            "-rc for recursive")
        sys.exit(1)

    arguments["check_skip"] = False
    if "settings_path" in arguments:
        sp = arguments["settings_path"]
        arguments["settings_path"] = (os.path.abspath(sp) if
                                      os.path.isdir(sp) else os.path.dirname(
                                          os.path.abspath(sp)))
        if not os.path.isdir(arguments["settings_path"]):
            print("WARNING: settings_path dir does not exist: {}".format(
                arguments["settings_path"]))

    if "virtual_env" in arguments:
        venv = arguments["virtual_env"]
        arguments["virtual_env"] = os.path.abspath(venv)
        if not os.path.isdir(arguments["virtual_env"]):
            print("WARNING: virtual_env dir does not exist: {}".format(
                arguments["virtual_env"]))

    file_names = arguments.pop("files", [])
    if file_names == ["-"]:
        SortImports(file_contents=sys.stdin.read(),
                    write_to_stdout=True,
                    **arguments)
    else:
        if not file_names:
            file_names = ["."]
            arguments["recursive"] = True
            if not arguments.get("apply", False):
                arguments["ask_to_apply"] = True

        config = from_path(
            arguments.get("settings_path", "")
            or os.path.abspath(file_names[0]) or os.getcwd()).copy()
        config.update(arguments)
        wrong_sorted_files = False
        skipped = []  # type: List[str]

        if config.get("filter_files"):
            filtered_files = []
            for file_name in file_names:
                if file_should_be_skipped(file_name, config):
                    skipped.append(file_name)
                else:
                    filtered_files.append(file_name)
            file_names = filtered_files

        if arguments.get("recursive", False):
            file_names = iter_source_code(file_names, config, skipped)
        num_skipped = 0
        if config["verbose"] or config.get("show_logo", False):
            print(INTRO)

        jobs = arguments.get("jobs")
        if jobs:
            import multiprocessing

            executor = multiprocessing.Pool(jobs)
            attempt_iterator = executor.imap(
                functools.partial(sort_imports, **arguments), file_names)
        else:
            # https://github.com/python/typeshed/pull/2814
            attempt_iterator = (  # type: ignore
                sort_imports(file_name, **arguments)
                for file_name in file_names)

        for sort_attempt in attempt_iterator:
            if not sort_attempt:
                continue
            incorrectly_sorted = sort_attempt.incorrectly_sorted
            if arguments.get("check", False) and incorrectly_sorted:
                wrong_sorted_files = True
            if sort_attempt.skipped:
                num_skipped += 1

        if wrong_sorted_files:
            sys.exit(1)

        num_skipped += len(skipped)
        if num_skipped and not arguments.get("quiet", False):
            if config["verbose"]:
                for was_skipped in skipped:
                    print(
                        "WARNING: {} was skipped as it's listed in 'skip' setting"
                        " or matches a glob in 'skip_glob' setting".format(
                            was_skipped))
            print("Skipped {} files".format(num_skipped))
Exemple #11
0
 def finalize_options(self) -> None:
     "Get options from config files."
     self.arguments = {}  # type: Dict[str, Any]
     computed_settings = from_path(os.getcwd())
     for key, value in computed_settings.items():
         self.arguments[key] = value