Beispiel #1
0
def test_isort_respects_quiet_from_sort_file_api_see_1461(capsys, tmpdir):
    """Test to ensure isort respects the quiet API parameter when passed in via the API.
    See: https://github.com/PyCQA/isort/issues/1461.
    """
    settings_file = tmpdir.join(".isort.cfg")
    custom_settings_file = tmpdir.join(".custom.isort.cfg")
    tmp_file = tmpdir.join("file.py")
    tmp_file.write("import b\nimport a\n")
    isort.file(tmp_file)

    out, error = capsys.readouterr()
    assert not error
    assert "Fixing" in out

    # When passed in directly as a setting override
    tmp_file.write("import b\nimport a\n")
    isort.file(tmp_file, quiet=True)
    out, error = capsys.readouterr()
    assert not error
    assert not out

    # Present in an automatically loaded configuration file
    isort.settings._find_config.cache_clear()
    settings_file.write(
        """
[isort]
quiet = true
"""
    )
    tmp_file.write("import b\nimport a\n")
    isort.file(tmp_file)
    out, error = capsys.readouterr()
    assert not error
    assert not out

    # In a custom configuration file
    settings_file.write(
        """
[isort]
quiet = false
"""
    )
    custom_settings_file.write(
        """
[isort]
quiet = true
"""
    )
    tmp_file.write("import b\nimport a\n")
    isort.file(tmp_file, settings_file=str(custom_settings_file))
    out, error = capsys.readouterr()
    assert not error
    assert not out

    # Reused configuration object
    custom_config = Config(settings_file=str(custom_settings_file))
    isort.file(tmp_file, config=custom_config)
    out, error = capsys.readouterr()
    assert not error
    assert not out
Beispiel #2
0
def test_api_to_allow_custom_diff_and_output_stream_1583(capsys, tmpdir):
    """isort should provide a way from the Python API to process an existing
    file and output to a stream the new version of that file, as well as a diff
    to a different stream.
    See: https://github.com/PyCQA/isort/issues/1583
    """

    tmp_file = tmpdir.join("file.py")
    tmp_file.write("import b\nimport a\n")

    isort_diff = StringIO()
    isort_output = StringIO()

    isort.file(tmp_file, show_diff=isort_diff, output=isort_output)

    _, error = capsys.readouterr()
    assert not error

    isort_diff.seek(0)
    isort_diff_content = isort_diff.read()
    assert "+import a" in isort_diff_content
    assert " import b" in isort_diff_content
    assert "-import a" in isort_diff_content

    isort_output.seek(0)
    assert isort_output.read().splitlines() == ["import a", "import b"]
Beispiel #3
0
def format(path):
    black.format_file_in_place(
        src=path,
        fast=False,
        mode=black.Mode(target_versions={black.TargetVersion.PY38}),
        write_back=black.WriteBack.YES,
    )
    isort.file(path)
Beispiel #4
0
def test_windows_diff_too_large_misrepresentative_issue_1348(test_path):
    """Ensure isort handles windows files correctly when it come to producing a diff with --diff.
    See: https://github.com/timothycrosley/isort/issues/1348
    """
    diff_output = StringIO()
    isort.file(test_path / "example_crlf_file.py", show_diff=diff_output)
    diff_output.seek(0)
    assert diff_output.read().endswith(
        "-1,5 +1,5 @@\n+import a\r\n import b\r\n"
        "-import a\r\n \r\n \r\n def func():\r\n")
Beispiel #5
0
            # https://github.com/home-assistant/core/pull/61989#discussion_r770614380
            # content = re.sub(
            #     rf"==(\s*){class_}\.{enum}\b",
            #     rf"is\1{class_}.{enum}",
            #     content,
            # )
            # Swap '==' for 'is' for sensorstateclass
            if class_ == "SensorStateClass":
                content = re.sub(
                    rf"==(\s*){class_}\.{enum}\b",
                    rf"is\1{class_}.{enum}",
                    content,
                )
            modified = True

    if modified:
        with open(
                name,
                "w",
        ) as file1:
            file1.write(content)
        isort.file(name)

    for match, _, _, _ in manualsubs:
        strings = re.findall(re.escape(match), content)
        if len(strings) > 0:
            print(
                f"MANUAL rework needed for {name} - {match} has more than one substitue"
            )
            exit(1)
Beispiel #6
0
def format_py_file(filename):
    FormatFile(filename, in_place=True, style_config=_yapf_config_path)
    if _has_isort:
        isort.file(filename)
    format_plain_text(filename)
