mirror of
https://github.com/kuhyx/screen-locker.git
synced 2026-11-27 08:49:18 +01:00
Compare commits
2 Commits
d35097f461
...
fbf09fdfef
| Author | SHA1 | Date | |
|---|---|---|---|
| fbf09fdfef | |||
| d6e8c0973f |
@ -122,8 +122,12 @@ repos:
|
|||||||
- --jobs=4
|
- --jobs=4
|
||||||
additional_dependencies:
|
additional_dependencies:
|
||||||
- pytest
|
- pytest
|
||||||
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.7.1#subdirectory=gatelock
|
# Kept in step with pyproject.toml: pip refuses two different
|
||||||
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.0#subdirectory=crdt-sync
|
# direct URLs for one distribution, so a stale pin here becomes
|
||||||
|
# an unresolvable hook env once freedays joins the list.
|
||||||
|
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.7.3#subdirectory=gatelock
|
||||||
|
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.1#subdirectory=crdt-sync
|
||||||
|
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.1.0#subdirectory=freedays
|
||||||
- mcp>=2,<3
|
- mcp>=2,<3
|
||||||
- pydantic
|
- pydantic
|
||||||
- id: pylint
|
- id: pylint
|
||||||
@ -137,8 +141,12 @@ repos:
|
|||||||
- --disable=protected-access,unused-argument,duplicate-code
|
- --disable=protected-access,unused-argument,duplicate-code
|
||||||
additional_dependencies:
|
additional_dependencies:
|
||||||
- pytest
|
- pytest
|
||||||
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.7.1#subdirectory=gatelock
|
# Kept in step with pyproject.toml: pip refuses two different
|
||||||
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.0#subdirectory=crdt-sync
|
# direct URLs for one distribution, so a stale pin here becomes
|
||||||
|
# an unresolvable hook env once freedays joins the list.
|
||||||
|
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.7.3#subdirectory=gatelock
|
||||||
|
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.1#subdirectory=crdt-sync
|
||||||
|
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.1.0#subdirectory=freedays
|
||||||
- mcp>=2,<3
|
- mcp>=2,<3
|
||||||
- pydantic
|
- pydantic
|
||||||
|
|
||||||
|
|||||||
@ -9,6 +9,7 @@ requires-python = ">=3.14"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.7.3#subdirectory=gatelock",
|
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.7.3#subdirectory=gatelock",
|
||||||
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.1#subdirectory=crdt-sync",
|
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.1#subdirectory=crdt-sync",
|
||||||
|
"freedays @ git+https://github.com/kuhyx/utils@freedays-v0.1.0#subdirectory=freedays",
|
||||||
]
|
]
|
||||||
|
|
||||||
[project.scripts]
|
[project.scripts]
|
||||||
|
|||||||
@ -4,6 +4,7 @@ bandit==1.9.4
|
|||||||
codespell==2.4.3
|
codespell==2.4.3
|
||||||
coverage==7.16.0
|
coverage==7.16.0
|
||||||
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.1#subdirectory=crdt-sync
|
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.1#subdirectory=crdt-sync
|
||||||
|
freedays @ git+https://github.com/kuhyx/utils@freedays-v0.1.0#subdirectory=freedays
|
||||||
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.7.3#subdirectory=gatelock
|
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.7.3#subdirectory=gatelock
|
||||||
mcp==2.1.1
|
mcp==2.1.1
|
||||||
mypy==2.3.1
|
mypy==2.3.1
|
||||||
@ -11,12 +12,12 @@ pre-commit==4.6.2
|
|||||||
pylint==4.0.8
|
pylint==4.0.8
|
||||||
pytest==9.1.1
|
pytest==9.1.1
|
||||||
pytest-cov==7.1.0
|
pytest-cov==7.1.0
|
||||||
pytest-randomly==4.1.0
|
pytest-randomly==5.0.0
|
||||||
pytest-sugar==1.1.1
|
pytest-sugar==1.1.1
|
||||||
pytest-xdist==3.8.0
|
pytest-xdist==3.8.0
|
||||||
# Direct dependency since the Firebase session recovery exchanges a refresh
|
# Direct dependency since the Firebase session recovery exchanges a refresh
|
||||||
# token over the REST endpoint; crdt-sync already pulls requests in, but this
|
# token over the REST endpoint; crdt-sync already pulls requests in, but this
|
||||||
# module imports it itself, so it is declared rather than assumed.
|
# module imports it itself, so it is declared rather than assumed.
|
||||||
requests==2.34.2
|
requests==2.34.2
|
||||||
ruff==0.16.5
|
ruff==0.16.6
|
||||||
types-requests==2.33.0.20260712
|
types-requests==2.33.0.20260906
|
||||||
|
|||||||
@ -19,6 +19,7 @@ import json
|
|||||||
import logging
|
import logging
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
import freedays
|
||||||
from gatelock.log_integrity import compute_entry_hmac, verify_entry_hmac
|
from gatelock.log_integrity import compute_entry_hmac, verify_entry_hmac
|
||||||
|
|
||||||
from screen_locker._constants import (
|
from screen_locker._constants import (
|
||||||
@ -31,6 +32,7 @@ from screen_locker._sick_tracker import is_sick_day as _is_sick_day
|
|||||||
from screen_locker._weekly_check import RELAXED_DAY_SKIP_TYPE
|
from screen_locker._weekly_check import RELAXED_DAY_SKIP_TYPE
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
|
from datetime import date
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from screen_locker._sick_tracker import SickHistory
|
from screen_locker._sick_tracker import SickHistory
|
||||||
@ -43,24 +45,22 @@ def _today_str() -> str:
|
|||||||
return datetime.now(tz=UTC).strftime("%Y-%m-%d")
|
return datetime.now(tz=UTC).strftime("%Y-%m-%d")
|
||||||
|
|
||||||
|
|
||||||
def is_scheduled_skip_today(
|
def is_scheduled_skip_today(today: date | None = None) -> bool:
|
||||||
scheduled_skips_file: Path, *, today: str | None = None
|
"""Return True if *today* is in the shared free-day pool.
|
||||||
) -> bool:
|
|
||||||
"""Return True if *today* is listed in *scheduled_skips_file*."""
|
The source moved from this app's own ``scheduled_skips.json`` to the
|
||||||
if not scheduled_skips_file.exists():
|
fleet-wide pool (``~/utils/freedays``), so one marked day now stands down
|
||||||
return False
|
every gate app at once instead of only this one.
|
||||||
try:
|
|
||||||
with scheduled_skips_file.open() as f:
|
The date is **local**, not UTC. The file-backed check this replaces
|
||||||
skips = json.load(f)
|
compared against a UTC day while ``add_scheduled_skip.py`` wrote a local
|
||||||
except (OSError, json.JSONDecodeError) as exc:
|
one, so a skip added near midnight could name a date the chain never
|
||||||
_logger.warning(
|
matched. freedays owns "what is today" for all of them now.
|
||||||
"Could not read scheduled skips from %s: %s — treating today as NOT "
|
|
||||||
"a scheduled skip (the lock chain continues)",
|
Still fails closed: an unreadable pool reads as "not free", so the lock
|
||||||
scheduled_skips_file,
|
chain continues rather than the lock silently switching itself off.
|
||||||
exc,
|
"""
|
||||||
)
|
return freedays.is_free_day(today)
|
||||||
return False
|
|
||||||
return (today or _today_str()) in skips
|
|
||||||
|
|
||||||
|
|
||||||
def has_logged_today(log_file: Path, *, today: str | None = None) -> bool:
|
def has_logged_today(log_file: Path, *, today: str | None = None) -> bool:
|
||||||
|
|||||||
@ -63,7 +63,6 @@ __all__ = [
|
|||||||
def explain_lock_decision(
|
def explain_lock_decision(
|
||||||
*,
|
*,
|
||||||
log_file: Path,
|
log_file: Path,
|
||||||
scheduled_skips_file: Path,
|
|
||||||
early_bird_pending_file: Path,
|
early_bird_pending_file: Path,
|
||||||
sick_history: SickHistory,
|
sick_history: SickHistory,
|
||||||
extended_early_bird: bool,
|
extended_early_bird: bool,
|
||||||
@ -84,7 +83,7 @@ def explain_lock_decision(
|
|||||||
local_dt = instant.astimezone()
|
local_dt = instant.astimezone()
|
||||||
local_minutes = local_dt.hour * 60 + local_dt.minute
|
local_minutes = local_dt.hour * 60 + local_dt.minute
|
||||||
|
|
||||||
scheduled = is_scheduled_skip_today(scheduled_skips_file, today=today_str)
|
scheduled = is_scheduled_skip_today(local_dt.date())
|
||||||
pending = is_early_bird_pending(early_bird_pending_file, today=today_str)
|
pending = is_early_bird_pending(early_bird_pending_file, today=today_str)
|
||||||
window_open = _early_bird_window_open(
|
window_open = _early_bird_window_open(
|
||||||
extended=extended_early_bird, local_minutes=local_minutes
|
extended=extended_early_bird, local_minutes=local_minutes
|
||||||
|
|||||||
@ -11,7 +11,6 @@ from typing import TYPE_CHECKING
|
|||||||
from gatelock.log_integrity import compute_entry_hmac
|
from gatelock.log_integrity import compute_entry_hmac
|
||||||
|
|
||||||
from screen_locker import _compliance_state
|
from screen_locker import _compliance_state
|
||||||
from screen_locker._constants import SCHEDULED_SKIPS_FILE
|
|
||||||
from screen_locker._log_io import load_workout_log
|
from screen_locker._log_io import load_workout_log
|
||||||
from screen_locker._manual_workout import MANUAL_WORKOUT_TYPE, manual_sync_record_id
|
from screen_locker._manual_workout import MANUAL_WORKOUT_TYPE, manual_sync_record_id
|
||||||
|
|
||||||
@ -144,7 +143,7 @@ class LogMixin:
|
|||||||
|
|
||||||
def _is_scheduled_skip_today(self) -> bool:
|
def _is_scheduled_skip_today(self) -> bool:
|
||||||
"""Return True if today's date is listed in the scheduled skips file."""
|
"""Return True if today's date is listed in the scheduled skips file."""
|
||||||
return _compliance_state.is_scheduled_skip_today(SCHEDULED_SKIPS_FILE)
|
return _compliance_state.is_scheduled_skip_today()
|
||||||
|
|
||||||
def save_workout_log(self) -> RecordResult:
|
def save_workout_log(self) -> RecordResult:
|
||||||
"""Append today's workout to the log (HMAC-signed) and report the result.
|
"""Append today's workout to the log (HMAC-signed) and report the result.
|
||||||
|
|||||||
@ -48,7 +48,6 @@ from screen_locker._compliance_state import (
|
|||||||
)
|
)
|
||||||
from screen_locker._constants import (
|
from screen_locker._constants import (
|
||||||
EARLY_BIRD_PENDING_FILE,
|
EARLY_BIRD_PENDING_FILE,
|
||||||
SCHEDULED_SKIPS_FILE,
|
|
||||||
)
|
)
|
||||||
from screen_locker._sick_tracker import load_history
|
from screen_locker._sick_tracker import load_history
|
||||||
from screen_locker._status_data import format_summary_line, gather_status
|
from screen_locker._status_data import format_summary_line, gather_status
|
||||||
@ -137,7 +136,7 @@ def get_flags() -> dict[str, bool]:
|
|||||||
history = load_history()
|
history = load_history()
|
||||||
return {
|
return {
|
||||||
"has_logged_today": has_logged_today(_LOG_FILE),
|
"has_logged_today": has_logged_today(_LOG_FILE),
|
||||||
"is_scheduled_skip_today": is_scheduled_skip_today(SCHEDULED_SKIPS_FILE),
|
"is_scheduled_skip_today": is_scheduled_skip_today(),
|
||||||
"is_early_bird_pending": is_early_bird_pending(EARLY_BIRD_PENDING_FILE),
|
"is_early_bird_pending": is_early_bird_pending(EARLY_BIRD_PENDING_FILE),
|
||||||
"is_sick_day_today": is_sick_day_today(history),
|
"is_sick_day_today": is_sick_day_today(history),
|
||||||
}
|
}
|
||||||
|
|||||||
@ -46,7 +46,6 @@ from screen_locker._constants import (
|
|||||||
EXTRA_BENEFITS_FILE,
|
EXTRA_BENEFITS_FILE,
|
||||||
MANUAL_WORKOUT_BUDGET_PER_7_DAYS,
|
MANUAL_WORKOUT_BUDGET_PER_7_DAYS,
|
||||||
MANUAL_WORKOUT_BUDGET_PER_30_DAYS,
|
MANUAL_WORKOUT_BUDGET_PER_30_DAYS,
|
||||||
SCHEDULED_SKIPS_FILE,
|
|
||||||
SHUTDOWN_BASE_FILE,
|
SHUTDOWN_BASE_FILE,
|
||||||
SHUTDOWN_CONFIG_FILE,
|
SHUTDOWN_CONFIG_FILE,
|
||||||
SICK_BUDGET_PER_7_DAYS,
|
SICK_BUDGET_PER_7_DAYS,
|
||||||
@ -174,7 +173,6 @@ def gather_status(
|
|||||||
extra_benefits_file: Path = EXTRA_BENEFITS_FILE,
|
extra_benefits_file: Path = EXTRA_BENEFITS_FILE,
|
||||||
shutdown_base_file: Path = SHUTDOWN_BASE_FILE,
|
shutdown_base_file: Path = SHUTDOWN_BASE_FILE,
|
||||||
shutdown_config_file: Path = SHUTDOWN_CONFIG_FILE,
|
shutdown_config_file: Path = SHUTDOWN_CONFIG_FILE,
|
||||||
scheduled_skips_file: Path = SCHEDULED_SKIPS_FILE,
|
|
||||||
early_bird_pending_file: Path = EARLY_BIRD_PENDING_FILE,
|
early_bird_pending_file: Path = EARLY_BIRD_PENDING_FILE,
|
||||||
now: datetime | None = None,
|
now: datetime | None = None,
|
||||||
) -> StatusSnapshot:
|
) -> StatusSnapshot:
|
||||||
@ -196,7 +194,6 @@ def gather_status(
|
|||||||
|
|
||||||
lock_explanation = explain_lock_decision(
|
lock_explanation = explain_lock_decision(
|
||||||
log_file=log_file,
|
log_file=log_file,
|
||||||
scheduled_skips_file=scheduled_skips_file,
|
|
||||||
early_bird_pending_file=early_bird_pending_file,
|
early_bird_pending_file=early_bird_pending_file,
|
||||||
sick_history=sick_history,
|
sick_history=sick_history,
|
||||||
extended_early_bird=early_bird_extended,
|
extended_early_bird=early_bird_extended,
|
||||||
|
|||||||
@ -40,7 +40,6 @@ ISOLATED_STATE: tuple[tuple[str, tuple[str, ...]], ...] = (
|
|||||||
"_shutdown_sick_state.SICK_DAY_STATE_FILE",
|
"_shutdown_sick_state.SICK_DAY_STATE_FILE",
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
("scheduled_skips.json", ("_log_mixin.SCHEDULED_SKIPS_FILE",)),
|
|
||||||
# The durable lock-decision trail. Written on EVERY locker run, so without
|
# The durable lock-decision trail. Written on EVERY locker run, so without
|
||||||
# this the suite would append test decisions to the user's real
|
# this the suite would append test decisions to the user's real
|
||||||
# enforcement history in ~/.local/share/screen_locker/.
|
# enforcement history in ~/.local/share/screen_locker/.
|
||||||
|
|||||||
72
screen_locker/tests/_real_state_fixtures.py
Normal file
72
screen_locker/tests/_real_state_fixtures.py
Normal file
@ -0,0 +1,72 @@
|
|||||||
|
"""Autouse fixtures whose one job is keeping tests off real user state.
|
||||||
|
|
||||||
|
Split out of ``conftest.py`` for the 250-line cap, and grouped because they
|
||||||
|
answer the same question in two different ways: what stops this suite from
|
||||||
|
reading or overwriting the developer's own files? Loaded through
|
||||||
|
``pytest_plugins`` in ``conftest.py``, so both stay autouse for every test.
|
||||||
|
|
||||||
|
The two seams are genuinely different, which is why neither subsumes the
|
||||||
|
other. ``_isolate_home`` covers paths resolved at *call* time from
|
||||||
|
``Path.home()``; ``_no_free_days_by_default`` covers paths bound into module
|
||||||
|
constants at *import* time, which redirecting home afterwards cannot reach.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Iterator
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _no_free_days_by_default(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
"""Never let the lock chain read the developer's real free-day pool.
|
||||||
|
|
||||||
|
``_isolate_home`` cannot cover this one. freedays binds its paths from
|
||||||
|
``Path.home()`` at *import* time into module constants, so redirecting
|
||||||
|
home afterwards leaves them pointing at the real
|
||||||
|
``~/.local/share/freedays``. Every writer resolves through
|
||||||
|
``resolve_paths``, so that is the seam.
|
||||||
|
|
||||||
|
Without it, a real free day on this machine would short-circuit the lock
|
||||||
|
chain in every test here -- it is the very first check in the chain --
|
||||||
|
and the failures would name early-bird and sick-day logic instead.
|
||||||
|
"""
|
||||||
|
import freedays._api
|
||||||
|
|
||||||
|
monkeypatch.setattr(
|
||||||
|
freedays._api,
|
||||||
|
"resolve_paths",
|
||||||
|
lambda paths: paths or freedays.Paths.under(tmp_path / "freedays"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _isolate_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
|
||||||
|
"""Point ``$HOME`` and ``Path.home()`` at tmp_path for every test.
|
||||||
|
|
||||||
|
``ISOLATED_STATE`` cannot cover this. Everything under ``~/.config`` is
|
||||||
|
resolved at *call* time by ``crdt_sync.credential_store_for``
|
||||||
|
(``Path.home() / ".config" / app / "firebase_auth.json"``), not bound to a
|
||||||
|
module-level constant, so there is no attribute to patch -- the only seam
|
||||||
|
is home itself.
|
||||||
|
|
||||||
|
What this protects is a live credential, not a scratch file. A test that
|
||||||
|
reaches ``credential_store_for("screen_locker")`` and saves would overwrite
|
||||||
|
the machine's real Firebase session with fixture values, and the damage is
|
||||||
|
invisible until the next sync fails with HTTP 401. The same redirect also
|
||||||
|
covers the sync PAT and the shared ``~/.config/crdt-sync/`` password and
|
||||||
|
OAuth secret, which are read the same way.
|
||||||
|
|
||||||
|
``Path.home()`` is patched as well as ``$HOME``: it consults ``os.environ``
|
||||||
|
on POSIX, but only via ``expanduser``, and a test that patches the
|
||||||
|
environment differently must not silently regain access to the real one.
|
||||||
|
"""
|
||||||
|
monkeypatch.setenv("HOME", str(tmp_path))
|
||||||
|
with patch.object(Path, "home", lambda: tmp_path):
|
||||||
|
yield
|
||||||
@ -68,6 +68,11 @@ if TYPE_CHECKING:
|
|||||||
from collections.abc import Generator, Iterator
|
from collections.abc import Generator, Iterator
|
||||||
|
|
||||||
|
|
||||||
|
# Autouse fixtures that keep this suite off real user state live here; see
|
||||||
|
# that module for why the two seams are different.
|
||||||
|
pytest_plugins = ("screen_locker.tests._real_state_fixtures",)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
@pytest.fixture(autouse=True)
|
||||||
def _block_real_tk_and_exit() -> Iterator[None]:
|
def _block_real_tk_and_exit() -> Iterator[None]:
|
||||||
"""Replace the whole ``tk`` module and ``sys.exit`` for every test.
|
"""Replace the whole ``tk`` module and ``sys.exit`` for every test.
|
||||||
@ -130,32 +135,6 @@ def _block_real_network() -> Iterator[None]:
|
|||||||
yield
|
yield
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
|
||||||
def _isolate_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
|
|
||||||
"""Point ``$HOME`` and ``Path.home()`` at tmp_path for every test.
|
|
||||||
|
|
||||||
``ISOLATED_STATE`` cannot cover this. Everything under ``~/.config`` is
|
|
||||||
resolved at *call* time by ``crdt_sync.credential_store_for``
|
|
||||||
(``Path.home() / ".config" / app / "firebase_auth.json"``), not bound to a
|
|
||||||
module-level constant, so there is no attribute to patch -- the only seam
|
|
||||||
is home itself.
|
|
||||||
|
|
||||||
What this protects is a live credential, not a scratch file. A test that
|
|
||||||
reaches ``credential_store_for("screen_locker")`` and saves would overwrite
|
|
||||||
the machine's real Firebase session with fixture values, and the damage is
|
|
||||||
invisible until the next sync fails with HTTP 401. The same redirect also
|
|
||||||
covers the sync PAT and the shared ``~/.config/crdt-sync/`` password and
|
|
||||||
OAuth secret, which are read the same way.
|
|
||||||
|
|
||||||
``Path.home()`` is patched as well as ``$HOME``: it consults ``os.environ``
|
|
||||||
on POSIX, but only via ``expanduser``, and a test that patches the
|
|
||||||
environment differently must not silently regain access to the real one.
|
|
||||||
"""
|
|
||||||
monkeypatch.setenv("HOME", str(tmp_path))
|
|
||||||
with patch.object(Path, "home", lambda: tmp_path):
|
|
||||||
yield
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
@pytest.fixture(autouse=True)
|
||||||
def _clear_degraded_sources() -> Iterator[None]:
|
def _clear_degraded_sources() -> Iterator[None]:
|
||||||
"""Reset the process-scoped degraded-backend registry around every test.
|
"""Reset the process-scoped degraded-backend registry around every test.
|
||||||
|
|||||||
@ -2,11 +2,13 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import UTC, datetime
|
from datetime import UTC, date, datetime
|
||||||
import json
|
import json
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import freedays
|
||||||
|
|
||||||
from screen_locker._compliance_state import (
|
from screen_locker._compliance_state import (
|
||||||
has_logged_today,
|
has_logged_today,
|
||||||
is_early_bird_pending,
|
is_early_bird_pending,
|
||||||
@ -26,33 +28,39 @@ def _today() -> str:
|
|||||||
class TestIsScheduledSkipToday:
|
class TestIsScheduledSkipToday:
|
||||||
"""Mirrors test_scheduled_skip.py's coverage, for the standalone function."""
|
"""Mirrors test_scheduled_skip.py's coverage, for the standalone function."""
|
||||||
|
|
||||||
def test_missing_file(self, tmp_path: Path) -> None:
|
def test_empty_pool(self, tmp_path: Path) -> None:
|
||||||
"""A missing skips file means today is not a scheduled skip."""
|
"""An empty pool means today is not a free day."""
|
||||||
assert is_scheduled_skip_today(tmp_path / "skips.json") is False
|
assert is_scheduled_skip_today() is False
|
||||||
|
|
||||||
def test_today_listed(self, tmp_path: Path) -> None:
|
def test_today_marked(self, tmp_path: Path) -> None:
|
||||||
"""Today's date in the skips list makes it a scheduled skip."""
|
"""Today in the shared pool makes it a free day."""
|
||||||
skip_file = tmp_path / "skips.json"
|
freedays.mark(
|
||||||
skip_file.write_text(json.dumps([_today()]))
|
freedays.today(), paths=freedays.Paths.under(tmp_path / "freedays")
|
||||||
assert is_scheduled_skip_today(skip_file) is True
|
)
|
||||||
|
assert is_scheduled_skip_today() is True
|
||||||
|
|
||||||
def test_today_not_listed(self, tmp_path: Path) -> None:
|
def test_today_not_marked(self, tmp_path: Path) -> None:
|
||||||
"""A list without today is not a scheduled skip."""
|
"""A pool holding some other date is not today's free day."""
|
||||||
skip_file = tmp_path / "skips.json"
|
freedays.mark(
|
||||||
skip_file.write_text(json.dumps(["1999-01-01"]))
|
date(2026, 12, 24),
|
||||||
assert is_scheduled_skip_today(skip_file) is False
|
paths=freedays.Paths.under(tmp_path / "freedays"),
|
||||||
|
)
|
||||||
|
assert is_scheduled_skip_today() is False
|
||||||
|
|
||||||
def test_corrupt_json(self, tmp_path: Path) -> None:
|
def test_corrupt_pool(self, tmp_path: Path) -> None:
|
||||||
"""Unparsable JSON fails closed: not a skip."""
|
"""Unparsable JSON fails closed: not a free day, the chain continues."""
|
||||||
skip_file = tmp_path / "skips.json"
|
pool = tmp_path / "freedays"
|
||||||
skip_file.write_text("{bad}")
|
pool.mkdir(exist_ok=True)
|
||||||
assert is_scheduled_skip_today(skip_file) is False
|
(pool / "free_days.json").write_text("{bad}")
|
||||||
|
assert is_scheduled_skip_today() is False
|
||||||
|
|
||||||
def test_explicit_today_override(self, tmp_path: Path) -> None:
|
def test_explicit_day_override(self, tmp_path: Path) -> None:
|
||||||
"""The `today` argument overrides the real date."""
|
"""The `today` argument overrides the real date."""
|
||||||
skip_file = tmp_path / "skips.json"
|
freedays.mark(
|
||||||
skip_file.write_text(json.dumps(["2020-05-05"]))
|
date(2026, 12, 24),
|
||||||
assert is_scheduled_skip_today(skip_file, today="2020-05-05") is True
|
paths=freedays.Paths.under(tmp_path / "freedays"),
|
||||||
|
)
|
||||||
|
assert is_scheduled_skip_today(date(2026, 12, 24)) is True
|
||||||
|
|
||||||
|
|
||||||
class TestHasLoggedToday:
|
class TestHasLoggedToday:
|
||||||
|
|||||||
@ -7,6 +7,8 @@ import json
|
|||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import freedays
|
||||||
|
|
||||||
from screen_locker._compliance_state import explain_lock_decision
|
from screen_locker._compliance_state import explain_lock_decision
|
||||||
from screen_locker._sick_tracker import SickHistory
|
from screen_locker._sick_tracker import SickHistory
|
||||||
|
|
||||||
@ -24,13 +26,15 @@ class TestExplainLockDecision:
|
|||||||
def _files(self, tmp_path: Path) -> dict[str, Path]:
|
def _files(self, tmp_path: Path) -> dict[str, Path]:
|
||||||
return {
|
return {
|
||||||
"log_file": tmp_path / "log.json",
|
"log_file": tmp_path / "log.json",
|
||||||
"scheduled_skips_file": tmp_path / "scheduled_skips.json",
|
|
||||||
"early_bird_pending_file": tmp_path / "early_bird_pending.json",
|
"early_bird_pending_file": tmp_path / "early_bird_pending.json",
|
||||||
}
|
}
|
||||||
|
|
||||||
def test_scheduled_skip_short_circuits(self, tmp_path: Path) -> None:
|
def test_scheduled_skip_short_circuits(self, tmp_path: Path) -> None:
|
||||||
files = self._files(tmp_path)
|
files = self._files(tmp_path)
|
||||||
files["scheduled_skips_file"].write_text(json.dumps([_today()]))
|
freedays.mark(
|
||||||
|
freedays.today(),
|
||||||
|
paths=freedays.Paths.under(tmp_path / "freedays"),
|
||||||
|
)
|
||||||
result = explain_lock_decision(
|
result = explain_lock_decision(
|
||||||
**files,
|
**files,
|
||||||
sick_history=SickHistory(),
|
sick_history=SickHistory(),
|
||||||
|
|||||||
@ -137,7 +137,7 @@ class TestGetFlags:
|
|||||||
}
|
}
|
||||||
lh.assert_called_once_with()
|
lh.assert_called_once_with()
|
||||||
hlt.assert_called_once_with(_mcp._LOG_FILE)
|
hlt.assert_called_once_with(_mcp._LOG_FILE)
|
||||||
iss.assert_called_once_with(_mcp.SCHEDULED_SKIPS_FILE)
|
iss.assert_called_once_with()
|
||||||
iep.assert_called_once_with(_mcp.EARLY_BIRD_PENDING_FILE)
|
iep.assert_called_once_with(_mcp.EARLY_BIRD_PENDING_FILE)
|
||||||
isd.assert_called_once_with("HIST")
|
isd.assert_called_once_with("HIST")
|
||||||
|
|
||||||
|
|||||||
@ -2,17 +2,17 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import UTC, datetime
|
from datetime import date
|
||||||
import json
|
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
from unittest.mock import MagicMock, patch
|
|
||||||
|
|
||||||
|
import freedays
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from screen_locker.tests.conftest import create_locker
|
from screen_locker.tests.conftest import create_locker
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
from screen_locker.screen_lock import ScreenLocker
|
from screen_locker.screen_lock import ScreenLocker
|
||||||
|
|
||||||
@ -23,104 +23,69 @@ class TestIsScheduledSkipToday:
|
|||||||
def _make_locker(self, mock_tk: MagicMock, tmp_path: Path) -> ScreenLocker:
|
def _make_locker(self, mock_tk: MagicMock, tmp_path: Path) -> ScreenLocker:
|
||||||
return create_locker(mock_tk, tmp_path)
|
return create_locker(mock_tk, tmp_path)
|
||||||
|
|
||||||
def test_returns_false_when_file_absent(
|
def test_returns_false_when_pool_empty(
|
||||||
self,
|
self,
|
||||||
mock_tk: MagicMock,
|
mock_tk: MagicMock,
|
||||||
mock_sys_exit: MagicMock,
|
mock_sys_exit: MagicMock,
|
||||||
tmp_path: Path,
|
tmp_path: Path,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Returns False when scheduled_skips.json does not exist."""
|
"""Returns False when nothing has ever been marked."""
|
||||||
locker = self._make_locker(mock_tk, tmp_path)
|
locker = self._make_locker(mock_tk, tmp_path)
|
||||||
skip_file = tmp_path / "scheduled_skips.json"
|
assert locker._is_scheduled_skip_today() is False
|
||||||
with patch(
|
|
||||||
"screen_locker._log_mixin.SCHEDULED_SKIPS_FILE",
|
|
||||||
skip_file,
|
|
||||||
):
|
|
||||||
assert locker._is_scheduled_skip_today() is False
|
|
||||||
|
|
||||||
def test_returns_true_when_today_listed(
|
def test_returns_true_when_today_marked(
|
||||||
self,
|
self,
|
||||||
mock_tk: MagicMock,
|
mock_tk: MagicMock,
|
||||||
mock_sys_exit: MagicMock,
|
mock_sys_exit: MagicMock,
|
||||||
tmp_path: Path,
|
tmp_path: Path,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Returns True when today's date is in the skips list."""
|
"""Returns True when today is in the shared free-day pool."""
|
||||||
locker = self._make_locker(mock_tk, tmp_path)
|
locker = self._make_locker(mock_tk, tmp_path)
|
||||||
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
|
freedays.mark(
|
||||||
skip_file = tmp_path / "scheduled_skips.json"
|
freedays.today(), paths=freedays.Paths.under(tmp_path / "freedays")
|
||||||
skip_file.write_text(json.dumps([today]))
|
)
|
||||||
with patch(
|
assert locker._is_scheduled_skip_today() is True
|
||||||
"screen_locker._log_mixin.SCHEDULED_SKIPS_FILE",
|
|
||||||
skip_file,
|
|
||||||
):
|
|
||||||
assert locker._is_scheduled_skip_today() is True
|
|
||||||
|
|
||||||
def test_returns_false_when_today_not_listed(
|
def test_returns_false_when_only_another_day_marked(
|
||||||
self,
|
self,
|
||||||
mock_tk: MagicMock,
|
mock_tk: MagicMock,
|
||||||
mock_sys_exit: MagicMock,
|
mock_sys_exit: MagicMock,
|
||||||
tmp_path: Path,
|
tmp_path: Path,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Returns False when today's date is not in the skips list."""
|
"""A pool holding some other date does not free today."""
|
||||||
locker = self._make_locker(mock_tk, tmp_path)
|
locker = self._make_locker(mock_tk, tmp_path)
|
||||||
skip_file = tmp_path / "scheduled_skips.json"
|
freedays.mark(
|
||||||
skip_file.write_text(json.dumps(["1999-01-01", "2000-06-15"]))
|
date(2026, 12, 24),
|
||||||
with patch(
|
paths=freedays.Paths.under(tmp_path / "freedays"),
|
||||||
"screen_locker._log_mixin.SCHEDULED_SKIPS_FILE",
|
)
|
||||||
skip_file,
|
assert locker._is_scheduled_skip_today() is False
|
||||||
):
|
|
||||||
assert locker._is_scheduled_skip_today() is False
|
|
||||||
|
|
||||||
def test_returns_false_on_corrupt_json(
|
def test_returns_false_on_corrupt_pool(
|
||||||
self,
|
self,
|
||||||
mock_tk: MagicMock,
|
mock_tk: MagicMock,
|
||||||
mock_sys_exit: MagicMock,
|
mock_sys_exit: MagicMock,
|
||||||
tmp_path: Path,
|
tmp_path: Path,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Returns False when the skips file contains invalid JSON."""
|
"""Fail closed: an unparsable pool locks normally rather than opening."""
|
||||||
locker = self._make_locker(mock_tk, tmp_path)
|
locker = self._make_locker(mock_tk, tmp_path)
|
||||||
skip_file = tmp_path / "scheduled_skips.json"
|
pool = tmp_path / "freedays"
|
||||||
skip_file.write_text("{not valid json}")
|
pool.mkdir(exist_ok=True)
|
||||||
with patch(
|
(pool / "free_days.json").write_text("{not valid json}")
|
||||||
"screen_locker._log_mixin.SCHEDULED_SKIPS_FILE",
|
assert locker._is_scheduled_skip_today() is False
|
||||||
skip_file,
|
|
||||||
):
|
|
||||||
assert locker._is_scheduled_skip_today() is False
|
|
||||||
|
|
||||||
def test_returns_false_on_read_error(
|
def test_returns_false_when_the_day_was_released(
|
||||||
self,
|
self,
|
||||||
mock_tk: MagicMock,
|
mock_tk: MagicMock,
|
||||||
mock_sys_exit: MagicMock,
|
mock_sys_exit: MagicMock,
|
||||||
tmp_path: Path,
|
tmp_path: Path,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Returns False when the skips file cannot be read (OSError)."""
|
"""Giving a day back re-arms the lock for it."""
|
||||||
locker = self._make_locker(mock_tk, tmp_path)
|
locker = self._make_locker(mock_tk, tmp_path)
|
||||||
skip_file = tmp_path / "scheduled_skips.json"
|
paths = freedays.Paths.under(tmp_path / "freedays")
|
||||||
skip_file.write_text("[]")
|
freedays.mark(freedays.today(), paths=paths)
|
||||||
with (
|
assert locker._is_scheduled_skip_today() is True
|
||||||
patch(
|
freedays.release(freedays.today(), paths=paths)
|
||||||
"screen_locker._log_mixin.SCHEDULED_SKIPS_FILE",
|
assert locker._is_scheduled_skip_today() is False
|
||||||
skip_file,
|
|
||||||
),
|
|
||||||
patch("builtins.open", side_effect=OSError("permission denied")),
|
|
||||||
):
|
|
||||||
assert locker._is_scheduled_skip_today() is False
|
|
||||||
|
|
||||||
def test_empty_list_returns_false(
|
|
||||||
self,
|
|
||||||
mock_tk: MagicMock,
|
|
||||||
mock_sys_exit: MagicMock,
|
|
||||||
tmp_path: Path,
|
|
||||||
) -> None:
|
|
||||||
"""Returns False for an empty skips list."""
|
|
||||||
locker = self._make_locker(mock_tk, tmp_path)
|
|
||||||
skip_file = tmp_path / "scheduled_skips.json"
|
|
||||||
skip_file.write_text("[]")
|
|
||||||
with patch(
|
|
||||||
"screen_locker._log_mixin.SCHEDULED_SKIPS_FILE",
|
|
||||||
skip_file,
|
|
||||||
):
|
|
||||||
assert locker._is_scheduled_skip_today() is False
|
|
||||||
|
|
||||||
|
|
||||||
class TestScheduledSkipEarlyExit:
|
class TestScheduledSkipEarlyExit:
|
||||||
@ -128,9 +93,10 @@ class TestScheduledSkipEarlyExit:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _write_today_skip(tmp_path: Path) -> None:
|
def _write_today_skip(tmp_path: Path) -> None:
|
||||||
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
|
"""Mark today free in the shared pool the conftest redirected here."""
|
||||||
skip_file = tmp_path / "scheduled_skips.json"
|
freedays.mark(
|
||||||
skip_file.write_text(json.dumps([today]))
|
freedays.today(), paths=freedays.Paths.under(tmp_path / "freedays")
|
||||||
|
)
|
||||||
|
|
||||||
def test_exits_on_scheduled_skip_day(
|
def test_exits_on_scheduled_skip_day(
|
||||||
self,
|
self,
|
||||||
|
|||||||
@ -22,6 +22,5 @@ def _files(tmp_path: Path) -> dict[str, Path]:
|
|||||||
"extra_benefits_file": tmp_path / "extra_benefits_state.json",
|
"extra_benefits_file": tmp_path / "extra_benefits_state.json",
|
||||||
"shutdown_base_file": tmp_path / "shutdown_base.json",
|
"shutdown_base_file": tmp_path / "shutdown_base.json",
|
||||||
"shutdown_config_file": tmp_path / "shutdown_config.conf",
|
"shutdown_config_file": tmp_path / "shutdown_config.conf",
|
||||||
"scheduled_skips_file": tmp_path / "scheduled_skips.json",
|
|
||||||
"early_bird_pending_file": tmp_path / "early_bird_pending.json",
|
"early_bird_pending_file": tmp_path / "early_bird_pending.json",
|
||||||
}
|
}
|
||||||
|
|||||||
@ -7,11 +7,13 @@ weekly minimum) means no lock is needed.
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import UTC, datetime
|
from datetime import UTC, date, datetime
|
||||||
import json
|
import json
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import freedays
|
||||||
|
|
||||||
from screen_locker._status_data import gather_status
|
from screen_locker._status_data import gather_status
|
||||||
from screen_locker.tests.test_status_data import _files
|
from screen_locker.tests.test_status_data import _files
|
||||||
|
|
||||||
@ -73,7 +75,11 @@ class TestGatherStatusLockSuppression:
|
|||||||
def test_scheduled_skip_stops_lock(self, tmp_path: Path) -> None:
|
def test_scheduled_skip_stops_lock(self, tmp_path: Path) -> None:
|
||||||
"""Scheduled skip stops lock."""
|
"""Scheduled skip stops lock."""
|
||||||
files = _files(tmp_path)
|
files = _files(tmp_path)
|
||||||
files["scheduled_skips_file"].write_text(json.dumps(["2024-01-05"]))
|
freedays.mark(
|
||||||
|
date(2024, 1, 5),
|
||||||
|
paths=freedays.Paths.under(tmp_path / "freedays"),
|
||||||
|
now=date(2024, 1, 5),
|
||||||
|
)
|
||||||
with patch(
|
with patch(
|
||||||
"screen_locker._status_data.has_workout_skip_today", return_value=False
|
"screen_locker._status_data.has_workout_skip_today", return_value=False
|
||||||
):
|
):
|
||||||
|
|||||||
@ -44,7 +44,6 @@ class TestUnreadableSourceIsNotNoWorkout:
|
|||||||
def _files(self, tmp_path: Path) -> dict[str, Path]:
|
def _files(self, tmp_path: Path) -> dict[str, Path]:
|
||||||
return {
|
return {
|
||||||
"log_file": tmp_path / "log.json",
|
"log_file": tmp_path / "log.json",
|
||||||
"scheduled_skips_file": tmp_path / "scheduled_skips.json",
|
|
||||||
"early_bird_pending_file": tmp_path / "early_bird_pending.json",
|
"early_bird_pending_file": tmp_path / "early_bird_pending.json",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -1,111 +1,80 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""Add a date to ``scheduled_skips.json`` — the locker's first early exit.
|
"""Mark a day free, for this app and every other gate app at once.
|
||||||
|
|
||||||
A scheduled skip is the supported way to exempt a specific day without
|
This used to append to ``screen_locker/scheduled_skips.json``, which only
|
||||||
weakening enforcement for any other day: the lock chain checks it first, and
|
screen-locker read. That file is no longer consulted by anything: the lock
|
||||||
(since the 2026-08 logging work) records the exemption as a decision, so an
|
chain now asks the shared pool (``~/utils/freedays``), so a day taken here
|
||||||
unexpected quiet day is traceable to the date that caused it instead of looking
|
also stands down diet-guard, wake-alarm, leetcode-guard and home-guard.
|
||||||
like the enforcer silently died again.
|
|
||||||
|
|
||||||
Kept out of ``arm.sh`` because the file it edits is the one the lock chain
|
Kept as a thin wrapper rather than deleted because ``arm.sh`` calls it, and
|
||||||
reads: a malformed write is read as "not a skip" and the machine locks anyway,
|
because this is the name already in muscle memory. ``freedays mark`` does
|
||||||
so this belongs somewhere the repo's linters and tests actually apply.
|
exactly the same thing.
|
||||||
|
|
||||||
Usage:
|
scripts/add_scheduled_skip.py --date today
|
||||||
python3 scripts/add_scheduled_skip.py --date today
|
scripts/add_scheduled_skip.py --date 2026-12-24
|
||||||
python3 scripts/add_scheduled_skip.py --date 2026-08-20
|
|
||||||
python3 scripts/add_scheduled_skip.py --list
|
The date is **local**. The old version computed a local "today" while the
|
||||||
|
lock chain compared against a UTC one, so a skip added near midnight could
|
||||||
|
name a date the chain never matched. freedays owns "what is today" for both
|
||||||
|
sides now, so that disagreement cannot recur.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
from datetime import UTC, datetime
|
import logging
|
||||||
import json
|
|
||||||
from pathlib import Path
|
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
SKIPS_FILE = (
|
import freedays
|
||||||
Path(__file__).resolve().parent.parent / "screen_locker" / ("scheduled_skips.json")
|
|
||||||
)
|
|
||||||
|
|
||||||
|
_logger = logging.getLogger(__name__)
|
||||||
def _today() -> str:
|
|
||||||
"""Return today's local date as YYYY-MM-DD.
|
|
||||||
|
|
||||||
Local, not UTC: the skip must match the day the user is living in, and the
|
|
||||||
lock chain's own ``_today_str`` is local for the same reason.
|
|
||||||
"""
|
|
||||||
return datetime.now().astimezone().strftime("%Y-%m-%d")
|
|
||||||
|
|
||||||
|
|
||||||
def _report(message: str) -> None:
|
def _report(message: str) -> None:
|
||||||
"""Write one line to stdout (matches the other scripts in this directory)."""
|
|
||||||
sys.stdout.write(f"{message}\n")
|
sys.stdout.write(f"{message}\n")
|
||||||
|
|
||||||
|
|
||||||
def load_skips(path: Path) -> list[str]:
|
|
||||||
"""Return the recorded skip dates, or [] when the file is absent."""
|
|
||||||
if not path.exists():
|
|
||||||
return []
|
|
||||||
try:
|
|
||||||
data = json.loads(path.read_text(encoding="utf-8"))
|
|
||||||
except (OSError, json.JSONDecodeError) as exc:
|
|
||||||
# Refuse rather than silently starting a fresh list: overwriting an
|
|
||||||
# unreadable file would drop skips the user still expects to hold.
|
|
||||||
msg = f"could not read {path}: {exc}"
|
|
||||||
msg = f"ERROR: {msg}"
|
|
||||||
raise SystemExit(msg) from exc
|
|
||||||
if not isinstance(data, list):
|
|
||||||
msg = f"ERROR: {path} does not contain a JSON list"
|
|
||||||
raise SystemExit(msg)
|
|
||||||
return [str(entry) for entry in data]
|
|
||||||
|
|
||||||
|
|
||||||
def add_skip(path: Path, date: str) -> bool:
|
|
||||||
"""Add ``date`` to the skips file. True if it was newly added."""
|
|
||||||
skips = load_skips(path)
|
|
||||||
if date in skips:
|
|
||||||
return False
|
|
||||||
skips.append(date)
|
|
||||||
path.parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
path.write_text(json.dumps(sorted(skips), indent=2) + "\n", encoding="utf-8")
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
def main(argv: list[str] | None = None) -> int:
|
def main(argv: list[str] | None = None) -> int:
|
||||||
"""Add the requested date, or list what is already recorded."""
|
"""Mark the requested day free in the shared pool.
|
||||||
parser = argparse.ArgumentParser(description=__doc__)
|
|
||||||
|
Returns:
|
||||||
|
``0`` when the day is free (including when it already was), ``1``
|
||||||
|
when the pool refused, ``2`` when the date could not be parsed.
|
||||||
|
"""
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--date",
|
"--date",
|
||||||
help="date to skip: 'today' or YYYY-MM-DD",
|
default="today",
|
||||||
|
help="YYYY-MM-DD, or 'today'/'tomorrow' (default: today)",
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--list",
|
"--reason",
|
||||||
action="store_true",
|
default="",
|
||||||
help="print the recorded skip dates and exit",
|
help="optional free text; never required",
|
||||||
)
|
)
|
||||||
args = parser.parse_args(argv)
|
args = parser.parse_args(argv)
|
||||||
|
|
||||||
if args.list:
|
try:
|
||||||
for entry in sorted(load_skips(SKIPS_FILE)):
|
day = freedays.resolve(args.date)
|
||||||
_report(entry)
|
except ValueError as exc:
|
||||||
|
_logger.warning("could not parse the requested date: %s", exc)
|
||||||
|
_report(f"error: {exc}")
|
||||||
|
return 2
|
||||||
|
|
||||||
|
iso = freedays.to_iso(day)
|
||||||
|
if freedays.is_free_day(day):
|
||||||
|
_report(f"{iso} is already a free day; nothing to do")
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
if not args.date:
|
|
||||||
parser.error("--date is required (or use --list)")
|
|
||||||
|
|
||||||
date = _today() if args.date == "today" else args.date
|
|
||||||
try:
|
try:
|
||||||
datetime.strptime(date, "%Y-%m-%d").replace(tzinfo=UTC)
|
freedays.mark(day, reason=args.reason)
|
||||||
except ValueError:
|
except freedays.FreeDayError as exc:
|
||||||
msg = f"ERROR: {date!r} is not a YYYY-MM-DD date"
|
_logger.warning("the pool refused %s: %s", iso, exc)
|
||||||
raise SystemExit(msg) from None
|
_report(f"error: {exc}")
|
||||||
|
return 1
|
||||||
|
|
||||||
if add_skip(SKIPS_FILE, date):
|
left = freedays.status(year=day.year).left
|
||||||
_report(f"Added scheduled skip for {date} — the locker will not lock that day.")
|
_report(f"{iso} is now a free day for every gate app ({left} left in {day.year})")
|
||||||
else:
|
|
||||||
_report(f"{date} is already a scheduled skip; nothing to do.")
|
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
132
scripts/migrate_scheduled_skips.py
Executable file
132
scripts/migrate_scheduled_skips.py
Executable file
@ -0,0 +1,132 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Move ``scheduled_skips.json`` into the shared free-day pool, once.
|
||||||
|
|
||||||
|
screen-locker's scheduled skips were the first version of "a day when the
|
||||||
|
gate stands down", and the only one any app had. freedays generalises them:
|
||||||
|
the same idea, but one marked day now stands down every gate app at once.
|
||||||
|
|
||||||
|
This copies the dates across and leaves the original file untouched, so the
|
||||||
|
migration can be inspected -- and rerun -- before anything is deleted.
|
||||||
|
Rerunning is safe: a date already in the pool is reported and skipped, never
|
||||||
|
duplicated or double-counted.
|
||||||
|
|
||||||
|
scripts/migrate_scheduled_skips.py --dry-run # show what would happen
|
||||||
|
scripts/migrate_scheduled_skips.py # do it
|
||||||
|
|
||||||
|
Every imported date is in the past, and ``freedays.mark`` deliberately
|
||||||
|
refuses to backdate -- that refusal is what stops a gate you already failed
|
||||||
|
being erased afterwards. Passing ``now=day`` supplies the day itself as the
|
||||||
|
reference instead of reaching for the system clock, which is the one honest
|
||||||
|
way to say "this day was taken, and it was taken then". Each lands as spent
|
||||||
|
(``consumed``), which is correct: these days happened.
|
||||||
|
|
||||||
|
Output goes through ``_report`` rather than ``print``. ruff's T201 fix is
|
||||||
|
*unsafe* -- it deletes the whole call, message and all -- and it did exactly
|
||||||
|
that to the first draft of this file, leaving a migration that moved data
|
||||||
|
while appearing to do nothing.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
from datetime import date
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import freedays
|
||||||
|
|
||||||
|
DEFAULT_SKIPS_FILE = (
|
||||||
|
Path(__file__).resolve().parent.parent / "screen_locker" / "scheduled_skips.json"
|
||||||
|
)
|
||||||
|
_REASON = "migrated from screen-locker scheduled_skips.json"
|
||||||
|
|
||||||
|
_logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _report(message: str) -> None:
|
||||||
|
"""Write one line to stdout, un-deletable by an autofixer."""
|
||||||
|
sys.stdout.write(f"{message}\n")
|
||||||
|
|
||||||
|
|
||||||
|
def read_skips(path: Path) -> list[date]:
|
||||||
|
"""Return the dates listed in ``path``, ascending.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
SystemExit: If the file is missing or is not a JSON list of dates.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
raw = json.loads(path.read_text(encoding="utf-8"))
|
||||||
|
except FileNotFoundError as exc:
|
||||||
|
msg = f"no scheduled-skips file at {path} -- nothing to migrate"
|
||||||
|
raise SystemExit(msg) from exc
|
||||||
|
except (OSError, json.JSONDecodeError) as exc:
|
||||||
|
msg = f"could not read {path}: {exc}"
|
||||||
|
raise SystemExit(msg) from exc
|
||||||
|
if not isinstance(raw, list):
|
||||||
|
sys.exit(f"{path} is not a JSON list of dates")
|
||||||
|
try:
|
||||||
|
return sorted(date.fromisoformat(str(entry)) for entry in raw)
|
||||||
|
except ValueError as exc:
|
||||||
|
msg = f"{path} holds something that is not a YYYY-MM-DD date: {exc}"
|
||||||
|
raise SystemExit(msg) from exc
|
||||||
|
|
||||||
|
|
||||||
|
def migrate(days: list[date], *, dry_run: bool) -> int:
|
||||||
|
"""Mark each day in the shared pool. Returns how many were newly added."""
|
||||||
|
added = 0
|
||||||
|
for day in days:
|
||||||
|
iso = freedays.to_iso(day)
|
||||||
|
if freedays.is_free_day(day):
|
||||||
|
_report(f" {iso} already in the pool, leaving it alone")
|
||||||
|
continue
|
||||||
|
if dry_run:
|
||||||
|
_report(f" {iso} would be added")
|
||||||
|
added += 1
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
freedays.mark(day, reason=_REASON, now=day)
|
||||||
|
except freedays.FreeDayError as exc:
|
||||||
|
_logger.warning("the pool refused %s: %s", iso, exc)
|
||||||
|
_report(f" {iso} REFUSED: {exc}")
|
||||||
|
continue
|
||||||
|
_report(f" {iso} added")
|
||||||
|
added += 1
|
||||||
|
return added
|
||||||
|
|
||||||
|
|
||||||
|
def _report_budget(days: list[date]) -> None:
|
||||||
|
"""Print each affected year's remaining budget."""
|
||||||
|
years = sorted({day.year for day in days})
|
||||||
|
for year in years:
|
||||||
|
status = freedays.status(year=year)
|
||||||
|
_report(
|
||||||
|
f"{year}: {status.spent} of {status.budget} free days spent, "
|
||||||
|
f"{status.left} left"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: list[str] | None = None) -> int:
|
||||||
|
"""Read the skips file and copy its dates into the shared pool."""
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||||
|
parser.add_argument("--skips-file", type=Path, default=DEFAULT_SKIPS_FILE)
|
||||||
|
parser.add_argument(
|
||||||
|
"--dry-run", action="store_true", help="show what would change, write nothing"
|
||||||
|
)
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
|
||||||
|
days = read_skips(args.skips_file)
|
||||||
|
_report(f"{len(days)} scheduled skip(s) in {args.skips_file}:")
|
||||||
|
added = migrate(days, dry_run=args.dry_run)
|
||||||
|
_report_budget(days)
|
||||||
|
|
||||||
|
verb = "would be added" if args.dry_run else "added"
|
||||||
|
_report(f"{added} {verb}.")
|
||||||
|
if not args.dry_run and added:
|
||||||
|
_report(f"{args.skips_file} left in place -- delete it once this looks right.")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@ -59,7 +59,7 @@ SecureCredentialStore credentialStore() {
|
|||||||
read: (key) async {
|
read: (key) async {
|
||||||
final file = _desktopCredentialFile();
|
final file = _desktopCredentialFile();
|
||||||
if (!file.existsSync()) return null;
|
if (!file.existsSync()) return null;
|
||||||
return file.readAsString();
|
return await file.readAsString();
|
||||||
},
|
},
|
||||||
write: (key, value) async {
|
write: (key, value) async {
|
||||||
final file = _desktopCredentialFile();
|
final file = _desktopCredentialFile();
|
||||||
@ -86,7 +86,7 @@ SecureCredentialStore credentialStore() {
|
|||||||
Future<FirebaseAccount?> loadAccount() async {
|
Future<FirebaseAccount?> loadAccount() async {
|
||||||
// Linux desktop reads the shared PC credential instead of the keystore,
|
// Linux desktop reads the shared PC credential instead of the keystore,
|
||||||
// so a fresh desktop install is connected the moment it starts.
|
// so a fresh desktop install is connected the moment it starts.
|
||||||
if (Platform.isLinux) return _accountFromDesktopConfig();
|
if (Platform.isLinux) return await _accountFromDesktopConfig();
|
||||||
try {
|
try {
|
||||||
return FirebaseAccount.tryParse(
|
return FirebaseAccount.tryParse(
|
||||||
await _secure.read(key: kFirebaseAccountKey),
|
await _secure.read(key: kFirebaseAccountKey),
|
||||||
@ -149,9 +149,9 @@ Future<FirebaseRestClient?> openFirebase() async {
|
|||||||
// marker beside it. Treating the marker as the source of truth is what
|
// marker beside it. Treating the marker as the source of truth is what
|
||||||
// made a phone with a live session sync over GitHub and 401 forever --
|
// made a phone with a live session sync over GitHub and 401 forever --
|
||||||
// the credential was in the keystore the whole time, unused.
|
// the credential was in the keystore the whole time, unused.
|
||||||
return _clientFromStoredSession();
|
return await _clientFromStoredSession();
|
||||||
}
|
}
|
||||||
return firebaseClientFor(
|
return await firebaseClientFor(
|
||||||
config: kProject.configFor(account.email),
|
config: kProject.configFor(account.email),
|
||||||
store: credentialStore(),
|
store: credentialStore(),
|
||||||
// A Google-provisioned account stores an empty password.
|
// A Google-provisioned account stores an empty password.
|
||||||
|
|||||||
@ -75,7 +75,7 @@ Future<String?> googleIdToken({
|
|||||||
Future<String?> Function()? signInFn,
|
Future<String?> Function()? signInFn,
|
||||||
String serverClientId = kServerClientId,
|
String serverClientId = kServerClientId,
|
||||||
}) async {
|
}) async {
|
||||||
if (signInFn != null) return signInFn();
|
if (signInFn != null) return await signInFn();
|
||||||
if (serverClientId.isEmpty) {
|
if (serverClientId.isEmpty) {
|
||||||
// A build without --dart-define=GOOGLE_SERVER_CLIENT_ID would otherwise
|
// A build without --dart-define=GOOGLE_SERVER_CLIENT_ID would otherwise
|
||||||
// fail inside the plugin with a far less obvious message.
|
// fail inside the plugin with a far less obvious message.
|
||||||
|
|||||||
@ -207,7 +207,7 @@ class StorageService {
|
|||||||
Future<List<Map<String, dynamic>>> getWorkoutHistory({
|
Future<List<Map<String, dynamic>>> getWorkoutHistory({
|
||||||
int limit = 60,
|
int limit = 60,
|
||||||
}) async {
|
}) async {
|
||||||
return _db.rawQuery(
|
return await _db.rawQuery(
|
||||||
'SELECT date, workout_type, duration_seconds, succeeded, json '
|
'SELECT date, workout_type, duration_seconds, succeeded, json '
|
||||||
'FROM workout_history ORDER BY date DESC LIMIT ?',
|
'FROM workout_history ORDER BY date DESC LIMIT ?',
|
||||||
[limit],
|
[limit],
|
||||||
|
|||||||
@ -102,7 +102,7 @@ extension StorageServiceSchema on StorageService {
|
|||||||
final dir = await getApplicationSupportDirectory();
|
final dir = await getApplicationSupportDirectory();
|
||||||
return dir.path;
|
return dir.path;
|
||||||
}
|
}
|
||||||
return getDatabasesPath();
|
return await getDatabasesPath();
|
||||||
}
|
}
|
||||||
// coverage:ignore-end
|
// coverage:ignore-end
|
||||||
|
|
||||||
|
|||||||
@ -119,7 +119,7 @@ class WorkoutSyncService {
|
|||||||
log('WorkoutSyncService.push skipped: $reason', level: 900);
|
log('WorkoutSyncService.push skipped: $reason', level: 900);
|
||||||
return const PushResult(pushed: false, reason: reason);
|
return const PushResult(pushed: false, reason: reason);
|
||||||
}
|
}
|
||||||
return _session(settings.token).run(
|
return await _session(settings.token).run(
|
||||||
operation: 'push',
|
operation: 'push',
|
||||||
successReason: 'pushed',
|
successReason: 'pushed',
|
||||||
failurePrefix: 'push failed',
|
failurePrefix: 'push failed',
|
||||||
@ -165,7 +165,7 @@ class WorkoutSyncService {
|
|||||||
}
|
}
|
||||||
// No addition: whatever this device already has, unchanged. The point is
|
// No addition: whatever this device already has, unchanged. The point is
|
||||||
// the round trip, not the payload.
|
// the round trip, not the payload.
|
||||||
return _session(settings.token).run(
|
return await _session(settings.token).run(
|
||||||
operation: 'syncNow',
|
operation: 'syncNow',
|
||||||
successReason: 'synced',
|
successReason: 'synced',
|
||||||
failurePrefix: 'sync failed',
|
failurePrefix: 'sync failed',
|
||||||
@ -183,7 +183,7 @@ class WorkoutSyncService {
|
|||||||
log('WorkoutSyncService.pushManual skipped: $reason', level: 900);
|
log('WorkoutSyncService.pushManual skipped: $reason', level: 900);
|
||||||
return const PushResult(pushed: false, reason: reason);
|
return const PushResult(pushed: false, reason: reason);
|
||||||
}
|
}
|
||||||
return _session(settings.token).run(
|
return await _session(settings.token).run(
|
||||||
operation: 'pushManual',
|
operation: 'pushManual',
|
||||||
successReason: 'pushed',
|
successReason: 'pushed',
|
||||||
failurePrefix: 'push failed',
|
failurePrefix: 'push failed',
|
||||||
|
|||||||
@ -557,18 +557,18 @@ packages:
|
|||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
name: permission_handler
|
name: permission_handler
|
||||||
sha256: e7317eb2eb611d1bf0386b6b974be9c50449f975f19a90a7b8ea013550302b30
|
sha256: e6bcecadfe40df6b888141f23cbaf6ba6c3da49fb33f6ff887d060dd48544fbd
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "13.0.1"
|
version: "13.0.2"
|
||||||
permission_handler_android:
|
permission_handler_android:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
name: permission_handler_android
|
name: permission_handler_android
|
||||||
sha256: d7676c6fcf2f0b92537ec41476a6ead45a00b0d8bbb852395a6f9f33f49d6242
|
sha256: b1ce660f4d0dcaffdf2605a19544c129fb5adda4e6fd039992ae356c4e437039
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "14.0.0"
|
version: "14.1.0"
|
||||||
permission_handler_apple:
|
permission_handler_apple:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@ -915,18 +915,18 @@ packages:
|
|||||||
dependency: "direct dev"
|
dependency: "direct dev"
|
||||||
description:
|
description:
|
||||||
name: very_good_analysis
|
name: very_good_analysis
|
||||||
sha256: "481af67ab5877af20325251dc215a4ebac7666a1c8cf09198ffd457bc612b33d"
|
sha256: "0bd5eb8d6be76aa0d71e70cbdae6cac8f784f761170568e3c2214a6948c7f6d3"
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "10.3.0"
|
version: "11.0.0"
|
||||||
vibration:
|
vibration:
|
||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
name: vibration
|
name: vibration
|
||||||
sha256: c6c25eb7acadfd231925a60004736443cbf63f1eb5740d6dd83a1bc09cf00f6d
|
sha256: "3424f7856b971a2ce94d22be3a3abfb5b9b5984562fdedd621f4e67574be7254"
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "3.2.0"
|
version: "3.2.1"
|
||||||
vibration_platform_interface:
|
vibration_platform_interface:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@ -984,5 +984,5 @@ packages:
|
|||||||
source: hosted
|
source: hosted
|
||||||
version: "3.1.3"
|
version: "3.1.3"
|
||||||
sdks:
|
sdks:
|
||||||
dart: ">=3.12.2 <4.0.0"
|
dart: ">=3.13.0 <4.0.0"
|
||||||
flutter: ">=3.44.0"
|
flutter: ">=3.44.0"
|
||||||
|
|||||||
@ -24,7 +24,7 @@ dependencies:
|
|||||||
http: 1.6.0
|
http: 1.6.0
|
||||||
path: 1.9.1
|
path: 1.9.1
|
||||||
path_provider: 2.1.6
|
path_provider: 2.1.6
|
||||||
permission_handler: 13.0.1
|
permission_handler: 13.0.2
|
||||||
shared_preferences: 2.5.5
|
shared_preferences: 2.5.5
|
||||||
sqflite: 2.4.3
|
sqflite: 2.4.3
|
||||||
# Linux desktop has no sqflite plugin; the FFI factory drives the same
|
# Linux desktop has no sqflite plugin; the FFI factory drives the same
|
||||||
@ -37,7 +37,7 @@ dependencies:
|
|||||||
path: sync_settings_ui
|
path: sync_settings_ui
|
||||||
url_launcher: 6.3.2
|
url_launcher: 6.3.2
|
||||||
uuid: 4.6.0
|
uuid: 4.6.0
|
||||||
vibration: 3.2.0
|
vibration: 3.2.1
|
||||||
|
|
||||||
dev_dependencies:
|
dev_dependencies:
|
||||||
audioplayers_platform_interface: 7.2.0
|
audioplayers_platform_interface: 7.2.0
|
||||||
@ -47,7 +47,7 @@ dev_dependencies:
|
|||||||
flutter_lints: ^6.0.0
|
flutter_lints: ^6.0.0
|
||||||
flutter_test:
|
flutter_test:
|
||||||
sdk: flutter
|
sdk: flutter
|
||||||
very_good_analysis: ^10.3.0
|
very_good_analysis: ^11.0.0
|
||||||
|
|
||||||
flutter:
|
flutter:
|
||||||
uses-material-design: true
|
uses-material-design: true
|
||||||
|
|||||||
688
web/package-lock.json
generated
688
web/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -22,20 +22,20 @@
|
|||||||
"@testing-library/dom": "10.4.1",
|
"@testing-library/dom": "10.4.1",
|
||||||
"@testing-library/jest-dom": "7.0.1",
|
"@testing-library/jest-dom": "7.0.1",
|
||||||
"@testing-library/react": "16.3.3",
|
"@testing-library/react": "16.3.3",
|
||||||
"@testing-library/user-event": "14.6.6",
|
"@testing-library/user-event": "14.6.7",
|
||||||
"@types/node": "26.4.0",
|
"@types/node": "26.4.1",
|
||||||
"@types/react": "19.2.18",
|
"@types/react": "19.2.18",
|
||||||
"@types/react-dom": "19.2.5",
|
"@types/react-dom": "19.2.7",
|
||||||
"@vitejs/plugin-react": "6.1.1",
|
"@vitejs/plugin-react": "6.1.1",
|
||||||
"@vitest/coverage-v8": "4.1.11",
|
"@vitest/coverage-v8": "5.0.0",
|
||||||
"eslint": "10.9.1",
|
"eslint": "10.10.0",
|
||||||
"eslint-plugin-react-hooks": "7.1.1",
|
"eslint-plugin-react-hooks": "7.1.1",
|
||||||
"eslint-plugin-react-refresh": "0.5.5",
|
"eslint-plugin-react-refresh": "0.5.6",
|
||||||
"globals": "17.11.0",
|
"globals": "17.12.0",
|
||||||
"jsdom": "30.0.1",
|
"jsdom": "30.0.1",
|
||||||
"typescript": "6.0.3",
|
"typescript": "6.0.3",
|
||||||
"typescript-eslint": "8.68.0",
|
"typescript-eslint": "8.69.0",
|
||||||
"vite": "8.2.2",
|
"vite": "8.2.2",
|
||||||
"vitest": "4.1.11"
|
"vitest": "5.0.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user