Configure more lints and switch from black to ruff format

This commit is contained in:
link2xt 2024-05-06 13:02:10 +00:00
parent 462e92cca0
commit 879cffc056
27 changed files with 136 additions and 112 deletions

View File

@ -36,6 +36,16 @@ log_format = "%(asctime)s %(levelname)s %(message)s"
log_date_format = "%Y-%m-%d %H:%M:%S" log_date_format = "%Y-%m-%d %H:%M:%S"
log_level = "INFO" log_level = "INFO"
[tool.ruff]
lint.select = [
"F", # Pyflakes
"I", # isort
"PLC", # Pylint Convention
"PLE", # Pylint Error
"PLW", # Pylint Warning
]
[tool.tox] [tool.tox]
legacy_tox_ini = """ legacy_tox_ini = """
[tox] [tox]
@ -47,10 +57,9 @@ skipdist = True
skip_install = True skip_install = True
deps = deps =
ruff ruff
black
commands = commands =
black --quiet --check --diff src/ ruff format --quiet --diff src/
ruff src/ ruff check src/
[testenv] [testenv]
deps = pytest deps = pytest

View File

@ -1,5 +1,5 @@
import sqlite3
import contextlib import contextlib
import sqlite3
import time import time
from pathlib import Path from pathlib import Path

View File

@ -1,18 +1,18 @@
import crypt
import json
import logging import logging
import os import os
import time
import sys import sys
import json import time
import crypt
from pathlib import Path from pathlib import Path
from socketserver import ( from socketserver import (
UnixStreamServer,
StreamRequestHandler, StreamRequestHandler,
ThreadingMixIn, ThreadingMixIn,
UnixStreamServer,
) )
from .config import Config, read_config
from .database import Database from .database import Database
from .config import read_config, Config
NOCREATE_FILE = "/etc/chatmail-nocreate" NOCREATE_FILE = "/etc/chatmail-nocreate"

View File

@ -6,11 +6,11 @@ it will echo back any message that has non-empty text and also supports the /hel
import logging import logging
import os import os
import sys
import subprocess import subprocess
import sys
from pathlib import Path
from deltachat_rpc_client import Bot, DeltaChat, EventType, Rpc, events from deltachat_rpc_client import Bot, DeltaChat, EventType, Rpc, events
from pathlib import Path
from chatmaild.config import read_config from chatmaild.config import read_config
from chatmaild.newemail import create_newemail_dict from chatmaild.newemail import create_newemail_dict

View File

@ -1,9 +1,10 @@
import os
import logging
import json import json
import filelock import logging
import os
from contextlib import contextmanager from contextlib import contextmanager
import filelock
class FileDict: class FileDict:
"""Concurrency-safe multi-reader/single-writer persistent dict.""" """Concurrency-safe multi-reader/single-writer persistent dict."""

View File

@ -1,14 +1,14 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import asyncio import asyncio
import logging import logging
import time
import sys import sys
from email.parser import BytesParser import time
from email import policy from email import policy
from email.parser import BytesParser
from email.utils import parseaddr from email.utils import parseaddr
from smtplib import SMTP as SMTPClient
from aiosmtpd.controller import Controller from aiosmtpd.controller import Controller
from smtplib import SMTP as SMTPClient
from .config import read_config from .config import read_config

View File

@ -1,17 +1,16 @@
from pathlib import Path
from socketserver import (
UnixStreamServer,
StreamRequestHandler,
ThreadingMixIn,
)
import sys
import logging import logging
import os import os
import sys
from pathlib import Path
from socketserver import (
StreamRequestHandler,
ThreadingMixIn,
UnixStreamServer,
)
from .filedict import FileDict from .filedict import FileDict
from .notifier import Notifier from .notifier import Notifier
DICTPROXY_HELLO_CHAR = "H" DICTPROXY_HELLO_CHAR = "H"
DICTPROXY_LOOKUP_CHAR = "L" DICTPROXY_LOOKUP_CHAR = "L"
DICTPROXY_ITERATE_CHAR = "I" DICTPROXY_ITERATE_CHAR = "I"

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from pathlib import Path
import time
import sys import sys
import time
from pathlib import Path
def main(vmail_dir=None): def main(vmail_dir=None):

