Template
mirror of
https://github.com/MorpheApp/morphe-patches-template.git
synced 2026-12-01 00:19:34 +00:00
chore: Add patches list readme generator
This commit is contained in:
1 parent
56d5f7d1c3
commit
7c2f0adeaa
5 files changed
+317
-35
No files matched your search
@@ -0,0 +1,217 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Generates the patches section of README.md from patches-list.json
|
||||
and injects it between <!-- PATCHES_START --> / <!-- PATCHES_END --> markers.
|
||||
|
||||
Spoilers are expanded (open by default) if:
|
||||
1. Total patch count <= AUTO_EXPAND_THRESHOLD.
|
||||
2. The README marker explicitly says: <!-- PATCHES_START EXPANDED -->
|
||||
|
||||
python3 generate_patches_readme.py <owner/repo> <branch> [patches-list.json] [README.md]
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
if len(sys.argv) < 3:
|
||||
print("Usage: generate_patches_readme.py <owner/repo> <branch> [json] [readme]")
|
||||
sys.exit(1)
|
||||
|
||||
repo_full = sys.argv[1]
|
||||
branch = sys.argv[2]
|
||||
json_path = Path(sys.argv[3]) if len(sys.argv) > 3 else Path("patches-list.json")
|
||||
readme_path = Path(sys.argv[4]) if len(sys.argv) > 4 else Path("README.md")
|
||||
|
||||
|
||||
if "/" not in repo_full:
|
||||
raise ValueError(f"Invalid repo format: {repo_full} (expected owner/repo)")
|
||||
|
||||
owner, repo = repo_full.split("/", 1)
|
||||
|
||||
|
||||
with open(json_path) as f:
|
||||
data = json.load(f)
|
||||
|
||||
|
||||
def pkg_emoji(pkg):
|
||||
"""Return a standard package emoji regardless of the package name."""
|
||||
return "📦"
|
||||
|
||||
# Group patches by package; patches with no compatiblePackages are universal.
|
||||
# JSON structure: compatiblePackages is a list of objects with
|
||||
# { packageName, name, targets: [{ version, isExperimental, description }] }
|
||||
by_pkg = {} # packageName -> { name, emoji, patches, targets }
|
||||
universal = {}
|
||||
|
||||
for patch in data["patches"]:
|
||||
cp = patch.get("compatiblePackages")
|
||||
if not cp:
|
||||
# Deduplicate universal patches by name
|
||||
if patch["name"] not in universal:
|
||||
universal[patch["name"]] = patch
|
||||
continue
|
||||
for pkg_entry in cp:
|
||||
pkg = pkg_entry["packageName"]
|
||||
name = pkg_entry.get("name") or pkg # fall back to package name if no label
|
||||
if pkg not in by_pkg:
|
||||
by_pkg[pkg] = {
|
||||
"name": name,
|
||||
"emoji": pkg_emoji(pkg),
|
||||
"patches": {},
|
||||
"targets": pkg_entry.get("targets", []),
|
||||
}
|
||||
# Deduplicate patches that appear across multiple packages
|
||||
if patch["name"] not in by_pkg[pkg]["patches"]:
|
||||
by_pkg[pkg]["patches"][patch["name"]] = patch
|
||||
|
||||
|
||||
def anchor(name):
|
||||
"""Convert a patch name to a GitHub-compatible anchor slug."""
|
||||
return re.sub(r"-+", "-", re.sub(r"[^a-z0-9]+", "-", name.lower())).strip("-")
|
||||
|
||||
|
||||
def patches_table(patches):
|
||||
"""Render a sorted markdown table of patches with name, description, and options."""
|
||||
rows = [
|
||||
"| 💊 Patch | 📜 Description | ⚙️ Options |",
|
||||
"|----------|----------------|-----------|",
|
||||
]
|
||||
for p in sorted(patches, key=lambda x: x["name"]):
|
||||
a = anchor(p["name"])
|
||||
options = p.get("options") or []
|
||||
if options:
|
||||
# Show only option titles as a bullet list
|
||||
parts = [opt.get("title") or opt.get("key") or "" for opt in options]
|
||||
opts_cell = "<br>".join(f"• {t}" for t in parts)
|
||||
else:
|
||||
opts_cell = ""
|
||||
desc = p.get("description") or ""
|
||||
rows.append(f"| [{p['name']}](#{a}) | {desc} | {opts_cell} |")
|
||||
return "\n".join(rows)
|
||||
|
||||
|
||||
def versions_table(targets):
|
||||
"""Render a markdown table of supported versions.
|
||||
Experimental versions get a 🧪 prefix.
|
||||
Versions with a description get it shown in a second row below.
|
||||
"""
|
||||
if not targets:
|
||||
return ""
|
||||
|
||||
cells = []
|
||||
for t in targets:
|
||||
ver = t["version"]
|
||||
label = f"🧪 {ver}" if t.get("isExperimental") else ver
|
||||
cells.append(label)
|
||||
|
||||
header = "| " + " | ".join(cells) + " |"
|
||||
sep = "| " + " | ".join(":---:" for _ in cells) + " |"
|
||||
rows = [header, sep]
|
||||
|
||||
# Optional description row — only rendered if at least one target has one
|
||||
descs = [t.get("description") or "" for t in targets]
|
||||
if any(descs):
|
||||
rows.append("| " + " | ".join(descs) + " |")
|
||||
|
||||
return "\n".join(rows)
|
||||
|
||||
|
||||
def spoiler(label, count, targets, tbl, expanded=False):
|
||||
"""Wrap a patches table in a <details> spoiler with a versions sub-table.
|
||||
If expanded=True, the spoiler is open by default (for repos with few patches).
|
||||
"""
|
||||
noun = "patch" if count == 1 else "patches"
|
||||
vtbl = versions_table(targets)
|
||||
versions_section = f"**🎯 Supported versions:**\n\n{vtbl}\n\n" if vtbl else ""
|
||||
tag = "<details open>" if expanded else "<details>"
|
||||
return f"""{tag}
|
||||
<summary>{label} • {count} {noun}</summary>
|
||||
<br>
|
||||
|
||||
{versions_section}{tbl}
|
||||
|
||||
</details>"""
|
||||
|
||||
|
||||
def build_content(expanded=False):
|
||||
"""Build the full generated patches section."""
|
||||
lines = [
|
||||
f"> **[v{ver}](https://github.com/{owner}/{repo}/releases/tag/v{ver})**"
|
||||
f" • `{branch}` • "
|
||||
f"{total} patches total"
|
||||
]
|
||||
|
||||
# One spoiler per app, in the order they appear in the JSON
|
||||
for pkg, entry in by_pkg.items():
|
||||
patches = list(entry["patches"].values())
|
||||
label = f"{entry['emoji']} {entry['name']}"
|
||||
lines.append(spoiler(label, len(patches), entry["targets"], patches_table(patches), expanded))
|
||||
lines.append("")
|
||||
|
||||
# Universal patches (no specific app)
|
||||
if universal:
|
||||
uni_patches = list(universal.values())
|
||||
noun = "patch" if len(uni_patches) == 1 else "patches"
|
||||
tag = "<details open>" if expanded else "<details>"
|
||||
lines.append(f"""{tag}
|
||||
<summary>🌐 Universal • {len(uni_patches)} {noun}</summary>
|
||||
<br>
|
||||
|
||||
{patches_table(uni_patches)}
|
||||
|
||||
</details>""")
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# Build and inject
|
||||
raw_ver = data["version"]
|
||||
# Strip leading "v" if present
|
||||
ver = raw_ver.lstrip("v")
|
||||
total = sum(len(e["patches"]) for e in by_pkg.values()) + len(universal)
|
||||
|
||||
readme = readme_path.read_text(encoding="utf-8")
|
||||
|
||||
# Marker pattern — matches both <!-- PATCHES_START --> and <!-- PATCHES_START EXPANDED -->
|
||||
START_PATTERN = r"<!-- PATCHES_START(?:\s+EXPANDED)?\s*-->"
|
||||
END_MARKER = "<!-- PATCHES_END -->"
|
||||
|
||||
marker_match = re.search(START_PATTERN, readme)
|
||||
|
||||
if not marker_match or END_MARKER not in readme:
|
||||
# Fallback: print to stdout so CI can catch the issue
|
||||
print(build_content(expanded=False))
|
||||
sys.stderr.write(
|
||||
f"⚠️ Markers <!-- PATCHES_START [EXPANDED] --> / {END_MARKER} not found in {readme_path}. "
|
||||
"Printed to stdout instead.\n"
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
actual_start = marker_match.group(0)
|
||||
|
||||
# Auto-expand threshold
|
||||
AUTO_EXPAND_THRESHOLD = 20
|
||||
|
||||
# Spoilers are expanded if:
|
||||
# 1. Total patch count is small (≤ AUTO_EXPAND_THRESHOLD)
|
||||
# with only a few patches where collapsing adds no benefit.
|
||||
# 2. The README marker explicitly requests it: <!-- PATCHES_START EXPANDED -->
|
||||
expanded = (
|
||||
total <= AUTO_EXPAND_THRESHOLD or
|
||||
"EXPANDED" in actual_start
|
||||
)
|
||||
|
||||
generated = build_content(expanded=expanded)
|
||||
new_readme = re.sub(
|
||||
rf"{START_PATTERN}.*?{re.escape(END_MARKER)}",
|
||||
f"{actual_start}\n{generated}\n{END_MARKER}",
|
||||
readme,
|
||||
flags=re.DOTALL,
|
||||
)
|
||||
readme_path.write_text(new_readme, encoding="utf-8")
|
||||
print(f"✅ Injected patches section into {readme_path} (v{ver}, branch={branch}, {total} patches, expanded={expanded})")
|
||||
@@ -18,7 +18,9 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v5
|
||||
|
||||
+7
-4
@@ -20,7 +20,7 @@
|
||||
"releaseJson": {
|
||||
"path": "patches-bundle.json",
|
||||
"downloadUrlTemplate": "https://github.com/${owner}/${repo}/releases/download/v${version}/patches-${version}.mpp",
|
||||
"signatureUrlTemplate": "https://github.com/${owner}/${repo}/releases/download/v${version}/patches-${version}.mpp.asc"
|
||||
"signatureUrlTemplate": ""
|
||||
}
|
||||
}
|
||||
],
|
||||
@@ -28,7 +28,9 @@
|
||||
[
|
||||
"@semantic-release/exec",
|
||||
{
|
||||
"prepareCmd": "jq '.version=\"${nextRelease.version}\"' patches-list.json > patches-list.json.tmp && mv patches-list.json.tmp patches-list.json"
|
||||
"prepareCmd": "./gradlew generatePatchesList \
|
||||
&& jq '.version=\"${nextRelease.version}\"' patches-list.json > patches-list.json.tmp && mv patches-list.json.tmp patches-list.json \
|
||||
&& python3 .github/scripts/generate_patches_readme.py $GITHUB_REPOSITORY $GITHUB_REF_NAME patches-list.json README.md"
|
||||
}
|
||||
],
|
||||
[
|
||||
@@ -38,7 +40,8 @@
|
||||
"CHANGELOG.md",
|
||||
"gradle.properties",
|
||||
"patches-bundle.json",
|
||||
"patches-list.json"
|
||||
"patches-list.json",
|
||||
"README.md"
|
||||
],
|
||||
"message": "chore: Release v${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"
|
||||
}
|
||||
@@ -55,7 +58,7 @@
|
||||
}
|
||||
],
|
||||
[
|
||||
"@saithodev/semantic-release-backmerge",
|
||||
"@cleyrop-org/semantic-release-backmerge",
|
||||
{
|
||||
"backmergeBranches": [{"from": "main", "to": "dev"}],
|
||||
"clearWorkspace": true
|
||||
|
||||
@@ -2,6 +2,22 @@
|
||||
|
||||
Template repository for Morphe Patches.
|
||||
|
||||
|
||||
## 🩹 Patches list
|
||||
|
||||
<!-- PATCHES_START EXPANDED -->
|
||||
|
||||
<!-- Do not modify this section by hand. The patch list is generated when release.yml creates a new release.
|
||||
|
||||
If you wish for the patches list to be collapsed, then remove the word 'EXPANDED' from the comment tag above.
|
||||
|
||||
If you wish to manually keep this list updated then remove the PATCHES_START and PATCHES_END
|
||||
comment blocks entirely. -->
|
||||
|
||||
#### A list of your patches will be automatically shown here after your first patches release is created.
|
||||
|
||||
<!-- PATCHES_END -->
|
||||
|
||||
|
||||
## ❓ About
|
||||
|
||||
@@ -18,8 +34,9 @@ To start using this template, follow these steps:
|
||||
1. [Create a new repository using this template](https://github.com/new?template_name=morphe-patches-template&template_owner=MorpheApp)
|
||||
2. Set up the [build.gradle.kts](patches/build.gradle.kts) file (Specifically, the
|
||||
[group of the project](patches/build.gradle.kts#L1), and the [About](patches/build.gradle.kts#L5-L11))
|
||||
3. Set up the [README.md](README.md) file[^1] (e.g, title, description, license, summary of the patches
|
||||
that are included in the repository), the [issue templates](.github/ISSUE_TEMPLATE)[^2] and the [contribution guidelines](CONTRIBUTING.md)[^3]
|
||||
3. Set up the [README.md](README.md) file[^1] (e.g, title, description, license,
|
||||
summary of the patches that are included in the repository), the [issue templates](.github/ISSUE_TEMPLATE)[^2]
|
||||
and the [contribution guidelines](CONTRIBUTING.md)[^3].
|
||||
4. Choose a name for your patches project. Keep in mind you must use a unique name that does not
|
||||
imply or suggest authorship by the Morphe open source project. If unsure, then simply name these
|
||||
patches after yourself ("UserXYZ Morphe patches"). See the [NOTICE](NOTICE) for details.
|
||||
@@ -69,12 +86,12 @@ Or manually add this repository url as a patch source in Morphe: https://github.
|
||||
|
||||
### 📙 Contributing
|
||||
|
||||
Thank you for considering contributing to UserXYZ Morphe Patches template.
|
||||
Thank you for considering contributing to UserXYZ Morphe Patches.
|
||||
You can find the contribution guidelines [here](CONTRIBUTING.md).
|
||||
|
||||
### 🛠️ Building
|
||||
|
||||
To build UserXYZ Morphe Patches template,
|
||||
To build UserXYZ Morphe Patches,
|
||||
you can follow the [Morphe documentation](https://github.com/MorpheApp/morphe-documentation).
|
||||
|
||||
## 📜 License
|
||||
|
||||
@@ -41,10 +41,7 @@ import java.io.File
|
||||
import java.net.URLClassLoader
|
||||
import java.util.jar.Manifest
|
||||
|
||||
typealias PackageName = String
|
||||
typealias VersionName = String
|
||||
|
||||
internal fun main() {
|
||||
fun main() {
|
||||
val patchFiles = setOf(
|
||||
File("build/libs/").listFiles { file ->
|
||||
val fileName = file.name
|
||||
@@ -71,28 +68,48 @@ internal fun main() {
|
||||
private fun generatePatchList(version: String, patches: Set<Patch<*>>) {
|
||||
val listJson = File("../patches-list.json")
|
||||
|
||||
val patchesMap = patches.sortedBy { it.name }.map {
|
||||
val patchesMap = patches.sortedBy { it.name }.map { patch ->
|
||||
JsonPatch(
|
||||
it.name!!,
|
||||
it.description,
|
||||
it.use,
|
||||
it.dependencies.map { dependency -> dependency.javaClass.simpleName },
|
||||
it.compatiblePackages?.associate { (packageName, versions) -> packageName to versions },
|
||||
it.options.values.map { option ->
|
||||
JsonPatch.Option(
|
||||
option.key,
|
||||
option.title,
|
||||
option.description,
|
||||
option.required,
|
||||
option.type.toString(),
|
||||
option.default,
|
||||
option.values,
|
||||
name = patch.name!!,
|
||||
description = patch.description,
|
||||
default = patch.default,
|
||||
dependencies = patch.dependencies.map { it.javaClass.simpleName },
|
||||
// Map each Compatibility to a JsonCompatibility object with full metadata.
|
||||
// Patches with null compatiblePackages are universal (apply to any app).
|
||||
compatiblePackages = patch.compatibility?.map { compat ->
|
||||
JsonCompatibility(
|
||||
packageName = compat.packageName!!,
|
||||
name = compat.name,
|
||||
description = compat.description,
|
||||
apkFileType = compat.apkFileType?.name,
|
||||
// Format as #RRGGBB string for readability; null if not set
|
||||
appIconColor = compat.appIconColor?.let { "#%06X".format(it) },
|
||||
signatures = compat.signatures,
|
||||
targets = compat.targets.map { target ->
|
||||
JsonCompatibility.Target(
|
||||
version = target.version,
|
||||
isExperimental = target.isExperimental,
|
||||
minSdk = target.minSdk,
|
||||
description = target.description,
|
||||
)
|
||||
},
|
||||
)
|
||||
},
|
||||
options = patch.options.values.map { option ->
|
||||
JsonPatch.Option(
|
||||
key = option.key,
|
||||
title = option.title,
|
||||
description = option.description,
|
||||
required = option.required,
|
||||
type = option.type.toString(),
|
||||
default = option.default,
|
||||
values = option.values,
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
val gsonBuilder = GsonBuilder()
|
||||
val gson = GsonBuilder()
|
||||
.serializeNulls()
|
||||
.disableHtmlEscaping()
|
||||
.setPrettyPrinting()
|
||||
@@ -100,20 +117,20 @@ private fun generatePatchList(version: String, patches: Set<Patch<*>>) {
|
||||
|
||||
val jsonObject = JsonObject()
|
||||
jsonObject.addProperty("version", "v$version")
|
||||
jsonObject.add("patches", gsonBuilder.toJsonTree(patchesMap))
|
||||
jsonObject.add("patches", gson.toJsonTree(patchesMap))
|
||||
|
||||
listJson.writeText(
|
||||
gsonBuilder.toJson(jsonObject)
|
||||
)
|
||||
listJson.writeText(gson.toJson(jsonObject))
|
||||
}
|
||||
|
||||
/** JSON representation of a patch entry in patches-list.json. */
|
||||
@Suppress("unused")
|
||||
private class JsonPatch(
|
||||
val name: String? = null,
|
||||
val description: String? = null,
|
||||
val use: Boolean = true,
|
||||
val default: Boolean = true,
|
||||
val dependencies: List<String>,
|
||||
val compatiblePackages: Map<PackageName, Set<VersionName>?>? = null,
|
||||
/** Null means the patch is universal and applies to any app. */
|
||||
val compatiblePackages: List<JsonCompatibility>? = null,
|
||||
val options: List<Option>,
|
||||
) {
|
||||
class Option(
|
||||
@@ -127,3 +144,29 @@ private class JsonPatch(
|
||||
)
|
||||
}
|
||||
|
||||
/** JSON representation of a compatible app entry, including name and per-version metadata. */
|
||||
@Suppress("unused")
|
||||
private class JsonCompatibility(
|
||||
/** Android package name, e.g. com.google.android.youtube. */
|
||||
val packageName: String,
|
||||
/** Human-readable app name declared in Compatibility, e.g. "YouTube". */
|
||||
val name: String?,
|
||||
/** User-facing description of the app. */
|
||||
val description: String?,
|
||||
/** Target unpatched app file type, e.g. APK, APKM. Null if not specified. */
|
||||
val apkFileType: String?,
|
||||
/** App icon background color as #RRGGBB string, or null if not set. */
|
||||
val appIconColor: String?,
|
||||
/** Valid SHA-256 signatures of the app. */
|
||||
val signatures: Set<String>?,
|
||||
val targets: List<Target>,
|
||||
) {
|
||||
class Target(
|
||||
val version: String?,
|
||||
val isExperimental: Boolean,
|
||||
/** Minimum device SDK version. Null means any SDK version. */
|
||||
val minSdk: Int?,
|
||||
/** Optional user-facing note about this specific version. */
|
||||
val description: String?,
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user