| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221 |
- #!/usr/bin/env python3
- """Generate the "Inspired by the classics" section of README.md, docs/PLUGINS.md and the website (website/_src/plugins.js).
- Sources: the built-in substitute table in src/core/PluginSubstitutes.cpp (product -> LYNX engine pairs, which also
- auto-open in projects that use the missing original), docs/inspired-by.json (descriptions, short names, work in
- progress) and the Featured / Summary tables of docs/PLUGINS.md (the FL Studio natives line).
- scripts/gen-inspired.py rewrite the three generated blocks in place
- scripts/gen-inspired.py --check exit 1 if any block is out of date (release step / CI)
- """
- import json
- import re
- import sys
- from pathlib import Path
- ROOT = Path(__file__).resolve().parent.parent
- TABLE = ROOT / "src/core/PluginSubstitutes.cpp"
- OVERLAY = ROOT / "docs/inspired-by.json"
- README = ROOT / "README.md"
- PLUGINS = ROOT / "docs/PLUGINS.md"
- SITE = ROOT / "website/_src/plugins.js"
- MD_BEGIN, MD_END = "<!-- inspired:begin (generated by scripts/gen-inspired.py) -->", "<!-- inspired:end -->"
- JS_BEGIN, JS_END = "/* inspired:begin (generated by scripts/gen-inspired.py) */", "/* inspired:end */"
- TM_EN = ("Product and company names are trademarks of their respective owners. They are used only to describe "
- "compatibility and the role each LYNX SHARE engine plays. LYNX SHARE is not affiliated with, endorsed or sponsored by any "
- "of them and contains none of their code, presets, graphics or audio.")
- TM_PT = ("Nomes de produtos e empresas são marcas de seus respectivos donos, citadas só para descrever compatibilidade e "
- "o papel de cada motor do LYNX SHARE. O LYNX SHARE não é afiliado, endossado nem patrocinado por nenhum deles e não contém "
- "código, presets, gráficos nem áudio deles.")
- def parse_table():
- src = TABLE.read_text(encoding="utf-8")
- m = re.search(r'builtInTable = R"TABLE\((.*?)\)TABLE"', src, re.S)
- if not m:
- sys.exit("gen-inspired: substitute table not found in " + str(TABLE))
- entries, cur = [], None
- for line in m.group(1).splitlines():
- line = line.strip()
- if not line or line.startswith("#"):
- continue
- if line.startswith("[") and line.endswith("]"):
- cur = {"id": line[1:-1]}
- entries.append(cur)
- elif cur is not None and "=" in line:
- k, v = line.split("=", 1)
- k = k.strip()
- if k in ("product", "vendor", "lynx"):
- cur[k] = v.strip()
- return [e for e in entries if {"product", "vendor", "lynx"} <= e.keys()]
- def short_name(product, vendor):
- first = vendor.split()[0]
- return product[len(first) + 1:] if product.startswith(first + " ") else product
- def build():
- ov = json.loads(OVERLAY.read_text(encoding="utf-8"))
- engines, products = ov["engines"], ov.get("products", {})
- items, warnings = [], []
- table = parse_table()
- ids = {e["id"] for e in table}
- for e in table:
- p = products.get(e["id"], {})
- it = {"id": e["id"], "vendor": e["vendor"], "product": e["product"],
- "short": p.get("short") or short_name(e["product"], e["vendor"]), "lynx": e["lynx"], "auto": True}
- wip = p.get("wip")
- eng = engines.get(e["lynx"])
- if wip and wip["standIn"] == e["lynx"]:
- it.update(state="wip", name={"en": wip["en"], "pt": wip["pt"]}, kind=wip.get("kind", ""),
- desc={"en": wip["noteEn"], "pt": wip["notePt"]})
- elif eng is None or eng.get("own"):
- if eng is None:
- warnings.append(f"engine '{e['lynx']}' ({e['id']}) has no entry in {OVERLAY.name}: add a description")
- eng = {}
- it.update(state="own", name={"en": e["lynx"], "pt": e["lynx"]}, kind=eng.get("kind", ""),
- desc={"en": eng.get("en", ""), "pt": eng.get("pt", eng.get("en", ""))})
- else:
- it.update(state="standin", name={"en": e["lynx"], "pt": e["lynx"]}, kind="", desc={"en": "", "pt": ""})
- items.append(it)
- for u in ov.get("upcoming", []):
- if u["id"] in ids:
- continue
- items.append({"id": u["id"], "vendor": u["vendor"], "product": u["product"], "short": u.get("short", u["product"]),
- "lynx": "", "auto": False, "state": "wip", "name": {"en": u["en"], "pt": u["pt"]},
- "kind": u.get("kind", ""), "desc": {"en": u["noteEn"], "pt": u["notePt"]}})
- order = ov.get("vendorOrder", [])
- vendors = sorted({i["vendor"] for i in items}, key=lambda v: (order.index(v) if v in order else len(order), v))
- rank = {"own": 0, "wip": 1, "standin": 2}
- vshort = ov.get("vendorShort", {})
- groups = [{"vendor": v, "label": vshort.get(v, v), "items": sorted([i for i in items if i["vendor"] == v], key=lambda i: rank[i["state"]])}
- for v in vendors]
- return groups, fl_natives(), warnings
- def md_table_after(text, heading):
- """Rows (list of cells) of the first Markdown table after a heading line."""
- lines = text.splitlines()
- try:
- start = next(i for i, l in enumerate(lines) if l.strip() == heading)
- except StopIteration:
- return []
- rows = []
- for l in lines[start + 1:]:
- if l.startswith("|"):
- cells = [c.strip() for c in l.strip().strip("|").split("|")]
- if not all(re.fullmatch(r":?-+:?", c) for c in cells):
- rows.append(cells)
- elif rows:
- break
- elif l.startswith("## "):
- break
- return rows[1:] # without the header
- def fl_natives():
- text = PLUGINS.read_text(encoding="utf-8")
- featured = [r[0].replace(" engine", "").replace(" †", "").strip() for r in md_table_after(text, "## Featured")]
- exact = 0
- for r in md_table_after(text, "## Summary"):
- try:
- exact += int(r[1]) + int(r[2])
- except (ValueError, IndexError):
- pass
- return {"featured": featured, "exact": exact}
- STATE_MD = {"own": "native LYNX SHARE engine", "wip": "in progress", "standin": "stand-in"}
- def markdown(groups, fl, full):
- own = len({i["lynx"] for g in groups for i in g["items"] if i["state"] == "own"})
- auto = sum(i["auto"] for g in groups for i in g["items"])
- out = ["## Inspired by the classics", ""]
- out.append(f"LYNX SHARE ships **native** plugins inspired by the third-party plugins producers use most, next to its "
- f"clean-room FL Studio natives. {own} dedicated LYNX SHARE engines are in, more are being built, and a project "
- f"that uses one of the {auto} originals below **opens with the LYNX SHARE equivalent** when the original is "
- f"not installed (its settings are kept and come back once it is; see "
- f"[PLUGIN_FALLBACK.md]({'' if full else 'docs/'}PLUGIN_FALLBACK.md)).")
- out.append("")
- if full:
- out += ["| Inspired by | LYNX SHARE plugin | Status | What it is |", "|---|---|---|---|"]
- for g in groups:
- for i in g["items"]:
- name = i["name"]["en"] if i["state"] != "standin" else i["lynx"]
- status = STATE_MD[i["state"]]
- if i["state"] == "wip" and i["lynx"]:
- status += f" (opens as {i['lynx']} today)"
- if i["auto"]:
- status += " · auto-opens"
- what = i["desc"]["en"] or "an existing LYNX SHARE effect plays its role until a dedicated engine exists"
- out.append(f"| {g['label']} {i['short']} | **{name}** | {status} | {what} |")
- else:
- out += ["| Vendor | Inspired by → LYNX SHARE plugin |", "|---|---|"]
- for g in groups:
- parts = []
- for i in g["items"]:
- if i["state"] == "own":
- parts.append(f"{i['short']} → **{i['lynx']}**")
- elif i["state"] == "wip":
- parts.append(f"{i['short']} → *{i['name']['en'].replace('New LYNX ', '')} in progress*")
- else:
- parts.append(f"{i['short']} → {i['lynx']} (stand-in)")
- out.append(f"| **{g['vendor']}** | {' · '.join(parts)} |")
- natives = ", ".join(fl["featured"])
- if full:
- out.append(f"| FL Studio | **{fl['exact']} FL Studio natives** | Exact / Near-exact | {natives} … "
- f"([all of them](#fl-studio-natives)) |")
- else:
- out.append(f"| **Image-Line FL Studio** | {fl['exact']} natives at Exact / Near-exact quality: {natives} … "
- f"([all of them](docs/PLUGINS.md)) |")
- out += ["", f"<sub>{TM_EN}</sub>"]
- return "\n".join(out)
- def site_data(groups, fl):
- data = {"groups": [{"vendor": g["vendor"], "label": g["label"], "items": [
- {k: i[k] for k in ("short", "lynx", "state", "name", "kind", "desc", "auto")} for i in g["items"]]}
- for g in groups], "fl": fl, "tm": {"en": TM_EN, "pt": TM_PT}}
- return "const INSPIRED = " + json.dumps(data, ensure_ascii=False, separators=(",", ":")) + ";"
- def replace_block(path, begin, end, body, check):
- text = path.read_text(encoding="utf-8")
- a, b = text.find(begin), text.find(end)
- if a < 0 or b < 0:
- sys.exit(f"gen-inspired: markers not found in {path}")
- new = text[:a + len(begin)] + "\n" + body + "\n" + text[b:]
- if new == text:
- return False
- if not check:
- path.write_text(new, encoding="utf-8")
- return True
- def main():
- check = "--check" in sys.argv
- groups, fl, warnings = build()
- for w in warnings:
- print("warning:", w, file=sys.stderr)
- changed = [p.name for p, body, (b, e) in (
- (README, markdown(groups, fl, False), (MD_BEGIN, MD_END)),
- (PLUGINS, markdown(groups, fl, True), (MD_BEGIN, MD_END)),
- (SITE, site_data(groups, fl), (JS_BEGIN, JS_END)),
- ) if replace_block(p, b, e, body, check)]
- n = sum(len(g["items"]) for g in groups)
- if check:
- if changed:
- print("gen-inspired: out of date:", ", ".join(changed), "(run scripts/gen-inspired.py)")
- sys.exit(1)
- print(f"gen-inspired: up to date ({n} entries)")
- else:
- print(f"gen-inspired: {n} entries in {len(groups)} vendor groups; updated: {', '.join(changed) or 'nothing'}")
- if __name__ == "__main__":
- main()
|