Skip to content

Commit

Permalink
feat: code quality
Browse files Browse the repository at this point in the history
fixes

yo

make black

add ci

add pytestmd
  • Loading branch information
dni committed Aug 13, 2024
1 parent 388227d commit edf7914
Show file tree
Hide file tree
Showing 25 changed files with 3,183 additions and 221 deletions.
34 changes: 34 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
name: CI
on:
push:
branches:
- main
pull_request:

jobs:
lint:
uses: lnbits/lnbits/.github/workflows/lint.yml@dev
tests:
runs-on: ubuntu-latest
needs: [lint]
strategy:
matrix:
python-version: ['3.9', '3.10']
steps:
- uses: actions/checkout@v4
- uses: lnbits/lnbits/.github/actions/prepare@dev
with:
python-version: ${{ matrix.python-version }}
- name: Run pytest
uses: pavelzw/pytest-action@v2
env:
LNBITS_BACKEND_WALLET_CLASS: FakeWallet
PYTHONUNBUFFERED: 1
DEBUG: true
with:
verbose: true
job-summary: true
emoji: false
click-to-expand: true
custom-pytest: poetry run pytest
report-title: 'test (${{ matrix.python-version }})'
2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,4 @@ jobs:
# check if pr exists before creating it
gh config set pager cat
check=$(gh pr list -H $branch | wc -l)
test $check -ne 0 || gh pr create --title "$title" --body "$body" --repo lnbits/lnbits-extensions
test $check -ne 0 || gh pr create --title "$title" --body "$body" --repo lnbits/lnbits-extensions
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
__pycache__
__pycache__
node_modules
.mypy_cache
.venv
12 changes: 12 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"semi": false,
"arrowParens": "avoid",
"insertPragma": false,
"printWidth": 80,
"proseWrap": "preserve",
"singleQuote": true,
"trailingComma": "none",
"useTabs": false,
"bracketSameLine": false,
"bracketSpacing": false
}
47 changes: 47 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
all: format check

format: prettier black ruff

check: mypy pyright checkblack checkruff checkprettier

prettier:
poetry run ./node_modules/.bin/prettier --write .
pyright:
poetry run ./node_modules/.bin/pyright

mypy:
poetry run mypy .

black:
poetry run black .

ruff:
poetry run ruff check . --fix

checkruff:
poetry run ruff check .

checkprettier:
poetry run ./node_modules/.bin/prettier --check .

checkblack:
poetry run black --check .

checkeditorconfig:
editorconfig-checker

test:
PYTHONUNBUFFERED=1 \
DEBUG=true \
poetry run pytest
install-pre-commit-hook:
@echo "Installing pre-commit hook to git"
@echo "Uninstall the hook with poetry run pre-commit uninstall"
poetry run pre-commit install

pre-commit:
poetry run pre-commit run --all-files


checkbundle:
@echo "skipping checkbundle"
34 changes: 19 additions & 15 deletions __init__.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
import asyncio

from fastapi import APIRouter

from lnbits.db import Database
from lnbits.helpers import template_renderer
from lnbits.tasks import create_permanent_unique_task
from loguru import logger

db = Database("ext_eightball")
from .crud import db
from .tasks import wait_for_paid_invoices
from .views import eightball_generic_router
from .views_api import eightball_api_router
from .views_lnurl import eightball_lnurl_router

eightball_ext: APIRouter = APIRouter(prefix="/eightball", tags=["EightBall"])
eightball_ext.include_router(eightball_generic_router)
eightball_ext.include_router(eightball_api_router)
eightball_ext.include_router(eightball_lnurl_router)

eightball_static_files = [
{
Expand All @@ -18,16 +21,6 @@
}
]


def eightball_renderer():
return template_renderer(["eightball/templates"])


from .lnurl import *
from .tasks import wait_for_paid_invoices
from .views import *
from .views_api import *

scheduled_tasks: list[asyncio.Task] = []


Expand All @@ -40,5 +33,16 @@ def eightball_stop():


def eightball_start():
from lnbits.tasks import create_permanent_unique_task

task = create_permanent_unique_task("ext_eightball", wait_for_paid_invoices)
scheduled_tasks.append(task)


__all__ = [
"db",
"eightball_ext",
"eightball_static_files",
"eightball_start",
"eightball_stop",
]
34 changes: 34 additions & 0 deletions ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
name: CI
on:
push:
branches:
- main
pull_request:

