Skip to content

Commit

Permalink
ruff fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
FredHappyface committed Feb 18, 2025
1 parent bc6fcad commit 3b0c3a8
Show file tree
Hide file tree
Showing 32 changed files with 197 additions and 191 deletions.
4 changes: 2 additions & 2 deletions cli2gui/application/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@
import sys
from typing import Any

from cli2gui import types
from cli2gui import models
from cli2gui.application.application2args import argFormat
from cli2gui.gui import helpers
from cli2gui.gui.dearpygui_wrapper import DearPyGuiWrapper
from cli2gui.gui.pysimplegui_wrapper import PySimpleGUIWrapper


def run(buildSpec: types.FullBuildSpec) -> Any:
def run(buildSpec: models.FullBuildSpec) -> Any:
"""Establish the main entry point.
Args:
Expand Down
22 changes: 11 additions & 11 deletions cli2gui/application/application2args.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from pathlib import Path
from typing import Any

from cli2gui.types import SEP, ParserType
from cli2gui.models import SEP, ParserType


def processValue(key: str, value: str) -> tuple[str, Any]:
Expand Down Expand Up @@ -44,44 +44,44 @@ def processValue(key: str, value: str) -> tuple[str, Any]:
def argparseFormat(values: dict[str, Any]) -> argparse.Namespace:
"""Format args for argparse."""
args = {}
for key in values:
cleankey, value = processValue(key, values[key])
for key, _value in values.items():
cleankey, value = processValue(key, _value)
args[cleankey] = value
return argparse.Namespace(**args)


def optparseFormat(values: dict[str, Any]) -> tuple[optparse.Values, list[str]]:
"""Format args for optparse."""
args = {}
for key in values:
cleankey, value = processValue(key, values[key])
for key, _value in values.items():
cleankey, value = processValue(key, _value)
args[cleankey] = value
return (optparse.Values(args), [])


def getoptFormat(values: dict[str, Any]) -> tuple[list[Any], list[Any]]:
"""Format args for getopt."""
return ([processValue(key, values[key]) for key in values if values[key]], [])
return ([processValue(key, _value) for key, _value in values.items() if _value], [])


def docoptFormat(values: dict[str, Any]) -> dict[str, Any]:
"""Format args for docopt."""
import docopt

args = {}
for key in values:
cleankey, value = processValue(key, values[key])
for key, _value in values.items():
cleankey, value = processValue(key, _value)
args[cleankey] = value
return docopt.Dict(args)


def clickFormat(values: dict[str, Any]) -> list[Any]:
"""Format args for click."""
args = []
for key in values:
val = str(values[key])
for key, _value in values.items():
val = str(_value)
if not callable(key) and len(val) > 0:
cleankey, value = processValue(key, values[key])
cleankey, value = processValue(key, _value)
args.extend([cleankey, value])
return args

Expand Down
2 changes: 1 addition & 1 deletion cli2gui/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@
from typing import Any, Iterable

from cli2gui.application import application
from cli2gui.models import BuildSpec, FullBuildSpec, GUIType, ParserType
from cli2gui.tojson import (
argparse2json,
click2json,
docopt2json,
getopt2json,
optparse2json,
)
from cli2gui.types import BuildSpec, FullBuildSpec, GUIType, ParserType

DO_COMMAND = "--cli2gui"
DO_NOT_COMMAND = "--disable-cli2gui"
Expand Down
2 changes: 2 additions & 0 deletions cli2gui/gui/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
"""Package containing GUI classes and functionality, responsible for driving the various
GUI backends supported by cli2gui."""
12 changes: 9 additions & 3 deletions cli2gui/gui/abstract_gui.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,26 @@
"""Abstract base class for GUI wrappers."""

from __future__ import annotations

from abc import ABC, abstractmethod
from typing import Any, Callable

from cli2gui import types
from cli2gui import models


class AbstractGUI(ABC):
"""Abstract base class for GUI wrappers."""

@abstractmethod
def __init__(self) -> None:
pass
"""Abstract base class for GUI wrappers."""

@abstractmethod
def main(
self, buildSpec: types.FullBuildSpec, menu: list[str], quit_callback, run_callback
self,
buildSpec: models.FullBuildSpec,
quit_callback: Callable[[], None],
run_callback: Callable[[dict[str, Any]], None],
) -> None:
"""Abstract method for the main function."""
raise NotImplementedError
9 changes: 8 additions & 1 deletion cli2gui/gui/dearpygui_wrapper.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Wrapper class for Dear PyGui."""

from __future__ import annotations

from pathlib import Path
Expand All @@ -7,7 +9,7 @@

from cli2gui.gui import helpers
from cli2gui.gui.abstract_gui import AbstractGUI
from cli2gui.types import SEP, FullBuildSpec, Group, Item, ItemType
from cli2gui.models import SEP, FullBuildSpec, Group, Item, ItemType

THISDIR = Path(__file__).resolve().parent

