station-appkit 1.1.2__tar.gz → 1.3.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.1.2 → station_appkit-1.3.0}/PKG-INFO +1 -1
  2. {station_appkit-1.1.2 → station_appkit-1.3.0}/pyproject.toml +1 -1
  3. {station_appkit-1.1.2 → station_appkit-1.3.0}/station_appkit/__init__.py +1 -1
  4. station_appkit-1.3.0/station_appkit/changelog.py +172 -0
  5. station_appkit-1.3.0/station_appkit/report.py +88 -0
  6. {station_appkit-1.1.2 → station_appkit-1.3.0}/station_appkit/updates.py +86 -8
  7. station_appkit-1.3.0/tests/test_changelog.py +91 -0
  8. station_appkit-1.3.0/tests/test_report.py +85 -0
  9. {station_appkit-1.1.2 → station_appkit-1.3.0}/tests/test_updates.py +66 -0
  10. {station_appkit-1.1.2 → station_appkit-1.3.0}/.gitignore +0 -0
  11. {station_appkit-1.1.2 → station_appkit-1.3.0}/LICENSE +0 -0
  12. {station_appkit-1.1.2 → station_appkit-1.3.0}/README.md +0 -0
  13. {station_appkit-1.1.2 → station_appkit-1.3.0}/station_appkit/applog.py +0 -0
  14. {station_appkit-1.1.2 → station_appkit-1.3.0}/station_appkit/login.py +0 -0
  15. {station_appkit-1.1.2 → station_appkit-1.3.0}/station_appkit/macwindow.py +0 -0
  16. {station_appkit-1.1.2 → station_appkit-1.3.0}/station_appkit/selfupdate.py +0 -0
  17. {station_appkit-1.1.2 → station_appkit-1.3.0}/station_appkit/testing.py +0 -0
  18. {station_appkit-1.1.2 → station_appkit-1.3.0}/station_appkit/window.py +0 -0
  19. {station_appkit-1.1.2 → station_appkit-1.3.0}/tests/conftest.py +0 -0
  20. {station_appkit-1.1.2 → station_appkit-1.3.0}/tests/test_applog.py +0 -0
  21. {station_appkit-1.1.2 → station_appkit-1.3.0}/tests/test_login.py +0 -0
  22. {station_appkit-1.1.2 → station_appkit-1.3.0}/tests/test_macwindow.py +0 -0
  23. {station_appkit-1.1.2 → station_appkit-1.3.0}/tests/test_selfupdate.py +0 -0
  24. {station_appkit-1.1.2 → station_appkit-1.3.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.1.2
3
+ Version: 1.3.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.1.2"
18
+ version = "1.3.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.1.2"
12
+ __version__ = "1.3.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("`", "")
@@ -0,0 +1,88 @@
1
+ """Report a problem: a link to a new GitHub issue with the app, its version
2
+ and the computer already filled in, and where the app's log file is.
3
+
4
+ The issue gets what helps and nothing personal: the app and version, how
5
+ it was installed, the system and Python. Not the log file's path (it holds
6
+ the user's name on most computers): that's shown in the app instead, so
7
+ the person can look at the log and attach it if they choose.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ import platform
13
+ import sys
14
+ import urllib.parse
15
+ from pathlib import Path
16
+
17
+ ISSUES_NEW = "https://github.com/raby/station-studio/issues/new"
18
+
19
+ # How each install kind reads in a report. None (pip, pipx, a checkout)
20
+ # is "installed with pip", the commonest of those; in a container, "Docker".
21
+ INSTALLED = {"mac": "downloaded Mac app", "windows": "downloaded Windows app", None: "installed with pip"}
22
+
23
+
24
+ def in_docker() -> bool:
25
+ """Running in a Docker container (Station Studio's image): its log is
26
+ the container's (docker compose logs), not a file or a terminal."""
27
+ return Path("/.dockerenv").exists()
28
+
29
+
30
+ def system(platform_name: str | None = None) -> str:
31
+ """The operating system, as people know it: "macOS 15.1 (Apple Silicon)",
32
+ "Windows 11 (10.0.22631)", "Ubuntu 24.04.1 LTS"."""
33
+ platform_name = platform_name or sys.platform
34
+ machine = platform.machine()
35
+ if platform_name == "darwin":
36
+ chip = "Apple Silicon" if machine == "arm64" else "Intel"
37
+ return f"macOS {platform.mac_ver()[0] or platform.release()} ({chip})"
38
+ if platform_name == "win32":
39
+ return f"Windows {platform.release()} ({platform.version()})"
40
+ try:
41
+ name = platform.freedesktop_os_release().get("PRETTY_NAME")
42
+ except (OSError, AttributeError):
43
+ name = None
44
+ return f"{name or 'Linux ' + platform.release()} ({machine})"
45
+
46
+
47
+ def log_file() -> Path | None:
48
+ """The file this app is logging to (station_appkit.applog), or None when
49
+ it logs to the terminal it was started from."""
50
+ for handler in logging.getLogger().handlers:
51
+ name = getattr(handler, "baseFilename", None)
52
+ if name:
53
+ return Path(name)
54
+ return None
55
+
56
+
57
+ def details(app_name: str, version: str, kind: str | None) -> dict:
58
+ """What a report says about this copy, and what the app shows beside it."""
59
+ log = log_file()
60
+ docker = kind is None and in_docker()
61
+ about = {
62
+ "app": app_name,
63
+ "version": version,
64
+ "installed": "Docker" if docker else INSTALLED.get(kind, INSTALLED[None]),
65
+ "system": system(),
66
+ "python": platform.python_version(),
67
+ }
68
+ return {**about, "log_file": str(log) if log else None, "in_docker": docker, "issue_url": issue_url(about)}
69
+
70
+
71
+ def issue_url(about: dict) -> str:
72
+ """A new issue, titled with the app and with its details in the body."""
73
+ body = "\n".join([
74
+ "**What happened**",
75
+ "",
76
+ "",
77
+ "**What I expected**",
78
+ "",
79
+ "",
80
+ "**Steps to make it happen again**",
81
+ "1. ",
82
+ "",
83
+ "---",
84
+ f"- App: {about['app']} {about['version']} ({about['installed']})",
85
+ f"- System: {about['system']}",
86
+ f"- Python: {about['python']}",
87
+ ])
88
+ return ISSUES_NEW + "?" + urllib.parse.urlencode({"title": f"[{about['app']}] ", "body": body})
@@ -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"
@@ -0,0 +1,85 @@
1
+ import logging
2
+ import logging.handlers
3
+ import urllib.parse
4
+
5
+ import pytest
6
+
7
+ from station_appkit import report
8
+
9
+
10
+ def _query(url: str) -> dict:
11
+ base, _, query = url.partition("?")
12
+ assert base == "https://github.com/raby/station-studio/issues/new"
13
+ return {k: v[0] for k, v in urllib.parse.parse_qs(query).items()}
14
+
15
+
16
+ def test_the_issue_has_the_app_version_and_computer_filled_in(monkeypatch):
17
+ monkeypatch.setattr(report, "system", lambda: "macOS 15.1 (Apple Silicon)")
18
+ monkeypatch.setattr(report.platform, "python_version", lambda: "3.12.7")
19
+ got = report.details("Station Player", "0.25.1", "mac")
20
+ assert got["installed"] == "downloaded Mac app"
21
+ q = _query(got["issue_url"])
22
+ assert q["title"] == "[Station Player] "
23
+ assert "- App: Station Player 0.25.1 (downloaded Mac app)" in q["body"]
24
+ assert "- System: macOS 15.1 (Apple Silicon)" in q["body"]
25
+ assert "- Python: 3.12.7" in q["body"]
26
+ assert "**What happened**" in q["body"]
27
+
28
+
29
+ @pytest.fixture(autouse=True)
30
+ def not_in_docker(monkeypatch):
31
+ monkeypatch.setattr(report, "in_docker", lambda: False)
32
+
33
+
34
+ def test_in_docker_it_says_so(monkeypatch):
35
+ monkeypatch.setattr(report, "in_docker", lambda: True)
36
+ got = report.details("Station Studio", "1.24.0", None)
37
+ assert got["installed"] == "Docker" and got["in_docker"] is True
38
+ assert "(Docker)" in urllib.parse.unquote_plus(got["issue_url"])
39
+ # A downloaded app is never "Docker", whatever the computer has at /.dockerenv.
40
+ assert report.details("Station Studio", "1.24.0", "mac")["in_docker"] is False
41
+
42
+
43
+ @pytest.mark.parametrize("kind, says", [("windows", "downloaded Windows app"), (None, "installed with pip"),
44
+ ("something new", "installed with pip")])
45
+ def test_how_it_was_installed(kind, says):
46
+ assert report.details("Station Server", "0.24.1", kind)["installed"] == says
47
+
48
+
49
+ def test_the_log_file_is_shown_but_never_put_in_the_issue(tmp_path, monkeypatch):
50
+ log = tmp_path / "Rob" / "station-studio.log"
51
+ log.parent.mkdir()
52
+ handler = logging.handlers.RotatingFileHandler(log, encoding="utf-8")
53
+ root = logging.getLogger()
54
+ monkeypatch.setattr(root, "handlers", [handler])
55
+ try:
56
+ got = report.details("Station Studio", "1.23.1", None)
57
+ assert got["log_file"] == str(log)
58
+ assert "Rob" not in got["issue_url"] and "station-studio.log" not in got["issue_url"]
59
+ finally:
60
+ handler.close()
61
+
62
+
63
+ def test_no_log_file_when_it_logs_to_the_terminal(monkeypatch):
64
+ monkeypatch.setattr(logging.getLogger(), "handlers", [logging.StreamHandler()])
65
+ assert report.log_file() is None
66
+ assert report.details("Station Studio", "1.23.1", None)["log_file"] is None
67
+
68
+
69
+ def test_the_system_as_people_know_it(monkeypatch):
70
+ monkeypatch.setattr(report.platform, "machine", lambda: "arm64")
71
+ monkeypatch.setattr(report.platform, "mac_ver", lambda: ("15.1", ("", "", ""), "arm64"))
72
+ assert report.system("darwin") == "macOS 15.1 (Apple Silicon)"
73
+ monkeypatch.setattr(report.platform, "machine", lambda: "x86_64")
74
+ assert report.system("darwin") == "macOS 15.1 (Intel)"
75
+ monkeypatch.setattr(report.platform, "release", lambda: "11")
76
+ monkeypatch.setattr(report.platform, "version", lambda: "10.0.22631")
77
+ assert report.system("win32") == "Windows 11 (10.0.22631)"
78
+ monkeypatch.setattr(report.platform, "freedesktop_os_release", lambda: {"PRETTY_NAME": "Ubuntu 24.04.1 LTS"})
79
+ assert report.system("linux") == "Ubuntu 24.04.1 LTS (x86_64)"
80
+
81
+ def missing():
82
+ raise OSError("no os-release")
83
+ monkeypatch.setattr(report.platform, "freedesktop_os_release", missing)
84
+ monkeypatch.setattr(report.platform, "release", lambda: "6.8.0")
85
+ assert report.system("linux") == "Linux 6.8.0 (x86_64)"
@@ -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