View File

@ -1,13 +1,13 @@
#!/usr/local/lib/chatmaild/venv/bin/python3 #!/usr/local/lib/chatmaild/venv/bin/python3
""" CGI script for creating new accounts. """ """CGI script for creating new accounts."""
import json import json
import random import random
import secrets import secrets
import string import string
from chatmaild.config import read_config, Config from chatmaild.config import Config, read_config
CONFIG_PATH = "/usr/local/lib/chatmaild/chatmail.ini" CONFIG_PATH = "/usr/local/lib/chatmaild/chatmail.ini"
ALPHANUMERIC = string.ascii_lowercase + string.digits ALPHANUMERIC = string.ascii_lowercase + string.digits

View File

@ -25,15 +25,16 @@ The meaning and format of tokens is basically a matter of Delta-Chat Core and
the `notification.delta.chat` service. the `notification.delta.chat` service.
""" """
import logging
import math
import os import os
import time import time
import math from dataclasses import dataclass
import logging
from uuid import uuid4
from threading import Thread
from pathlib import Path from pathlib import Path
from queue import PriorityQueue from queue import PriorityQueue
from dataclasses import dataclass from threading import Thread
from uuid import uuid4
import requests import requests

View File

@ -1,14 +1,14 @@
import random
from pathlib import Path
import os
import importlib.resources import importlib.resources
import itertools import itertools
from email.parser import BytesParser import os
import random
from email import policy from email import policy
import pytest from email.parser import BytesParser
from pathlib import Path
from chatmaild.database import Database import pytest
from chatmaild.config import read_config, write_initial_config from chatmaild.config import read_config, write_initial_config
from chatmaild.database import Database
@pytest.fixture @pytest.fixture

View File

@ -1,18 +1,18 @@
import io import io
import json import json
import pytest
import queue import queue
import threading import threading
import traceback import traceback
import chatmaild.doveauth import chatmaild.doveauth
import pytest
from chatmaild.database import DBError
from chatmaild.doveauth import ( from chatmaild.doveauth import (
get_user_data, get_user_data,
lookup_passdb,
handle_dovecot_request,
handle_dovecot_protocol, handle_dovecot_protocol,
handle_dovecot_request,
lookup_passdb,
) )
from chatmaild.database import DBError
def test_basic(db, example_config): def test_basic(db, example_config):

View File

@ -1,12 +1,11 @@
import pytest
from chatmaild.filtermail import ( from chatmaild.filtermail import (
check_encrypted,
BeforeQueueHandler, BeforeQueueHandler,
SendRateLimiter, SendRateLimiter,
check_encrypted,
check_mdn, check_mdn,
) )
import pytest
@pytest.fixture @pytest.fixture
def maildomain(): def maildomain():

View File