Expand All @@ -25,6 +27,11 @@ class DearPyGuiWrapper(AbstractGUI):
"""Wrapper class for Dear PyGui."""

def __init__(self, base24Theme: list[str]) -> None:
"""Dearpygui wrapper class.
:param list[str] base24Theme: list representing a base24 theme. Containing 24 elements
(of hex strings like "#e7e7e9")
"""
self.base24Theme = base24Theme
super().__init__()

Expand Down
3 changes: 3 additions & 0 deletions cli2gui/gui/helpers.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
"""Basic helper package containing commonly used functions, such as isDarkMode,
get_base24_theme etc."""

from __future__ import annotations

from pathlib import Path
Expand Down
27 changes: 14 additions & 13 deletions cli2gui/gui/pysimplegui_wrapper.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Wrapper class for PySimpleGUI."""

from __future__ import annotations

import io
Expand All @@ -8,15 +10,19 @@

from cli2gui.gui import helpers
from cli2gui.gui.abstract_gui import AbstractGUI
from cli2gui.types import SEP, FullBuildSpec, Group, Item, ItemType

# ruff: noqa: ANN401
from cli2gui.models import SEP, FullBuildSpec, Group, Item, ItemType


class PySimpleGUIWrapper(AbstractGUI):
"""Wrapper class for PySimpleGUI."""

def __init__(self, base24Theme: list[str], psg_lib: str) -> None:
"""PySimpleGUI wrapper class.
:param list[str] base24Theme: list representing a base24 theme. Containing 24 elements
(of hex strings like "#e7e7e9")
:param str psg_lib: string representing the pysimplegui lib to use
"""
super().__init__()

if psg_lib == "psg":
Expand Down Expand Up @@ -138,14 +144,14 @@ def _fileBrowser(
additional_properties: dict | None = None,
) -> list[Any]:
"""Return a fileBrowser button and field."""
additional_properties = additional_properties or {}
prop = additional_properties or {}

height = self.sizes["input_size"][1]
width = self.sizes["input_size"][0]

key = f"{key}{SEP}{_type}"
if _type in [ItemType.FileWrite, ItemType.File]:
key += f";{additional_properties.get('file_mode')};{additional_properties.get('file_encoding')}"
key += f";{prop.get('file_mode')};{prop.get('file_encoding')}"

browser = self.sg.FileBrowse(
key="@@" + key,
Expand Down Expand Up @@ -394,15 +400,10 @@ def createLayout(
) -> list[list[Any]]:
"""Create the pysimplegui layout from the build spec.
Args:
----
buildSpec (FullBuildSpec): build spec containing widget
self (self): class to build self
:param FullBuildSpec buildSpec: build spec containing widget
:param str | list[str] menu: menu definition. containing menu keys
Returns:
-------
list[list[Any]]: list of self (layout list)
:return list[list[Any]]: list of self (layout list)
"""
argConstruct = []
Expand Down
16 changes: 4 additions & 12 deletions cli2gui/types.py → cli2gui/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,13 +98,6 @@ class FullBuildSpec:
class ParserType(str, Enum):
"""Supported parser types.
OPTPARSE = "optparse"
ARGPARSE = "argparse"
DEPHELL_ARGPARSE = "dephell_argparse"
DOCOPT = "docopt"
GETOPT = "getopt"
CLICK = "click"
CUSTOM = "input()" # this seems like a pretty poor pattern to use
"""

OPTPARSE = "optparse"
Expand All @@ -120,13 +113,12 @@ class ParserType(str, Enum):
class GUIType(str, Enum):
"""Supported gui types.
DEFAULT = "pysimplegui"
WEB = "pysimpleguiweb"
QT = "pysimpleguiqt"
FSG = "freesimplegui"
"""

DEFAULT = "pysimplegui"
PSG = "pysimplegui"
WEB = "pysimpleguiweb"
QT = "pysimpleguiqt"
FSG = "freesimplegui"
FSGWEB = "freesimpleguiweb"
FSGQT = "freesimpleguiqt"
DPG = "dearpygui"
2 changes: 2 additions & 0 deletions cli2gui/tojson/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
"""Package containing transforms for each supported parser/cli library, responsible for
taking each parser representation (and BuildSpec) and generating a FullBuildSpec."""
9 changes: 5 additions & 4 deletions cli2gui/tojson/argparse2json.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
from sys import argv
from typing import Any, Generator, TypedDict

from cli2gui.types import Group, Item, ItemType, ParserRep
from cli2gui.models import Group, Item, ItemType, ParserRep


class ArgparseGroup(TypedDict):
Expand Down Expand Up @@ -109,6 +109,7 @@ def extractRawGroups(actionGroup: argparse._ArgumentGroup) -> ArgparseGroup:


def fileActionToJson(action: argparse.Action, widget: ItemType) -> Item:
"""Convert an action of type Path or argparse.FileType to an Item."""
item = actionToJson(action=action, widget=widget)
if isinstance(action.type, argparse.FileType):
item.additional_properties = {
Expand Down Expand Up @@ -166,12 +167,12 @@ def categorizeItems(

elif isinstance(action.type, argparse.FileType):
yield fileActionToJson(action, ItemType.File)
elif action.type == Path:
elif action.type is Path:
yield actionToJson(action, ItemType.Path)

elif action.type == int:
elif action.type is int:
yield actionToJson(action, ItemType.Int)
elif action.type == float:
elif action.type is float:
yield actionToJson(action, ItemType.Float)
else:
yield actionToJson(action, ItemType.Text)
Expand Down
2 changes: 1 addition & 1 deletion cli2gui/tojson/click2json.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import contextlib
from typing import Any, Generator

from cli2gui.types import Group, Item, ItemType, ParserRep
from cli2gui.models import Group, Item, ItemType, ParserRep


def extract(parser: Any) -> list[Group]:
Expand Down
10 changes: 5 additions & 5 deletions cli2gui/tojson/docopt2json.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import re
from typing import Any, Iterator

from cli2gui.types import Group, Item, ItemType, ParserRep
from cli2gui.models import Group, Item, ItemType, ParserRep


def actionToJson(action: tuple[str, str, int, Any, str], widget: ItemType, *, isPos: bool) -> Item:
Expand Down Expand Up @@ -94,8 +94,8 @@ def parse(optionDescription: str) -> tuple[str, str, int, Any, str]:
def parseOpt(doc: Any) -> list[tuple[str, str, int, Any, str]]:
"""Parse an option help text, adapted from docopt."""
defaults = []
for section in parseSection("options:", doc):
_, _, section = section.partition(":")
for _section in parseSection("options:", doc):
_, _, section = _section.partition(":")
split = re.split(r"\n[ \t]*(-\S+?)", "\n" + section)[1:]
split = [s1 + s2 for s1, s2 in zip(split[::2], split[1::2])]
options = [parse(s) for s in split if s.startswith("-")]
Expand All @@ -106,8 +106,8 @@ def parseOpt(doc: Any) -> list[tuple[str, str, int, Any, str]]:
def parsePos(doc: str) -> list[tuple[str, str]]:
"""Parse positional arguments from docstring."""
defaults = []
for section in parseSection("arguments:", doc):
_, _, section = section.partition(":")
for _section in parseSection("arguments:", doc):
_, _, section = _section.partition(":")
defaults.append(
tuple(col.strip() for col in section.strip().partition(" ") if len(col.strip()) > 0)
)
Expand Down
2 changes: 1 addition & 1 deletion cli2gui/tojson/getopt2json.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from collections.abc import Callable
from typing import Generator

from cli2gui.types import Group, Item, ItemType, ParserRep
from cli2gui.models import Group, Item, ItemType, ParserRep

# ruff: noqa: SLF001

Expand Down
2 changes: 1 addition & 1 deletion cli2gui/tojson/optparse2json.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import optparse
from typing import Generator

from cli2gui.types import Group, Item, ItemType, ParserRep
from cli2gui.models import Group, Item, ItemType, ParserRep


def extractOptions(optionGroup: optparse.OptionGroup) -> Group:
Expand Down
2 changes: 1 addition & 1 deletion documentation/reference/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ A full list of `Cli2gui` project modules.
- [DearPyGuiWrapper](cli2gui/gui/dearpygui_wrapper.md#dearpyguiwrapper)
- [Helpers](cli2gui/gui/helpers.md#helpers)
- [PySimpleGUIWrapper](cli2gui/gui/pysimplegui_wrapper.md#pysimpleguiwrapper)
- [Models](cli2gui/models.md#models)
- [Tojson](cli2gui/tojson/index.md#tojson)
- [Argparse2json](cli2gui/tojson/argparse2json.md#argparse2json)
- [Click2json](cli2gui/tojson/click2json.md#click2json)
- [Docopt2json](cli2gui/tojson/docopt2json.md#docopt2json)
- [Getopt2json](cli2gui/tojson/getopt2json.md#getopt2json)
- [Optparse2json](cli2gui/tojson/optparse2json.md#optparse2json)
- [Types](cli2gui/types.md#types)
2 changes: 1 addition & 1 deletion documentation/reference/cli2gui/application/application.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,5 @@ Establish the main entry point.
#### Signature

```python
def run(buildSpec: types.FullBuildSpec) -> Any: ...
def run(buildSpec: models.FullBuildSpec) -> Any: ...
```
4 changes: 2 additions & 2 deletions documentation/reference/cli2gui/decorators.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,5 +169,5 @@ def createFromParser(

#### See also

- [BuildSpec](./types.md#buildspec)
- [FullBuildSpec](./types.md#fullbuildspec)
- [BuildSpec](./models.md#buildspec)
- [FullBuildSpec](./models.md#fullbuildspec)
Loading

0 comments on commit 3b0c3a8

Please sign in to comment.