Beispiel #7
0
    def menu_or_quit(self):
        option = console.input(
            "[slate_blue1]\nEnter '!m' for menu or '!q' for exit: [/slate_blue1]"
        ).lower()
        print("")
        if option == "!m":
            return self.menu()
        elif option == "!q":
            exit()
        else:
            console.print("\n[red3][INVALID][/red3]\n")
            return self.menu_or_quit()


app = App()

if __name__ == "__main__":
    print(r"""
   ___                                    _                                                
  / _ \__ _ ___ _____      _____  _ __ __| |       /\/\   __ _ _ __   __ _  __ _  ___ _ __ 
 / /_)/ _` / __/ __\ \ /\ / / _ \| '__/ _` |_____ /    \ / _` | '_ \ / _` |/ _` |/ _ \ '__|
/ ___/ (_| \__ \__ \\ V  V / (_) | | | (_| |_____/ /\/\ \ (_| | | | | (_| | (_| |  __/ |   
\/    \__,_|___/___/ \_/\_/ \___/|_|  \__,_|     \/    \/\__,_|_| |_|\__,_|\__, |\___|_|   
                                                                           |___/           
        """)

    isort.file(__file__)

    if db.create_db():
        app.verify_key()
Beispiel #8
0
    writer.write("\n")
    writer.write("    def accept(self, visitor):\n")
    writer.write(f"        return visitor.visit{className}{baseName}(self)\n")
    writer.write("\n\n")


if __name__ == "__main__":
    main()

    p = pathlib.Path(__file__).resolve().parent.parent / "expr.py"
    print(p)
    print(
        black.format_file_in_place(
            src=p,
            fast=False,
            mode=black.Mode(target_versions={black.TargetVersion.PY38}),
            write_back=black.WriteBack.YES,
        ))
    print(isort.file(p))

    p = pathlib.Path(__file__).resolve().parent.parent / "stmt.py"
    print(p)
    print(
        black.format_file_in_place(
            src=p,
            fast=False,
            mode=black.Mode(target_versions={black.TargetVersion.PY38}),
            write_back=black.WriteBack.YES,
        ))
    print(isort.file(p))
Beispiel #9
0
def generate_stub_for_c_module(module_name: str, output_path: Path) -> Path:

    module = importlib.import_module(module_name)
    if not is_c_module(module):
        raise RuntimeError(f"{module_name} is not a C module")

    hier_list = module_name.split(".")
    hier_list[-1] += ".pyi"
    target = output_path.joinpath(*hier_list)
    target.parent.mkdir(parents=True, exist_ok=True)

    # parse all members of this module
    imports: Dict[str, str] = {}
    types: List[List[str]] = []
    variables: List[str] = []
    functions: List[str] = []
    for name, obj in sorted(module.__dict__.items(), key=lambda x: x[0]):
        if process_c_function(name, obj, functions, imports):
            pass
        elif process_c_type(name, obj, types, imports):
            pass
        else:
            process_c_var(name, obj, variables, imports)

    ndarray_module = ""
    import_reformat: Dict[str, List[str]] = {}
    for c_name, m_name in imports.items():
        if m_name != module_name:
            if c_name == "ndarray":
                # NOTE: numpy.ndarray is special because we need to alias
                ndarray_module = m_name
            else:
                cur_list = import_reformat.get(m_name, None)
                if cur_list is None:
                    import_reformat[m_name] = [c_name]
                else:
                    cur_list.append(c_name)

    # write output to file
    with open(target, "w") as file:
        write_header(file, module_name)
        file.write("from __future__ import annotations\n\n")

        if import_reformat or ndarray_module:
            for m_name, cls_list in sorted(import_reformat.items(),
                                           key=lambda x: x[0]):
                file.write(
                    f"from {m_name} import {','.join(sorted(cls_list))}\n")

            if ndarray_module:
                # numpy array alias
                file.write(f"from {ndarray_module} import ndarray as array\n")

            file.write("\n")

        if variables:
            for line in variables:
                file.write(line)
                file.write("\n")
            file.write("\n\n")
        else:
            # if no variables section, add extra blank line so import/variable
            # section is 2 spaces from class/function section
            file.write("\n")

        for line in functions:
            file.write(line)
            file.write("\n\n\n")
        for cls_lines in types:
            for line in cls_lines:
                file.write(line)
                file.write("\n")
            file.write("\n\n")

    # Run isort/black to format file
    isort.file(target)

    if importlib.util.find_spec("black") is None:
        raise RuntimeError(
            'Cannot find "black" Python module, is it installed?')

    subprocess.check_call([sys.executable, "-m", "black", str(target)])

    return target
