Skip to content

Commit

Permalink
feat: code quality (#31)
Browse files Browse the repository at this point in the history
* feat: code quality
  • Loading branch information
dni authored Aug 30, 2024
1 parent d656d41 commit a8eb139
Show file tree
Hide file tree
Showing 25 changed files with 3,192 additions and 237 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 }})'
15 changes: 7 additions & 8 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
on:
push:
tags:
- "v[0-9]+.[0-9]+.[0-9]+"
- 'v[0-9]+.[0-9]+.[0-9]+'

jobs:

release:
runs-on: ubuntu-latest
steps:
Expand Down Expand Up @@ -34,12 +33,12 @@ jobs:
- name: Create pull request in extensions repo
env:
GH_TOKEN: ${{ secrets.EXT_GITHUB }}
repo_name: "${{ github.event.repository.name }}"
tag: "${{ github.ref_name }}"
branch: "update-${{ github.event.repository.name }}-${{ github.ref_name }}"
title: "[UPDATE] ${{ github.event.repository.name }} to ${{ github.ref_name }}"
body: "https://github.com/lnbits/${{ github.event.repository.name }}/releases/${{ github.ref_name }}"
archive: "https://github.com/lnbits/${{ github.event.repository.name }}/archive/refs/tags/${{ github.ref_name }}.zip"
repo_name: '${{ github.event.repository.name }}'
tag: '${{ github.ref_name }}'
branch: 'update-${{ github.event.repository.name }}-${{ github.ref_name }}'
title: '[UPDATE] ${{ github.event.repository.name }} to ${{ github.ref_name }}'
body: 'https://github.com/lnbits/${{ github.event.repository.name }}/releases/${{ github.ref_name }}'
archive: 'https://github.com/lnbits/${{ github.event.repository.name }}/archive/refs/tags/${{ github.ref_name }}.zip'
run: |
cd lnbits-extensions
git checkout -b $branch
Expand Down
24 changes: 2 additions & 22 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,24 +1,4 @@
.DS_Store
._*

__pycache__
*.py[cod]
*$py.class
node_modules
.mypy_cache
.vscode
*-lock.json

