Skip to content

Commit

Permalink
ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
FredHappyface committed Jan 20, 2024
1 parent 1e648bd commit a291a8b
Show file tree
Hide file tree
Showing 56 changed files with 608 additions and 610 deletions.
57 changes: 31 additions & 26 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,44 +1,49 @@
repos:
- repo: https://github.com/FHPythonUtils/Blackt
rev: '2022.0.3'
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.14
hooks:
- id: blackt
- id: ruff
args: [ --fix ]

- repo: https://github.com/RobertCraigie/pyright-python
rev: v1.1.347
hooks:
- id: pyright

- repo: https://github.com/pycqa/isort
rev: 5.12.0
- repo: https://github.com/FHPythonUtils/Blackt
rev: '2024.0.1'
hooks:
- id: isort
- id: blackt

- repo: https://github.com/pycqa/pylint
rev: v3.0.0a6
- repo: https://github.com/Lucas-C/pre-commit-hooks-safety
rev: v1.3.2
hooks:
- id: pylint
exclude: "tests/"
args: [--disable=import-error,--jobs=0]
- id: python-safety-dependencies-check
files: pyproject.toml

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
rev: v4.5.0
hooks:
- id: trailing-whitespace
exclude: "tests/"
- id: end-of-file-fixer
exclude: "tests/"
- id: check-case-conflict
- id: check-executables-have-shebangs
- id: check-json
- id: check-merge-conflict
- id: check-shebang-scripts-are-executable
- id: check-symlinks
- id: check-toml
- id: check-vcs-permalinks
- id: check-yaml
- id: detect-private-key
- id: mixed-line-ending

- repo: https://github.com/asottile/pyupgrade
rev: v3.7.0
hooks:
- id: pyupgrade
args: [--py38-plus]
- repo: https://github.com/boidolr/pre-commit-images
rev: v1.2.1
rev: v1.5.1
hooks:
- id: optimize-avif
exclude: "tests/"
- id: optimize-jpg
exclude: "tests/"
- id: optimize-png
exclude: "tests/"
- id: optimize-svg
exclude: "tests/"
- id: optimize-webp
exclude: "tests/"

exclude: "tests/data|documentation/reference"
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@
All major and minor version changes will be documented in this file. Details of
patch-level version changes can be found in [commit messages](../../commits/master).

## 2024 - 2024/01/20

- Update deps
- Code improvements

## 2023 - 2023/08/31

- Update deps
Expand Down
4 changes: 3 additions & 1 deletion cli2gui/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,6 @@
"""
from __future__ import annotations

from cli2gui.decorators import *
from cli2gui.decorators import Cli2Gui, Click2Gui

_ = (Cli2Gui, Click2Gui)
1 change: 1 addition & 0 deletions cli2gui/application/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""The GUI application and related functionality."""
47 changes: 32 additions & 15 deletions cli2gui/application/application.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Application here uses PySimpleGUI.
"""
# pylint: disable=import-outside-toplevel

from __future__ import annotations

import logging
Expand All @@ -11,7 +11,12 @@
try:
from getostheme import isDarkMode
except ImportError:
isDarkMode = lambda: True

def isDarkMode() -> bool:
"""Monkeypatch for getostheme.isDarkMode."""
return True


import yaml
from PySimpleGUI import Element, Window

Expand All @@ -24,13 +29,15 @@ def themeFromFile(themeFile: str) -> list[str]:
"""Set the base24 theme from a base24 scheme.yaml to the application.
Args:
----
themeFile (str): path to file
Returns:
-------
list[str]: theme to set
"""
schemeDictTheme = yaml.safe_load(Path(themeFile).read_text(encoding="utf-8"))
return ["#" + schemeDictTheme[f"base{x:02X}"] for x in range(0, 24)]
return ["#" + schemeDictTheme[f"base{x:02X}"] for x in range(24)]


def setBase24Theme(
Expand All @@ -41,6 +48,7 @@ def setBase24Theme(
"""Set the base24 theme to the application.
Args:
----
theme (Union[str, list[str]]): the light theme
darkTheme (Union[str, list[str]]): the dark theme
pySimpleGui (Any): pysimplegui module
Expand Down Expand Up @@ -119,18 +127,20 @@ def setBase24Theme(
"SLIDER_DEPTH": 0,
"PROGRESS_DEPTH": 0,
}
pySimpleGui.theme("theme") # type: ignore
pySimpleGui.theme("theme")