@ -1,12 +1,12 @@
import io import io
import pytest
import requests
import time import time
import pytest
import requests
from chatmaild.metadata import ( from chatmaild.metadata import (
handle_dovecot_request,
handle_dovecot_protocol,
Metadata, Metadata,
handle_dovecot_protocol,
handle_dovecot_request,
) )
from chatmaild.notifier import ( from chatmaild.notifier import (
Notifier, Notifier,

View File

@ -16,7 +16,6 @@ dependencies = [
"build", "build",
"tox", "tox",
"ruff", "ruff",
"black",
"pytest", "pytest",
"pytest-xdist", "pytest-xdist",
"imap_tools", "imap_tools",
@ -31,3 +30,13 @@ cmdeploy = "cmdeploy.cmdeploy:main"
[tool.pytest.ini_options] [tool.pytest.ini_options]
addopts = "-v -ra --strict-markers" addopts = "-v -ra --strict-markers"
[tool.ruff]
lint.select = [
"F", # Pyflakes
"I", # isort
"PLC", # Pylint Convention
"PLE", # Pylint Error
"PLW", # Pylint Warning
]

View File

@ -2,20 +2,20 @@
Chat Mail pyinfra deploy. Chat Mail pyinfra deploy.
""" """
import sys
import importlib.resources import importlib.resources
import subprocess
import shutil
import io import io
import shutil
import subprocess
import sys
from pathlib import Path from pathlib import Path
from chatmaild.config import Config, read_config
from pyinfra import host from pyinfra import host
from pyinfra.operations import apt, files, server, systemd, pip
from pyinfra.facts.files import File from pyinfra.facts.files import File
from pyinfra.facts.systemd import SystemdEnabled from pyinfra.facts.systemd import SystemdEnabled
from .acmetool import deploy_acmetool from pyinfra.operations import apt, files, pip, server, systemd
from chatmaild.config import read_config, Config from .acmetool import deploy_acmetool
def _build_chatmaild(dist_dir) -> None: def _build_chatmaild(dist_dir) -> None:
@ -486,19 +486,19 @@ def deploy_chatmail(config_path: Path) -> None:
# Add our OBS repository for dovecot_no_delay # Add our OBS repository for dovecot_no_delay
files.put( files.put(
name = "Add Deltachat OBS GPG key to apt keyring", name="Add Deltachat OBS GPG key to apt keyring",
src = importlib.resources.files(__package__).joinpath("obs-home-deltachat.gpg"), src=importlib.resources.files(__package__).joinpath("obs-home-deltachat.gpg"),
dest = "/etc/apt/keyrings/obs-home-deltachat.gpg", dest="/etc/apt/keyrings/obs-home-deltachat.gpg",
user="root", user="root",
group="root", group="root",
mode="644", mode="644",
) )
files.line( files.line(
name = "Add DeltaChat OBS home repository to sources.list", name="Add DeltaChat OBS home repository to sources.list",
path = "/etc/apt/sources.list", path="/etc/apt/sources.list",
line = "deb [signed-by=/etc/apt/keyrings/obs-home-deltachat.gpg] https://download.opensuse.org/repositories/home:/deltachat/Debian_12/ ./", line="deb [signed-by=/etc/apt/keyrings/obs-home-deltachat.gpg] https://download.opensuse.org/repositories/home:/deltachat/Debian_12/ ./",
ensure_newline = True, ensure_newline=True,
) )
apt.update(name="apt update", cache_time=24 * 3600) apt.update(name="apt update", cache_time=24 * 3600)

View File

@ -1,8 +1,8 @@
import importlib.resources import importlib.resources
from pyinfra.operations import apt, files, systemd, server
from pyinfra import host from pyinfra import host
from pyinfra.facts.systemd import SystemdStatus from pyinfra.facts.systemd import SystemdStatus
from pyinfra.operations import apt, files, server, systemd
def deploy_acmetool(email="", domains=[]): def deploy_acmetool(email="", domains=[]):

View File

@ -4,19 +4,18 @@ along with command line option and subcommand parsing.
""" """
import argparse import argparse
import shutil
import subprocess
import importlib.resources import importlib.resources
import importlib.util import importlib.util
import os import os
import shutil
import subprocess
import sys import sys
from pathlib import Path from pathlib import Path
from termcolor import colored
from chatmaild.config import read_config, write_initial_config from chatmaild.config import read_config, write_initial_config
from cmdeploy.dns import show_dns, check_necessary_dns from termcolor import colored
from cmdeploy.dns import check_necessary_dns, show_dns
# #
# cmdeploy sub commands and options # cmdeploy sub commands and options
@ -157,26 +156,26 @@ def fmt_cmd_options(parser):
def fmt_cmd(args, out): def fmt_cmd(args, out):
"""Run formattting fixes (ruff and black) on all chatmail source code.""" """Run formattting fixes on all chatmail source code."""
sources = [str(importlib.resources.files(x)) for x in ("chatmaild", "cmdeploy")] sources = [str(importlib.resources.files(x)) for x in ("chatmaild", "cmdeploy")]
black_args = [shutil.which("black")] format_args = [shutil.which("ruff"), "format"]
ruff_args = [shutil.which("ruff")] check_args = [shutil.which("ruff"), "check"]
if args.check: if args.check:
black_args.append("--check") format_args.append("--diff")
else: else:
ruff_args.append("--fix") check_args.append("--fix")
if not args.verbose: if not args.verbose:
black_args.append("-q") check_args.append("--quiet")
ruff_args.append("-q") format_args.append("--quiet")
black_args.extend(sources) format_args.extend(sources)
ruff_args.extend(sources) check_args.extend(sources)
out.check_call(" ".join(black_args), quiet=not args.verbose) out.check_call(" ".join(format_args), quiet=not args.verbose)
out.check_call(" ".join(ruff_args), quiet=not args.verbose) out.check_call(" ".join(check_args), quiet=not args.verbose)
return 0 return 0
@ -232,7 +231,7 @@ class Out:
if not quiet: if not quiet:
cmdstring = " ".join(args) cmdstring = " ".join(args)
self(f"[$ {cmdstring}]", file=sys.stderr) self(f"[$ {cmdstring}]", file=sys.stderr)
proc = subprocess.run(args, env=env) proc = subprocess.run(args, env=env, check=False)
return proc.returncode return proc.returncode

View File

@ -1,6 +1,8 @@
import os
import importlib.resources import importlib.resources
import os
import pyinfra import pyinfra
from cmdeploy import deploy_chatmail from cmdeploy import deploy_chatmail

View File

@ -1,9 +1,9 @@
import datetime
import importlib
import subprocess
import sys import sys
import requests import requests
import importlib
import subprocess
import datetime
class DNS: class DNS:
@ -104,8 +104,8 @@ def show_dns(args, out) -> int:
return 0 return 0
except TypeError: except TypeError:
pass pass
for line in zonefile.splitlines(): for raw_line in zonefile.splitlines():
line = line.format( line = raw_line.format(
acme_account_url=acme_account_url, acme_account_url=acme_account_url,
sts_id=datetime.datetime.now().strftime("%Y%m%d%H%M"), sts_id=datetime.datetime.now().strftime("%Y%m%d%H%M"),
chatmail_domain=args.config.mail_domain, chatmail_domain=args.config.mail_domain,

View File

@ -1,8 +1,9 @@
import importlib import importlib
import qrcode
import os
from PIL import ImageFont, ImageDraw, Image
import io import io
import os
import qrcode
from PIL import Image, ImageDraw, ImageFont
def gen_qr_png_data(maildomain): def gen_qr_png_data(maildomain):

View File

@ -1,9 +1,10 @@
import pytest
import threading
import queue import queue
import socket import socket
import threading
import pytest
from chatmaild.config import read_config from chatmaild.config import read_config
from cmdeploy.cmdeploy import main from cmdeploy.cmdeploy import main

View File

@ -1,4 +1,5 @@
import smtplib import smtplib
import pytest import pytest

View File

@ -1,11 +1,11 @@
import time import ipaddress
import re
import random import random
import re
import time
import imap_tools
import pytest import pytest
import requests import requests
import ipaddress
import imap_tools
@pytest.fixture @pytest.fixture

View File

@ -1,17 +1,16 @@
import os
import io
import time
import random
import subprocess
import imaplib import imaplib
import smtplib import io
import itertools import itertools
import os
import random
import smtplib
import subprocess
import time
from pathlib import Path from pathlib import Path
import pytest import pytest
from chatmaild.database import Database
from chatmaild.config import read_config from chatmaild.config import read_config
from chatmaild.database import Database
conftestdir = Path(__file__).parent conftestdir = Path(__file__).parent

View File

@ -1,6 +1,7 @@
import os import os
import pytest import pytest
from cmdeploy.cmdeploy import get_parser, main from cmdeploy.cmdeploy import get_parser, main

View File

@ -1,13 +1,14 @@
import importlib.resources
import webbrowser
import hashlib import hashlib
import importlib.resources
import time import time
import traceback import traceback
import webbrowser
import markdown import markdown
from jinja2 import Template
from .genqr import gen_qr_png_data
from chatmaild.config import read_config from chatmaild.config import read_config
from jinja2 import Template
from .genqr import gen_qr_png_data
def snapshot_dir_stats(somedir): def snapshot_dir_stats(somedir):
@ -120,7 +121,8 @@ def main():
print(f"watching {src_path} directory for changes") print(f"watching {src_path} directory for changes")
changenum = 0 changenum = 0
for count in range(0, 1000000): count = 0
while True:
newstats = snapshot_dir_stats(src_path) newstats = snapshot_dir_stats(src_path)
if newstats == stats and count % 60 != 0: if newstats == stats and count % 60 != 0:
count += 1 count += 1