Skip to content

Commit

Permalink
Format apps with ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
delfick committed Dec 26, 2024
1 parent b63cb9d commit 807c69e
Show file tree
Hide file tree
Showing 52 changed files with 275 additions and 704 deletions.
17 changes: 6 additions & 11 deletions apps/arranger/arranger/addon.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@
import subprocess
import webbrowser

from arranger.options import Options
from arranger.server import ArrangerServer
from delfick_project.addons import addon_hook
from delfick_project.norms import sb
from photons_app import helpers as hp
Expand All @@ -17,14 +15,15 @@
from photons_app.tasks import task_register as task
from photons_web_server.server import WebServerTask

from arranger.options import Options
from arranger.server import ArrangerServer

log = logging.getLogger("arranger.addon")


@addon_hook(extras=[("lifx.photons", "__all__")])
def __lifx__(collector, *args, **kwargs):
collector.register_converters(
{"arranger": Options.FieldSpec(formatter=MergedOptionStringFormatter)}
)
collector.register_converters({"arranger": Options.FieldSpec(formatter=MergedOptionStringFormatter)})


def port_connected(port):
Expand Down Expand Up @@ -84,9 +83,7 @@ async def open_browser(self):
break

if not port_connected(self.options.port):
self.photons_app.final_future.set_exception(
PhotonsAppError("Failed to start the server")
)
self.photons_app.final_future.set_exception(PhotonsAppError("Failed to start the server"))
return

if "NO_WEB_OPEN" not in os.environ:
Expand Down Expand Up @@ -129,9 +126,7 @@ async def execute_task(self, **kwargs):
assets.run("run", "generate")

else:
raise PhotonsAppError(
"Didn't get a recognised command", want=self.reference, available=available
)
raise PhotonsAppError("Didn't get a recognised command", want=self.reference, available=available)
except subprocess.CalledProcessError as error:
raise PhotonsAppError("Failed to run command", error=error)

Expand Down
35 changes: 12 additions & 23 deletions apps/arranger/arranger/arranger.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@
import colorsys
import logging

from arranger.colors import convert_K_to_RGB
from arranger.patterns import Patterns
from delfick_project.norms import dictobj, sb
from photons_app import helpers as hp
from photons_canvas import point_helpers as php
from photons_canvas.animations import Animation, AnimationRunner
from photons_messages import TileMessages

from arranger.colors import convert_K_to_RGB
from arranger.patterns import Patterns

log = logging.getLogger("arranger.arranger")


Expand Down Expand Up @@ -163,9 +164,7 @@ async def process_event(self, event):
return event.state.next_layer

async def make_user_events(self, animation_state):
async with hp.ResultStreamer(
self.final_future, name="ArrangerAnimation::make_user_events[streamer]"
) as streamer:
async with hp.ResultStreamer(self.final_future, name="ArrangerAnimation::make_user_events[streamer]") as streamer:
self.options.arranger.animation_streamer = streamer

if self.options.arranger.progress_cbs:
Expand Down Expand Up @@ -204,7 +203,7 @@ def start_instruction(self, progress_cb):

try:
progress_cb({"instruction": "parts", "parts": self.all_info}, do_log=False)
except:
except Exception:
log.exception("Failed to send progress")
else:
sent["parts"] = True
Expand All @@ -218,7 +217,7 @@ def send_instruction(self, parts):
progress_cb({"instruction": "parts", "parts": self.info}, do_log=False)
else:
progress_cb({"instruction": "parts", "parts": self.all_info}, do_log=False)
except:
except Exception:
log.exception("Failed to send progress")
else:
sent["parts"] = True
Expand Down Expand Up @@ -272,7 +271,7 @@ def __init__(self, final_future, sender, reference, animation_options, cleaners)

async def animation_event(self, event):
if self.animation_streamer:
if not isinstance(event, (str, tuple)):
if not isinstance(event, str | tuple):
await self.animation_streamer.add_generator(event)
else:
await self.animation_streamer.add_value(event)
Expand Down Expand Up @@ -325,9 +324,7 @@ async def gen():
yield "changing", part

try:
new_position = await self._change_position(
part, new_position["user_x"], new_position["user_y"]
)
new_position = await self._change_position(part, new_position["user_x"], new_position["user_y"])
except asyncio.CancelledError:
raise
except Exception as error:
Expand All @@ -346,17 +343,13 @@ async def gen():
async def _change_position(self, part, new_user_x, new_user_y):
part.update(new_user_x, new_user_y, part.width, part.height)

msg = TileMessages.SetUserPosition(
tile_index=part.part_number, user_x=part.user_x, user_y=part.user_y, res_required=False
)
msg = TileMessages.SetUserPosition(tile_index=part.part_number, user_x=part.user_x, user_y=part.user_y, res_required=False)

await self.sender(msg, part.device.serial, message_timeout=2)

