fishin 0.2.2__tar.gz → 0.3.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: fishin
3
- Version: 0.2.2
3
+ Version: 0.3.2
4
4
  Summary: Terminal solunar, tide, and weather forecast for the fishing / hunting day-planner crowd
5
5
  Author: Steve Wasko
6
6
  License-Expression: MIT
@@ -25,12 +25,19 @@ Requires-Dist: rich>=13
25
25
  Requires-Dist: skyfield>=1.45
26
26
  Requires-Dist: timezonefinder>=6
27
27
  Requires-Dist: tzdata>=2024.1
28
+ Provides-Extra: dev
29
+ Requires-Dist: pytest>=8; extra == 'dev'
28
30
  Description-Content-Type: text/markdown
29
31
 
30
32
  # fishin
31
33
 
34
+ [![Sponsor](https://img.shields.io/badge/Sponsor-%E2%9D%A4-db61a2?logo=githubsponsors&logoColor=white)](https://github.com/sponsors/sjwasko)
35
+ [![Buy me a coffee](https://img.shields.io/badge/Buy%20me%20a%20coffee-ffdd00?logo=buymeacoffee&logoColor=black)](https://buymeacoffee.com/sutibu)
36
+
32
37
  Terminal solunar, tide, and weather forecast — one command, full picture, btop-dense layout.
33
38
 
39
+ ![Day view panel for Sarasota, FL](docs/screenshots/day-panel.png)
40
+
34
41
  `fishin` rolls a solunar app, a tide app (xtides-style), and `wttr.in` into a single
35
42
  terminal panel. Solunar major/minor periods, sun/moon ephemera, NOAA tide
36
43
  predictions, open-meteo weather, and a per-day "best fishing window" cross-correlation
@@ -52,7 +59,7 @@ Requires Python ≥ 3.11. Works on Linux, macOS, and Windows
52
59
  (see [Windows note](#windows) below).
53
60
 
54
61
  First run downloads the JPL DE421 ephemeris (~17 MB) into `~/.cache/fishin/ephemeris/`.
55
- NOAA, open-meteo, and Nominatim responses are cached at `~/.cache/fishin/responses/`.
62
+ NOAA, open-meteo, and Nominatim responses are cached at `~/.cache/fishin/responses-v2/`.
56
63
 
57
64
  ### Windows
58
65
 
@@ -121,8 +128,33 @@ fishin --no-tides --no-weather # astro-only, no network
121
128
  | `fishin best N` | Next N days sorted by score, top 5 highlighted |
122
129
  | `fishin --days N` | Legacy: render N full panels back-to-back |
123
130
 
131
+ `N` must be a whole number of at least 1; anything else (`fishin 0`,
132
+ `fishin best abc`) exits with a short error message.
133
+
124
134
  Skip network fetches with `--no-tides` / `--no-weather` (e.g. offline or for quick recompute).
125
135
 
136
+ Weather comes from open-meteo's free forecast, which covers today plus the next
137
+ 15 days (and about 3 months back). Days outside that window still get solunar
138
+ and tides; a dim `weather forecast ends <date>` line notes where weather stops.
139
+
140
+ ## Views
141
+
142
+ ### Day panel
143
+
144
+ ![](docs/screenshots/day-panel.png)
145
+
146
+ ### 7-day list
147
+
148
+ ![](docs/screenshots/list-7day.png)
149
+
150
+ ### Month grid
151
+
152
+ ![](docs/screenshots/month-grid.png)
153
+
154
+ ### Best 14 days, ranked
155
+
156
+ ![](docs/screenshots/best-14.png)
157
+
126
158
  ## Configuration
127
159
 
128
160
  The easy path is `fishin --city "..." --save` (described above). If you'd
@@ -138,6 +170,11 @@ station = "8726083"
138
170
 
139
171
  Resolution order: explicit flags > `--city` > config file > built-in default.
140
172
 
173
+ `tz` must be an IANA zone name such as `America/Chicago`. An unknown zone
174
+ (from `--tz` or the config file) stops `fishin` with an error before anything
175
+ is saved, so `--tz Typo/Zone --save` leaves your existing config untouched.
176
+ If the file itself holds a bad zone, fix that line or override it with `--tz`.
177
+
141
178
  ## How the "Best" ranking works
142
179
 
143
180
  Every major/minor period is scored:
@@ -193,6 +230,11 @@ The visual language and information density of `fishin` borrow shamelessly from:
193
230
 
194
231
  None of these projects are affiliated with `fishin`; we just learned from them.
195
232
 
233
+ ## A note on the name
234
+
235
+ Because that's how Karrie says it. The `g` got left somewhere in the
236
+ South and we never went lookin' for it.
237
+
196
238
  ## License
197
239
 
198
240
  [MIT](LICENSE). Fork, improve, redistribute — just keep the copyright notice.
@@ -1,7 +1,12 @@
1
1
  # fishin
2
2
 
3
+ [![Sponsor](https://img.shields.io/badge/Sponsor-%E2%9D%A4-db61a2?logo=githubsponsors&logoColor=white)](https://github.com/sponsors/sjwasko)
4
+ [![Buy me a coffee](https://img.shields.io/badge/Buy%20me%20a%20coffee-ffdd00?logo=buymeacoffee&logoColor=black)](https://buymeacoffee.com/sutibu)
5
+
3
6
  Terminal solunar, tide, and weather forecast — one command, full picture, btop-dense layout.
4
7
 
8
+ ![Day view panel for Sarasota, FL](docs/screenshots/day-panel.png)
9
+
5
10
  `fishin` rolls a solunar app, a tide app (xtides-style), and `wttr.in` into a single
6
11
  terminal panel. Solunar major/minor periods, sun/moon ephemera, NOAA tide
7
12
  predictions, open-meteo weather, and a per-day "best fishing window" cross-correlation
@@ -23,7 +28,7 @@ Requires Python ≥ 3.11. Works on Linux, macOS, and Windows
23
28
  (see [Windows note](#windows) below).
24
29
 
25
30
  First run downloads the JPL DE421 ephemeris (~17 MB) into `~/.cache/fishin/ephemeris/`.
26
- NOAA, open-meteo, and Nominatim responses are cached at `~/.cache/fishin/responses/`.
31
+ NOAA, open-meteo, and Nominatim responses are cached at `~/.cache/fishin/responses-v2/`.
27
32
 
28
33
  ### Windows
29
34
 
@@ -92,8 +97,33 @@ fishin --no-tides --no-weather # astro-only, no network
92
97
  | `fishin best N` | Next N days sorted by score, top 5 highlighted |
93
98
  | `fishin --days N` | Legacy: render N full panels back-to-back |
94
99
 
100
+ `N` must be a whole number of at least 1; anything else (`fishin 0`,
101
+ `fishin best abc`) exits with a short error message.
102
+
95
103
  Skip network fetches with `--no-tides` / `--no-weather` (e.g. offline or for quick recompute).
96
104
 
105
+ Weather comes from open-meteo's free forecast, which covers today plus the next
106
+ 15 days (and about 3 months back). Days outside that window still get solunar
107
+ and tides; a dim `weather forecast ends <date>` line notes where weather stops.
108
+
109
+ ## Views
110
+
111
+ ### Day panel
112
+
113
+ ![](docs/screenshots/day-panel.png)
114
+
115
+ ### 7-day list
116
+
117
+ ![](docs/screenshots/list-7day.png)
118
+
119
+ ### Month grid
120
+
121
+ ![](docs/screenshots/month-grid.png)
122
+
123
+ ### Best 14 days, ranked
124
+
125
+ ![](docs/screenshots/best-14.png)
126
+
97
127
  ## Configuration
98
128
 
99
129
  The easy path is `fishin --city "..." --save` (described above). If you'd
@@ -109,6 +139,11 @@ station = "8726083"
109
139
 
110
140
  Resolution order: explicit flags > `--city` > config file > built-in default.
111
141
 
142
+ `tz` must be an IANA zone name such as `America/Chicago`. An unknown zone
143
+ (from `--tz` or the config file) stops `fishin` with an error before anything
144
+ is saved, so `--tz Typo/Zone --save` leaves your existing config untouched.
145
+ If the file itself holds a bad zone, fix that line or override it with `--tz`.
146
+
112
147
  ## How the "Best" ranking works
113
148
 
114
149
  Every major/minor period is scored:
@@ -164,6 +199,11 @@ The visual language and information density of `fishin` borrow shamelessly from:
164
199
 
165
200
  None of these projects are affiliated with `fishin`; we just learned from them.
166
201
 
202
+ ## A note on the name
203
+
204
+ Because that's how Karrie says it. The `g` got left somewhere in the
205
+ South and we never went lookin' for it.
206
+
167
207
  ## License
168
208
 
169
209
  [MIT](LICENSE). Fork, improve, redistribute — just keep the copyright notice.
@@ -1,3 +1,3 @@
1
1
  """fishin — terminal solunar, tide & weather forecast."""
2
2
 
3
- __version__ = "0.2.2"
3
+ __version__ = "0.3.2"
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
@@ -0,0 +1,84 @@
1
+ """Disk-backed response cache for tide & weather fetches.
2
+
3
+ `diskcache` gives us a per-entry-TTL shelf with zero ceremony. By default it
4
+ serializes values with **pickle**, which would let a local actor who can write
5
+ to `~/.cache/fishin/` craft a malicious blob and gain arbitrary code execution
6
+ on the next run. We avoid that by passing a JSON-based `Disk` subclass —
7
+ JSON is data-only, no eval surface.
8
+
9
+ Cached values nest `datetime` objects (tide events, weather samples). The
10
+ custom `FishinDisk` round-trips those via a `{"__dt__": iso}` tag so the rest
11
+ of the codebase keeps receiving real datetimes.
12
+
13
+ Tide predictions are deterministic and cached for a year; weather forecasts
14
+ get 1h for today/future and a long TTL for past dates (forecasts freeze).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import os
21
+ from datetime import date, datetime
22
+ from functools import lru_cache
23
+ from pathlib import Path
24
+
25
+ import diskcache
26
+ from diskcache import UNKNOWN
27
+
28
+
29
+ YEAR_SECONDS = 365 * 24 * 3600
30
+ HOUR_SECONDS = 3600
31
+
32
+ # Directory bumped from `responses` → `responses-v2` so existing pickle-backed
33
+ # caches from 0.2.x don't trip JSON deserialization on first read after
34
+ # upgrade. The old directory is harmless; users can `rm -rf` it at leisure.
35
+ _CACHE_SUBDIR = "responses-v2"
36
+
37
+
38
+ def _cache_dir() -> Path:
39
+ base = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache"))
40
+ return base / "fishin" / _CACHE_SUBDIR
41
+
42
+
43
+ def _encode_dt(obj):
44
+ if isinstance(obj, datetime):
45
+ return {"__dt__": obj.isoformat()}
46
+ raise TypeError(f"not JSON serializable: {type(obj).__name__}")
47
+
48
+
49
+ def _decode_dt(obj: dict):
50
+ if len(obj) == 1 and "__dt__" in obj:
51
+ return datetime.fromisoformat(obj["__dt__"])
52
+ return obj
53
+
54
+
55
+ class FishinDisk(diskcache.Disk):
56
+ """JSON-serializing Disk that preserves datetime objects.
57
+
58
+ Overrides only the value-side serialization (store/fetch). Keys remain
59
+ handled by the parent class (they're plain strings in our usage).
60
+ """
61
+
62
+ def store(self, value, read, key=UNKNOWN):
63
+ if not read:
64
+ value = json.dumps(value, default=_encode_dt).encode("utf-8")
65
+ return super().store(value, read, key=key)
66
+
67
+ def fetch(self, mode, filename, value, read):
68
+ data = super().fetch(mode, filename, value, read)
69
+ if not read and isinstance(data, (bytes, bytearray)):
70
+ return json.loads(data.decode("utf-8"), object_hook=_decode_dt)
71
+ return data
72
+
73
+
74
+ @lru_cache(maxsize=1)
75
+ def get_cache() -> diskcache.Cache:
76
+ path = _cache_dir()
77
+ path.mkdir(parents=True, exist_ok=True)
78
+ return diskcache.Cache(str(path), disk=FishinDisk)
79
+
80
+
81
+ def weather_ttl(target_date: date) -> int:
82
+ """Past dates: forecast no longer updates, cache effectively forever.
83
+ Today/future: hourly model run, so 1h TTL keeps things fresh."""
84
+ return YEAR_SECONDS if target_date < date.today() else HOUR_SECONDS
@@ -20,14 +20,14 @@ from __future__ import annotations
20
20
  import argparse
21
21
  import calendar
22
22
  from datetime import datetime, timedelta, date
23
- from zoneinfo import ZoneInfo
23
+ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
24
24
 
25
25
  from rich.console import Console
26
26
 
27
27
  from .astro import build_day, evaluate_windows
28
28
  from .render import render_day, render_list, render_month, render_best
29
29
  from .tides import DEFAULT_STATION, get_tides_many, tide_curve
30
- from .weather import get_weather_many
30
+ from .weather import forecast_window, get_weather_many
31
31
  from .config import load_config, save_config, config_path
32
32
 
33
33
 
@@ -81,20 +81,37 @@ def _resolve_city(query: str, console: Console) -> dict:
81
81
  return result
82
82
 
83
83
 
84
+ def _day_count(token: str, what: str) -> int:
85
+ """Parse a day count for `what`, rejecting non-integers and N < 1.
86
+
87
+ Every view indexes its first/last target day, so an empty range would
88
+ crash downstream — refuse it here with a readable message instead.
89
+ """
90
+ try:
91
+ n = int(token)
92
+ except ValueError as exc:
93
+ raise SystemExit(f"{what}: expected a whole number of days, "
94
+ f"got {token!r}") from exc
95
+ if n < 1:
96
+ raise SystemExit(f"{what}: number of days must be at least 1, got {n}")
97
+ return n
98
+
99
+
84
100
  def _parse_mode(tokens: list[str], legacy_days: int) -> dict:
85
101
  if not tokens:
86
- return {"type": "panel", "days": legacy_days}
102
+ return {"type": "panel",
103
+ "days": _day_count(str(legacy_days), "--days")}
87
104
  first = tokens[0].lower()
88
105
  if first == "month":
89
106
  return {"type": "month"}
90
107
  if first == "best":
91
- n = int(tokens[1]) if len(tokens) > 1 else 14
108
+ n = _day_count(tokens[1], "best") if len(tokens) > 1 else 14
92
109
  return {"type": "best", "days": n, "top": 5}
93
110
  try:
94
- n = int(first)
111
+ int(first)
95
112
  except ValueError as exc:
96
113
  raise SystemExit(f"unknown mode {first!r}") from exc
97
- return {"type": "list", "days": n}
114
+ return {"type": "list", "days": _day_count(first, "list")}
98
115
 
99
116
 
100
117
  def _build_days(loc: dict, tz: ZoneInfo, targets: list[date],
@@ -150,6 +167,18 @@ def _build_days(loc: dict, tz: ZoneInfo, targets: list[date],
150
167
  return days
151
168
 
152
169
 
170
+ def _print_weather_note(targets: list[date], tz: ZoneInfo, *,
171
+ want_weather: bool, console: Console) -> None:
172
+ """Explain missing weather on days outside open-meteo's window."""
173
+ if not want_weather:
174
+ return
175
+ first, last = forecast_window(tz)
176
+ if targets[-1] > last:
177
+ console.print(f"[dim]weather forecast ends {last:%b} {last.day}[/dim]")
178
+ elif targets[0] < first:
179
+ console.print(f"[dim]weather history starts {first:%b} {first.day}[/dim]")
180
+
181
+
153
182
  _EPILOG = """\
154
183
  Examples:
155
184
  fishin --city "your town st" --save set your default location once
@@ -222,12 +251,23 @@ def main(argv: list[str] | None = None) -> int:
222
251
  if v is not None:
223
252
  loc[key] = v
224
253
 
254
+ # Validate before saving: a bad zone written to config.toml would make
255
+ # every later run fail until the file was hand-edited.
256
+ try:
257
+ tz = ZoneInfo(loc["tz"])
258
+ except (ZoneInfoNotFoundError, ValueError):
259
+ console.print(f"[red]unknown timezone {loc['tz']!r} — use an IANA "
260
+ f"name like 'America/Chicago'[/red]")
261
+ if not args.tz:
262
+ console.print(f"[dim]fix or remove the tz line in "
263
+ f"{config_path()}, or pass --tz[/dim]")
264
+ return 1
265
+ mode = _parse_mode(args.mode, args.days)
266
+
225
267
  if args.save:
226
268
  path = save_config(loc)
227
269
  console.print(f"[dim]saved → {path}[/dim]")
228
270
 
229
- tz = ZoneInfo(loc["tz"])
230
- mode = _parse_mode(args.mode, args.days)
231
271
  want_tides = not args.no_tides
232
272
  want_weather = not args.no_weather
233
273
 
@@ -261,6 +301,7 @@ def _run_panel(loc, tz, start_date, days, *,
261
301
  for i, day in enumerate(built):
262
302
  day["trend"] = trend_scores[i:i + 7]
263
303
  render_day(day, loc["location"], console=console)
304
+ _print_weather_note(targets, tz, want_weather=want_weather, console=console)
264
305
 
265
306
 
266
307
  def _run_list(loc, tz, start_date, days, *,
@@ -270,6 +311,7 @@ def _run_list(loc, tz, start_date, days, *,
270
311
  want_tides=want_tides, want_weather=want_weather,
271
312
  console=console)
272
313
  render_list(built, loc["location"], console=console)
314
+ _print_weather_note(targets, tz, want_weather=want_weather, console=console)
273
315
 
274
316
 
275
317
  def _run_month(loc, ref_date, *, console):
@@ -288,6 +330,7 @@ def _run_best(loc, tz, start_date, days, top, *,
288
330
  want_tides=want_tides, want_weather=want_weather,
289
331
  console=console)
290
332
  render_best(built, loc["location"], top_n=top, console=console)
333
+ _print_weather_note(targets, tz, want_weather=want_weather, console=console)
291
334
 
292
335
 
293
336
  def cli_main() -> None:
@@ -14,6 +14,18 @@ from pathlib import Path
14
14
 
15
15
  _VALID_KEYS = {"location", "lat", "lon", "tz", "station"}
16
16
 
17
+ # TOML basic-string escapes per https://toml.io/en/v1.0.0#string. Backslash
18
+ # must come first or it'll re-escape the escapes we just added.
19
+ _TOML_ESCAPES = [
20
+ ("\\", "\\\\"),
21
+ ('"', '\\"'),
22
+ ("\b", "\\b"),
23
+ ("\t", "\\t"),
24
+ ("\n", "\\n"),
25
+ ("\f", "\\f"),
26
+ ("\r", "\\r"),
27
+ ]
28
+
17
29
 
18
30
  def config_path() -> Path:
19
31
  base = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"))
@@ -29,6 +41,23 @@ def load_config(path: Path | None = None) -> dict:
29
41
  return {k: v for k, v in data.items() if k in _VALID_KEYS}
30
42
 
31
43
 
44
+ def _toml_escape(s: str) -> str:
45
+ """Escape a string for a TOML basic-string literal.
46
+
47
+ Covers backslash, double-quote, and the common control characters
48
+ (\\b \\t \\n \\f \\r). Other C0 controls are encoded as \\uXXXX so the
49
+ resulting file is always parseable by tomllib — a stray newline in a
50
+ geocoded display name would otherwise corrupt the config.
51
+ """
52
+ out = s
53
+ for raw, esc in _TOML_ESCAPES:
54
+ out = out.replace(raw, esc)
55
+ return "".join(
56
+ ch if ord(ch) >= 0x20 or ch in "\t" else f"\\u{ord(ch):04X}"
57
+ for ch in out
58
+ )
59
+
60
+
32
61
  def save_config(values: dict, path: Path | None = None) -> Path:
33
62
  path = path or config_path()
34
63
  path.parent.mkdir(parents=True, exist_ok=True)
@@ -37,10 +66,9 @@ def save_config(values: dict, path: Path | None = None) -> Path:
37
66
  if key not in values or values[key] is None:
38
67
  continue
39
68
  v = values[key]
40
- if isinstance(v, (int, float)):
69
+ if isinstance(v, (int, float)) and not isinstance(v, bool):
41
70
  lines.append(f"{key} = {v}")
42
71
  else:
43
- escaped = str(v).replace("\\", "\\\\").replace('"', '\\"')
44
- lines.append(f'{key} = "{escaped}"')
72
+ lines.append(f'{key} = "{_toml_escape(str(v))}"')
45
73
  path.write_text("\n".join(lines) + "\n")
46
74
  return path
@@ -70,7 +70,8 @@ def nearest_station(lat: float, lon: float, refresh: bool = False) -> dict:
70
70
  stations = load_stations(refresh=refresh)
71
71
  if not stations:
72
72
  raise LookupError("no NOAA stations available")
73
- best = min(stations, key=lambda s: haversine_km(lat, lon, s["lat"], s["lng"]))
74
- best = dict(best)
75
- best["distance_km"] = haversine_km(lat, lon, best["lat"], best["lng"])
76
- return best
73
+ distance, _, best = min(
74
+ (haversine_km(lat, lon, s["lat"], s["lng"]), i, s)
75
+ for i, s in enumerate(stations)
76
+ )
77
+ return {**best, "distance_km": distance}
@@ -66,12 +66,6 @@ def fetch_predictions_range(station: str, start_date: date, end_date: date,
66
66
  return events
67
67
 
68
68
 
69
- def fetch_predictions(station: str, target_date: date, tz: ZoneInfo,
70
- timeout: float = 10.0) -> list[dict]:
71
- """Single-day shim around `fetch_predictions_range`."""
72
- return fetch_predictions_range(station, target_date, target_date, tz, timeout)
73
-
74
-
75
69
  def _cache_key(station: str, d: date) -> str:
76
70
  return f"tide:{station}:{d.isoformat()}"
77
71
 
@@ -110,26 +104,6 @@ def get_tides_many(station: str, dates: list[date], tz: ZoneInfo,
110
104
  return results
111
105
 
112
106
 
113
- def get_tide_day(station: str, target_date: date, tz: ZoneInfo,
114
- cache=None) -> tuple[list[dict], list[dict]]:
115
- """Return (target_day_events, neighbor_context).
116
-
117
- `neighbor_context` holds the prior day's last extremum and the next day's
118
- first extremum so `tide_curve()` can anchor the start/end of the rendered
119
- curve rather than extrapolating flat.
120
- """
121
- from datetime import timedelta as _td
122
- prior = target_date - _td(days=1)
123
- after = target_date + _td(days=1)
124
- days = get_tides_many(station, [prior, target_date, after], tz, cache=cache)
125
- context: list[dict] = []
126
- if days.get(prior):
127
- context.append(days[prior][-1])
128
- if days.get(after):
129
- context.append(days[after][0])
130
- return days[target_date], context
131
-
132
-
133
107
  def tide_curve(events: list[dict], target_date: date, tz: ZoneInfo,
134
108
  n_points: int = 48,
135
109
  context: list[dict] | None = None) -> list[float]:
@@ -19,6 +19,14 @@ from zoneinfo import ZoneInfo
19
19
 
20
20
  OPENMETEO_URL = "https://api.open-meteo.com/v1/forecast"
21
21
 
22
+ # open-meteo's free forecast endpoint only serves a sliding window of dates:
23
+ # `forecast_days` tops out at 16 (today + 15) and `past_days` at 92. Asking for
24
+ # any date outside it fails the *whole* request with HTTP 400, so we clamp to
25
+ # the window and let out-of-range days go without weather.
26
+ # https://open-meteo.com/en/docs
27
+ FORECAST_DAYS = 16
28
+ PAST_DAYS = 92
29
+
22
30
  # WMO weather code → (label, day glyph, night glyph).
23
31
  # Glyphs lean monochrome / text-style to stay close to wttr.in / btop tone.
24
32
  WEATHER_CODES: dict[int, tuple[str, str, str]] = {
@@ -66,14 +74,32 @@ def hpa_to_inhg(hpa: float) -> float:
66
74
  return hpa * 0.02953
67
75
 
68
76
 
77
+ def forecast_window(tz: ZoneInfo, now: datetime | None = None) -> tuple[date, date]:
78
+ """First and last dates open-meteo will serve, inclusive.
79
+
80
+ "Today" differs between the target timezone and UTC near midnight, and we
81
+ don't know which one open-meteo anchors on, so take the narrower window.
82
+ """
83
+ now = now or datetime.now(ZoneInfo("UTC"))
84
+ local, utc = now.astimezone(tz).date(), now.astimezone(ZoneInfo("UTC")).date()
85
+ first = max(local, utc) - timedelta(days=PAST_DAYS)
86
+ last = min(local, utc) + timedelta(days=FORECAST_DAYS - 1)
87
+ return first, last
88
+
89
+
69
90
  def fetch_weather_range(lat: float, lon: float,
70
91
  start_date: date, end_date: date, tz: ZoneInfo,
71
92
  timeout: float = 10.0) -> dict:
72
- """One open-meteo request for [start_date, end_date + 1] inclusive.
93
+ """One open-meteo request for [start_date, end_date + 1] inclusive,
94
+ clamped to the forecast window.
73
95
 
74
96
  The trailing +1 day ensures the last in-range day's midnight "Night"
75
- sample (hour 0 of next day) is present.
97
+ sample (hour 0 of next day) is present. On the window's last day it isn't,
98
+ so that day comes back with Morn/Noon/Eve only.
76
99
  """
100
+ first, last = forecast_window(tz)
101
+ req_start = max(start_date, first)
102
+ req_end = min(end_date + timedelta(days=1), last)
77
103
  params = {
78
104
  "latitude": f"{lat}",
79
105
  "longitude": f"{lon}",
@@ -98,8 +124,8 @@ def fetch_weather_range(lat: float, lon: float,
98
124
  "precipitation_sum",
99
125
  "precipitation_probability_max",
100
126
  ]),
101
- "start_date": start_date.isoformat(),
102
- "end_date": (end_date + timedelta(days=1)).isoformat(),
127
+ "start_date": req_start.isoformat(),
128
+ "end_date": req_end.isoformat(),
103
129
  }
104
130
  url = f"{OPENMETEO_URL}?{urllib.parse.urlencode(params)}"
105
131
  with urllib.request.urlopen(url, timeout=timeout) as resp:
@@ -156,24 +182,23 @@ def _cache_key(lat: float, lon: float, d: date) -> str:
156
182
  return f"wx:{lat:.4f}:{lon:.4f}:{d.isoformat()}"
157
183
 
158
184
 
159
- def fetch_weather(lat: float, lon: float, target_date: date, tz: ZoneInfo,
160
- timeout: float = 10.0) -> dict:
161
- """Single-day shim around the range fetcher."""
162
- raw = fetch_weather_range(lat, lon, target_date, target_date, tz, timeout)
163
- return _day_from_raw(raw, target_date, tz)
164
-
165
-
166
185
  def get_weather_many(lat: float, lon: float, dates: list[date],
167
186
  tz: ZoneInfo, cache=None) -> dict[date, dict]:
168
- """Return {date: per_day_dict} for each requested date, using the cache.
187
+ """Return {date: per_day_dict} for each requested date open-meteo covers,
188
+ using the cache.
169
189
 
170
- Cache misses are coalesced into one open-meteo call, then split per-day."""
190
+ Dates outside `forecast_window` are left out of the result (not cached
191
+ as empty, so they pick up weather once they come into range). Cache
192
+ misses are coalesced into one open-meteo call, then split per-day."""
171
193
  from .cache import get_cache, weather_ttl
172
- cache = cache or get_cache()
194
+ cache = cache if cache is not None else get_cache()
173
195
 
196
+ first, last = forecast_window(tz)
174
197
  results: dict[date, dict] = {}
175
198
  missing: list[date] = []
176
199
  for d in dates:
200
+ if not first <= d <= last:
201
+ continue
177
202
  hit = cache.get(_cache_key(lat, lon, d), default=None)
178
203
  if hit is not None:
179
204
  results[d] = hit
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "fishin"
7
- version = "0.2.2"
7
+ version = "0.3.2"
8
8
  description = "Terminal solunar, tide, and weather forecast for the fishing / hunting day-planner crowd"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -37,6 +37,9 @@ dependencies = [
37
37
  "tzdata>=2024.1",
38
38
  ]
39
39
 
40
+ [project.optional-dependencies]
41
+ dev = ["pytest>=8"]
42
+
40
43
  [project.scripts]
41
44
  fishin = "fishin.cli:cli_main"
42
45
 
@@ -45,3 +48,6 @@ packages = ["fishin"]
45
48
 
46
49
  [tool.hatch.build.targets.sdist]
47
50
  include = ["fishin", "README.md"]
51
+
52
+ [tool.pytest.ini_options]
53
+ testpaths = ["tests"]
@@ -1,3 +0,0 @@
1
- from .cli import main
2
-
3
- raise SystemExit(main())
@@ -1,37 +0,0 @@
1
- """Disk-backed response cache for tide & weather fetches.
2
-
3
- `diskcache` gives us a pickle-backed shelf with per-entry TTLs and zero ceremony.
4
- Tide predictions are deterministic and cached for a year; weather forecasts get
5
- 1h for today/future and a long TTL for past dates (forecasts no longer update).
6
- """
7
-
8
- from __future__ import annotations
9
-
10
- import os
11
- from datetime import date
12
- from functools import lru_cache
13
- from pathlib import Path
14
-
15
- import diskcache
16
-
17
-
18
- YEAR_SECONDS = 365 * 24 * 3600
19
- HOUR_SECONDS = 3600
20
-
21
-
22
- def _cache_dir() -> Path:
23
- base = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache"))
24
- return base / "fishin" / "responses"
25
-
26
-
27
- @lru_cache(maxsize=1)
28
- def get_cache() -> diskcache.Cache:
29
- path = _cache_dir()
30
- path.mkdir(parents=True, exist_ok=True)
31
- return diskcache.Cache(str(path))
32
-
33
-
34
- def weather_ttl(target_date: date) -> int:
35
- """Past dates: forecast no longer updates, cache effectively forever.
36
- Today/future: hourly model run, so 1h TTL keeps things fresh."""
37
- return YEAR_SECONDS if target_date < date.today() else HOUR_SECONDS
File without changes
File without changes
File without changes
File without changes
File without changes