mirror of
https://github.com/kuhyx/screen-locker.git
synced 2026-11-26 01:47:15 +01:00
Compare commits
2 Commits
c4cc39759a
...
589b9e227d
| Author | SHA1 | Date | |
|---|---|---|---|
| 589b9e227d | |||
| 7b61619a7a |
36
run.sh
36
run.sh
@ -1,10 +1,40 @@
|
||||
#!/usr/bin/env bash
|
||||
set -e
|
||||
set -euo pipefail
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
VENV="$SCRIPT_DIR/.venv"
|
||||
[[ ! -d "$VENV" ]] && python3 -m venv "$VENV"
|
||||
# tkinter is from Python stdlib; install python-tk system package if missing:
|
||||
# Arch: sudo pacman -S python-tk
|
||||
# Debian: sudo apt-get install python3-tk
|
||||
cd "$SCRIPT_DIR"
|
||||
"$VENV/bin/python" -m screen_locker.screen_lock "$@"
|
||||
|
||||
if [[ ! -d "$VENV" ]]; then
|
||||
python3 -m venv "$VENV"
|
||||
fi
|
||||
|
||||
# Reconcile the venv against requirements.txt whenever that file changes.
|
||||
# Without this the venv is created once and never updated, so a dependency pin
|
||||
# bump stays invisible until it surfaces as an ImportError at startup --
|
||||
# crdt-sync sat at 0.6.0 for months after the pin moved to 0.9.0.
|
||||
#
|
||||
# Gated on a hash stamp so the common case costs nothing: pip re-resolves the
|
||||
# git-pinned deps over the network (~5s) on every call, and this is a screen
|
||||
# locker that must still start when the network is down.
|
||||
STAMP="$VENV/.requirements.sha256"
|
||||
WANT="$(sha256sum requirements.txt | cut -d" " -f1)"
|
||||
HAVE="$(cat "$STAMP" 2>/dev/null || true)"
|
||||
|
||||
if [[ "$WANT" != "$HAVE" ]]; then
|
||||
echo "Dependencies changed; reconciling venv against requirements.txt..." >&2
|
||||
if "$VENV/bin/pip" install -q -r requirements.txt; then
|
||||
printf '%s\n' "$WANT" > "$STAMP"
|
||||
else
|
||||
# Do not stamp on failure, so the next launch retries. Abort rather
|
||||
# than run on dependencies we know are wrong.
|
||||
echo "ERROR: failed to install dependencies from requirements.txt" >&2
|
||||
echo " Refusing to launch with unreconciled dependencies." >&2
|
||||
echo " Retry manually: $VENV/bin/pip install -r requirements.txt" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
exec "$VENV/bin/python" -m screen_locker.screen_lock "$@"
|
||||
|
||||
@ -13,7 +13,9 @@ import sys
|
||||
|
||||
from screen_locker import _sick_tracker
|
||||
from screen_locker._decision_log import LockDecision, record_decision
|
||||
from screen_locker._decision_reasons import reasons_extra
|
||||
from screen_locker._wake_state import has_workout_skip_today
|
||||
from screen_locker._weekly_check import has_weekly_minimum, is_relaxed_day
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
@ -32,7 +34,37 @@ def _skip(reason: str, detail: str, **extra: object) -> None:
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
class AutoUpgradeMixin:
|
||||
class _ReasonsMixin:
|
||||
"""Supplies the side-effect-free conditions that annotate a decision.
|
||||
|
||||
The ladder below is first-match-wins, so only the acting reason was ever
|
||||
recorded. These predicates let a line also name the conditions that held
|
||||
but were never reached -- notably "the workout is already logged" hiding
|
||||
behind "the early-bird window is open".
|
||||
"""
|
||||
|
||||
def _other_conditions(self, acting: str) -> dict[str, object]:
|
||||
"""Return the ``also=`` extra naming every other condition that holds.
|
||||
|
||||
Strictly read-only. ``_try_auto_upgrade_*`` and
|
||||
``_save_early_bird_pending`` are deliberately absent: they write log
|
||||
entries and state, and must never run to produce a log line.
|
||||
"""
|
||||
return reasons_extra(
|
||||
acting,
|
||||
{
|
||||
"scheduled_skip_day": self._is_scheduled_skip_today,
|
||||
"early_bird_window_active": self._is_early_bird_pending,
|
||||
"sick_day": self._is_sick_day_today,
|
||||
"workout_logged_today": self.has_logged_today,
|
||||
"wake_alarm_skip": has_workout_skip_today,
|
||||
"relaxed_day": is_relaxed_day,
|
||||
"weekly_minimum_met": lambda: has_weekly_minimum(self.log_file),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class AutoUpgradeMixin(_ReasonsMixin):
|
||||
"""Handles today-state detection and silent log-entry upgrading.
|
||||
|
||||
Relies on methods from EarlyBirdMixin, PhoneVerificationMixin,
|
||||
@ -71,6 +103,7 @@ class AutoUpgradeMixin:
|
||||
"Early bird window still active — deferring to the 08:30/09:05 "
|
||||
"re-check timer.",
|
||||
recheck_by="early-bird-workout-check.timer",
|
||||
**self._other_conditions("early_bird_window_active"),
|
||||
)
|
||||
elif self._is_sick_day_today():
|
||||
if self._try_auto_upgrade_sick_day():
|
||||
@ -79,11 +112,23 @@ class AutoUpgradeMixin:
|
||||
"Auto-upgraded today's sick_day entry to phone_verified.",
|
||||
)
|
||||
else:
|
||||
_skip("sick_day", "Sick day already logged today.")
|
||||
_skip(
|
||||
"sick_day",
|
||||
"Sick day already logged today.",
|
||||
**self._other_conditions("sick_day"),
|
||||
)
|
||||
elif self.has_logged_today():
|
||||
_skip("workout_logged_today", "Workout already logged today.")
|
||||
_skip(
|
||||
"workout_logged_today",
|
||||
"Workout already logged today.",
|
||||
**self._other_conditions("workout_logged_today"),
|
||||
)
|
||||
elif has_workout_skip_today():
|
||||
_skip("wake_alarm_skip", "Wake alarm earned a workout skip.")
|
||||
_skip(
|
||||
"wake_alarm_skip",
|
||||
"Wake alarm earned a workout skip.",
|
||||
**self._other_conditions("wake_alarm_skip"),
|
||||
)
|
||||
elif self._is_early_bird_time():
|
||||
self._save_early_bird_pending()
|
||||
_skip(
|
||||
|
||||
74
screen_locker/_decision_reasons.py
Normal file
74
screen_locker/_decision_reasons.py
Normal file
@ -0,0 +1,74 @@
|
||||
"""Collect *every* condition that bears on a lock decision, not just the first.
|
||||
|
||||
The decision ladders in ``_auto_upgrade`` and ``_startup_checks`` are
|
||||
first-match-wins: the branch that matches calls ``sys.exit(0)``, so every
|
||||
later condition is never evaluated and never recorded. That made a line like
|
||||
|
||||
DECISION lock=no reason=early_bird_window_active
|
||||
|
||||
ambiguous in the one way that matters: it cannot say whether the workout was
|
||||
*also* already done. A reader seeing only the early-bird reason cannot tell a
|
||||
deferred-but-compliant day from a deferred-and-idle one, which is precisely
|
||||
the question "was it right to skip?" that the decision log exists to answer.
|
||||
|
||||
So the acting reason stays exactly as it was -- it is the branch that actually
|
||||
controlled behaviour, and it stays a stable grep-able slug -- and this module
|
||||
supplies the *other* conditions that also held, as an ``also=`` extra.
|
||||
|
||||
Only side-effect-free predicates belong here. ``_try_auto_upgrade_*`` writes
|
||||
log entries and does ADB/network work, and ``_save_early_bird_pending`` writes
|
||||
state; calling any of those to produce a *log line* would turn a reporting
|
||||
change into a state mutation in the enforcer. Every predicate below is a pure
|
||||
read.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable, Mapping
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
__all__ = ["collect_reasons", "reasons_extra"]
|
||||
|
||||
|
||||
def _holds(slug: str, predicate: Callable[[], bool]) -> bool:
|
||||
"""Return whether ``predicate`` holds, reporting rather than raising.
|
||||
|
||||
A predicate that fails is reported at ``warning`` and treated as not
|
||||
holding: this runs to *annotate* a decision, so a broken annotation must
|
||||
never take down the decision itself. Silence would defeat the point --
|
||||
a missing reason would otherwise read as a condition that did not hold.
|
||||
"""
|
||||
try:
|
||||
return predicate()
|
||||
except (OSError, ValueError, KeyError, TypeError) as exc:
|
||||
_logger.warning(
|
||||
"Could not evaluate the '%s' condition while annotating a lock "
|
||||
"decision (%s) — it is omitted from this line, so treat its "
|
||||
"absence as unknown rather than false",
|
||||
slug,
|
||||
exc,
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
def collect_reasons(predicates: Mapping[str, Callable[[], bool]]) -> list[str]:
|
||||
"""Return the slugs of every predicate that currently holds."""
|
||||
return [slug for slug, pred in predicates.items() if _holds(slug, pred)]
|
||||
|
||||
|
||||
def reasons_extra(
|
||||
acting: str, predicates: Mapping[str, Callable[[], bool]]
|
||||
) -> dict[str, object]:
|
||||
"""Build the ``also=`` extra for a decision whose acting reason is ``acting``.
|
||||
|
||||
Returns an empty mapping when nothing else applied, so a genuinely
|
||||
single-reason decision keeps rendering exactly the line it did before and
|
||||
no reader has to learn a new format for the common case.
|
||||
"""
|
||||
others = [slug for slug in collect_reasons(predicates) if slug != acting]
|
||||
return {"also": ",".join(others)} if others else {}
|
||||
@ -68,7 +68,10 @@ class StartupChecksMixin(SyncMixin):
|
||||
detail=detail,
|
||||
weekly_count=count_weekly_workouts(self.log_file),
|
||||
weekly_required=WEEKLY_WORKOUT_MINIMUM,
|
||||
extra=extra,
|
||||
# Annotate with the conditions this first-match-wins ladder
|
||||
# never reached, so "why not lock?" is answerable from the one
|
||||
# line rather than by re-deriving the ladder by hand.
|
||||
extra={**self._other_conditions(reason), **extra},
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
78
screen_locker/tests/test_decision_reasons.py
Normal file
78
screen_locker/tests/test_decision_reasons.py
Normal file
@ -0,0 +1,78 @@
|
||||
"""Tests for the multi-reason annotation on lock decisions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker._decision_reasons import collect_reasons, reasons_extra
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import pytest
|
||||
|
||||
|
||||
class TestCollectReasons:
|
||||
"""Every condition that holds is reported, not just the first."""
|
||||
|
||||
def test_returns_only_the_predicates_that_hold(self) -> None:
|
||||
held = collect_reasons(
|
||||
{"a": lambda: True, "b": lambda: False, "c": lambda: True}
|
||||
)
|
||||
assert held == ["a", "c"]
|
||||
|
||||
def test_empty_when_nothing_holds(self) -> None:
|
||||
assert collect_reasons({"a": lambda: False}) == []
|
||||
|
||||
def test_a_failing_predicate_is_reported_and_skipped(
|
||||
self, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""A broken annotation must not take down the decision it annotates."""
|
||||
|
||||
def boom() -> bool:
|
||||
msg = "log unreadable"
|
||||
raise OSError(msg)
|
||||
|
||||
with caplog.at_level(logging.WARNING):
|
||||
held = collect_reasons({"a": lambda: True, "boom": boom})
|
||||
|
||||
assert held == ["a"]
|
||||
# The omission must be loud: an invisible gap would read as "the
|
||||
# condition did not hold", which is the opposite of what happened.
|
||||
assert "boom" in caplog.text
|
||||
assert "log unreadable" in caplog.text
|
||||
|
||||
|
||||
class TestReasonsExtra:
|
||||
"""The acting reason is never repeated back as an 'also'."""
|
||||
|
||||
def test_excludes_the_acting_reason(self) -> None:
|
||||
extra = reasons_extra(
|
||||
"early_bird_window_active",
|
||||
{
|
||||
"early_bird_window_active": lambda: True,
|
||||
"workout_logged_today": lambda: True,
|
||||
},
|
||||
)
|
||||
assert extra == {"also": "workout_logged_today"}
|
||||
|
||||
def test_orders_and_joins_every_other_condition(self) -> None:
|
||||
extra = reasons_extra(
|
||||
"early_bird_window_active",
|
||||
{
|
||||
"early_bird_window_active": lambda: True,
|
||||
"workout_logged_today": lambda: True,
|
||||
"weekly_minimum_met": lambda: True,
|
||||
},
|
||||
)
|
||||
assert extra == {"also": "workout_logged_today,weekly_minimum_met"}
|
||||
|
||||
def test_empty_when_the_acting_reason_is_the_only_one(self) -> None:
|
||||
"""A single-reason decision keeps rendering exactly its old line."""
|
||||
extra = reasons_extra(
|
||||
"early_bird_window_active",
|
||||
{
|
||||
"early_bird_window_active": lambda: True,
|
||||
"workout_logged_today": lambda: False,
|
||||
},
|
||||
)
|
||||
assert extra == {}
|
||||
Loading…
Reference in New Issue
Block a user