Skip to content

Commit

Permalink
replace flake8 by ruff (#167)
Browse files Browse the repository at this point in the history
* chore: Update dependencies and project configuration

* chore: Update .ruff.toml file

* chore: Update Ruff version to v0.5.6 and run linter and formatter

This commit updates the Ruff version to v0.5.6 in the .pre-commit-config.yaml file. It also adds the linter and formatter hooks for Ruff, with the "--fix" argument for the linter. This ensures that the code is properly formatted and follows the linting rules.

Note: This message does not include any issue references, tags, or author names.

* chore: Update Ruff version to v0.5.6, add linter and formatter hooks, and update dependencies

* chore: Update mermaid-py dependencies and add Ruff badge

This commit updates the dependencies for mermaid-py and adds a Ruff badge to the README.md file. The Ruff badge provides information about the latest version of Ruff being used in the project.

Note: This message does not include any issue references, tags, or author names.
  • Loading branch information
ouhammmourachid authored Aug 6, 2024
1 parent 0fc6b5c commit 59eca08
Show file tree
Hide file tree
Showing 54 changed files with 1,422 additions and 1,212 deletions.
18 changes: 0 additions & 18 deletions .flake8

This file was deleted.

2 changes: 1 addition & 1 deletion .github/workflows/deploy-docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: chnage directory
- name: change directory
run: cd docs
- uses: actions/setup-node@v3
with:
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,4 @@ db.sqlite3
/site/
.vscode/*
.vscode/
.mypy_cache/
36 changes: 14 additions & 22 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,23 @@ repos:
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
exclude: '^site/assets/.*'
- repo: https://github.com/pycqa/isort
rev: 5.12.0
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.5.6
hooks:
- id: isort
name: isort (python)
- repo: https://github.com/pre-commit/mirrors-yapf
rev: v0.31.0
hooks:
- id: yapf
additional_dependencies: [toml]
- repo: https://github.com/pycqa/flake8
rev: 4.0.1
hooks:
- id: flake8
additional_dependencies:
- flake8-bugbear
- flake8-builtins
- flake8-coding
- flake8-import-order
- flake8-polyfill
- flake8-quotes
# Run the linter.
- id: ruff
args: [ --fix ]
# Run the formatter.
- id: ruff-format
- repo: https://github.com/pre-commit/mirrors-mypy
rev: 'v1.9.0'
rev: 'v1.11.1'
hooks:
- id: mypy
additional_dependencies: [types-requests, types-PyYAML, types-toml]
args: ["--exclude", "requests-stubs"]
- repo: https://github.com/codespell-project/codespell
rev: v2.3.0
hooks:
- id: codespell
additional_dependencies: [tomli]
17 changes: 17 additions & 0 deletions .ruff.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[lint]
mccabe = { max-complexity = 14 }
select = [
"E", # pycodestyle errors
"W", # pycodestyle warnings
"F", # pyflakes
"I", # isort
"C", # flake8-comprehensions
"B", # flake8-bugbear
]
ignore = [
"E501", # line too long, handled by black
"B018", # Found useless expression.
]

[lint.pyupgrade]
keep-runtime-typing = true
2 changes: 1 addition & 1 deletion CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
identity and expression, level of experience, education, socioeconomic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.

Expand Down
16 changes: 12 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,17 @@ this package works as an interface for the famous mermaid-js library that uses s
alt="latest version" /></a>
<a href="https://pypi.org/project/mermaid-py/">
<img src="https://img.shields.io/pypi/pyversions/mermaid-py"
alt="suported python version" /></a>
alt="supported python version" /></a>
<a href="https://github.com/astral-sh/ruff">
<img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json"
alt="ruff badge"/></a>
<a href="https://snyk.io/advisor/python/mermaid-py">
<img src="https://snyk.io/advisor/python/mermaid-py/badge.svg"
alt="mermaid-py on snyk"/></a>
</p>

[![mermaid-py]()]()

## Description

mermaid-py is a dynamic Python library designed to serve as a seamless interface for
Expand Down Expand Up @@ -88,13 +96,13 @@ diagram

## To contribute to `mermaid-py`

If you'd like to contribute to this open source project folow this steps:
If you'd like to contribute to this open source project follow this steps:

1. Forke the repo and then clone it.
2. Navigate to the project directory: `cd mermaid-py`.
3. create a local enviroment `python3 -m venv env`.
3. create a local environment `python3 -m venv env`.
4. activate the env `source env/bin/activate`.
5. install the dependecies `poetry install`.
5. install the dependencies `poetry install`.
6. happy coding :) .

## List of Diagrames
Expand Down
23 changes: 16 additions & 7 deletions mermaid/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
load(file_path): Load data from a file.
text_to_snake_case(text): Convert a string of text to snake case.
"""

from enum import Enum

from .__main__ import Mermaid, Position
Expand All @@ -19,18 +20,26 @@
from .style import Style
from .utils import load, text_to_snake_case

__version__: str = '0.5.2'
__version__: str = "0.5.2"


class Direction(Enum):
"""Enum for representing the direction of a Mermaid diagram."""
LEFT_TO_RIGHT = 'LR'
RIGHT_TO_LEFT = 'RL'
TOP_TO_BOTTOM = 'TB'
BOTTOM_TO_TOP = 'BT'

LEFT_TO_RIGHT = "LR"
RIGHT_TO_LEFT = "RL"
TOP_TO_BOTTOM = "TB"
BOTTOM_TO_TOP = "BT"


__all__ = [
'Mermaid', 'load', 'Direction', 'Graph', 'Style', 'Config', 'Icon',
'Position'
"Mermaid",
"load",
"Direction",
"Graph",
"Style",
"Config",
"Icon",
"Position",
"text_to_snake_case",
]
51 changes: 27 additions & 24 deletions mermaid/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@ class Position(Enum):
"""
This class represents the position of the node in a Mermaid diagram.
"""
LEFT = 'left'
RIGHT = 'right'
CENTER = 'center'
NONE = 'none'

LEFT = "left"
RIGHT = "right"
CENTER = "center"
NONE = "none"


class Mermaid:
Expand All @@ -28,17 +29,15 @@ class Mermaid:
svg_response (Response): The response from the GET request to the Mermaid SVG API.
img_response (Response): The response from the GET request to the Mermaid IMG API.
"""
def __init__(self,
graph: Graph,
position: Union[Position, str] = Position.NONE):

def __init__(self, graph: Graph, position: Union[Position, str] = Position.NONE):
"""
The constructor for the Mermaid class.
Parameters:
graph (Graph): The Graph object containing the Mermaid diagram script.
"""
self.__position: str = position if isinstance(position,
str) else position.value
self.__position: str = position if isinstance(position, str) else position.value
self._diagram = self._process_diagram(graph.script)
self._make_request_to_mermaid()

Expand All @@ -49,8 +48,7 @@ def set_position(self, position: Union[Position, str]) -> None:
Parameters:
position (Union[Position, str]): The position of the node.
"""
self.__position = position if isinstance(position,
str) else position.value
self.__position = position if isinstance(position, str) else position.value

@staticmethod
def _process_diagram(diagram: str) -> str:
Expand All @@ -63,9 +61,9 @@ def _process_diagram(diagram: str) -> str:
Returns:
str: The base64 encoded string of the Mermaid diagram script.
"""
graphbytes = diagram.encode('utf8')
graphbytes = diagram.encode("utf8")
base64_bytes = base64.b64encode(graphbytes)
diagram = base64_bytes.decode('ascii')
diagram = base64_bytes.decode("ascii")
return diagram

def _repr_html_(self) -> str:
Expand All @@ -77,17 +75,21 @@ def _repr_html_(self) -> str:
"""
if self.__position == Position.NONE.value:
return self.svg_response.text
return f'<div style="text-align:{self.__position}">{self.svg_response.text}</div>'
return (
f'<div style="text-align:{self.__position}">{self.svg_response.text}</div>'
)

def _make_request_to_mermaid(self) -> None:
"""
Make GET requests to the Mermaid SVG and IMG APIs using
the base64 encoded string of the Mermaid diagram script.
"""
self.svg_response: Response = requests.get('https://mermaid.ink/svg/' +
self._diagram)
self.img_response: Response = requests.get('https://mermaid.ink/img/' +
self._diagram)
self.svg_response: Response = requests.get(
"https://mermaid.ink/svg/" + self._diagram
)
self.img_response: Response = requests.get(
"https://mermaid.ink/img/" + self._diagram
)

def to_svg(self, path: Union[str, Path]) -> None:
"""
Expand All @@ -96,7 +98,7 @@ def to_svg(self, path: Union[str, Path]) -> None:
Parameters:
path (Union[str, Path]): The path of the file to write to.
"""
with open(path, 'w', encoding='utf-8') as file:
with open(path, "w", encoding="utf-8") as file:
file.write(self.svg_response.text)

def to_png(self, path: Union[str, Path]) -> None:
Expand All @@ -106,12 +108,13 @@ def to_png(self, path: Union[str, Path]) -> None:
Parameters:
path (Union[str, Path]): The path of the file to write to.
"""
with open(path, 'wb') as file:
with open(path, "wb") as file:
file.write(self.img_response.content)


try:
from IPython import get_ipython

if get_ipython() is not None:
from IPython.core.magic import register_cell_magic
from IPython.display import Image, display
Expand All @@ -120,14 +123,14 @@ def to_png(self, path: Union[str, Path]) -> None:
def mermaidjs(line, cell):
options = line.strip().split()
script: str = cell.strip()
graph: Graph = Graph('mermaid diagram', script)
graph: Graph = Graph("mermaid diagram", script)
mermaid: Mermaid = Mermaid(graph)
if '--img' in options:
if "--img" in options:
display(Image(mermaid.img_response.content))
else:
display(Mermaid(graph))

get_ipython().register_magic_function(mermaidjs, magic_kind='cell')
get_ipython().register_magic_function(mermaidjs, magic_kind="cell")
except ImportError:
# TODO: add a suitible handler for exception.
print('Error acured while importing mermaidjs .')
print("Error acured while importing mermaidjs .")
42 changes: 23 additions & 19 deletions mermaid/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,12 @@ class Themes(Enum):
methods:
value: returns the value of the Enum class
"""
DEFAULT = 'default'
FOREST = 'forest'
DARK = 'dark'
NEUTRAL = 'neutral'
BASE = 'base'

DEFAULT = "default"
FOREST = "forest"
DARK = "dark"
NEUTRAL = "neutral"
BASE = "base"


class Config:
Expand All @@ -34,14 +35,17 @@ class Config:
__init__: initializes the class
__str__: returns the string representation of the class
"""
def __init__(self,
theme: Themes = Themes.DEFAULT,
primary_color: Optional[str] = None,
primary_text_color: Optional[str] = None,
primary_border_color: Optional[str] = None,
line_color: Optional[str] = None,
secondary_color: Optional[str] = None,
tertiary_color: Optional[str] = None) -> None:

def __init__(
self,
theme: Themes = Themes.DEFAULT,
primary_color: Optional[str] = None,
primary_text_color: Optional[str] = None,
primary_border_color: Optional[str] = None,
line_color: Optional[str] = None,
secondary_color: Optional[str] = None,
tertiary_color: Optional[str] = None,
) -> None:
"""Initializes the class
args:
Expand All @@ -67,9 +71,9 @@ def __str__(self) -> str:
returns:
str: string representation of the class
"""
string: str = '%%{\n\tinit: {\n'
string: str = "%%{\n\tinit: {\n"

string += f'\t\t"theme": "{self.theme.value}",\n\t\t"themeVariables": ' + '{\n'
string += f'\t\t"theme": "{self.theme.value}",\n\t\t"themeVariables": ' + "{\n"
if self.primary_color:
string += f'\t\t\t"primaryColor": "{self.primary_color}",\n'
if self.primary_text_color:
Expand All @@ -82,8 +86,8 @@ def __str__(self) -> str:
string += f'\t\t\t"secondaryColor": "{self.secondary_color}",\n'
if self.tertiary_color:
string += f'\t\t\t"tertiaryColor": "{self.tertiary_color}",\n'
if string.endswith(',\n'):
string = string[:-2] + '\n'
string += '\t\t}\n'
string += '\t}\n}%%\n'
if string.endswith(",\n"):
string = string[:-2] + "\n"
string += "\t\t}\n"
string += "\t}\n}%%\n"
return string
Loading

0 comments on commit 59eca08

Please sign in to comment.