Files

73 lines
3.1 KiB
Python
Executable File

#!/usr/bin/env python3
# pomodoro - pomodoro timer with work/break cycles and a session log
# Usage: pomodoro [--work MIN] [--break MIN] [--cycles N] [--log FILE] [--no-log]
# Runs work/break cycles with a live countdown; each completed work block is
# appended to the session log (default ~/.local/share/fileutils/pomodoro.log).
import argparse, os, sys, time
from datetime import datetime
DEFAULT_LOG = os.path.expanduser("~/.local/share/fileutils/pomodoro.log")
def run_phase(label, seconds):
end = time.monotonic() + seconds
try:
while True:
left = end - time.monotonic()
if left <= 0:
print(f"\r{label}: done!{' ' * 20}")
return
m, s = divmod(int(left), 60)
print(f"\r{label}: {m:02d}:{s:02d} remaining", end="", flush=True)
time.sleep(min(1.0, max(0.05, left)))
except KeyboardInterrupt:
print(f"\n{label} interrupted")
raise
def selftest():
import tempfile
with tempfile.TemporaryDirectory() as d:
log = os.path.join(d, "pomodoro.log")
t0 = time.monotonic()
run_phase("work (selftest)", 0.5)
run_phase("break (selftest)", 0.5)
with open(log, "a") as f:
f.write(f"{datetime.now():%Y-%m-%d %H:%M} work 1s (selftest)\n")
assert time.monotonic() - t0 >= 1.0
assert open(log).read().strip().endswith("(selftest)")
print("pomodoro selftest: ok (0.5s work + 0.5s break + log write)")
return 0
def main():
p = argparse.ArgumentParser(prog="pomodoro",
description="Pomodoro timer with work/break cycles and a session log.")
p.add_argument("--work", type=float, default=25, help="work minutes per cycle (default 25)")
p.add_argument("--break", dest="brk", type=float, default=5, help="break minutes (default 5)")
p.add_argument("--cycles", type=int, default=4, help="number of work cycles (default 4)")
p.add_argument("--log", default=DEFAULT_LOG, help="session log file")
p.add_argument("--no-log", action="store_true", help="do not write the session log")
p.add_argument("--selftest", action="store_true", help="run built-in checks and exit")
a = p.parse_args()
if a.selftest:
return selftest()
if a.work <= 0 or a.brk < 0 or a.cycles < 1:
print("pomodoro: --work must be > 0, --break >= 0, --cycles >= 1", file=sys.stderr)
return 2
try:
for c in range(1, a.cycles + 1):
run_phase(f"work {c}/{a.cycles}", a.work * 60)
if not a.no_log:
os.makedirs(os.path.dirname(a.log), exist_ok=True)
with open(a.log, "a") as f:
f.write(f"{datetime.now():%Y-%m-%d %H:%M} work {a.work:g}m cycle {c}/{a.cycles}\n")
print(f"work block {c}/{a.cycles} logged")
if c < a.cycles or True:
run_phase(f"break {c}/{a.cycles}", a.brk * 60)
print(f"pomodoro complete: {a.cycles} cycles ({a.cycles * a.work:g}m work)")
except KeyboardInterrupt:
print("pomodoro stopped early")
return 130
return 0
if __name__ == "__main__":
sys.exit(main())