Beispiel #10
0
def autopep8(file_path, ignore_pep):
    isort.file(file_path)
    print(f'isort file: {file_path} SUCCESSFULLY.')
    if not ignore_pep:
        os.system(f"autopep8 -j 0 -i {file_path} --max-line-length 120")
        print(f'autopep8 file: {file_path} SUCCESSFULLY.')
Beispiel #11
0
import isort

isort.file("assign3.py")
from pathlib import Path
from statistics import mean
from typing import Union

import numpy as np
import pandas as pd
import scipy.io
from pandas import DataFrame
from scipy.stats import mannwhitneyu
from sklearn.model_selection import StratifiedShuffleSplit, cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neural_network import MLPClassifier
from tensorflow import keras
from tensorflow.keras import Input, Sequential
from tensorflow.keras.layers import Conv2D, Dense, Flatten, MaxPooling2D, ReLU


def save_data_kfold(kfold_scores: pd.DataFrame) -> None:
    from pathlib import Path

    import numpy as np
    from pandas import DataFrame

    KNN_COLS = sorted(["knn1", "knn5", "knn10"])
    df = kfold_scores
    for knn_col in KNN_COLS:
        if knn_col not in df.columns:
            raise ValueError(
def handle_make_component_command(base_package: str,
                                  root_of_git_repository: str, component: str,
                                  name: str, args: dict) -> None:
    # 1. Construct component package
    component_package_path = Path(
        os.path.join(
            root_of_git_repository,
            map_base_package_to_library_or_workbench_package(
                base_package, component), component))
    component_package_path.mkdir(exist_ok=True)

    # 2. Construct new component sub-package
    #    Stop if it exists
    new_component_sub_package = '_' + camel_case_to_snake_case(name)
    new_component_sub_package_path = Path(component_package_path).joinpath(
        new_component_sub_package)
    if (new_component_sub_package_path.exists()):
        print('{} package already exists. Skipping creation.'.format(
            new_component_sub_package))
        return None
    new_component_sub_package_path.mkdir(exist_ok=True)

    # 3. Update init module of component package
    component_package_init_module_path = component_package_path.joinpath(
        '__init__.py')
    component_package_init_module_path.touch(exist_ok=True)
    component_name = map_name_to_component_name(name, component)
    with component_package_init_module_path.open('r+') as f:
        lines = f.readlines()
        text = ''.join(lines)
        white_space = '[\s\S]+'
        all_pattern = white_space.join(['__all__', '=', '(\[', '\])'])
        match = re.search(all_pattern, text)
        all_members = []
        if match:
            all_members = eval(match.group(1))
        next_all_string = build_next_all_string(all_members, component_name)
        if not match:
            text = next_all_string
        new_contents = re.sub(all_pattern, next_all_string, text)
        import_statement = 'from .{} import {}\n'.format(
            new_component_sub_package, component_name)
        new_contents = import_statement + '\n' + new_contents
        f.seek(0)
        f.write(new_contents)
    isort.file(component_package_init_module_path.resolve())

    # 4. Setup init module in component sub-package
    component_module_name = map_name_to_component_module_name(name, component)
    init_module_path = new_component_sub_package_path.joinpath('__init__.py')
    init_module_path.touch(exist_ok=True)
    with init_module_path.open('a') as f:
        import_statement = 'from .{} import {}\n'.format(
            component_module_name, component_name)
        all_declaration = "__all__ = ['{}']".format(component_name)
        f.write('\n'.join([import_statement, all_declaration]))
    isort.file(init_module_path.resolve())

    # 5. Create new component module using template
    module_name = '{}.py'.format(component_module_name)
    component_module_path = new_component_sub_package_path.joinpath(
        module_name)
    component_module_existed_before = component_module_path.exists()
    component_module_path.touch(exist_ok=True)
    if component_module_existed_before:
        print('{} already exists. Skipping {} class creation.'.format(
            module_name, component))
        return None
    component_module_text = render_template(component, name, base_package,
                                            args)
    component_module_path.write_text(component_module_text)
    if component == 'model' and args['part']:
        del args['part']
        handle_make_component_command(base_package, root_of_git_repository,
                                      'part', name, args)