station-appkit 1.2.0__tar.gz → 1.4.0__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.
Files changed (24) hide show
  1. {station_appkit-1.2.0 → station_appkit-1.4.0}/PKG-INFO +1 -1
  2. {station_appkit-1.2.0 → station_appkit-1.4.0}/pyproject.toml +1 -1
  3. {station_appkit-1.2.0 → station_appkit-1.4.0}/station_appkit/__init__.py +1 -1
  4. station_appkit-1.4.0/station_appkit/changelog.py +172 -0
  5. {station_appkit-1.2.0 → station_appkit-1.4.0}/station_appkit/macwindow.py +12 -0
  6. {station_appkit-1.2.0 → station_appkit-1.4.0}/station_appkit/updates.py +86 -8
  7. station_appkit-1.4.0/tests/test_changelog.py +91 -0
  8. {station_appkit-1.2.0 → station_appkit-1.4.0}/tests/test_macwindow.py +19 -0
  9. {station_appkit-1.2.0 → station_appkit-1.4.0}/tests/test_updates.py +66 -0
  10. {station_appkit-1.2.0 → station_appkit-1.4.0}/.gitignore +0 -0
  11. {station_appkit-1.2.0 → station_appkit-1.4.0}/LICENSE +0 -0
  12. {station_appkit-1.2.0 → station_appkit-1.4.0}/README.md +0 -0
  13. {station_appkit-1.2.0 → station_appkit-1.4.0}/station_appkit/applog.py +0 -0
  14. {station_appkit-1.2.0 → station_appkit-1.4.0}/station_appkit/login.py +0 -0
  15. {station_appkit-1.2.0 → station_appkit-1.4.0}/station_appkit/report.py +0 -0
  16. {station_appkit-1.2.0 → station_appkit-1.4.0}/station_appkit/selfupdate.py +0 -0
  17. {station_appkit-1.2.0 → station_appkit-1.4.0}/station_appkit/testing.py +0 -0
  18. {station_appkit-1.2.0 → station_appkit-1.4.0}/station_appkit/window.py +0 -0
  19. {station_appkit-1.2.0 → station_appkit-1.4.0}/tests/conftest.py +0 -0
  20. {station_appkit-1.2.0 → station_appkit-1.4.0}/tests/test_applog.py +0 -0
  21. {station_appkit-1.2.0 → station_appkit-1.4.0}/tests/test_login.py +0 -0
  22. {station_appkit-1.2.0 → station_appkit-1.4.0}/tests/test_report.py +0 -0
  23. {station_appkit-1.2.0 → station_appkit-1.4.0}/tests/test_selfupdate.py +0 -0
  24. {station_appkit-1.2.0 → station_appkit-1.4.0}/tests/test_window.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: station-appkit
3
- Version: 1.2.0
3
+ Version: 1.4.0
4
4
  Summary: Update check, self-updater and app window shared by Station Studio, Station Player and Station Server
5
5
  Project-URL: Homepage, https://github.com/raby/station-studio
6
6
  Project-URL: Repository, https://github.com/raby/station-studio
@@ -15,7 +15,7 @@ build-backend = "hatchling.build"
15
15
 
16
16
  [project]
17
17
  name = "station-appkit"
18
- version = "1.2.0"
18
+ version = "1.4.0"
19
19
  description = "Update check, self-updater and app window shared by Station Studio, Station Player and Station Server"
20
20
  readme = "README.md"
21
21
  license = { file = "LICENSE" }
@@ -9,7 +9,7 @@ from __future__ import annotations
9
9
 
10
10
  from dataclasses import dataclass, field
11
11
 
12
- __version__ = "1.2.0"
12
+ __version__ = "1.4.0"
13
13
 
14
14
  REPO = "raby/station-studio"
15
15
 
