build: version from one file, and the release/update contract (#49)

Groundwork for the in-app updater: nothing in the app changes behaviour
yet, but the numbers and the rules it will rely on are fixed now.

version.properties is the single source of truth (0.1.0 / 1 today) and
build.gradle.kts reads it, so the APK, the tag (vX.Y.Z) and the release
description can no longer disagree. versionName stays semver for humans;
versionCode is a plain counter because it is the ONLY value Android and
Play order by — a tag can never answer "is this newer".

The release description carries the truth as a machine-readable line
("versionCode: N"), which the update check will read together with the
changelog; ReleaseDescription parses it, refuses to guess from tags, and
rejects nonsense instead of overflowing into a negative code. Unit tests
pin the shapes people actually type, the changelog split, https-only
downloads, and that only a HIGHER versionCode counts as an update.

docs/releases.md is the runbook: versions, the description contract,
publishing step by step (script and the manual curl fallback), signing
and its one-time-key rule, installing on the TV, and a symptom/cause/
fix table for the failures that strand clients silently.

Refs #49
This commit is contained in:
Jeena 2026-10-30 23:40:11 +00:00
parent f1dcbafe0a
commit c73749f4fb
6 changed files with 411 additions and 2 deletions

View file

@ -122,6 +122,19 @@ adb connect <tv-ip>:<port>
adb install -r app/build/outputs/apk/debug/app-debug.apk
```
Debug builds are interpreted by ART (a debuggable APK cannot be AOT-compiled),
so do not judge speed with them — see `docs/perf-debug-builds.md`. The APK that
gets installed on a TV is `:app:assembleRelease`.
### Releasing
Releases are published as Forgejo releases, and the app updates itself from
them (an **Update** row appears in the sidebar when a newer version exists).
The version lives in `version.properties`, and the release description carries
the `versionCode` the update check reads. The full runbook — bumping, tagging,
signing, publishing, and what to check when an update does not show up — is in
[`docs/releases.md`](docs/releases.md).
## Architecture
A single-module app, deliberately small:

View file

@ -1,3 +1,5 @@
import java.util.Properties
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android)
@ -13,8 +15,14 @@ android {
applicationId = "net.jeena.jtubetv"
minSdk = 26
targetSdk = 35
versionCode = 1
versionName = "0.1.0"
// Version comes from version.properties at the repo root — ONE place to
// bump, so the APK, the release tag (vX.Y.Z) and the versionCode written
// into the release description can never disagree (docs/releases.md).
val versionProps = Properties()
val versionFile = rootProject.file("version.properties")
if (versionFile.exists()) versionFile.inputStream().use { versionProps.load(it) }
versionName = versionProps.getProperty("versionName", "1.0.0")
versionCode = versionProps.getProperty("versionCode", "1").trim().toInt()
// Compose UI tests (androidTest) — see app/src/androidTest/README.md
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}

View file

@ -0,0 +1,103 @@
package net.jeena.jtubetv.data.update
/**
* What a release offers us: its versionCode (the only value Android/Play order
* by), the human version name, the changelog and the APK to download.
*/
data class UpdateInfo(
/** `versionCode` as declared in the release description. */
val versionCode: Int,
/** The release tag's version, e.g. "1.2.3" (display only). */
val versionName: String,
val changelog: String,
val downloadUrl: String,
val assetSizeBytes: Long = 0,
)
/**
* Release descriptions are the source of truth for the update check (decided with
* Jeena): clean tags (`v1.2.3`) and one machine-readable line in the description —
*
* ```
* versionCode: 58
*
* ## Changelog
* - …
* ```
*
* We deliberately do NOT guess the versionCode from the tag: a tag says nothing
* about whether Android would consider the APK newer, and a wrong guess either
* hides real updates or offers a downgrade. A release without the line is simply
* not an update.
*
* Kept pure so it can be unit-tested without a device (this is the piece that,
* when wrong, silently strands every installed app on an old version).
*/
object ReleaseDescription {
/** Matches `versionCode: 58`, `versionCode = 58`, `**versionCode:** 58`. */
private val VersionCodeLine = Regex(
"""(?im)^[\s>#*_`-]*versioncode[\s*_`]*[:=][\s*_`]*(\d{1,10})\b""",
)
/** The declared versionCode, or null when the description does not declare one. */
fun versionCode(body: String?): Int? {
if (body.isNullOrBlank()) return null
val raw = VersionCodeLine.find(body)?.groupValues?.get(1) ?: return null
// A code above Int.MAX_VALUE cannot be installed by Android anyway; treat
// it as garbage rather than letting it overflow into a negative number.
return raw.toLongOrNull()?.takeIf { it in 1..Int.MAX_VALUE.toLong() }?.toInt()
}
/**
* The changelog: the description minus the machine-readable versionCode line,
* so the update row shows exactly what a human wrote and nothing else.
*/
fun changelog(body: String?): String =
(body ?: "")
.lineSequence()
.filterNot { VersionCodeLine.containsMatchIn(it) && versionCode(it) != null }
.joinToString("\n")
.trim()
/** "v1.2.3" -> "1.2.3" (display only; never used for ordering). */
fun versionNameFromTag(tag: String?): String =
(tag ?: "").trim().removePrefix("v").removePrefix("V").ifBlank { "?" }
/**
* Builds an [UpdateInfo] from a release description, or null when the release
* cannot be installed from (no versionCode line, no APK).
*/
fun parse(
tag: String?,
body: String?,
downloadUrl: String?,
assetSizeBytes: Long = 0,
): UpdateInfo? {
val code = versionCode(body) ?: return null
val url = downloadUrl?.takeIf { it.startsWith("https://") } ?: return null
return UpdateInfo(
versionCode = code,
versionName = versionNameFromTag(tag),
changelog = changelog(body),
downloadUrl = url,
assetSizeBytes = assetSizeBytes,
)
}
/** True when [candidate] is a genuine upgrade over [installedVersionCode]. */
fun isNewer(candidate: UpdateInfo?, installedVersionCode: Int): Boolean =
candidate != null && candidate.versionCode > installedVersionCode
/**
* The description a release must carry, written by scripts/release.sh — kept
* here so the format has exactly one definition and a test can pin it.
*/
fun description(versionCode: Int, changelog: String): String =
buildString {
append("versionCode: ").append(versionCode).append("\n")
append("\n")
val body = changelog.trim()
if (body.isNotEmpty()) append(body).append("\n")
}
}

View file

@ -0,0 +1,102 @@
package net.jeena.jtubetv.data.update
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* Guards the update check's only real input: the release description. Getting this
* wrong is silent and permanent — a client either never learns about updates, or is
* offered one that Android refuses (downgrade), and "check for updates" has to
* work first try on someone else's TV.
*/
class ReleaseDescriptionTest {
private val body = """
versionCode: 58
## Changelog
- Scrolling in the info panel moves one line per press (#47)
- Links show which one OK will open (#48)
""".trimIndent()
@Test
fun `reads the declared versionCode`() {
assertEquals(58, ReleaseDescription.versionCode(body))
}
@Test
fun `tolerates the shapes people actually type`() {
assertEquals(7, ReleaseDescription.versionCode("versionCode = 7"))
assertEquals(9, ReleaseDescription.versionCode("**versionCode:** 9"))
assertEquals(11, ReleaseDescription.versionCode("### versionCode: 11"))
assertEquals(13, ReleaseDescription.versionCode(" VersionCode: 13 "))
assertEquals(15, ReleaseDescription.versionCode("Release notes\n\nversionCode: 15\nmore"))
}
@Test
fun `a release without the line is not an update`() {
assertNull(ReleaseDescription.versionCode("Just some notes, no version."))
assertNull(ReleaseDescription.versionCode(""))
assertNull(ReleaseDescription.versionCode(null))
assertNull(ReleaseDescription.parse("v1.2.3", "no code here", "https://x/app.apk"))
// The tag must never be used as a fallback: it cannot answer "is this newer".
assertNull(ReleaseDescription.versionCode("tag v1.2.3"))
}
@Test
fun `nonsense values are rejected instead of overflowing`() {
assertNull(ReleaseDescription.versionCode("versionCode: 0"))
assertNull(ReleaseDescription.versionCode("versionCode: -5"))
assertNull(ReleaseDescription.versionCode("versionCode: 99999999999"))
}
@Test
fun `the changelog excludes the machine-readable line`() {
val changelog = ReleaseDescription.changelog(body)
assertFalse("the versionCode line must not show up as changelog", changelog.contains("versionCode"))
assertTrue(changelog.contains("moves one line per press"))
assertTrue(changelog.startsWith("## Changelog"))
}
@Test
fun `parsing yields a usable update`() {
val info = ReleaseDescription.parse(
tag = "v1.2.3",
body = body,
downloadUrl = "https://git.jeena.net/jeena/jtube-tv/releases/download/v1.2.3/app-release.apk",
assetSizeBytes = 3_100_000,
)
assertEquals(58, info?.versionCode)
assertEquals("1.2.3", info?.versionName)
assertEquals(3_100_000L, info?.assetSizeBytes)
assertTrue(info!!.changelog.contains("#47"))
}
@Test
fun `only https downloads are accepted`() {
assertNull(ReleaseDescription.parse("v1", body, "http://insecure/app.apk"))
assertNull(ReleaseDescription.parse("v1", body, "ftp://nope/app.apk"))
assertNull(ReleaseDescription.parse("v1", body, null))
}
@Test
fun `newer means a higher versionCode, never a tag comparison`() {
val info = UpdateInfo(58, "1.10.0", "", "https://x/app.apk")
assertTrue(ReleaseDescription.isNewer(info, installedVersionCode = 57))
assertFalse("same build is not an update", ReleaseDescription.isNewer(info, 58))
assertFalse("an older build must never be offered", ReleaseDescription.isNewer(info, 59))
assertFalse(ReleaseDescription.isNewer(null, 1))
}
@Test
fun `the generated description round-trips through the parser`() {
val generated = ReleaseDescription.description(58, "## Changelog\n- something")
assertEquals(58, ReleaseDescription.versionCode(generated))
assertEquals("## Changelog\n- something", ReleaseDescription.changelog(generated))
// The release script writes exactly this, so the format has one definition.
assertTrue(generated.startsWith("versionCode: 58"))
}
}

177
docs/releases.md Normal file
View file

@ -0,0 +1,177 @@
# Releases and updates
The app updates itself from this repo's **Forgejo releases**. This file is the
contract between the release script, the release description and the update
check — all three read the same numbers — followed by the step-by-step runbook.
---
## 1. Versions
One source of truth, at the repo root:
```properties
# version.properties
versionName=0.1.0
versionCode=1
```
- **`versionName`** is semver (`major.minor.patch`) and is what humans see: the
release tag, the update row, the APK name.
- **`versionCode`** is a plain integer counter, **+1 per published release**.
Android (and Play) order by this value only — `versionName` is never compared
anywhere, which is why `1.10.0` vs `1.9.9` cannot bite us.
- The tag is `v<versionName>`: `v0.1.0`.
Bump both lines in the same commit as the release. `scripts/release.sh` refuses
to publish otherwise.
## 2. The release description is the machine-readable truth
The update check reads the newest release from
`/api/v1/repos/jeena/jtube-tv/releases` (public repo, no token needed) and takes
the `versionCode` **from the description body**, not from the tag:
```
versionCode: 1
## Changelog
- Info panel scrolls one line per press (#47)
- Cards that did not come from this instance show a small ↗ (#41)
```
Rules:
- A release **without** a `versionCode:` line is never offered — a tag cannot
answer "would Android consider this newer", and guessing either hides real
updates or offers a downgrade.
- Everything else in the body becomes the changelog, shown verbatim.
- Draft releases are ignored.
- Tags are immutable: never re-upload an asset over a published version. A bad
release gets a new `versionCode`, not a silent replacement.
## 3. How to publish a release
### One-time setup
1. **Signing key** (once, forever — see §4): `jtube-release.jks` +
`keystore.properties` at the repo root.
2. **Forgejo token** for uploading: Forgejo → Settings → Applications → generate
a token with `write:repository`. Store it in the agent secrets, not in the
repo:
```bash
sops ~/.agents/secrets/jtube.env # add FORGEJO_TOKEN=...
```
3. Check the tooling: `java` on PATH and the Android SDK's `aapt2`
(`~/Android/Sdk/build-tools/<ver>/aapt2`).
### The release itself
```bash
# 1. bump the version, in the same commit as the change you are shipping
$EDITOR version.properties # versionName=0.2.0 versionCode=2
git commit -am "release: 0.2.0"
# 2. tag it — the tag must equal versionName
git tag v0.2.0
git push origin main && git push origin v0.2.0
# 3. build, verify, publish (creates the release, writes the description
# with the versionCode line, uploads the APK)
./scripts/release.sh
# 4. check what the app will see
curl -s https://git.jeena.net/api/v1/repos/jeena/jtube-tv/releases | \
python3 -c "import json,sys; r=json.load(sys.stdin)[0]; print(r['tag_name']); print(r['body'][:200])"
```
`scripts/release.sh` does, in order:
1. read `version.properties` and refuse to continue if the tag `v<versionName>`
is not what is checked out;
2. build `:app:assembleRelease`;
3. read the **built APK's own** `versionCode`/`versionName` (`aapt2 dump badging`)
and abort if it disagrees with `version.properties` — this is the check that
stops a stale APK from being published under a new tag;
4. refuse to publish if the new `versionCode` is not greater than the newest
published release's;
5. create the release with the generated description
(`versionCode: N` + the changelog text) and upload `app-release.apk`;
6. print the release URL.
### Manual fallback (no script, same result)
If the script is not available yet, do it by hand — the important part is the
description format and the checks:
```bash
# build and read the truth out of the artifact
export JAVA_HOME=/usr/lib/jvm/java-17-openjdk
./gradlew :app:assembleRelease
~/Android/Sdk/build-tools/36.0.0/aapt2 dump badging \
app/build/outputs/apk/release/app-release.apk | head -1
# package: name='net.jeena.jtubetv' versionCode='2' versionName='0.2.0' ...
# create the release (TAG/BODY from the checks above)
set -a; source <(sops -d --output-type dotenv ~/.agents/secrets/jtube.env); set +a
API=https://git.jeena.net/api/v1/repos/jeena/jtube-tv
ID=$(curl -s -X POST "$API/releases" \
-H "Authorization: token $FORGEJO_TOKEN" -H 'Content-Type: application/json' \
-d '{"tag_name":"v0.2.0","name":"0.2.0","body":"versionCode: 2\n\n## Changelog\n- …"}' \
| python3 -c 'import json,sys; print(json.load(sys.stdin)["id"])')
# upload the APK as an asset of that release
curl -s -X POST "$API/releases/$ID/assets?name=app-release.apk" \
-H "Authorization: token $FORGEJO_TOKEN" \
-F "attachment=@app/build/outputs/apk/release/app-release.apk"
```
Or in the web UI: **Releases → New Release**, tag `v0.2.0`, paste the description
with its `versionCode:` line first, attach the APK.
### After publishing
- Install it on the TV once by hand (`adb install -r`) to confirm the build is
good; from the next release on, the app's **Update** row does it.
- The row appears only when the release's `versionCode` is greater than the
installed app's — so if it does not show up, compare those two numbers first.
## 4. Signing
Releases must be signed with the **same key forever**: Android refuses to install
an update signed by a different key, and the app also verifies the downloaded
APK's signer before handing it to the installer.
- Keystore: `jtube-release.jks` — **not** in git. Backed up in KeePassXC (the
file as an attachment, passwords in the same entry).
- `keystore.properties` at the repo root (gitignored):
```properties
storeFile=../jtube-release.jks
storePassword=…
keyAlias=jtube
keyPassword=…
```
- Without that file, `assembleRelease` builds unsigned — fine locally, not
publishable.
- Losing the key means every install must be uninstalled and reinstalled by hand
(and the login typed again). Treat the KeePassXC entry as a release artifact.
## 5. Installing an update on the TV
The app downloads the APK, verifies size/version/signature, and hands it to the
system installer. Android always shows **its own confirmation** — that is the
"install" step, and it needs "install unknown apps" allowed for JTube once. See
`INSTALL.md`.
## 6. When something is wrong
| Symptom | Cause | Fix |
|---|---|---|
| Update row never appears | release body has no `versionCode:` line, or its code is not greater than installed | check §2, compare with `aapt2 dump badging` |
| Row appears, install fails with "App not installed" | different signing key | rebuild and re-publish with the right keystore; users must reinstall once |
| Install fails with "invalid APK" / parse error | truncated or wrong asset | re-check the upload, publish a **new** versionCode |
| Release published with the wrong version | stale APK or tag/version mismatch | publish a new, higher versionCode; never overwrite the tag |

6
version.properties Normal file
View file

@ -0,0 +1,6 @@
# Single source of truth for the app version (docs/releases.md).
# Bump BOTH lines; scripts/release.sh refuses to publish a tag that disagrees
# with these, and it writes versionCode into the release description, which is
# what the app's update check reads.
versionName=0.1.0
versionCode=1