def setupWidgets(gui: str, sizes: dict[str, Any], pySimpleGui: Any) -> Widgets:
"""Set the widget sizes to the application.
Args:
----
gui (str): user selected gui eg. pysimpleguiqt
sizes (Union[dict[str, Any]]): widget sizes
pySimpleGui (Any): pysimplegui module
Returns:
-------
Widgets: widgets object all set up nicely
"""
if sizes:
Expand Down Expand Up @@ -166,10 +176,11 @@ def addItemsAndGroups(
section: types.Group,
argConstruct: list[list[Element]],
widgets: Widgets,
):
) -> list[list[Element]]:
"""Add arg_items and groups to the argConstruct list.
Args:
----
section (types.Group): contents/ section containing name, arg_items
and groups
argConstruct (list[list[Element]]): list of widgets to
Expand All @@ -178,7 +189,8 @@ def addItemsAndGroups(
argConstruct
Returns:
list: updated argConstruct
-------
list[list[Element]]: updated argConstruct
"""
argConstruct.append([widgets.label(widgets.stringTitlecase(section["name"], " "), 14)])
for item in section["arg_items"]:
Expand All @@ -202,13 +214,15 @@ def generatePopup(
"""Create the popup window.
Args:
----
buildSpec (types.FullBuildSpec): [description]
values (Union[dict[Any, Any]): Returned when a button is clicked. Such
as the menu
widgets (Widgets): class to build widgets
pySimpleGui (Any): PySimpleGui class
Returns:
-------
pySimpleGui.Window: A PySimpleGui Window
"""
maxLines = 30 if buildSpec["gui"] == "pysimpleguiqt" else 200
Expand All @@ -220,7 +234,7 @@ def generatePopup(
popupText = "\n".join(lines[:maxLines]) + "\n\nMORE TEXT IN SRC FILE"
else:
popupText = "\n".join(lines)
except:
except ImportError:
popupText = Path(buildSpec["menu"][values[0]]).read_text(encoding="utf-8")
if buildSpec["gui"] == "pysimplegui":
popupLayout = [
Expand Down Expand Up @@ -271,12 +285,14 @@ def createLayout(
"""Create the pysimplegui layout from the build spec.
Args:
----
buildSpec (types.FullBuildSpec): build spec containing widget
widgets (Widgets): class to build widgets
pySimpleGui (Any): version of PySimpleGui to use
menu (list[str]]): menu data
Returns:
-------
list[list[Element]]: list of widgets (layout list)
"""
argConstruct = []
Expand Down Expand Up @@ -325,20 +341,21 @@ def createLayout(
return layout


def run(buildSpec: types.FullBuildSpec):
"""Main entry point for the application.
def run(buildSpec: types.FullBuildSpec) -> None:
"""Establish the main entry point.
Args:
----
buildSpec (types.FullBuildSpec): args that customise the application such as the theme
or the function to run
"""
import PySimpleGUI as psg # pylint: disable=reimported
import PySimpleGUI as psg

if buildSpec["gui"] == "pysimpleguiqt":
import PySimpleGUIQt as psg
elif buildSpec["gui"] == "pysimpleguiweb":
import PySimpleGUIWeb as psg
pySimpleGui: Any = psg # type: ignore
pySimpleGui: Any = psg

# Set the theme
setBase24Theme(buildSpec["theme"], buildSpec["darkTheme"], pySimpleGui)
Expand All @@ -358,7 +375,7 @@ def run(buildSpec: types.FullBuildSpec):

# While the application is running
while True:
eventAndValues: tuple[Any, dict[Any, Any] | list[Any]] = window.read() # type: ignore
eventAndValues: tuple[Any, dict[Any, Any] | list[Any]] = window.read()
event, values = eventAndValues
if event in (None, "Exit"):
sys.exit(0)
Expand All @@ -367,7 +384,7 @@ def run(buildSpec: types.FullBuildSpec):
if values is not None:
if 0 in values and values[0] is not None:
popup = generatePopup(buildSpec, values, widgets, pySimpleGui)
popup.read() # type: ignore
popup.read()
args = {}
for key in values:
if key != 0:
Expand All @@ -376,5 +393,5 @@ def run(buildSpec: types.FullBuildSpec):
if not buildSpec["run_function"]:
return args
buildSpec["run_function"](args)
except Exception as exception: # pylint: disable=broad-except
logging.exception(exception)
except Exception:
logging.exception("Something went wrong: ")
6 changes: 3 additions & 3 deletions cli2gui/application/pysimplegui2args.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@ def argparseFormat(values: dict[str, Any]) -> argparse.Namespace:
args[key] = None
# Paths end in '#', set the base key (used by argparse)
elif key[-1] == "#": # File
args[key[:-1]] = open( # pylint:disable=consider-using-with
values[key], encoding="utf-8"
)
args[key[:-1]] = open(values[key], encoding="utf-8")
else:
args[key] = values[key]
return argparse.Namespace(**args)
Expand Down Expand Up @@ -62,10 +60,12 @@ def argFormat(values: dict[str, Any], argumentParser: str | ParserType) -> Any:
"""Format the args for the desired parser.
Args:
----
values (dict[str, Any]): values from simple gui
argumentParser (str): argument parser to use
Returns:
-------
Any: args
"""
formattedArgs = None
Expand Down
34 changes: 23 additions & 11 deletions cli2gui/application/widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,31 @@


class Widgets:
"""Widgets class holding methods to create widgets in addition to a sizes.
attribute that can be overridden to provide the end user with customisation
over the size of the gui.
"""
Methods to create widgets and a sizes attribute to provide users with
customization options for the size of the GUI.
def __init__(self, sizes: dict[str, Any], pySimpleGui: Any):
Utility functions within the class manipulate images and text and create PySimpleGUI
Elements
"""

def __init__(self, sizes: dict[str, Any], pySimpleGui: Any) -> None:
"""Methods to create widgets and a sizes attribute to provide users with
customization options for the size of the GUI.
Utility functions within the class manipulate images and text and create PySimpleGUI
Elements
:param dict[str, Any] sizes: A dictionary specifying sizes.
:param Any pySimpleGui: PySimpleGui module object
"""
self.sizes = sizes
self.pySimpleGui = pySimpleGui

"""Utility functions that manipulate images and text.
"""

def getImgData(self, imagePath: str, first: bool = False) -> bytes:
def getImgData(self, imagePath: str, *, first: bool = False) -> bytes:
"""Generate image data using PIL."""
img = Image.open(imagePath)
img.thumbnail((self.sizes["title_size"] * 3, self.sizes["title_size"] * 3))
Expand All @@ -37,7 +49,7 @@ def getImgData(self, imagePath: str, first: bool = False) -> bytes:
return bio.getvalue()
return ImageTk.PhotoImage(img) # type:ignore

def stringTitlecase(self, string: str, splitStr: str = "ALL"):
def stringTitlecase(self, string: str, splitStr: str = "ALL") -> str:
"""Convert a string to title case."""
_ = self
titleCase = ""
Expand All @@ -62,7 +74,7 @@ def stringSentencecase(self, string: str) -> str:
"""Individual widgets
"""

def inputText(self, key: str, default=None) -> Element:
def inputText(self, key: str, default: str | None = None) -> Element:
"""Return an input text field."""
return self.pySimpleGui.InputText(
default,
Expand All @@ -72,7 +84,7 @@ def inputText(self, key: str, default=None) -> Element:
font=("sans", self.sizes["text_size"]),
)

def spin(self, key: str, default=None) -> Element:
def spin(self, key: str, default: str | None = None) -> Element:
"""Return an input text field."""
return self.pySimpleGui.Spin(
list(range(-50, 51)),
Expand All @@ -83,7 +95,7 @@ def spin(self, key: str, default=None) -> Element:
font=("sans", self.sizes["text_size"]),
)

def check(self, key: str, default=None) -> Element:
def check(self, key: str, default: str | None = None) -> Element:
"""Return a checkbox."""
return self.pySimpleGui.Check(
"", size=self.sizes["input_size"], pad=self.sizes["padding"], key=key, default=default
Expand Down Expand Up @@ -119,7 +131,7 @@ def dropdown(self, key: str, argItems: list[str]) -> Element:
key=key,
)

def fileBrowser(self, key: str, default=None) -> list[Element]:
def fileBrowser(self, key: str, default: str | None = None) -> list[Element]:
"""Return a fileBrowser button and field."""
height = self.sizes["input_size"][1]
width = self.sizes["input_size"][0]
Expand Down Expand Up @@ -236,7 +248,7 @@ def helpDropdownWidget(
]

def addWidgetFromItem(self, item: types.Item) -> list[Element]:
"""Add a widget from an item (types.Item)"""
"""Add a widget from an item (types.Item)."""
functionMap = {
types.ItemType.Bool: self.helpFlagWidget,
types.ItemType.File: self.helpFileWidget,
Expand Down
Loading

0 comments on commit a291a8b

Please sign in to comment.