@@ -0,0 +1,172 @@
1
+ """Reading the apps' changelogs: CHANGELOG.md (Studio), player/CHANGELOG.md
2
+ and server/CHANGELOG.md, in Keep a Changelog's shape.
3
+
4
+ Each release is a `## [version] - date` heading, then an optional intro
5
+ paragraph, then bullets, optionally under `### Added`, `### Changed`,
6
+ `### Fixed` and the like. A bullet's wrapped lines are indented. Any
7
+ other `## ` heading (like "Earlier versions") ends the releases.
8
+
9
+ Used three ways: a release's notes on GitHub (`section`, by
10
+ scripts/release_notes.py), Station Server's Help › What's new (`parse`),
11
+ and what Update now says a new version brings (`whats_new`, from the
12
+ notes GitHub has).
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import re
17
+ from dataclasses import dataclass, field
18
+
19
+ _RELEASE = re.compile(r"^## \[(?P<version>[^\]]+)\](?:\s+-\s+(?P<date>\d{4}-\d{2}-\d{2}))?\s*$")
20
+ _LINK_DEF = re.compile(r"^\[[^\]]+\]:\s")
21
+
22
+
23
+ @dataclass
24
+ class Release:
25
+ version: str
26
+ date: str | None = None
27
+ intro: list[str] = field(default_factory=list)
28
+ # (heading, bullets); heading None for bullets with none above them.
29
+ groups: list[tuple[str | None, list[str]]] = field(default_factory=list)
30
+
31
+ @property
32
+ def items(self) -> list[str]:
33
+ return [item for _, items in self.groups for item in items]
34
+
35
+ def as_dict(self, plain_text: bool = True) -> dict:
36
+ tidy = plain if plain_text else (lambda s: s)
37
+ return {
38
+ "version": self.version,
39
+ "date": self.date,
40
+ "intro": [tidy(p) for p in self.intro],
41
+ "groups": [{"heading": h, "items": [tidy(i) for i in items]} for h, items in self.groups],
42
+ }
43
+
44
+
45
+ def parse(text: str) -> list[Release]:
46
+ """The releases in a changelog, newest first as written ("Unreleased"
47
+ included, under that name)."""
48
+ releases: list[Release] = []
49
+ current: Release | None = None
50
+ paragraph: list[str] = []
51
+ bullet: list[str] | None = None
52
+ fenced = False
53
+
54
+ def finish():
55
+ nonlocal paragraph, bullet
56
+ if current is not None:
57
+ if bullet is not None:
58
+ if not current.groups:
59
+ current.groups.append((None, []))
60
+ current.groups[-1][1].append(" ".join(bullet))
61
+ elif paragraph:
62
+ current.intro.append(" ".join(paragraph))
63
+ paragraph, bullet = [], None
64
+
65
+ for raw in text.splitlines():
66
+ line = raw.rstrip()
67
+ if line.lstrip().startswith("```"):
68
+ fenced = not fenced
69
+ continue
70
+ if fenced:
71
+ continue
72
+ head = _RELEASE.match(line)
73
+ if head:
74
+ finish()
75
+ current = Release(head["version"], head["date"])
76
+ releases.append(current)
77
+ continue
78
+ if line.startswith("## ") or line.startswith("# "):
79
+ finish()
80
+ current = None
81
+ continue
82
+ if current is None or _LINK_DEF.match(line):
83
+ continue
84
+ if line.startswith("### "):
85
+ finish()
86
+ current.groups.append((line[4:].strip(), []))
87
+ elif line.startswith(("- ", "* ")):
88
+ finish()
89
+ bullet = [line[2:].strip()]
90
+ elif not line.strip():
91
+ finish()
92
+ elif bullet is not None and raw.startswith((" ", "\t")):
93
+ bullet.append(line.strip())
94
+ elif bullet is not None:
95
+ finish()
96
+ paragraph = [line.strip()]
97
+ else:
98
+ paragraph.append(line.strip())
99
+ finish()
100
+ return releases
101
+
102
+
103
+ def find(text: str, version: str) -> Release | None:
104
+ return next((r for r in parse(text) if r.version == version), None)
105
+
106
+
107
+ def _unwrap(lines: list[str]) -> list[str]:
108
+ """Markdown with each paragraph and bullet on one line: GitHub shows a
109
+ release's notes with every line break kept, so a changelog's wrapped
110
+ lines would break mid-sentence there. Headings, blank lines and code
111
+ blocks stay as they are."""
112
+ out: list[str] = []
113
+ joinable = False # the last line out is text a wrapped line continues
114
+ fenced = False
115
+ for line in lines:
116
+ stripped = line.strip()
117
+ if stripped.startswith("```"):
118
+ fenced = not fenced
119
+ out.append(line)
120
+ joinable = False
121
+ elif fenced or not stripped or stripped.startswith("#") or _LINK_DEF.match(stripped):
122
+ out.append(line)
123
+ joinable = False
124
+ elif stripped.startswith(("- ", "* ")) or not joinable:
125
+ out.append(line.rstrip())
126
+ joinable = True
127
+ else:
128
+ out[-1] += " " + stripped
129
+ return out
130
+
131
+
132
+ def section(text: str, version: str) -> str | None:
133
+ """A release's part of the changelog (markdown), without its heading,
134
+ each paragraph and bullet on one line: for its notes on GitHub. None
135
+ when it has none."""
136
+ lines = text.splitlines()
137
+ start = next((i for i, line in enumerate(lines)
138
+ if (m := _RELEASE.match(line.rstrip())) and m["version"] == version), None)
139
+ if start is None:
140
+ return None
141
+ end = next((i for i in range(start + 1, len(lines))
142
+ if lines[i].startswith("## ") or lines[i].startswith("# ")), len(lines))
143
+ body = "\n".join(_unwrap([line for line in lines[start + 1:end] if not _LINK_DEF.match(line)])).strip()
144
+ return body or None
145
+
146
+
147
+ # What a release's notes on GitHub start with (scripts/release_notes.py),
148
+ # and where that part ends.
149
+ NOTES_HEADING = "## What's new"
150
+ NOTES_END = "---"
151
+
152
+
153
+ def whats_new(release_body: str | None) -> Release | None:
154
+ """The changes in a release's notes on GitHub: the part under "## What's
155
+ new…" down to the first `---`. None for older releases without it."""
156
+ if not isinstance(release_body, str):
157
+ return None
158
+ lines = release_body.replace("\r\n", "\n").splitlines()
159
+ start = next((i for i, line in enumerate(lines) if line.startswith(NOTES_HEADING)), None)
160
+ if start is None:
161
+ return None
162
+ end = next((i for i in range(start + 1, len(lines)) if lines[i].strip() == NOTES_END), len(lines))
163
+ found = parse("## [notes]\n" + "\n".join(lines[start + 1:end]))
164
+ return found[0] if found and (found[0].intro or found[0].items) else None
165
+
166
+
167
+ _MD_LINK = re.compile(r"\[([^\]]+)\]\([^)]+\)")
168
+
169
+
170
+ def plain(text: str) -> str:
171
+ """Markdown read as plain text: links to their words, no ** or `."""
172
+ return _MD_LINK.sub(r"\1", text).replace("**", "").replace("`", "")
@@ -357,9 +357,21 @@ class StationAppWindow(AppKit.NSObject):
357
357
  elif body == "quit": # Quit on the page, which has stopped the app