*.egg
*.egg-info
.coverage
.pytest_cache
.webassets-cache
htmlcov
test-reports
tests/data/*.sqlite3

*.swo
*.swp
*.pyo
*.pyc
*.env
.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"
45 changes: 21 additions & 24 deletions __init__.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
import asyncio
from typing import List

from fastapi import APIRouter
from loguru import logger

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

from .nostr.client.client import NostrClient
from .router import NostrRouter

db = Database("ext_nostrclient")
from .crud import db
from .nostr_client import all_routers, nostr_client
from .tasks import check_relays, init_relays, subscribe_events
from .views import nostrclient_generic_router
from .views_api import nostrclient_api_router

nostrclient_static_files = [
{
Expand All @@ -21,23 +17,11 @@
]

nostrclient_ext: APIRouter = APIRouter(prefix="/nostrclient", tags=["nostrclient"])

nostr_client: NostrClient = NostrClient()

# we keep this in
all_routers: list[NostrRouter] = []
nostrclient_ext.include_router(nostrclient_generic_router)
nostrclient_ext.include_router(nostrclient_api_router)
scheduled_tasks: list[asyncio.Task] = []


def nostr_renderer():
return template_renderer(["nostrclient/templates"])


from .tasks import check_relays, init_relays, subscribe_events # noqa
from .views import * # noqa
from .views_api import * # noqa


async def nostrclient_stop():
for task in scheduled_tasks:
try:
Expand All @@ -56,7 +40,20 @@ async def nostrclient_stop():


def nostrclient_start():
from lnbits.tasks import create_permanent_unique_task

task1 = create_permanent_unique_task("ext_nostrclient_init_relays", init_relays)
task2 = create_permanent_unique_task("ext_nostrclient_subscrive_events", subscribe_events)
task2 = create_permanent_unique_task(
"ext_nostrclient_subscrive_events", subscribe_events
)
task3 = create_permanent_unique_task("ext_nostrclient_check_relays", check_relays)
scheduled_tasks.extend([task1, task2, task3])


__all__ = [
"db",
"nostrclient_ext",
"nostrclient_static_files",
"nostrclient_stop",
"nostrclient_start",
]
26 changes: 11 additions & 15 deletions crud.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
from typing import List, Optional

import json
from typing import Optional

from lnbits.db import Database

from . import db
from .models import Config, Relay

db = Database("ext_nostrclient")


async def get_relays() -> List[Relay]:
async def get_relays() -> list[Relay]:
rows = await db.fetchall("SELECT * FROM nostrclient.relays")
return [Relay.from_row(r) for r in rows]

Expand Down Expand Up @@ -37,27 +39,21 @@ async def create_config() -> Config:
INSERT INTO nostrclient.config (json_data)
VALUES (?)
""",
(json.dumps(config.dict())),
)
row = await db.fetchone(
"SELECT json_data FROM nostrclient.config", ()
(json.dumps(config.dict()),),
)
row = await db.fetchone("SELECT json_data FROM nostrclient.config", ())
return json.loads(row[0], object_hook=lambda d: Config(**d))


async def update_config(config: Config) -> Optional[Config]:
await db.execute(
"""UPDATE nostrclient.config SET json_data = ?""",
(json.dumps(config.dict())),
)
row = await db.fetchone(
"SELECT json_data FROM nostrclient.config", ()
(json.dumps(config.dict()),),
)
row = await db.fetchone("SELECT json_data FROM nostrclient.config", ())
return json.loads(row[0], object_hook=lambda d: Config(**d))


async def get_config() -> Optional[Config]:
row = await db.fetchone(
"SELECT json_data FROM nostrclient.config", ()
)
row = await db.fetchone("SELECT json_data FROM nostrclient.config", ())
return json.loads(row[0], object_hook=lambda d: Config(**d)) if row else None
3 changes: 1 addition & 2 deletions models.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
from sqlite3 import Row
from typing import List, Optional

from pydantic import BaseModel

from lnbits.helpers import urlsafe_short_hash
from pydantic import BaseModel


class RelayStatus(BaseModel):
Expand Down
16 changes: 9 additions & 7 deletions nostr/bech32.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,27 +124,29 @@ def decode(hrp, addr):
hrpgot, data, spec = bech32_decode(addr)
if hrpgot != hrp:
return (None, None)
decoded = convertbits(data[1:], 5, 8, False)
decoded = convertbits(data[1:], 5, 8, False) # type: ignore
if decoded is None or len(decoded) < 2 or len(decoded) > 40:
return (None, None)
if data[0] > 16:
if data[0] > 16: # type: ignore
return (None, None)
if data[0] == 0 and len(decoded) != 20 and len(decoded) != 32:
if data[0] == 0 and len(decoded) != 20 and len(decoded) != 32: # type: ignore
return (None, None)
if (
data[0] == 0
data[0] == 0 # type: ignore
and spec != Encoding.BECH32
or data[0] != 0
or data[0] != 0 # type: ignore
and spec != Encoding.BECH32M
):
return (None, None)
return (data[0], decoded)
return (data[0], decoded) # type: ignore


def encode(hrp, witver, witprog):
"""Encode a segwit address."""
spec = Encoding.BECH32 if witver == 0 else Encoding.BECH32M
ret = bech32_encode(hrp, [witver] + convertbits(witprog, 8, 5), spec)
wit_prog = convertbits(witprog, 8, 5)
assert wit_prog
ret = bech32_encode(hrp, [witver, *wit_prog], spec)
if decode(hrp, ret) == (None, None):
return None
return ret
Loading

0 comments on commit a8eb139

Please sign in to comment.