Skip to content

Commit

Permalink
Install and configure linter and formatter, check some lint issues, f…
Browse files Browse the repository at this point in the history
…ormat the code and add some github actions (#3)

* Install and configure linter and formatter, check some lint issues, format the code and add some github actions

* Update blitz/ui/components/gpt_chat_components.py with default value for text_is_finished

Co-authored-by: pbrochar <[email protected]>

---------

Co-authored-by: pbrochar <[email protected]>
  • Loading branch information
mde-pach and pbrochar authored Feb 16, 2024
1 parent bca1ce6 commit 81fac60
Show file tree
Hide file tree
Showing 37 changed files with 664 additions and 437 deletions.
102 changes: 84 additions & 18 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -1,30 +1,96 @@
name: documentation
name: Lint & Test
on:
push:
branches:
- main
workflow_dispatch:

permissions:
contents: write
jobs:
deploy:
lint:
runs-on: ubuntu-latest
steps:
#----------------------------------------------
# check-out repo and set-up python
#----------------------------------------------
- uses: actions/checkout@v4
- name: Configure Git Credentials
run: |
git config user.name github-actions[bot]
git config user.email 41898282+github-actions[bot]@users.noreply.github.com
- uses: actions/setup-python@v4
- name: Set up python
id: setup-python
uses: actions/setup-python@v5
with:
python-version: 3.x
- run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV
- uses: actions/cache@v3
python-version: '3.12'
#----------------------------------------------
# ----- install & configure poetry -----
#----------------------------------------------
- name: Install Poetry
uses: snok/install-poetry@v1
with:
key: mkdocs-material-${{ env.cache_id }}
path: .cache
restore-keys: |
mkdocs-material-
virtualenvs-create: true
virtualenvs-in-project: true
#----------------------------------------------
# load pip cache if cache exists
#----------------------------------------------
- name: Load cached venv
id: cached-poetry-dependencies
uses: actions/cache@v3
with:
path: .venv
key: lint-venv-${{ runner.os }}-${{ steps.setup-python.outputs.python-version }}-${{ hashFiles('**/poetry.lock') }}
#----------------------------------------------
# install and run linters
#----------------------------------------------
- name: Install dev dependencies
run: poetry install --with=dev --no-root
- name: Ruff
run: poetry run ruff check blitz/
- name: Mypy
run: poetry run mypy blitz/
test:
needs: lint
strategy:
fail-fast: true
matrix:
os: [ "ubuntu-latest", "macos-latest" ]
# python-version: [ "3.8", "3.9", "3.10", "3.11", "3.12" ]
python-version: [ "3.12" ]
runs-on: ${{ matrix.os }}
steps:
#----------------------------------------------
# check-out repo and set-up python
#----------------------------------------------
- name: Check out repository
uses: actions/checkout@v4
- name: Set up python ${{ matrix.python-version }}
id: setup-python
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
#----------------------------------------------
# ----- install & configure poetry -----
#----------------------------------------------
- name: Install Poetry
uses: snok/install-poetry@v1
- run: poetry install --with=doc
- run: poetry run mkdocs gh-deploy --force
with:
virtualenvs-create: true
virtualenvs-in-project: true
#----------------------------------------------
# load cached venv if cache exists
#----------------------------------------------
- name: Load cached venv
id: cached-poetry-dependencies
uses: actions/cache@v3
with:
path: .venv
key: test-venv-${{ runner.os }}-${{ steps.setup-python.outputs.python-version }}-${{ hashFiles('**/poetry.lock') }}
#----------------------------------------------
# install dependencies if cache does not exist
#----------------------------------------------
- name: Install dependencies
if: steps.cached-poetry-dependencies.outputs.cache-hit != 'true'
run: poetry install --no-interaction
#----------------------------------------------
# add matrix specifics and run test suite
#----------------------------------------------
- name: Run tests
run: |
source .venv/bin/activate
pytest ./tests/
32 changes: 32 additions & 0 deletions .github/workflows/documentation.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
name: Build & Deploy Documentation
on:
push:
branches:
- main
workflow_dispatch:

permissions:
contents: write
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Configure Git Credentials
run: |
git config user.name github-actions[bot]
git config user.email 41898282+github-actions[bot]@users.noreply.github.com
- uses: actions/setup-python@v4
with:
python-version: 3.x
- run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV
- uses: actions/cache@v3
with:
key: mkdocs-material-${{ env.cache_id }}
path: .cache
restore-keys: |
mkdocs-material-
- name: Install Poetry
uses: snok/install-poetry@v1
- run: poetry install --with=doc
- run: poetry run mkdocs gh-deploy --force
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ Here is an example of how simple a Blitz file is:
name: Hello world
description: Here is a simple blitz configuration file.
version: 0.1.0
models:
resources:
- name: TodoList
fields:
name: str
Expand Down
1 change: 1 addition & 0 deletions blitz/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@
__all__ = [
"BlitzCore",
]
__version__ = "0.1.0"
10 changes: 3 additions & 7 deletions blitz/api/blitz_admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,13 @@


class BlitzAdmin:
def __init__(
self, blitz_app: "BlitzApp", settings: Settings = get_settings()
) -> None:
def __init__(self, blitz_app: "BlitzApp", settings: Settings = get_settings()) -> None:
self.blitz_app = blitz_app
self.admin = Admin(
title=f"{blitz_app.name} Admin",
# FIXME find a better way to get the engine
engine=get_sqlite_engine(
blitz_app, in_memory=blitz_app._in_memory, file_name="app.db"
),
base_url=f"/admin/",
engine=get_sqlite_engine(blitz_app, in_memory=blitz_app._in_memory, file_name="app.db"),
base_url="/admin/",
)
for resource in blitz_app.resources:
self.admin.add_view(ModelView(resource.model))
Expand Down
21 changes: 16 additions & 5 deletions blitz/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,12 @@

class BlitzApp:
def __init__(
self, name: str, path: Path, file: BlitzFile, in_memory: bool = False, version: Version | None = None
self,
name: str,
path: Path,
file: BlitzFile,
in_memory: bool = False,
version: Version | None = None,
) -> None:
self.name = name
self.path = path
Expand All @@ -40,12 +45,12 @@ def _load_versions(self) -> None:
if directory.is_dir():
try:
version = Version.parse(directory.name)
except:
except Exception:
continue

try:
_find_blitz_file_path(self.path / str(version))
except:
except Exception:
raise ValueError(
f"Blitz app {self.name} has a version dir '{version}' without a blitz file inside."
)
Expand Down Expand Up @@ -101,7 +106,7 @@ def load(self) -> None:
# We loop through the relationships to create the relationship field in the other table
for relationship in relationships:
config.fields[relationship.lower()] = BlitzField(
type=AllowedBlitzFieldTypes.relationship, # type: ignore
type=AllowedBlitzFieldTypes.relationship,
relationship=relationship,
)
try:
Expand Down Expand Up @@ -133,6 +138,9 @@ def release(self, level: str, force: bool = False) -> Version:
case "patch":
new_version = latest_version.bump_patch()

if self.file.path is None:
# TODO: handle error
raise Exception
# We run the migrations to the latest version
latest_blitz_app = BlitzApp(
"", latest_version_path, parse_file(latest_version_path / self.file.path.name), in_memory=True
Expand All @@ -152,7 +160,7 @@ def release(self, level: str, force: bool = False) -> Version:
try:
# Use the version in the blitz file as initial version
new_version = Version.parse(self.file.config.version)
except:
except Exception:
logger.warning(
(
f"Version in blitz file {self.file.path} is not a valid semver version."
Expand Down Expand Up @@ -193,6 +201,9 @@ def release(self, level: str, force: bool = False) -> Version:
if not new_version_path.exists():
new_version_path.mkdir(parents=True)

if self.file.path is None:
# TODO: handle error
raise Exception
# We copy the current blitz file to the new version directory
new_version_blitz_file_path = new_version_path / self.file.path.name
new_version_blitz_file_path.write_text(self.file.path.read_text())
Expand Down
1 change: 0 additions & 1 deletion blitz/cli/app.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# from .commands.swagger import list_routes
from .commands.swagger import list_routes
from .commands.start import start_blitz
from .commands.clean import clean_blitz
from .commands.list import list_blitz_app
from .commands.create import create_blitz_app
from .commands.release import release_blitz
Expand Down
3 changes: 3 additions & 0 deletions blitz/cli/commands/create.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ def write_blitz_file(blitz_file: BlitzFile, blitz_file_format: str) -> Path:
else:
raise ValueError("Invalid blitz file format")

if blitz_file.path is None:
# TODO: handle error
raise Exception
with open(blitz_file.path, "w") as file:
file.write(blitz_file_data)

Expand Down
2 changes: 1 addition & 1 deletion blitz/cli/commands/release.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def release_blitz(
try:
new_version = app.release(level.value, force=force)
except NoChangesDetectedError:
typer.echo(f"No changes detected since the latest version. Use --force to release anyway.")
typer.echo("No changes detected since the latest version. Use --force to release anyway.")
raise typer.Exit(code=1)
typer.echo(f"Blitz app {blitz_app_name} released at version {new_version}")
typer.echo("You can now start your versioned blitz app by running:")
Expand Down
4 changes: 3 additions & 1 deletion blitz/cli/commands/start.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,9 @@ def start_blitz(
os.environ["BLITZ_VERSION"] = str(version)
os.environ["BLITZ_ADMIN"] = str(admin).lower()
os.environ["BLITZ_CONFIG_ROUTE"] = str(config_route).lower()

if blitz_app.file.path is None:
# TODO: handle error
raise Exception
server_config = uvicorn.Config(
"blitz.api:create_blitz_api",
factory=True,
Expand Down
23 changes: 10 additions & 13 deletions blitz/cli/commands/swagger.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,13 @@ class SwaggerPrinter:
def __init__(self, routes: list[BlitzResource]) -> None:
self.routes = routes

def _get_create_panel(self, resource_name: str):
def _get_create_panel(self, resource_name: str) -> Panel:
return Panel(
f"[{self.POST_STYLE}]POST [white bold]/{resource_name} [white dim frame]Create One",
border_style=self.POST_STYLE,
)

def _get_read_panel(self, resource_name: str):

def _get_read_panel(self, resource_name: str) -> list[Panel]:
return [
Panel(
f"[{self.GET_STYLE}]GET [white bold]/{resource_name} [white dim frame]Get One",
Expand All @@ -37,23 +36,23 @@ def _get_read_panel(self, resource_name: str):
),
]

def _get_can_delete_panel(self, resource_name: str):
def _get_can_delete_panel(self, resource_name: str) -> Panel:
return Panel(
f"[{self.DELETE_STYLE}]DELETE [white bold]/{resource_name}/{{item_id}} [white dim frame]Delete One",
border_style=self.DELETE_STYLE,
)

def _get_can_update_panel(self, resource_name: str):
def _get_can_update_panel(self, resource_name: str) -> Panel:
return Panel(
f"[{self.PATCH_STYLE}]PUT [white bold]/{resource_name}/{{item_id}} [white dim frame]Update One",
border_style=self.PATCH_STYLE,
)

def _get_name_panel(self, resource_name: str):
def _get_name_panel(self, resource_name: str) -> Panel:
return Panel(f"[white bold]{resource_name.upper()}")

def get_panels(self):
panels = []
def get_panels(self) -> list[Panel | str]:
panels: list[Panel | str] = []
for resource in self.routes:
resource_name = resource.config.name.lower()
panels.append(self._get_name_panel(resource_name))
Expand All @@ -66,18 +65,16 @@ def get_panels(self):
panels.append("\n")
return panels

def print(self):
def print(self) -> None:
panels = self.get_panels()
for panel in panels:
print(panel)


def list_routes(
blitz_app_name: Annotated[str, typer.Argument(..., help="Blitz app name")],
model: Annotated[str, typer.Option()] = None,
version: Annotated[
Optional[str], typer.Option(help="Define the version of the app.")
] = None,
model: Annotated[Optional[str], typer.Option()] = None,
version: Annotated[Optional[str], typer.Option(help="Define the version of the app.")] = None,
) -> None:
blitz = BlitzCore()
try:
Expand Down
4 changes: 1 addition & 3 deletions blitz/db/db.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from pathlib import Path

from sqlmodel import Session, create_engine
from typing import Any, Generator
from functools import lru_cache
Expand Down Expand Up @@ -48,7 +46,7 @@ def get_db(blitz_app: "BlitzApp", in_memory: bool, file_name: str) -> Generator[
try:
yield session
session.commit()
except:
except Exception:
session.rollback()
finally:
session.close()
2 changes: 0 additions & 2 deletions blitz/db/migrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
from argparse import Namespace
from alembic.config import Config
from alembic.util import AutogenerateDiffsDetected
from functools import lru_cache

# from blitz.db.db import get_sqlite_engine

Expand All @@ -31,7 +30,6 @@ def get_alembic_config(
in_memory: bool = False,
is_release: bool = False,
) -> Config:

# TODO find a better implementation
if blitz_app.version:
file_name = f"{blitz_app.version}/{file_name}"
Expand Down
2 changes: 1 addition & 1 deletion blitz/models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ def create_resource_model(
else:
extra["nullable"] = True

if extra["nullable"] is True and not "default" in extra:
if extra["nullable"] is True and "default" not in extra:
extra["default"] = None

if not isinstance(field.unique, _BlitzNullValue):
Expand Down
Loading

0 comments on commit 81fac60

Please sign in to comment.