Skip to content

Commit 3704cd2

Browse files
authored
Merge pull request #77 from johnneerdael/feat/tagged-release-version
Tag a version-declaring release source and fix F-Droid recipe formatting
2 parents b6fab30 + 919176a commit 3704cd2

19 files changed

Lines changed: 732 additions & 92 deletions

‎.gitattributes‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# fdroiddata rewritemeta writes "Key: " before a long value on the next line.
2+
tools/fdroid/metadata/*.yml whitespace=-blank-at-eol

‎.github/scripts/fdroid_metadata.py‎

Lines changed: 90 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -59,13 +59,14 @@ def generate_metadata(release, target, existing=None):
5959
app.Repo = REPO + '.git'
6060
app.Binaries = REPO + f'/releases/download/v%v/projectM-{apk}-FDroid-%v.apk'
6161
app.AllowedAPKSigningKeys = [SIGNING_KEY]
62-
app.AutoUpdateMode = 'Version v%v'
63-
app.UpdateCheckMode = 'HTTP'
64-
# fdroidserver 2.4.5 cannot parse the conditional package/label in app/build.gradle.
65-
# HTTP discovery and APK identity checks are authoritative; retain each flavor's name.
62+
# Each release tag's gradle.properties declares that release's version and code.
63+
app.AutoUpdateMode = 'Version'
64+
app.UpdateCheckMode = r'Tags ^v\d+\.\d+\.\d+$'
65+
# fdroidserver cannot resolve the conditional package/label in app/build.gradle;
66+
# retain each flavor's name. Packaged identities are verified in Android CI.
6667
app.UpdateCheckName = 'Ignore'
67-
app.UpdateCheckData = (REPO + '/releases/latest/download/release-version.json|'
68-
r'"version_code"\s*:\s*(\d+)|.|"version"\s*:\s*"(\d+\.\d+\.\d+)"')
68+
app.UpdateCheckData = (r'gradle.properties|projectmReleaseVersionCode=(\d+)|'
69+
r'gradle.properties|projectmReleaseVersion=(\d+\.\d+\.\d+)')
6970
app.VercodeOperation = []
7071
app.UpdateCheckIgnore = None
7172
app.CurrentVersion = release['version']
@@ -81,15 +82,94 @@ def generate_metadata(release, target, existing=None):
8182
build.sudo = ["sdkmanager 'cmake;3.22.1'"]
8283
build.gradle = [flavor]
8384
build.gradleprops = ['projectmDistribution=fdroid', 'androidTouchscreen=' + str(target == 'android').lower()]
84-
# Runs in :app. F-Droid substitutes these constants for every auto-generated build.
85-
build.prebuild = ["sed -i.bak -e '/^projectmReleaseVersion=/d' -e '/^projectmReleaseVersionCode=/d' ../gradle.properties && "
86-
"rm ../gradle.properties.bak && "
87-
"printf '\\nprojectmReleaseVersion=$$VERSION$$\\nprojectmReleaseVersionCode=$$VERCODE$$\\n' >> ../gradle.properties"]
85+
# The tagged source declares its own version: no prebuild edits.
86+
build.prebuild = []
8887
build.ndk = '27.3.13750724'
8988
app.Builds = [build]
9089
return app
9190

9291

92+
ABSTRACTS = {
93+
'tv': ('ProjectM TV is a music visualizer for Android TV. It renders audio-reactive MilkDrop presets '
94+
'for the music another app plays on the TV, controlled with the remote.',
95+
'images/tvScreenshots/1.jpg'),
96+
'android': ('ProjectM Android is a music visualizer for phones and tablets. It renders audio-reactive '
97+
'MilkDrop presets from the microphone or, on Android 10 and later, from playback in '
98+
'another app that permits capture, controlled with touch gestures.',
99+
'images/phoneScreenshots/1.png'),
100+
}
101+
102+
103+
def merge_request_description(target):
104+
"""New-app merge request text following fdroiddata's 'App inclusion' template."""
105+
appid, flavor, _, title = TARGETS[target]
106+
summary, screenshot = ABSTRACTS[target]
107+
fastlane = f'src/{flavor}/fastlane/metadata/android/en-US'
108+
raw = REPO.replace('https://github.com/', 'https://raw.githubusercontent.com/') + '/main/' + fastlane
109+
return f'''## Abstract
110+
111+
### Please introduce the functions and usage of your app in summary, and also attach some screenshots.
112+
113+
{summary} This F-Droid edition bundles 20 starter presets; on first launch the user can choose to download the optional 9,606-preset *Cream of the Crop* collection (CC0) from this project's GitHub release, or continue offline. It has no built-in app updater: updates come from F-Droid.
114+
115+
![{title} screenshot]({raw}/{screenshot})
116+
117+
### Please elaborate why you wrote this app. Please highlight the unique functions it provides over other similar apps in F-Droid.
118+
119+
It runs ProjectM TV Engine, a maintained fork of [projectM](https://github.com/projectM-visualizer/projectm) (the open-source MilkDrop reimplementation) with compatibility and rendering fixes, so the large MilkDrop preset catalogue plays on Android devices.
120+
121+
- Source: {REPO} (I'm the author)
122+
- License: LGPL-2.1-only for the code; presets and textures are CC0 1.0
123+
- projectM and projectm-eval are git submodules and are built from source with the app.
124+
125+
## Checklist
126+
127+
### Policy
128+
129+
* [x] The app complies with the [inclusion criteria](https://f-droid.org/docs/Inclusion_Policy).
130+
* [x] The original app author has been notified (and does not oppose the inclusion). I am the author.
131+
* [x] The upstream app source code repo contains the app metadata in a Fastlane folder structure (`{fastlane}`: title, summary, description, changelogs, icon and screenshots).
132+
133+
### Docs
134+
135+
* [x] Please read [the guide](https://gitlab.com/fdroid/fdroiddata/-/blob/master/CONTRIBUTING.md) first if this is your first contribution.
136+
* [x] Please make sure your metadata follows the best practice in [our templates](https://gitlab.com/fdroid/fdroiddata/tree/master/templates).
137+
* [x] Please read the [Build Metadata Reference](https://f-droid.org/docs/Build_Metadata_Reference/) and make sure your metadata is valid.
138+
* [x] Please read the [Quick Start Guide](https://f-droid.org/en/docs/Submitting_to_F-Droid_Quick_Start_Guide/).
139+
140+
### Merge Request Setup
141+
142+
* [x] The title of this merge request should follow "New app: app name" format.
143+
* [x] Please make sure your fdroiddata fork is public and your branch is not protected.
144+
* [x] Please read [our Git guide](https://gitlab.com/fdroid/wiki/-/wikis/Tips-for-fdroiddata-contributors/Git-Usage) if you don't know how to rebase your branch.
145+
* [x] All related fdroiddata and RFP issues have been referenced in this merge request (there are none).
146+
* [x] Please only submit one app in one MR.
147+
148+
### Metadata
149+
150+
* [x] Metadata must be put in `metadata/{appid}.yml`.
151+
* [x] Metadata must be a valid YAML file.
152+
* [x] Metadata must use LF as line ending.
153+
* [x] Don't add summary/description/changelog/images or anything that should be provided in upstream repo.
154+
* [x] Releases are tagged and auto update is enabled (`UpdateCheckMode: Tags`). Each release tag's `gradle.properties` declares that release's version name and code.
155+
* [x] There is an issue tracker and contact info of the author (GitHub issues).
156+
* [x] An AuthorName must be added.
157+
* [x] External repos are added as git submodules instead of srclibs.
158+
* [x] Enable Reproducible Builds: `Binaries` and `AllowedAPKSigningKeys` are set, and `fdroid build` verifies the matching signed upstream APK.
159+
* [ ] Setup abi split if the APK is large and the splitted ones can be much smaller: not done, because the universal APK is about 2 MB.
160+
* [x] Only the latest versions should be kept in the metadata before it's merged.
161+
* [x] Don't add any disabled versions in the metadata.
162+
* [x] The `commit` field should be the full hash.
163+
164+
### Pipeline
165+
166+
* [ ] All pipelines should pass.
167+
* [ ] All warnings and errors in the Reports tab should be fixed or explained.
168+
169+
The author ticks the pipeline items once this merge request's pipeline has finished.
170+
'''
171+
172+
93173
def parse(text, appid):
94174
stream = io.StringIO(text)
95175
stream.name = appid + '.yml'

‎.github/scripts/fdroid_sync.py‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -170,12 +170,7 @@ def before_write():
170170
'source_branch': appid, 'target_branch': 'master', 'target_project_id': uid,
171171
'title': 'New app: ' + title, 'allow_collaboration': True,
172172
'remove_source_branch': True,
173-
'description': (f'{title} is an open-source MilkDrop music visualizer.\n\n'
174-
f'Source: {recipes.REPO}\nLicense: LGPL-2.1-only.\n\n'
175-
'This F-Droid edition includes 20 starter presets and an optional, '
176-
'verified Cream of the Crop download. App updates use F-Droid. '
177-
'The recipe builds all native code from source and verifies the '
178-
'matching upstream APK. Store metadata is in the selected Fastlane flavor.\n')})
173+
'description': recipes.merge_request_description(target)})
179174
results.append({'package': appid, 'state': 'submission', 'merge_request': mr['iid'],
180175
'version_code': release['version_code']})
181176
return results
@@ -283,6 +278,11 @@ def latest_release():
283278
asset = next(asset for asset in release['assets'] if asset['name'] == 'release-version.json')
284279
if asset.get('digest') and asset['digest'] != 'sha256:' + hashlib.sha256(body).hexdigest():
285280
raise ValueError('Published metadata checksum differs')
281+
# F-Droid's tag update check reads the version from the tagged gradle.properties.
282+
from release_commit import declared_release
283+
properties = github_api(f"repos/{REPOSITORY}/contents/gradle.properties?ref={metadata['source_sha']}")
284+
if declared_release(base64.b64decode(properties['content']).decode()) != (metadata['version'], metadata['version_code']):
285+
raise ValueError('Release tag source does not declare the published version and code')
286286
return metadata
287287

288288

‎.github/scripts/release_commit.py‎

Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
#!/usr/bin/env python3
2+
"""Create and verify the tagged release source that declares its own version.
3+
4+
Each release tag points to a commit whose only parent is the main commit being
5+
released and whose only change appends the release version and Android
6+
versionCode to gradle.properties. The commit is deterministic: rebuilding it
7+
from the same parent, version and code yields the same SHA, so the build and
8+
publish jobs agree without sharing Git objects. It is pushed only as a tag,
9+
never to a branch, so main's first-parent numbering is unaffected.
10+
"""
11+
12+
import argparse
13+
import os
14+
from pathlib import Path
15+
import re
16+
import subprocess
17+
import sys
18+
import tempfile
19+
20+
21+
PROPERTIES = "gradle.properties"
22+
VERSION_KEY = "projectmReleaseVersion"
23+
CODE_KEY = "projectmReleaseVersionCode"
24+
# Fixed identity and parent-derived date keep the commit SHA reproducible.
25+
AUTHOR = ("ProjectM release", "41898282+github-actions[bot]@users.noreply.github.com")
26+
VERSION_PATTERN = r"(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)"
27+
CODE_LIMIT = 2100000000
28+
SHA_PATTERN = r"[0-9a-f]{40}"
29+
KEY_LINE = re.compile(rf"^[ \t]*({VERSION_KEY}|{CODE_KEY})[ \t]*[=:\s]", re.MULTILINE)
30+
31+
32+
def validate(version: str, code: int) -> None:
33+
if not re.fullmatch(VERSION_PATTERN, version):
34+
raise ValueError(f"Invalid release version: {version!r}; expected X.Y.Z")
35+
if type(code) is not int or not 1 <= code <= CODE_LIMIT:
36+
raise ValueError(f"Android versionCode must be an integer from 1 to {CODE_LIMIT}")
37+
38+
39+
def release_properties(original: str, version: str, code: int) -> str:
40+
"""Append the release identity; main itself must never declare one."""
41+
validate(version, code)
42+
if KEY_LINE.search(original):
43+
raise ValueError(f"{PROPERTIES} on main must not declare {VERSION_KEY} or {CODE_KEY}")
44+
base = original if not original or original.endswith("\n") else original + "\n"
45+
return (base + f"\n# Release identity of tag v{version}; written by the release workflow.\n"
46+
f"{VERSION_KEY}={version}\n{CODE_KEY}={code}\n")
47+
48+
49+
def declared_release(text: str) -> tuple[str, int] | None:
50+
"""Return the (version, code) a tagged gradle.properties declares, if any."""
51+
values = {}
52+
for key, value in re.findall(rf"^({VERSION_KEY}|{CODE_KEY})=(.*)$", text, re.MULTILINE):
53+
if key in values:
54+
raise ValueError(f"{PROPERTIES} declares {key} more than once")
55+
values[key] = value
56+
if not values:
57+
return None
58+
version, code = values.get(VERSION_KEY, ""), values.get(CODE_KEY, "")
59+
if not re.fullmatch(r"[1-9][0-9]{0,9}", code):
60+
raise ValueError(f"{PROPERTIES} declares an invalid {CODE_KEY}")
61+
validate(version, int(code))
62+
return version, int(code)
63+
64+
65+
def message(version: str, code: int, source: str) -> str:
66+
return f"Release v{version}\n\nVersion-Code: {code}\nSource-Commit: {source}\n"
67+
68+
69+
def git(repo: Path, *args: str, stdin: str | None = None, env: dict | None = None, raw: bool = False) -> str:
70+
result = subprocess.run(["git", "-C", str(repo), *args], input=stdin, capture_output=True,
71+
text=True, env={**os.environ, **(env or {})})
72+
if result.returncode:
73+
raise ValueError(f"Git command failed: {result.stderr.strip()}")
74+
return result.stdout if raw else result.stdout.strip()
75+
76+
77+
def resolve(repo: Path, revision: str) -> str:
78+
return git(repo, "rev-parse", "--verify", "--end-of-options", revision + "^{commit}")
79+
80+
81+
def create(repo: Path, source: str, version: str, code: int) -> str:
82+
"""Write the release commit object (no ref, no working-tree change) and return its SHA."""
83+
source = resolve(repo, source)
84+
entry = git(repo, "ls-tree", source, "--", PROPERTIES).split()
85+
if len(entry) != 4 or entry[:2] != ["100644", "blob"]:
86+
raise ValueError(f"{PROPERTIES} must be a regular file in the released source")
87+
text = release_properties(git(repo, "cat-file", "blob", entry[2], raw=True), version, code)
88+
blob = git(repo, "hash-object", "-w", "--stdin", stdin=text)
89+
with tempfile.TemporaryDirectory() as directory:
90+
index = {"GIT_INDEX_FILE": str(Path(directory) / "index")}
91+
git(repo, "read-tree", source, env=index)
92+
git(repo, "update-index", "--add", "--cacheinfo", f"100644,{blob},{PROPERTIES}", env=index)
93+
tree = git(repo, "write-tree", env=index)
94+
date = git(repo, "show", "-s", "--format=%ct", source) + " +0000"
95+
identity = {"GIT_AUTHOR_NAME": AUTHOR[0], "GIT_AUTHOR_EMAIL": AUTHOR[1], "GIT_AUTHOR_DATE": date,
96+
"GIT_COMMITTER_NAME": AUTHOR[0], "GIT_COMMITTER_EMAIL": AUTHOR[1], "GIT_COMMITTER_DATE": date}
97+
return git(repo, "-c", "i18n.commitEncoding=UTF-8", "commit-tree", "--no-gpg-sign", tree,
98+
"-p", source, "-F", "-", stdin=message(version, code, source), env=identity)
99+
100+
101+
def inspect(repo: Path, commit: str) -> dict | None:
102+
"""Describe a release commit, None for an ordinary commit; reject malformed release commits."""
103+
commit = resolve(repo, commit)
104+
subject, _, body = git(repo, "show", "-s", "--format=%B", commit).partition("\n")
105+
match = re.fullmatch(rf"Release v({VERSION_PATTERN})", subject)
106+
if not match:
107+
return None
108+
parents = git(repo, "show", "-s", "--format=%P", commit).split()
109+
trailers = dict(re.findall(r"^(Version-Code|Source-Commit): (\S+)$", body, re.MULTILINE))
110+
version = match.group(1)
111+
if (len(parents) != 1 or trailers.get("Source-Commit") != parents[0] or
112+
not re.fullmatch(r"[1-9][0-9]{0,9}", trailers.get("Version-Code", ""))):
113+
raise ValueError(f"Release commit {commit} does not name its single source parent and code")
114+
code = int(trailers["Version-Code"])
115+
changed = git(repo, "diff-tree", "--no-commit-id", "--name-only", "-r", parents[0], commit).splitlines()
116+
expected = release_properties(git(repo, "show", f"{parents[0]}:{PROPERTIES}", raw=True), version, code)
117+
if changed != [PROPERTIES] or git(repo, "show", f"{commit}:{PROPERTIES}", raw=True) != expected:
118+
raise ValueError(f"Release commit {commit} changes more than its declared release identity")
119+
return {"commit": commit, "source": parents[0], "version": version, "version_code": code}
120+
121+
122+
def source_of(repo: Path, commit: str) -> str:
123+
"""Map a tag target to the main commit it releases (older tags point at it directly)."""
124+
details = inspect(repo, commit)
125+
return details["source"] if details else resolve(repo, commit)
126+
127+
128+
def remote_tag(repo: Path, remote: str, tag: str) -> str | None:
129+
"""Return the commit an existing remote tag points to (peeling annotated tags)."""
130+
refs = {}
131+
for line in git(repo, "ls-remote", "--tags", remote).splitlines():
132+
sha, _, name = line.partition("\t")
133+
refs[name] = sha
134+
return refs.get(f"refs/tags/{tag}^{{}}") or refs.get(f"refs/tags/{tag}")
135+
136+
137+
def publish_tag(repo: Path, remote: str, source: str, version: str, code: int, expected: str) -> str:
138+
"""Push the build's release commit as v<version>; an identical existing tag is reused."""
139+
commit = create(repo, source, version, code)
140+
if commit != expected:
141+
raise ValueError(f"Rebuilt release commit {commit} differs from the built source {expected}")
142+
tag = "v" + version
143+
existing = remote_tag(repo, remote, tag)
144+
if existing == commit:
145+
return "existing"
146+
if existing:
147+
raise ValueError(f"Tag {tag} already belongs to {existing}; refusing to move a release tag")
148+
git(repo, "push", "--quiet", remote, f"{commit}:refs/tags/{tag}")
149+
return "created"
150+
151+
152+
def main() -> int:
153+
parser = argparse.ArgumentParser(description=__doc__)
154+
commands = parser.add_subparsers(dest="command", required=True)
155+
for name in ("create", "tag"):
156+
command = commands.add_parser(name)
157+
command.add_argument("--repo", type=Path, default=Path("."))
158+
command.add_argument("--source", required=True)
159+
command.add_argument("--version", required=True)
160+
command.add_argument("--version-code", type=int, required=True)
161+
commands.choices["create"].add_argument("--checkout", action="store_true",
162+
help="Detach the working tree onto the release commit")
163+
commands.choices["create"].add_argument("--output", type=Path, help="Append GitHub Actions outputs")
164+
commands.choices["tag"].add_argument("--expected", required=True)
165+
commands.choices["tag"].add_argument("--remote", default="origin")
166+
args = parser.parse_args()
167+
try:
168+
if args.command == "create":
169+
source = resolve(args.repo, args.source)
170+
commit = create(args.repo, source, args.version, args.version_code)
171+
if args.checkout:
172+
git(args.repo, "checkout", "--quiet", "--detach", commit)
173+
if args.output:
174+
with args.output.open("a", encoding="utf-8") as stream:
175+
stream.write(f"release_sha={commit}\nsource_sha={source}\n")
176+
print(commit)
177+
else:
178+
if not re.fullmatch(SHA_PATTERN, args.expected):
179+
raise ValueError("--expected must be a full commit SHA")
180+
state = publish_tag(args.repo, args.remote, args.source, args.version, args.version_code, args.expected)
181+
print(f"v{args.version} {state} at {args.expected}")
182+
except (ValueError, OSError) as error:
183+
print(f"release_commit: {error}", file=sys.stderr)
184+
return 1
185+
return 0
186+
187+
188+
if __name__ == "__main__":
189+
sys.exit(main())

‎.github/scripts/release_notes.py‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@
1212
import sys
1313
from typing import Callable
1414

15+
sys.path.insert(0, str(Path(__file__).resolve().parent))
16+
from release_commit import source_of # noqa: E402
17+
1518

1619
@dataclass(frozen=True)
1720
class Commit:
@@ -254,8 +257,8 @@ def collect_commits(checkout: Path, sha: str, previous_tag: str | None) -> list[
254257
revision = current
255258
if previous_tag:
256259
try:
257-
previous = git(checkout, "rev-parse", "--verify", "--end-of-options", f"refs/tags/{previous_tag}^{{commit}}")
258-
except subprocess.CalledProcessError as error:
260+
previous = source_of(checkout, f"refs/tags/{previous_tag}")
261+
except ValueError as error:
259262
raise ValueError(f"Previous tag does not exist: {previous_tag}") from error
260263
parents = git(checkout, "rev-list", "--first-parent", current, "--").splitlines()
261264
if previous not in parents:
@@ -320,8 +323,8 @@ def previous_release_tag(checkout: Path, sha: str, version: str, hint: str | Non
320323
if release_version >= current_version:
321324
continue
322325
try:
323-
commit = git(checkout, "rev-parse", "--verify", "--end-of-options", f"refs/tags/{tag}^{{commit}}")
324-
except subprocess.CalledProcessError:
326+
commit = source_of(checkout, f"refs/tags/{tag}")
327+
except ValueError:
325328
continue
326329
if commit in history:
327330
candidates[tag] = release_version

0 commit comments

Comments
 (0)