4
0

gen-inspired.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. #!/usr/bin/env python3
  2. """Generate the "Inspired by the classics" section of README.md, docs/PLUGINS.md and the website (website/_src/plugins.js).
  3. Sources: the built-in substitute table in src/core/PluginSubstitutes.cpp (product -> LYNX engine pairs, which also
  4. auto-open in projects that use the missing original), docs/inspired-by.json (descriptions, short names, work in
  5. progress) and the Featured / Summary tables of docs/PLUGINS.md (the FL Studio natives line).
  6. scripts/gen-inspired.py rewrite the three generated blocks in place
  7. scripts/gen-inspired.py --check exit 1 if any block is out of date (release step / CI)
  8. """
  9. import json
  10. import re
  11. import sys
  12. from pathlib import Path
  13. ROOT = Path(__file__).resolve().parent.parent
  14. TABLE = ROOT / "src/core/PluginSubstitutes.cpp"
  15. OVERLAY = ROOT / "docs/inspired-by.json"
  16. README = ROOT / "README.md"
  17. PLUGINS = ROOT / "docs/PLUGINS.md"
  18. SITE = ROOT / "website/_src/plugins.js"
  19. MD_BEGIN, MD_END = "<!-- inspired:begin (generated by scripts/gen-inspired.py) -->", "<!-- inspired:end -->"
  20. JS_BEGIN, JS_END = "/* inspired:begin (generated by scripts/gen-inspired.py) */", "/* inspired:end */"
  21. TM_EN = ("Product and company names are trademarks of their respective owners. They are used only to describe "
  22. "compatibility and the role each LYNX SHARE engine plays. LYNX SHARE is not affiliated with, endorsed or sponsored by any "
  23. "of them and contains none of their code, presets, graphics or audio.")
  24. TM_PT = ("Nomes de produtos e empresas são marcas de seus respectivos donos, citadas só para descrever compatibilidade e "
  25. "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 "
  26. "código, presets, gráficos nem áudio deles.")
  27. def parse_table():
  28. src = TABLE.read_text(encoding="utf-8")
  29. m = re.search(r'builtInTable = R"TABLE\((.*?)\)TABLE"', src, re.S)
  30. if not m:
  31. sys.exit("gen-inspired: substitute table not found in " + str(TABLE))
  32. entries, cur = [], None
  33. for line in m.group(1).splitlines():
  34. line = line.strip()
  35. if not line or line.startswith("#"):
  36. continue
  37. if line.startswith("[") and line.endswith("]"):
  38. cur = {"id": line[1:-1]}
  39. entries.append(cur)
  40. elif cur is not None and "=" in line:
  41. k, v = line.split("=", 1)
  42. k = k.strip()
  43. if k in ("product", "vendor", "lynx"):
  44. cur[k] = v.strip()
  45. return [e for e in entries if {"product", "vendor", "lynx"} <= e.keys()]
  46. def short_name(product, vendor):
  47. first = vendor.split()[0]
  48. return product[len(first) + 1:] if product.startswith(first + " ") else product
  49. def build():
  50. ov = json.loads(OVERLAY.read_text(encoding="utf-8"))
  51. engines, products = ov["engines"], ov.get("products", {})
  52. items, warnings = [], []
  53. table = parse_table()
  54. ids = {e["id"] for e in table}
  55. for e in table:
  56. p = products.get(e["id"], {})
  57. it = {"id": e["id"], "vendor": e["vendor"], "product": e["product"],
  58. "short": p.get("short") or short_name(e["product"], e["vendor"]), "lynx": e["lynx"], "auto": True}
  59. wip = p.get("wip")
  60. eng = engines.get(e["lynx"])
  61. if wip and wip["standIn"] == e["lynx"]:
  62. it.update(state="wip", name={"en": wip["en"], "pt": wip["pt"]}, kind=wip.get("kind", ""),
  63. desc={"en": wip["noteEn"], "pt": wip["notePt"]})
  64. elif eng is None or eng.get("own"):
  65. if eng is None:
  66. warnings.append(f"engine '{e['lynx']}' ({e['id']}) has no entry in {OVERLAY.name}: add a description")
  67. eng = {}
  68. it.update(state="own", name={"en": e["lynx"], "pt": e["lynx"]}, kind=eng.get("kind", ""),
  69. desc={"en": eng.get("en", ""), "pt": eng.get("pt", eng.get("en", ""))})
  70. else:
  71. it.update(state="standin", name={"en": e["lynx"], "pt": e["lynx"]}, kind="", desc={"en": "", "pt": ""})
  72. items.append(it)
  73. for u in ov.get("upcoming", []):
  74. if u["id"] in ids:
  75. continue
  76. items.append({"id": u["id"], "vendor": u["vendor"], "product": u["product"], "short": u.get("short", u["product"]),
  77. "lynx": "", "auto": False, "state": "wip", "name": {"en": u["en"], "pt": u["pt"]},
  78. "kind": u.get("kind", ""), "desc": {"en": u["noteEn"], "pt": u["notePt"]}})
  79. order = ov.get("vendorOrder", [])
  80. vendors = sorted({i["vendor"] for i in items}, key=lambda v: (order.index(v) if v in order else len(order), v))
  81. rank = {"own": 0, "wip": 1, "standin": 2}
  82. vshort = ov.get("vendorShort", {})
  83. 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"]])}
  84. for v in vendors]
  85. return groups, fl_natives(), warnings
  86. def md_table_after(text, heading):
  87. """Rows (list of cells) of the first Markdown table after a heading line."""
  88. lines = text.splitlines()
  89. try:
  90. start = next(i for i, l in enumerate(lines) if l.strip() == heading)
  91. except StopIteration:
  92. return []
  93. rows = []
  94. for l in lines[start + 1:]:
  95. if l.startswith("|"):
  96. cells = [c.strip() for c in l.strip().strip("|").split("|")]
  97. if not all(re.fullmatch(r":?-+:?", c) for c in cells):
  98. rows.append(cells)
  99. elif rows:
  100. break
  101. elif l.startswith("## "):
  102. break
  103. return rows[1:] # without the header
  104. def fl_natives():
  105. text = PLUGINS.read_text(encoding="utf-8")
  106. featured = [r[0].replace(" engine", "").replace(" †", "").strip() for r in md_table_after(text, "## Featured")]
  107. exact = 0
  108. for r in md_table_after(text, "## Summary"):
  109. try:
  110. exact += int(r[1]) + int(r[2])
  111. except (ValueError, IndexError):
  112. pass
  113. return {"featured": featured, "exact": exact}
  114. STATE_MD = {"own": "native LYNX SHARE engine", "wip": "in progress", "standin": "stand-in"}
  115. def markdown(groups, fl, full):
  116. own = len({i["lynx"] for g in groups for i in g["items"] if i["state"] == "own"})
  117. auto = sum(i["auto"] for g in groups for i in g["items"])
  118. out = ["## Inspired by the classics", ""]
  119. out.append(f"LYNX SHARE ships **native** plugins inspired by the third-party plugins producers use most, next to its "
  120. f"clean-room FL Studio natives. {own} dedicated LYNX SHARE engines are in, more are being built, and a project "
  121. f"that uses one of the {auto} originals below **opens with the LYNX SHARE equivalent** when the original is "
  122. f"not installed (its settings are kept and come back once it is; see "
  123. f"[PLUGIN_FALLBACK.md]({'' if full else 'docs/'}PLUGIN_FALLBACK.md)).")
  124. out.append("")
  125. if full:
  126. out += ["| Inspired by | LYNX SHARE plugin | Status | What it is |", "|---|---|---|---|"]
  127. for g in groups:
  128. for i in g["items"]:
  129. name = i["name"]["en"] if i["state"] != "standin" else i["lynx"]
  130. status = STATE_MD[i["state"]]
  131. if i["state"] == "wip" and i["lynx"]:
  132. status += f" (opens as {i['lynx']} today)"
  133. if i["auto"]:
  134. status += " · auto-opens"
  135. what = i["desc"]["en"] or "an existing LYNX SHARE effect plays its role until a dedicated engine exists"
  136. out.append(f"| {g['label']} {i['short']} | **{name}** | {status} | {what} |")
  137. else:
  138. out += ["| Vendor | Inspired by → LYNX SHARE plugin |", "|---|---|"]
  139. for g in groups:
  140. parts = []
  141. for i in g["items"]:
  142. if i["state"] == "own":
  143. parts.append(f"{i['short']} → **{i['lynx']}**")
  144. elif i["state"] == "wip":
  145. parts.append(f"{i['short']} → *{i['name']['en'].replace('New LYNX ', '')} in progress*")
  146. else:
  147. parts.append(f"{i['short']} → {i['lynx']} (stand-in)")
  148. out.append(f"| **{g['vendor']}** | {' · '.join(parts)} |")
  149. natives = ", ".join(fl["featured"])
  150. if full:
  151. out.append(f"| FL Studio | **{fl['exact']} FL Studio natives** | Exact / Near-exact | {natives} … "
  152. f"([all of them](#fl-studio-natives)) |")
  153. else:
  154. out.append(f"| **Image-Line FL Studio** | {fl['exact']} natives at Exact / Near-exact quality: {natives} … "
  155. f"([all of them](docs/PLUGINS.md)) |")
  156. out += ["", f"<sub>{TM_EN}</sub>"]
  157. return "\n".join(out)
  158. def site_data(groups, fl):
  159. data = {"groups": [{"vendor": g["vendor"], "label": g["label"], "items": [
  160. {k: i[k] for k in ("short", "lynx", "state", "name", "kind", "desc", "auto")} for i in g["items"]]}
  161. for g in groups], "fl": fl, "tm": {"en": TM_EN, "pt": TM_PT}}
  162. return "const INSPIRED = " + json.dumps(data, ensure_ascii=False, separators=(",", ":")) + ";"
  163. def replace_block(path, begin, end, body, check):
  164. text = path.read_text(encoding="utf-8")
  165. a, b = text.find(begin), text.find(end)
  166. if a < 0 or b < 0:
  167. sys.exit(f"gen-inspired: markers not found in {path}")
  168. new = text[:a + len(begin)] + "\n" + body + "\n" + text[b:]
  169. if new == text:
  170. return False
  171. if not check:
  172. path.write_text(new, encoding="utf-8")
  173. return True
  174. def main():
  175. check = "--check" in sys.argv
  176. groups, fl, warnings = build()
  177. for w in warnings:
  178. print("warning:", w, file=sys.stderr)
  179. changed = [p.name for p, body, (b, e) in (
  180. (README, markdown(groups, fl, False), (MD_BEGIN, MD_END)),
  181. (PLUGINS, markdown(groups, fl, True), (MD_BEGIN, MD_END)),
  182. (SITE, site_data(groups, fl), (JS_BEGIN, JS_END)),
  183. ) if replace_block(p, b, e, body, check)]
  184. n = sum(len(g["items"]) for g in groups)
  185. if check:
  186. if changed:
  187. print("gen-inspired: out of date:", ", ".join(changed), "(run scripts/gen-inspired.py)")
  188. sys.exit(1)
  189. print(f"gen-inspired: up to date ({n} entries)")
  190. else:
  191. print(f"gen-inspired: {n} entries in {len(groups)} vendor groups; updated: {', '.join(changed) or 'nothing'}")
  192. if __name__ == "__main__":
  193. main()