358
358
  self.stopped = True
359
359
  app().terminate_(None)
360
+ elif isinstance(body, str) and body.startswith("appearance:"):
361
+ self.setAppearance(body.split(":", 1)[1])
360
362
  else:
361
363
  self.message(body)
362
364
 
365
+ @objc.python_method
366
+ def setAppearance(self, choice: str):
367
+ """Settings › Appearance, as the page's theme.js says it: "light" or
368
+ "dark" sets the window's (its title bar, and what the page sees as
369
+ the computer's setting), "system" goes back to the Mac's."""
370
+ if self.window is None:
371
+ return
372
+ name = {"light": AppKit.NSAppearanceNameAqua, "dark": AppKit.NSAppearanceNameDarkAqua}.get(choice)
373
+ self.window.setAppearance_(AppKit.NSAppearance.appearanceNamed_(name) if name else None)
374
+
363
375
  @objc.python_method
364
376
  def message(self, body):
365
377
  """For a subclass: anything else the page tells the app."""
@@ -1,7 +1,9 @@
1
1
  """The new-version notice: asks GitHub, at most once a day, for an app's
2
2
  newest release (`studio-v*`, `player-v*` or `server-v*`: the releases
3
- that carry its Mac and Windows downloads). Only release names are
4
- fetched; nothing is sent but the request itself.
3
+ that carry its Mac and Windows downloads), and keeps what each recent one
4
+ says it changes (the "What's new" at the top of its notes), for Update
5
+ now to show. One request, the same one as ever: nothing is sent but the
6
+ request itself.
5
7
  """
6
8
  from __future__ import annotations
7
9
 
