Skip to content

Commit

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

add ci

fixup ci
  • Loading branch information
dni committed Aug 13, 2024
1 parent 51d237c commit 47a2000
Show file tree
Hide file tree
Showing 26 changed files with 3,202 additions and 298 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 @@ -55,4 +55,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"
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,16 @@

## A Starter Template for Your Own Extension

Ready to start hacking? Once you've forked this extension, you can incorporate functions from other extensions as needed.
Ready to start hacking? Once you've forked this extension, you can incorporate functions from other extensions as needed.

### How to Use This Template

> This guide assumes you're using this extension as a base for a new one, and have installed LNbits using https://github.com/lnbits/lnbits/blob/main/docs/guide/installation.md#option-1-recommended-poetry.
1. Install and enable the extension either through the official LNbits manifest or by adding https://raw.githubusercontent.com/lnbits/myextension/main/manifest.json to `"Server"/"Server"/"Extension Sources"`. ![Extension Sources](https://i.imgur.com/MUGwAU3.png) ![image](https://github.com/lnbits/myextension/assets/33088785/4133123b-c747-4458-ba6c-5cc7c0f124d8)

2. `Ctrl c` shut down your LNbits installation.
3. Download the extension files from https://github.com/lnbits/myextension to a folder outside of `/lnbits`, and initialize the folder with `git`. Alternatively, create a repo, copy the myextension extension files into it, then `git clone` the extension to a location outside of `/lnbits`.
3. Download the extension files from https://github.com/lnbits/myextension to a folder outside of `/lnbits`, and initialize the folder with `git`. Alternatively, create a repo, copy the myextension extension files into it, then `git clone` the extension to a location outside of `/lnbits`.
4. Remove the installed extension from `lnbits/lnbits/extensions`.
5. Create a symbolic link using `ln -s /home/ben/Projects/<name of your extension> /home/ben/Projects/lnbits/lnbits/extensions`.
6. Restart your LNbits installation. You can now modify your extension and `git push` changes to a repo.
Expand Down
38 changes: 22 additions & 16 deletions __init__.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,24 @@
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

from .crud import db
from .tasks import wait_for_paid_invoices
from .views import myextension_generic_router
from .views_api import myextension_api_router
from .views_lnurl import myextension_lnurl_router

logger.debug(
"This logged message is from myextension/__init__.py, you can debug in your extension using 'import logger from loguru' and 'logger.debug(<thing-to-log>)'."
"This logged message is from myextension/__init__.py, you can debug in your "
"extension using 'import logger from loguru' and 'logger.debug(<thing-to-log>)'."
)

db = Database("ext_myextension")

myextension_ext: APIRouter = APIRouter(prefix="/myextension", tags=["MyExtension"])
myextension_ext.include_router(myextension_generic_router)
myextension_ext.include_router(myextension_api_router)
myextension_ext.include_router(myextension_lnurl_router)

myextension_static_files = [
{
Expand All @@ -22,16 +27,6 @@
}
]