plans = self.sender.make_plans("parts")

async for serial, _, info in self.sender.gatherer.gather(
plans, part.device.serial, message_timeou=2
):
async for serial, _, info in self.sender.gatherer.gather(plans, part.device.serial, message_timeou=2):
for found in info:
if found.part_number != part.part_number:
continue
Expand Down Expand Up @@ -399,14 +392,10 @@ async def run(self):
return

self.running = True
self.animation_fut = hp.ChildOfFuture(
self.final_future, name="Arranger::run[animation_fut]"
)
self.animation_fut = hp.ChildOfFuture(self.final_future, name="Arranger::run[animation_fut]")

run_options = {
"animations": [
[(ArrangerAnimation, Options), {"arranger": self, "patterns": self.patterns}]
],
"animations": [[(ArrangerAnimation, Options), {"arranger": self, "patterns": self.patterns}]],
"reinstate_on_end": True,
}

Expand Down
15 changes: 5 additions & 10 deletions apps/arranger/arranger/commander/parts.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@

import attrs
import strcs
from arranger.arranger import Arranger
from photons_app import helpers as hp
from photons_web_server import commander

from arranger.arranger import Arranger

from .selector import Serial

T = TypeVar("T")
Expand Down Expand Up @@ -106,9 +107,7 @@ async def highlight(self, respond: commander.Responder, body: HighlightBody) ->
await body.arranger.add_highlight((body.serial.serial, body.part_number))

async def change_position(self, respond: commander.Responder, body: ChangePositionBody) -> None:
await body.arranger.change_position(
body.serial.serial, body.part_number, body.user_x, body.user_y
)
await body.arranger.change_position(body.serial.serial, body.part_number, body.user_x, body.user_y)