@@ -14,6 +16,7 @@ import urllib.request
14
16
  from pathlib import Path
15
17
 
16
18
  from station_appkit import App
19
+ from station_appkit.changelog import whats_new
17
20
 
18
21
 
19
22
  def urlopen(*args, **kwargs):
@@ -63,12 +66,80 @@ def newest_release(releases, tag_prefix: str) -> str | None:
63
66
  return best
64
67
 
65
68
 
66
- def fetch_latest(app: App, opener=urlopen) -> str | None:
67
- """The app's newest release, from GitHub."""
69
+ # How many recent releases' "What's new" the cache keeps: enough for a
70
+ # copy a few releases behind.
71
+ NOTES_KEPT = 10
72
+
73
+
74
+ def release_notes(releases, tag_prefix: str) -> dict[str, dict]:
75
+ """Each recent published release's "What's new", by version (plain text;
76
+ see station_appkit.changelog). Releases from before notes said what they
77
+ changed have none, and are left out."""
78
+ found: list[tuple[str, dict]] = []
79
+ for release in releases if isinstance(releases, list) else []:
80
+ if not isinstance(release, dict) or release.get("draft") or release.get("prerelease"):
81
+ continue
82
+ tag = release.get("tag_name")
83
+ if not isinstance(tag, str) or not tag.startswith(tag_prefix) or not parse_version(tag[len(tag_prefix):]):
84
+ continue
85
+ notes = whats_new(release.get("body"))
86
+ if notes is not None:
87
+ notes.version = tag[len(tag_prefix):]
88
+ published = release.get("published_at")
89
+ notes.date = published[:10] if isinstance(published, str) and published else None
90
+ found.append((notes.version, notes.as_dict()))
91
+ found.sort(key=lambda pair: parse_version(pair[0]), reverse=True)
92
+ return dict(found[:NOTES_KEPT])
93
+
94
+
95
+ def _releases(app: App, opener=urlopen):
68
96
  req = urllib.request.Request(app.releases_api, headers={"Accept": "application/vnd.github+json",
69
97
  "User-Agent": app.slug})
70
98
  with opener(req, timeout=_TIMEOUT) as resp:
71
- return newest_release(json.loads(resp.read(5_000_000)), app.tag_prefix)
99
+ return json.loads(resp.read(5_000_000))
100
+
101
+
102
+ def fetch_latest(app: App, opener=urlopen) -> str | None:
103
+ """The app's newest release, from GitHub."""
104
+ return newest_release(_releases(app, opener), app.tag_prefix)
105
+
106
+
107
+ def fetch_latest_with_notes(app: App, opener=urlopen) -> tuple[str | None, dict[str, dict]]:
108
+ """The app's newest release, and what recent ones changed: one request."""
109
+ releases = _releases(app, opener)
110
+ return newest_release(releases, app.tag_prefix), release_notes(releases, app.tag_prefix)
111
+
112
+
113
+ # The cache's notes, read again only when the file changes (written here,
114
+ # or its time or size changed): Player's page asks once a second while a
115
+ # new version is on offer.
116
+ _notes_read: dict[Path, tuple[tuple[int, int], dict]] = {}
117
+
118
+
119
+ def _cached_notes(cache: Path) -> dict:
120
+ try:
121
+ stat = cache.stat()
122
+ changed = (stat.st_mtime_ns, stat.st_size) # Windows' clock may not tick between writes
123
+ seen = _notes_read.get(cache)
124
+ if seen and seen[0] == changed:
125
+ return seen[1]
126
+ notes = json.loads(cache.read_text(encoding="utf-8")).get("notes")
127
+ except (OSError, ValueError, AttributeError):
128
+ return {}
129
+ notes = notes if isinstance(notes, dict) else {}
130
+ _notes_read[cache] = (changed, notes)
131
+ return notes
132
+
133
+
134
+ def notes_since(cache: Path, current: str, latest: str | None) -> list[dict]:
135
+ """What the releases after `current`, up to `latest`, say they change,
136
+ newest first, from the cache latest_version keeps. Empty when there's
137
+ no newer version, or GitHub's notes didn't say (older releases)."""
138
+ if not is_newer(latest, current):
139
+ return []
140
+ notes = _cached_notes(cache)
141
+ return [notes[v] for v in sorted(notes, key=lambda v: parse_version(v) or (), reverse=True)
142
+ if isinstance(notes[v], dict) and is_newer(v, current) and not is_newer(v, latest)]
72
143
 
