#!/usr/bin/env python3
"""
fs_awake: wrapper around macOS `caffeinate` that takes a duration in hours
and prints a progress line each time the bar advances by one cell.
Disclaimer: This project was largely vibe-coded using Google Search's AI Mode.
[VER 1.261126.0 BY 4FIPS.COM, MIT-LICENSED, https://forums.4fips.com/viewtopic.php?t=6931]
Usage:
fs_awake <hours> [--quiet] [caffeinate-flags...]
Examples:
fs_awake 1.5 # 1h30m, print on every bar advance
fs_awake 2 -d # 2h, prevent display sleep
fs_awake 1 --quiet # 1h, no progress output
fs_awake 3 -d -m # 3h, prevent display + disk sleep
"""
from __future__ import annotations
import argparse
import shutil
import signal
import subprocess
import sys
import time
from datetime import datetime
BAR_WIDTH_DEFAULT = 30
BAR_FILL = "█"
BAR_EMPTY = "░"
def format_hms(seconds: int) -> str:
h, rem = divmod(max(seconds, 0), 3600)
m, s = divmod(rem, 60)
return f"{h:02d}:{m:02d}:{s:02d}"
def bar_filled_cells(fraction: float, width: int) -> int:
fraction = max(0.0, min(1.0, fraction))
return int(round(fraction * width))
def render_bar(filled: int, width: int) -> str:
return BAR_FILL * filled + BAR_EMPTY * (width - filled)
def parse_args() -> tuple[argparse.Namespace, list[str]]:
parser = argparse.ArgumentParser(
description="Run `caffeinate` for N hours; print a progress line each time the bar advances.",
)
parser.add_argument(
"hours",
type=float,
help="Duration in hours (e.g. 1, 0.5, 2.25).",
)
parser.add_argument(
"-q", "--quiet",
action="store_true",
help="Suppress progress output.",
)
args, extra = parser.parse_known_args()
if args.hours <= 0:
parser.error("hours must be a positive number")
return args, extra
def main() -> int:
args, extra_flags = parse_args()
total_seconds = int(round(args.hours * 3600))
cmd = ["caffeinate", "-t", str(total_seconds), *extra_flags]
try:
proc = subprocess.Popen(cmd)
except FileNotFoundError:
print("Error: `caffeinate` not found (this tool only runs on macOS).", file=sys.stderr)
return 127
start = time.time()
end_epoch = start + total_seconds
end_dt = datetime.fromtimestamp(end_epoch)
# Bar width fixed at startup so filled-cell counts are stable across ticks.
term_width = shutil.get_terminal_size((80, 20)).columns
bar_width = max(10, min(BAR_WIDTH_DEFAULT, term_width - 40))
flags_display = " ".join(extra_flags) if extra_flags else "<none>"
report_display = "on bar advance" if not args.quiet else "quiet"
print(f"☕ fs_awake active for {format_hms(total_seconds)} "
f"(PID {proc.pid}, flags: {flags_display}, reporting: {report_display})")
print(f" Ends at: {end_dt:%Y-%m-%d %H:%M:%S}")
def terminate(signum, frame):
if proc.poll() is None:
proc.terminate()
signal.signal(signal.SIGINT, terminate)
signal.signal(signal.SIGTERM, terminate)
def print_progress(remaining: int) -> None:
elapsed = total_seconds - remaining
fraction = elapsed / total_seconds if total_seconds > 0 else 1.0
filled = bar_filled_cells(fraction, bar_width)
percent = fraction * 100
bar = render_bar(filled, bar_width)
print(f"[{datetime.now():%H:%M:%S}] [{bar}] "
f"{percent:5.1f}% remaining: {format_hms(remaining)}",
flush=True)
# Time between bar-cell advances. round() matches the rendering threshold.
seconds_per_cell = total_seconds / bar_width
last_filled = -1
try:
while proc.poll() is None:
now = time.time()
remaining = int(end_epoch - now)
if remaining <= 0:
break
if not args.quiet:
elapsed = total_seconds - remaining
fraction = elapsed / total_seconds if total_seconds > 0 else 1.0
filled = bar_filled_cells(fraction, bar_width)
if filled != last_filled:
print_progress(remaining)
last_filled = filled
# Sleep until the next cell should fill (rendering uses round(),
# so a cell flips at (filled + 0.5) * seconds_per_cell elapsed).
next_flip_elapsed = (last_filled + 0.5) * seconds_per_cell
wait_for = max(1.0, next_flip_elapsed - (now - start))
wait_for = min(wait_for, remaining)
else:
wait_for = remaining
try:
proc.wait(timeout=wait_for)
except subprocess.TimeoutExpired:
continue
finally:
if proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
print(f"✅ Done - fs_awake finished at {datetime.now():%Y-%m-%d %H:%M:%S}")
return proc.returncode or 0
if __name__ == "__main__":
sys.exit(main())