jobs:
lint:
uses: lnbits/lnbits/.github/workflows/lint.yml@dev
tests:
runs-on: ubuntu-latest
needs: [lint]
strategy:
matrix:
python-version: ['3.9', '3.10']
steps:
- uses: actions/checkout@v4
- uses: lnbits/lnbits/.github/actions/prepare@dev
with:
python-version: ${{ matrix.python-version }}
- name: Run pytest
uses: pavelzw/pytest-action@v2
env:
LNBITS_BACKEND_WALLET_CLASS: FakeWallet
PYTHONUNBUFFERED: 1
DEBUG: true
with:
verbose: true
job-summary: true
emoji: false
click-to-expand: true
custom-pytest: poetry run pytest
report-title: 'test (${{ matrix.python-version }})'
75 changes: 21 additions & 54 deletions crud.py
Original file line number Diff line number Diff line change
@@ -1,80 +1,47 @@
from typing import List, Optional, Union
from typing import Optional, Union

from lnbits.helpers import urlsafe_short_hash
from lnbits.lnurl import encode as lnurl_encode
from . import db
from .models import CreateEightBallData, EightBall
from fastapi import Request
from lnurl import encode as lnurl_encode
from lnbits.db import Database
from lnbits.helpers import insert_query, update_query

from .models import EightBall

async def create_eightball(
wallet_id: str, data: CreateEightBallData, req: Request
) -> EightBall:
eightball_id = urlsafe_short_hash()
db = Database("ext_eightball")


async def create_eightball(data: EightBall) -> EightBall:
await db.execute(
"""
INSERT INTO eightball.maintable (id, wallet, name, lnurlpayamount, wordlist)
VALUES (?, ?, ?, ?, ?)
""",
(
eightball_id,
wallet_id,
data.name,
data.lnurlpayamount,
data.wordlist,
),
insert_query("eightball.maintable", data),
(*data.dict().values(),),
)
eightball = await get_eightball(eightball_id, req)
assert eightball, "Newly created table couldn't be retrieved"
return eightball
return data


async def get_eightball(
eightball_id: str, req: Optional[Request] = None
) -> Optional[EightBall]:
async def get_eightball(eightball_id: str) -> Optional[EightBall]:
row = await db.fetchone(
"SELECT * FROM eightball.maintable WHERE id = ?", (eightball_id,)
)
if not row:
return None
rowAmended = EightBall(**row)
if req:
rowAmended.lnurlpay = lnurl_encode(
req.url_for("eightball.api_lnurl_pay", eightball_id=row.id)._url
)
return rowAmended
return EightBall(**row) if row else None


async def get_eightballs(
wallet_ids: Union[str, List[str]], req: Optional[Request] = None
) -> List[EightBall]:
async def get_eightballs(wallet_ids: Union[str, list[str]]) -> list[EightBall]:
if isinstance(wallet_ids, str):
wallet_ids = [wallet_ids]

q = ",".join(["?"] * len(wallet_ids))
rows = await db.fetchall(
f"SELECT * FROM eightball.maintable WHERE wallet IN ({q})", (*wallet_ids,)
)
tempRows = [EightBall(**row) for row in rows]
if req:
for row in tempRows:
row.lnurlpay = lnurl_encode(
req.url_for("eightball.api_lnurl_pay", eightball_id=row.id)._url
)
return tempRows
return [EightBall(**row) for row in rows]


async def update_eightball(
eightball_id: str, req: Optional[Request] = None, **kwargs
) -> EightBall:
q = ", ".join([f"{field[0]} = ?" for field in kwargs.items()])
async def update_eightball(eightball: EightBall) -> EightBall:
await db.execute(
f"UPDATE eightball.maintable SET {q} WHERE id = ?",
(*kwargs.values(), eightball_id),
update_query("eightball.maintable", eightball),
(
*eightball.dict().values(),
eightball.id,
),
)
eightball = await get_eightball(eightball_id, req)
assert eightball, "Newly updated eightball couldn't be retrieved"
return eightball


Expand Down
7 changes: 4 additions & 3 deletions description.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
Make payment QR codes that people can pay some sats to an receive a random word from a list.

Example use cases:
* Magic 8 Ball
* Pay for satoshi quotes

As seen in the "1hr extension build tutorial" https://www.youtube.com/watch?v=zHXLvvjClHI
- Magic 8 Ball
- Pay for satoshi quotes

As seen in the "1hr extension build tutorial" https://www.youtube.com/watch?v=zHXLvvjClHI
22 changes: 9 additions & 13 deletions models.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,19 @@
from sqlite3 import Row
from typing import Optional

from pydantic import BaseModel


class CreateEightBallData(BaseModel):
wallet: Optional[str]
name: Optional[str]
wordlist: Optional[str]
lnurlpayamount: Optional[int]
name: str
wordlist: str
lnurlpayamount: int
wallet: Optional[str] = None


class EightBall(BaseModel):
id: str
wallet: Optional[str]
name: Optional[str]
wordlist: Optional[str]
lnurlpayamount: Optional[int]
wallet: str
name: str
wordlist: str
lnurlpayamount: int
lnurlpay: Optional[str]

@classmethod
def from_row(cls, row: Row) -> "EightBall":
return cls(**dict(row))
Loading

0 comments on commit edf7914

Please sign in to comment.