73
144
 
74
145
  def latest_version(app: App, cache: Path, fetch=None, now: float | None = None, force: bool = False,
@@ -82,7 +153,7 @@ def latest_version(app: App, cache: Path, fetch=None, now: float | None = None,
82
153
  check asked for by hand can say it couldn't, rather than that all is up
83
154
  to date."""
84
155
  now = time.time() if now is None else now
85
- fetch = fetch or (lambda: fetch_latest(app))
156
+ fetch = fetch or (lambda: fetch_latest_with_notes(app))
86
157
  cached: dict = {}
87
158
  try:
88
159
  cached = json.loads(cache.read_text(encoding="utf-8"))
@@ -95,16 +166,23 @@ def latest_version(app: App, cache: Path, fetch=None, now: float | None = None,
95
166
  if not force and isinstance(checked, (int, float)) and 0 <= now - checked < CHECK_EVERY:
96
167
  return known
97
168
  try:
98
- latest = fetch()
169
+ latest = fetch() # a version, or (version, notes) from fetch_latest_with_notes
99
170
  except Exception as exc: # offline, proxy, GitHub down: try again next time
100
171
  logger.info("Couldn't check for a new version of %s: %s", app.name, exc)
101
172
  if not quiet:
102
173
  raise
103
174
  return known
175
+ notes = None
176
+ if isinstance(latest, tuple):
177
+ latest, notes = latest
104
178
  logger.info("Newest %s release: %s", app.name, latest)
105
179
  try:
106
180
  cache.parent.mkdir(parents=True, exist_ok=True)
107
- cache.write_text(json.dumps({"checked": now, "latest": latest}), encoding="utf-8")
181
+ record = {"checked": now, "latest": latest}
182
+ if notes is not None:
183
+ record["notes"] = notes
184
+ cache.write_text(json.dumps(record), encoding="utf-8")
185
+ _notes_read.pop(cache, None)
108
186
  except OSError:
109
187
  pass
110
188
  return latest
@@ -0,0 +1,91 @@
1
+ from station_appkit import changelog
2
+
3
+ TEXT = """# Changelog
4
+
5
+ Some words about this file.
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.26.0] - 2026-11-27
10
+
11
+ A short intro,
12
+ over two lines.
13
+
14
+ ### Added
15
+
16
+ - Help › **Report a problem**: a button that opens a new
17
+ [GitHub issue](https://github.com/raby/station-studio/issues/new),
18
+ with `this` filled in.
19
+ - A second thing.
20
+
21
+ ### Fixed
22
+
23
+ - A fix.
24
+
25
+ ## [0.25.0] - 2026-11-24
26
+
27
+ - No groups here.
28
+
29
+ ```
30
+ - not a bullet: inside a code block
31
+ ```
32
+
33
+ [0.25.0]: https://example.com/a-link-definition
34
+
35
+ ## Earlier versions
36
+
37
+ - not part of any release
38
+ """
39
+
40
+
41
+ def test_parse_reads_releases_intros_groups_and_wrapped_bullets():
42
+ releases = changelog.parse(TEXT)
43
+ assert [r.version for r in releases] == ["Unreleased", "0.26.0", "0.25.0"]
44
+ new = releases[1]
45
+ assert new.date == "2026-11-27"
46
+ assert new.intro == ["A short intro, over two lines."]
47
+ assert [h for h, _ in new.groups] == ["Added", "Fixed"]
48
+ assert new.items[0] == ("Help › **Report a problem**: a button that opens a new "
49
+ "[GitHub issue](https://github.com/raby/station-studio/issues/new), with `this` filled in.")
50
+ assert new.items[1:] == ["A second thing.", "A fix."]
51
+ old = releases[2]
52
+ assert old.groups == [(None, ["No groups here."])] # code blocks, link definitions and "Earlier versions" left out
53
+
54
+
55
+ def test_as_dict_is_plain_text_for_a_page():
56
+ got = changelog.parse(TEXT)[1].as_dict()
57
+ assert got["groups"][0] == {"heading": "Added", "items": [
58
+ "Help › Report a problem: a button that opens a new GitHub issue, with this filled in.", "A second thing."]}
59
+ assert got["version"] == "0.26.0" and got["date"] == "2026-11-27"
60
+
61
+
62
+ def test_section_is_the_release_with_each_line_whole():
63
+ # GitHub keeps every line break in a release's notes: wrapped lines are joined.
64
+ got = changelog.section(TEXT, "0.26.0")
65
+ assert got.startswith("A short intro, over two lines.\n\n### Added\n\n- Help › **Report a problem**: a button "
66
+ "that opens a new [GitHub issue](https://github.com/raby/station-studio/issues/new), "
67
+ "with `this` filled in.\n- A second thing.")
68
+ assert got.endswith("- A fix.")
69
+ # A code block is kept as it is.
70
+ assert changelog.section(TEXT, "0.25.0") == "- No groups here.\n\n```\n- not a bullet: inside a code block\n```"
71
+ assert changelog.section(TEXT, "9.9.9") is None
72
+ assert changelog.section(TEXT, "Unreleased") is None # nothing under it
73
+
74
+
75
+ def test_whats_new_reads_a_releases_notes_back():
76
+ body = (f"{changelog.NOTES_HEADING} in Station Player 0.26.0\r\n\r\n"
77
+ + changelog.section(TEXT, "0.26.0").replace("\n", "\r\n")
78
+ + f"\r\n\r\n{changelog.NOTES_END}\r\nStation Player 0.26.0: plays…\r\n\r\n- **Mac:** not a change\r\n")
79
+ got = changelog.whats_new(body)
80
+ assert got.intro == ["A short intro, over two lines."]
81
+ assert got.items == changelog.parse(TEXT)[1].items # nothing from below the ---
82
+
83
+
84
+ def test_whats_new_of_an_older_release_is_none():
85
+ assert changelog.whats_new("Station Player 0.24.0: plays…\n\n**Download** …") is None
86
+ assert changelog.whats_new(None) is None
87
+ assert changelog.whats_new(f"{changelog.NOTES_HEADING}\n\n---\n") is None # nothing in it
88
+
89
+
90
+ def test_plain():
91
+ assert changelog.plain("**Bold** `code` and [a link](https://x)") == "Bold code and a link"
@@ -266,3 +266,22 @@ def test_a_menu_whose_page_took_too_long_to_come_back_is_dropped(mac, monkeypatc
266
266
  calls = len(mac.AppHelper.callLater.mock_calls)
267
267
  win.webView_didFinishNavigation_(None, None)
268
268
  assert win.pending is None and len(mac.AppHelper.callLater.mock_calls) == calls
269
+
270
+
271
+ def test_the_page_sets_the_windows_appearance(mac):
272
+ """Settings › Appearance: theme.js tells the window, so its title bar
273
+ matches the page; match the computer hands it back to the Mac's."""
274
+ win = window(mac)
275
+ win.window = mac.AppKit.NSWindow.alloc().init()
276
+ say = lambda body: win.userContentController_didReceiveScriptMessage_( # noqa: E731
277
+ None, type("M", (), {"body": lambda self: body})())
278
+ named = mac.AppKit.NSAppearance.appearanceNamed_
279
+ say("appearance:dark")
280
+ named.assert_called_with(mac.AppKit.NSAppearanceNameDarkAqua)
281
+ win.window.setAppearance_.assert_called_with(named.return_value)
282
+ say("appearance:light")
283
+ named.assert_called_with(mac.AppKit.NSAppearanceNameAqua)
284
+ say("appearance:system")
285
+ win.window.setAppearance_.assert_called_with(None)
286
+ say("appearance:neon") # anything else: the Mac's
287
+ win.window.setAppearance_.assert_called_with(None)
@@ -113,3 +113,69 @@ def test_a_release_check_github_refuses_lets_the_error_go_closed():
113
113
  finally:
114
114
  httpd.shutdown()
115
115
  httpd.server_close()
116
+
117
+
118
+ def _notes(version: str, *items: str) -> str:
119
+ """A release's notes on GitHub, as scripts/release_notes.py starts them."""
120
+ bullets = "\n".join(f"- {i}" for i in items)
121
+ return (f"## What's new in Station Test {version}\n\n### Fixed\n\n{bullets}\n\n---\n"
122
+ f"Station Test {version}: **Download** below.\n\n- **Mac:** not a change\n")
123
+
124
+
125
+ RELEASES = [
126
+ {"tag_name": "test-v1.3.0", "body": _notes("1.3.0", "Third."), "published_at": "2026-12-03T10:00:00Z"},
127
+ {"tag_name": "test-v1.2.0", "body": _notes("1.2.0", "Second, **bold**."), "published_at": "2026-12-02T10:00:00Z"},
128
+ {"tag_name": "test-v1.1.0", "body": "Station Test 1.1.0: from before notes said what changed."},
129
+ {"tag_name": "test-v1.4.0", "body": _notes("1.4.0", "A draft."), "draft": True},
130
+ {"tag_name": "server-v9.0.0", "body": _notes("9.0.0", "Another app's.")},
131
+ ]
132
+
133
+
134
+ def test_one_request_brings_the_newest_and_what_recent_ones_change(app):
135
+ asked = []
136
+
137
+ def opener(req, timeout):
138
+ asked.append(req.full_url)
139
+ return io.BytesIO(json.dumps(RELEASES).encode())
140
+
141
+ latest, notes = updates.fetch_latest_with_notes(app, opener)
142
+ assert latest == "1.3.0" and len(asked) == 1
143
+ assert list(notes) == ["1.3.0", "1.2.0"] # published, this app's, and saying what changed
144
+ assert notes["1.2.0"] == {"version": "1.2.0", "date": "2026-12-02", "intro": [],
145
+ "groups": [{"heading": "Fixed", "items": ["Second, bold."]}]}
146
+
147
+
148
+ def test_update_now_reads_what_changed_since_this_version(app, tmp_path):
149
+ cache = tmp_path / "update-check.json"
150
+ latest = updates.latest_version(app, cache, fetch=lambda: ("1.3.0", updates.release_notes(RELEASES, "test-v")),
151
+ now=1000.0)
152
+ assert latest == "1.3.0"
153
+ assert [r["version"] for r in updates.notes_since(cache, "1.1.0", latest)] == ["1.3.0", "1.2.0"]
154
+ assert [r["version"] for r in updates.notes_since(cache, "1.2.0", latest)] == ["1.3.0"]
155
+ assert updates.notes_since(cache, "1.3.0", latest) == [] # up to date
156
+ assert updates.notes_since(cache, "1.1.0", "1.2.0")[0]["version"] == "1.2.0" # never past the newest offered
157
+ # A check by hand that only got a version keeps no notes; nothing breaks.
158
+ updates.latest_version(app, cache, fetch=lambda: "1.3.0", now=1000.0, force=True)
159
+ assert updates.notes_since(cache, "1.1.0", "1.3.0") == []
160
+ assert updates.notes_since(tmp_path / "missing.json", "1.1.0", "1.3.0") == []
161
+
162
+
163
+ def test_only_the_last_few_releases_notes_are_kept():
164
+ many = [{"tag_name": f"test-v1.{i}.0", "body": _notes(f"1.{i}.0", "x")} for i in range(25)]
165
+ kept = updates.release_notes(many, "test-v")
166
+ assert len(kept) == updates.NOTES_KEPT and next(iter(kept)) == "1.24.0"
167
+
168
+
169
+ def test_the_notes_are_read_again_only_when_the_cache_changes(app, tmp_path, monkeypatch):
170
+ cache = tmp_path / "update-check.json"
171
+ updates.latest_version(app, cache, fetch=lambda: ("1.3.0", updates.release_notes(RELEASES, "test-v")), now=1.0)
172
+ reads = []
173
+ real = type(cache).read_text
174
+ monkeypatch.setattr(type(cache), "read_text", lambda self, *a, **k: reads.append(self) or real(self, *a, **k))
175
+ for _ in range(5):
176
+ assert updates.notes_since(cache, "1.1.0", "1.3.0")[0]["version"] == "1.3.0"
177
+ assert len(reads) <= 1 # once, then from memory
178
+ import os
179
+ updates.latest_version(app, cache, fetch=lambda: ("1.3.0", {}), now=2.0, force=True)
180
+ os.utime(cache, ns=(cache.stat().st_atime_ns, cache.stat().st_mtime_ns + 1_000_000))
181
+ assert updates.notes_since(cache, "1.1.0", "1.3.0") == [] # changed: read again
File without changes
File without changes