How to use the isort.SortImports function in isort

To help you get started, we’ve selected a few isort examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github konstellation-io / science-toolkit / vscode / extensions / ms-python.python-2020.3.69010 / pythonFiles / lib / python / isort / main.py View on Github external
def run(self):
        arguments = self.arguments
        wrong_sorted_files = False
        arguments['check'] = True
        for path in self.distribution_files():
            for python_file in glob.iglob(os.path.join(path, '*.py')):
                try:
                    incorrectly_sorted = SortImports(python_file, **arguments).incorrectly_sorted
                    if incorrectly_sorted:
                        wrong_sorted_files = True
                except IOError as e:
                    print("WARNING: Unable to parse file {0} due to {1}".format(python_file, e))
        if wrong_sorted_files:
            sys.exit(1)
github Revolution1 / etcd3-py / scripts / extract_apis.py View on Github external
with open(os.path.join(GENERATED_APIS_DIR, 'base.py'), 'w') as f:
        f.write(BASE_FILE)

    tags = {}
    for path in swaggerSpec.paths:
        tags.setdefault(path.post.tags[0], []).append(path)

    for tag, paths in tags.items():
        with open(os.path.join(GENERATED_APIS_DIR, '%s.py' % tag.lower()), 'w') as f:
            s = api_tpl.render(tag=tag, paths=paths)
            f.write(SortImports(file_contents=FormatCode(s, style_config='pep8')[0], force_single_line=True).output)

    with open(os.path.join(GENERATED_APIS_DIR, '__init__.py'), 'w') as f:
        s = init_tpl.render(tags=tags)
        f.write(SortImports(file_contents=FormatCode(s, style_config='pep8')[0], force_single_line=True).output)
github ESSS / esss_fix_format / src / esss_fix_format / cli.py View on Github external
eol = _peek_eol(first_line)
    ends_with_eol = new_contents.endswith(eol)
    extension = os.path.normcase(os.path.splitext(filename)[1])

    if extension == '.py':
        settings_path = os.path.abspath(os.path.dirname(filename))
        settings_loaded = isort.settings.from_path(settings_path)
        if settings_loaded['line_length'] < 80:
            # The default isort configuration has 79 chars, so, if the passed
            # does not have more than that, complain that .isort.cfg is not configured.
            msg = ': ERROR .isort.cfg not available in repository (or line_length config < 80).'
            error_msg = click.format_filename(filename) + msg
            click.secho(error_msg, fg='red')
            errors.append(error_msg)

        sorter = isort.SortImports(file_contents=new_contents, settings_path=settings_path)
        # On older versions if the entire file is skipped (eg.: by an "isort:skip_file")
        # instruction in the docstring, SortImports doesn't even contain an "output" attribute.
        # In some recent versions it is `None`.
        new_contents = getattr(sorter, 'output', None)
        if new_contents is None:
            new_contents = original_contents

        if format_code is not None:
            try:
                # Pass code formatter.
                new_contents = format_code(new_contents)
            except Exception as e:
                error_msg = f'Error formatting code: {e}'
                click.secho(error_msg, fg='red')
                errors.append(error_msg)
github timothycrosley / isort / isort / main.py View on Github external
)
        if not os.path.isdir(arguments["settings_path"]):
            warn(f"settings_path dir does not exist: {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"]):
            warn(f"virtual_env dir does not exist: {arguments['virtual_env']}")

    file_names = arguments.pop("files", [])
    if not file_names:
        print(QUICK_GUIDE)
        return
    elif file_names == ["-"]:
        SortImports(file_contents=sys.stdin.read(), write_to_stdout=True, **arguments)
    else:
        if "settings_path" not in arguments:
            arguments["settings_path"] = os.path.abspath(file_names[0]) or os.getcwd()
            if not os.path.isdir(arguments["settings_path"]):
                arguments["settings_path"] = os.path.dirname(arguments["settings_path"])

        config_dict = arguments.copy()
        ask_to_apply = config_dict.pop("ask_to_apply", False)
        jobs = config_dict.pop("jobs", ())
        show_logo = config_dict.pop("show_logo", False)
        filter_files = config_dict.pop("filter_files", False)
        check = config_dict.pop("check", False)
        show_diff = config_dict.pop("show_diff", False)
        config = Config(**config_dict)

        wrong_sorted_files = False
github leohemsted / smartypants.py / setup.py View on Github external
print('Options')
        print('=======')
        print()
        print('Exclude:', EXCLUDE_SCRIPTS)
        print()

        files = ['setup.py', CLI_script, module_file] + glob('tests/*.py')

        print('Results')
        print('=======')
        print()

        fails = 0
        for f in files:
            # unfortunately, we have to do it twice
            if isort.SortImports(f, check=True).incorrectly_sorted:
                fails += 1
                print()
                isort.SortImports(f, show_diff=True)
                print()

        print()
        print('Statistics')
        print('==========')
        print()
        print('%d files failed to pass' % fails)
github koxudaxi / datamodel-code-generator / datamodel_code_generator / format.py View on Github external
def apply_isort(code: str) -> str:
    return SortImports(file_contents=code).output
github konstellation-io / science-toolkit / vscode / extensions / ms-python.python-2020.3.69010 / pythonFiles / lib / python / isort / hooks.py View on Github external
for filename in files_modified:
        if filename.endswith('.py'):
            # Get the staged contents of the file
            staged_cmd = "git show :%s" % filename
            staged_contents = get_output(staged_cmd)

            sort = SortImports(
                file_path=filename,
                file_contents=staged_contents.decode(),
                check=True
            )

            if sort.incorrectly_sorted:
                errors += 1
                if modify:
                    SortImports(
                        file_path=filename,
                        file_contents=staged_contents.decode(),
                        check=False,
                    )

    return errors if strict else 0
github timothycrosley / isort / isort / hooks.py View on Github external
:return number of errors if in strict mode, 0 otherwise.
    """

    # Get list of files modified and staged
    diff_cmd = ["git", "diff-index", "--cached", "--name-only", "--diff-filter=ACMRTUXB HEAD"]
    files_modified = get_lines(diff_cmd)

    errors = 0
    for filename in files_modified:
        if filename.endswith(".py"):
            # Get the staged contents of the file
            staged_cmd = ["git", "show", ":%s" % filename]
            staged_contents = get_output(staged_cmd)

            sort = SortImports(file_path=filename, file_contents=staged_contents, check=True)

            if sort.incorrectly_sorted:
                errors += 1
                if modify:
                    SortImports(file_path=filename, file_contents=staged_contents, check=False)

    return errors if strict else 0