class PartsCommand(commander.Command):
Expand All @@ -128,12 +127,8 @@ async def parts(
if path != "/v1/lifx/command":
await respond(NoSuchPath(wanted=path, available=["/v1/lifx/command"]))

part_router = self.meta.retrieve_one(
PartRouter, type_cache=self.store.strcs_register.type_cache
)
tasks = self.meta.retrieve_one(
hp.TaskHolder, type_cache=self.store.strcs_register.type_cache
)
part_router = self.meta.retrieve_one(PartRouter, type_cache=self.store.strcs_register.type_cache)
tasks = self.meta.retrieve_one(hp.TaskHolder, type_cache=self.store.strcs_register.type_cache)
arranger = self.meta.retrieve_one(Arranger, type_cache=self.store.strcs_register.type_cache)

message_id = message.body.get("message_id") or None
Expand Down
5 changes: 1 addition & 4 deletions apps/arranger/arranger/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,7 @@ def ensure_npm(self):

@property
def needs_install(self):
return (
not os.path.exists(os.path.join(self.src, "node_modules"))
or os.environ.get("REBUILD") == 1
)
return not os.path.exists(os.path.join(self.src, "node_modules")) or os.environ.get("REBUILD") == 1

def run(self, *args, no_node_env=False):
env = None
Expand Down
15 changes: 4 additions & 11 deletions apps/arranger/arranger/patterns.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,7 @@ def __init__(self, original):
self.return_handle = None

def finish(self):
self.return_handle = hp.get_event_loop().call_later(
0.5, lambda: setattr(self, "returning", True)
)
self.return_handle = hp.get_event_loop().call_later(0.5, lambda: setattr(self, "returning", True))

def ensure(self):
if getattr(self, "return_handle", None):
Expand Down Expand Up @@ -71,9 +69,7 @@ def __init__(self, part, pattern, options):

@property
def has_change(self):
return (
not self.started or self.brightness_change is not None or self.highlight_row is not None
)
return not self.started or self.brightness_change is not None or self.highlight_row is not None

@hp.memoized_property
def pattern_canvas(self):
Expand Down Expand Up @@ -157,9 +153,7 @@ def progress(self):
self.highlight_row = direction, row + 1

if self.brightness_change is not None:
if self.brightness_change and not any(
b.has_change for b in self.brightness_change.values()
):
if self.brightness_change and not any(b.has_change for b in self.brightness_change.values()):
self.brightness_change = None


Expand Down Expand Up @@ -194,8 +188,7 @@ def compute_styles(self):

while True:
nxt = next(os)
for sp in nxt:
yield sp
yield from nxt

def options(self, colors):
shifted = colors[2:] + colors[:2]
Expand Down
15 changes: 6 additions & 9 deletions apps/arranger/arranger/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,6 @@
from collections.abc import Callable

import strcs
from arranger.arranger import Arranger
from arranger.commander.parts import PartRouter
from arranger.options import Options
from photons_app import helpers as hp
from photons_app.special import SpecialReference
from photons_transport.comms.base import Communication
Expand All @@ -14,6 +11,10 @@
from sanic.request import Request
from sanic.response import BaseHTTPResponse as Response

from arranger.arranger import Arranger
from arranger.commander.parts import PartRouter
from arranger.options import Options


class ArrangerMessageFromExc(commander.MessageFromExc):
def modify_error_dict(
Expand Down Expand Up @@ -55,9 +56,7 @@ async def setup(
self.server_options = options
self.wsconnections: dict[str, asyncio.Future] = {}

self.arranger = Arranger(
self.final_future, self.sender, reference, options.animation_options, cleaners
)
self.arranger = Arranger(self.final_future, self.sender, reference, options.animation_options, cleaners)
self.tasks.add(self.arranger.run())

self.meta = strcs.Meta(
Expand Down Expand Up @@ -88,9 +87,7 @@ async def setup_routes(self):
self.app.static("/", self.server_options.assets.dist, index="index.html")

async def before_stop(self):
await hp.wait_for_all_futures(
*self.wsconnections.values(), name="Server::cleanup[wait_for_wsconnections]"
)
await hp.wait_for_all_futures(*self.wsconnections.values(), name="Server::cleanup[wait_for_wsconnections]")

def log_ws_request(
self,
Expand Down
23 changes: 8 additions & 15 deletions apps/interactor/interactor/addon.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,22 @@
import aiohttp
from delfick_project.addons import addon_hook
from delfick_project.norms import sb
from interactor.errors import InteractorError
from interactor.options import Options
from interactor.server import InteractorServer as Server
from photons_app import helpers as hp
from photons_app.errors import PhotonsAppError
from photons_app.formatter import MergedOptionStringFormatter
from photons_app.tasks import task_register as task
from photons_web_server.server import WebServerTask

from interactor.errors import InteractorError
from interactor.options import Options
from interactor.server import InteractorServer as Server

log = logging.getLogger("interactor.addon")


@addon_hook(extras=[("lifx.photons", "core"), ("lifx.photons", "web_server")])
def __lifx__(collector, *args, **kwargs):
collector.register_converters(
{"interactor": Options.FieldSpec(formatter=MergedOptionStringFormatter)}
)
collector.register_converters({"interactor": Options.FieldSpec(formatter=MergedOptionStringFormatter)})


@task.register(task_group="Interactor")
Expand Down Expand Up @@ -50,9 +49,7 @@ def port(self):
async def server_kwargs(self):
async with self.target.session() as sender:
yield dict(
reference_resolver_register=self.collector.configuration[
"reference_resolver_register"
],
reference_resolver_register=self.collector.configuration["reference_resolver_register"],
sender=sender,
options=self.options,
cleaners=self.photons_app.cleaners,
Expand Down Expand Up @@ -147,14 +144,10 @@ async def execute_task(self, **kwargs):
assets.run("run", "build")

else:
raise PhotonsAppError(
"Didn't get a recognised command", want=self.reference, available=available
)
raise PhotonsAppError("Didn't get a recognised command", want=self.reference, available=available)
except subprocess.CalledProcessError as error:
raise PhotonsAppError("Failed to run command", error=error)


if (
importlib.resources.files("interactor") / ".." / "interactor_webapp" / "interactor" / "src"
).exists():
if (importlib.resources.files("interactor") / ".." / "interactor_webapp" / "interactor" / "src").exists():
task.register(task_group="Interactor")(interactor_assets)
16 changes: 4 additions & 12 deletions apps/interactor/interactor/commander/animations.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,17 +77,13 @@ def info(self, identity=None, expand=False, **extra):
else:
return self.animations[identity].info

animations = {
identity: animation.info for identity, animation in sorted(self.animations.items())
}
animations = {identity: animation.info for identity, animation in sorted(self.animations.items())}
if not expand:
animations = sorted(animations)

return {
"animations": animations,
"paused": sorted(
[animation.identity for animation in self.animations.values() if animation.paused]
),
"paused": sorted([animation.identity for animation in self.animations.values() if animation.paused]),
**extra,
}

Expand All @@ -100,9 +96,7 @@ async def start(
animations=sb.NotSpecified,
):
pauser = asyncio.Semaphore()
final_future = hp.ChildOfFuture(
self.final_future, name=f"Animations::start({identity})[final_future]"
)
final_future = hp.ChildOfFuture(self.final_future, name=f"Animations::start({identity})[final_future]")

if run_options is sb.NotSpecified:
run_options = {}
Expand All @@ -125,9 +119,7 @@ def remove(res):
if identity in self.animations:
del self.animations[identity]

self.animations[identity] = Animation(final_future, identity, runner, pauser).start(
self.tasks, remove
)
self.animations[identity] = Animation(final_future, identity, runner, pauser).start(self.tasks, remove)

return self.info(started=identity)

Expand Down
Loading

0 comments on commit 807c69e

Please sign in to comment.