def myextension_renderer():
return template_renderer(["myextension/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 @@ -44,5 +39,16 @@ def myextension_stop():


def myextension_start():
from lnbits.tasks import create_permanent_unique_task

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


__all__ = [
"db",
"myextension_ext",
"myextension_static_files",
"myextension_start",
"myextension_stop",
]
136 changes: 57 additions & 79 deletions crud.py
Original file line number Diff line number Diff line change
@@ -1,99 +1,77 @@
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 CreateMyExtensionData, MyExtension
from fastapi import Request
from lnurl import encode as lnurl_encode
import shortuuid
from lnbits.db import Database
from lnbits.helpers import insert_query, update_query

from .models import MyExtension

async def create_myextension(
wallet_id: str, data: CreateMyExtensionData, req: Request
) -> MyExtension:
myextension_id = urlsafe_short_hash()
db = Database("ext_myextension")
table_name = "myextension.maintable"


async def create_myextension(data: MyExtension) -> MyExtension:
await db.execute(
"""
INSERT INTO myextension.maintable (id, wallet, name, lnurlpayamount, lnurlwithdrawamount)
VALUES (?, ?, ?, ?, ?)
""",
(
myextension_id,
wallet_id,
data.name,
data.lnurlpayamount,
data.lnurlwithdrawamount,
),
insert_query(table_name, data),
(*data.dict().values(),),
)
myextension = await get_myextension(myextension_id, req)
assert myextension, "Newly created table couldn't be retrieved"
return myextension
return data

# this is how we used to do it

async def get_myextension(
myextension_id: str, req: Optional[Request] = None
) -> Optional[MyExtension]:
# myextension_id = urlsafe_short_hash()
# await db.execute(
# """
# INSERT INTO myextension.maintable
# (id, wallet, name, lnurlpayamount, lnurlwithdrawamount)
# VALUES (?, ?, ?, ?, ?)
# """,
# (
# myextension_id,
# wallet_id,
# data.name,
# data.lnurlpayamount,
# data.lnurlwithdrawamount,
# ),
# )
# myextension = await get_myextension(myextension_id)
# assert myextension, "Newly created table couldn't be retrieved"


async def get_myextension(myextension_id: str) -> Optional[MyExtension]:
row = await db.fetchone(
"SELECT * FROM myextension.maintable WHERE id = ?", (myextension_id,)
f"SELECT * FROM {table_name} WHERE id = ?", (myextension_id,)
)
if not row:
return None
rowAmended = MyExtension(**row)
if req:
rowAmended.lnurlpay = lnurl_encode(
req.url_for("myextension.api_lnurl_pay", myextension_id=row.id)._url
)
rowAmended.lnurlwithdraw = lnurl_encode(
req.url_for(
"myextension.api_lnurl_withdraw",
myextension_id=row.id,
tickerhash=shortuuid.uuid(name=rowAmended.id + str(rowAmended.ticker)),
)._url
)
return rowAmended


async def get_myextensions(
wallet_ids: Union[str, List[str]], req: Optional[Request] = None
) -> List[MyExtension]:
return MyExtension(**row) if row else None


async def get_myextensions(wallet_ids: Union[str, list[str]]) -> list[MyExtension]:
if isinstance(wallet_ids, str):
wallet_ids = [wallet_ids]

q = ",".join(["?"] * len(wallet_ids))
rows = await db.fetchall(
f"SELECT * FROM myextension.maintable WHERE wallet IN ({q})", (*wallet_ids,)
f"SELECT * FROM {table_name} WHERE wallet IN ({q})", (*wallet_ids,)
)
tempRows = [MyExtension(**row) for row in rows]
if req:
for row in tempRows:
row.lnurlpay = lnurl_encode(
req.url_for("myextension.api_lnurl_pay", myextension_id=row.id)._url
)
row.lnurlwithdraw = lnurl_encode(
req.url_for(
"myextension.api_lnurl_withdraw",
myextension_id=row.id,
tickerhash=shortuuid.uuid(name=row.id + str(row.ticker)),
)._url
)
return tempRows


async def update_myextension(
myextension_id: str, req: Optional[Request] = None, **kwargs
) -> MyExtension:
q = ", ".join([f"{field[0]} = ?" for field in kwargs.items()])
return [MyExtension(**row) for row in rows]


async def update_myextension(data: MyExtension) -> MyExtension:
await db.execute(
f"UPDATE myextension.maintable SET {q} WHERE id = ?",
(*kwargs.values(), myextension_id),
update_query(table_name, data),
(
*data.dict().values(),
data.id,
),
)
myextension = await get_myextension(myextension_id, req)
assert myextension, "Newly updated myextension couldn't be retrieved"
return myextension
return data
# this is how we used to do it

# q = ", ".join([f"{field[0]} = ?" for field in kwargs.items()])
# await db.execute(
# f"UPDATE myextension.maintable SET {q} WHERE id = ?",
# (*kwargs.values(), myextension_id),
# )


async def delete_myextension(myextension_id: str) -> None:
await db.execute(
"DELETE FROM myextension.maintable WHERE id = ?", (myextension_id,)
)
await db.execute(f"DELETE FROM {table_name} WHERE id = ?", (myextension_id,))
4 changes: 2 additions & 2 deletions description.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ This is a longform description that will be used in the advanced description whe

Adding some bullets is nice covering:

* Functionality
* Use cases
- Functionality
- Use cases

...and some other text about just how great this etension is.
17 changes: 2 additions & 15 deletions migrations.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# the migration file is where you build your database tables
# If you create a new release for your extension , remeember the migration file is like a blockchain, never edit only add!
# If you create a new release for your extension ,
# remember the migration file is like a blockchain, never edit only add!


async def m001_initial(db):
Expand All @@ -20,17 +21,3 @@ async def m001_initial(db):
);
"""
)


# Here we add another field to the database


async def m002_addtip_wallet(db):
"""
Add total to templates table
"""
await db.execute(
"""
ALTER TABLE myextension.maintable ADD ticker INTEGER DEFAULT 1;
"""
)
Loading

0 comments on commit 47a2000

Please sign in to comment.