Esempio n. 1
0
    async def coroutine():
        global current_file
        global isort_config
        global black_config

        save_dialog = TextInputDialog(
            title="Save file",
            label_text="Enter the path of a file:",
            completer=PathCompleter(),
        )

        filename = await show_dialog_as_float(save_dialog)

        if filename is not None:
            current_file = Path(filename).resolve()
            isort_config = isort.Config(settings_path=current_file.parent)
            black_config_file = black.find_pyproject_toml(
                (str(current_file), ))
            if black_config_file:
                black_config = black.parse_pyproject_toml(black_config_file)
            else:
                black_config = {}
            if not current_file.suffixes and not current_file.exists():
                current_file = current_file.with_suffix(".py")
            open_file_frame.title = current_file.name
            save_file()
Esempio n. 2
0
def start(argv=None):
    global current_file
    global isort_config
    global black_config

    argv = sys.argv if argv is None else argv
    if len(sys.argv) > 2:
        sys.exit("Usage: qpython [filename]")
    elif len(sys.argv) == 2:
        current_file = Path(sys.argv[1]).resolve()
        isort_config = isort.Config(settings_path=current_file.parent)
        black_config_file = black.find_pyproject_toml((str(current_file), ))
        if black_config_file:
            black_config = black.parse_pyproject_toml(black_config_file)
        else:
            black_config = {}

        open_file_frame.title = current_file.name
        if current_file.exists():
            with current_file.open(encoding="utf8") as open_file:
                code.buffer.text = open_file.read()
    else:
        message_dialog(
            title="Welcome to",
            text=ABOUT_MESSAGE,
            style=style,
        ).run()

    app.layout.focus(code.buffer)
    app.run()
Esempio n. 3
0
File: util.py Progetto: jreese/ufmt
def make_black_config(path: Path) -> BlackConfig:
    """
    Generate a basic black config object for the given path.
    """
    config_file = find_pyproject_toml((str(path), ))
    if not config_file:
        return BlackConfig()

    config = parse_pyproject_toml(config_file)

    # manually patch options that do not have a 1-to-1 match in Mode arguments
    config["target_versions"] = {
        TargetVersion[val.upper()]
        for val in config.pop("target_version", [])
    }
    config["string_normalization"] = not config.pop(
        "skip_string_normalization", False)

    names = {
        field.name
        for field in
        BlackConfig.__dataclass_fields__.values()  # type: ignore[attr-defined]
    }
    config = {name: value for name, value in config.items() if name in names}

    return BlackConfig(**config)
Esempio n. 4
0
    async def coroutine():
        global current_file
        global isort_config
        global black_config

        open_dialog = TextInputDialog(
            title="Open file",
            label_text="Enter the path of a file:",
            completer=PathCompleter(),
        )

        filename = await show_dialog_as_float(open_dialog)

        if filename is not None:
            current_file = Path(filename).resolve()
            isort_config = isort.Config(settings_path=current_file.parent)
            black_config_file = black.find_pyproject_toml(
                (str(current_file), ))
            if black_config_file:
                black_config = black.parse_pyproject_toml(black_config_file)
            else:
                black_config = {}

            try:
                with open(current_file, "r",
                          encoding="utf8") as new_file_conent:
                    code.buffer.text = new_file_conent.read()
                    open_file_frame.title = current_file.name
                feedback(f"Successfully opened {current_file}")
            except IOError as error:
                feedback(f"Error: {error}")
def get_black_mode(src: Path) -> black.Mode:
    """Read the black configuration from pyproject.toml"""

    value = black.find_pyproject_toml((str(src),))

    if not value:
        return black.Mode(line_length=DEFAULT_BLACK_LINE_LENGTH)

    config = black.parse_pyproject_toml(value)

    return black.Mode(**{
        key: value
        for key, value in config.items()
    })
Esempio n. 6
0
def read_black_config(src: Path, value: Optional[str]) -> BlackArgs:
    """Read the black configuration from pyproject.toml"""
    value = value or find_pyproject_toml((str(src),))

    if not value:
        return BlackArgs()

    config = parse_pyproject_toml(value)

    return cast(
        BlackArgs,
        {
            key: value
            for key, value in config.items()
            if key in ["line_length", "skip_string_normalization"]
        },
    )
def format_black(self, content):
    config_file = black.find_pyproject_toml((self.basedir, ))
    if config_file:
        config = black.parse_pyproject_toml(config_file)
    else:
        config = {}
    versions = config.get("target_version", [])
    mode = black.Mode(
        target_versions={black.TargetVersion[val.upper()]
                         for val in versions},
        line_length=config.get("line_length")
        or black.const.DEFAULT_LINE_LENGTH,
        string_normalization=not config.get("skip_string_normalization"),
        experimental_string_processing=bool(
            config.get("experimental_string_processing")),
        is_pyi=bool(config.get("pyi")),
    )
    return black.format_str(content, mode=mode)
Esempio n. 8
0
def _parse_pyproject_config(context: click.Context, param: click.Parameter,
                            value: Optional[str]) -> Mode:
    if not value:
        pyproject_toml = find_pyproject_toml(
            tuple(context.params.get("files", (".", ))))
        value = pyproject_toml if pyproject_toml else None
    if value:
        try:
            pyproject_toml = toml.load(value)
            config = pyproject_toml.get("tool", {}).get("docstrfmt", {})
            config = {
                k.replace("--", "").replace("-", "_"): v
                for k, v in config.items()
            }
        except (OSError, ValueError) as e:  # pragma: no cover
            raise click.FileError(
                filename=value, hint=f"Error reading configuration file: {e}")

        if config:
            for key in ["exclude", "extend_exclude", "files"]:
                config_value = config.get(key)
                if config_value is not None and not isinstance(
                        config_value, list):
                    raise click.BadOptionUsage(
                        key, f"Config key {key} must be a list")
            params = {}
            if context.params is not None:
                params.update(context.params)
            params.update(config)
            context.params = params

        black_config = parse_pyproject_toml(value)
        black_config.pop("exclude", None)
        black_config.pop("extend_exclude", None)
        target_version = black_config.pop("target_version", ["PY37"])
        if target_version:
            target_version = set(
                getattr(TargetVersion, version.upper())
                for version in target_version
                if hasattr(TargetVersion, version.upper()))
        black_config["target_versions"] = target_version
        return Mode(**black_config)
    else:
        return Mode(line_length=88)
Esempio n. 9
0
Simultanously distributed to the US and Canada.
And you know, the rest of the world.

A productive parody.
Made in Seattle.
"""

kb = KeyBindings()
eb = KeyBindings()
current_file: Optional[Path] = None

default_isort_config = isort.Config(settings_path=os.getcwd())
if default_isort_config == isort.settings.DEFAULT_CONFIG:
    default_isort_config = isort.Config(profile="black", float_to_top=True)

default_black_config_file = black.find_pyproject_toml((os.getcwd(), ))
if default_black_config_file:
    default_black_config = black.parse_pyproject_toml(
        default_black_config_file)
else:
    default_black_config = {}

default_black_config = {}

isort_config: isort.Config = default_isort_config
black_config: dict = default_black_config

code_frame_style = Style.from_dict({"frame.label": "bg:#AAAAAA fg:#0000aa"})
style = Style.from_dict({
    "menu-bar": "bg:#aaaaaa black bold",
    "menu-bar.selected-item": "bg:black #aaaaaa bold",