generate_mod_ui_pedalboard.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. #!/usr/bin/env python3
  2. """Generate Rigforge's four-source reference pedalboard bundle for mod-ui."""
  3. import argparse
  4. import hashlib
  5. import json
  6. import os
  7. import shutil
  8. import sys
  9. import tempfile
  10. from pathlib import Path, PurePosixPath
  11. import yaml
  12. from validate_desired_state import safe_relative_path, validate_state
  13. ROOT = Path(__file__).resolve().parents[1]
  14. def turtle_string(value):
  15. return json.dumps(str(value), ensure_ascii=False)
  16. def plugin_state_files(processor, plugin_path):
  17. instance = processor["instance"]
  18. plugin_uri = processor["plugin_uri"]
  19. state_dir = f"effect-{instance}"
  20. if processor.get("file_property"):
  21. effect_ttl = (
  22. "@prefix atom: <http://lv2plug.in/ns/ext/atom#> .\n"
  23. "@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n"
  24. "@prefix pset: <http://lv2plug.in/ns/ext/presets#> .\n"
  25. "@prefix state: <http://lv2plug.in/ns/ext/state#> .\n\n"
  26. "<>\n"
  27. " a pset:Preset ;\n"
  28. f" lv2:appliesTo <{plugin_uri}> ;\n"
  29. " state:state [\n"
  30. f" <{processor['file_property']}> {turtle_string(plugin_path)}^^atom:Path\n"
  31. " ] .\n"
  32. )
  33. else:
  34. effect_ttl = (
  35. "@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n"
  36. "@prefix pset: <http://lv2plug.in/ns/ext/presets#> .\n\n"
  37. "<>\n"
  38. " a pset:Preset ;\n"
  39. f" lv2:appliesTo <{plugin_uri}> .\n"
  40. )
  41. manifest_ttl = (
  42. "@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n"
  43. "@prefix pset: <http://lv2plug.in/ns/ext/presets#> .\n"
  44. "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\n"
  45. "<effect.ttl>\n"
  46. f" lv2:appliesTo <{plugin_uri}> ;\n"
  47. " a pset:Preset ;\n"
  48. " rdfs:seeAlso <effect.ttl> .\n"
  49. )
  50. return {
  51. f"{state_dir}/effect.ttl": effect_ttl.encode("utf-8"),
  52. f"{state_dir}/manifest.ttl": manifest_ttl.encode("utf-8"),
  53. }
  54. def resolved_asset(repo_root, relative):
  55. if not safe_relative_path(relative):
  56. raise ValueError(f"unsafe pedalboard asset path: {relative!r}")
  57. path = (repo_root / Path(*PurePosixPath(relative).parts)).resolve()
  58. if not path.is_relative_to(repo_root.resolve()) or not path.is_file():
  59. raise FileNotFoundError(f"pedalboard asset is missing or outside repository: {path}")
  60. return path
  61. def generate_bundle_files(state, repo_root=ROOT, asset_root=None, nam_model_path=None):
  62. errors = validate_state(state)
  63. if errors:
  64. raise ValueError("invalid desired state: " + "; ".join(errors))
  65. repo_root = Path(repo_root).resolve()
  66. asset_root = Path(asset_root or repo_root / "artifacts" / "mod-ui" / "arm64" / "current" / "app" / "default.pedalboard")
  67. routing = state["routing"]["mod_host_chains"]["guitar"]
  68. nam, ir = routing["processors"]
  69. voice_chain = state["routing"]["mod_host_chains"]["voice"]
  70. voice_processors = voice_chain["processors"]
  71. nam_source_path = resolved_asset(repo_root, nam["asset_path"])
  72. nam_path = Path(nam_model_path).resolve() if nam_model_path else nam_source_path
  73. if not nam_path.is_file():
  74. raise FileNotFoundError(f"NAM model file is missing: {nam_path}")
  75. ir_path = resolved_asset(repo_root, ir["asset_path"])
  76. output_level = nam["parameters"]["output_level"]
  77. plugin_files = {}
  78. for processor in voice_processors:
  79. plugin_files.update(plugin_state_files(processor, ""))
  80. nam_instance = nam["mod_ui_instance"].removeprefix("/graph/")
  81. ir_instance = ir["mod_ui_instance"].removeprefix("/graph/")
  82. nam_model_uri = nam["file_property"]
  83. ir_file_uri = ir["file_property"]
  84. source_labels = {
  85. "guitar": "Guitare",
  86. "bass": "Basse",
  87. "voice": "Micro",
  88. "synth": "Synthé",
  89. }
  90. source_ids = {source["id"] for source in state["sources"]}
  91. passthrough_channels = [
  92. (index, source_labels[source_id])
  93. for index, source_id in enumerate(("guitar", "bass", "voice", "synth"), start=1)
  94. if source_id not in ("guitar", "voice") and source_id in source_ids
  95. ]
  96. additional_ports_ttl = "\n\n".join(
  97. f'''<capture_{index}>
  98. lv2:index {9 + (index - 2) * 2} ;
  99. lv2:name "{label} - Entrée mod-ui" ;
  100. lv2:portProperty lv2:connectionOptional ;
  101. lv2:symbol "capture_{index}" ;
  102. a lv2:AudioPort, lv2:InputPort .
  103. <playback_{index}>
  104. lv2:index {10 + (index - 2) * 2} ;
  105. lv2:name "{label} - Sortie mod-ui" ;
  106. lv2:portProperty lv2:connectionOptional ;
  107. lv2:symbol "playback_{index}" ;
  108. a lv2:AudioPort, lv2:OutputPort .'''
  109. for index, label in passthrough_channels
  110. )
  111. additional_arcs_list = ", ".join(
  112. [f"_:b{index + 2}" for index, _label in passthrough_channels]
  113. + [f"_:voice{index}" for index in range(1, len(voice_processors))]
  114. + ["_:voice0", "_:voice_out"]
  115. )
  116. additional_arcs_ttl = "\n\n".join(
  117. f"_:b{index + 2} ingen:tail <capture_{index}> ;\n"
  118. f" ingen:head <playback_{index}> ."
  119. for index, _label in passthrough_channels
  120. )
  121. additional_ports_list = ",\n ".join(
  122. f"<{symbol}_{index}>"
  123. for index, _label in passthrough_channels
  124. for symbol in ("capture", "playback")
  125. )
  126. voice_processors_ttl = []
  127. voice_processor_blocks = []
  128. voice_processor_arcs = []
  129. for index, processor in enumerate(voice_processors):
  130. instance = processor["mod_ui_instance"].removeprefix("/graph/")
  131. plugin_uri = processor["plugin_uri"]
  132. if processor["id"] == "voice-reverb":
  133. plugin_uri = "urn:dragonfly:room"
  134. input_symbol = "input_l" if processor["id"] == "voice-reverb" else "in"
  135. output_symbol = "output_l" if processor["id"] == "voice-reverb" else "out"
  136. label = {
  137. "voice-high-pass": "Coupe-bas",
  138. "voice-compressor": "Compresseur voix",
  139. "voice-de-esser": "De-esser",
  140. "voice-reverb": "Réverbération voix",
  141. }[processor["id"]]
  142. x_position = 160.0 + index * 260.0
  143. port_symbols = {
  144. "voice-high-pass": ("in", "out", {"mode": "mode", "filter_type": "ft", "filter_mode": "fm", "slope": "s", "frequency_hz": "f", "quality": "q"}),
  145. "voice-compressor": ("in", "out", {"compression_mode": "cm", "ratio": "cr", "attack_time_ms": "at", "release_time_ms": "rt"}),
  146. "voice-de-esser": ("in", "out", {}),
  147. "voice-reverb": ("input_l", "output_l", {"dry_level": "dry_level", "early_level": "early_level", "late_level": "late_level", "size": "size", "predelay_ms": "predelay", "decay_seconds": "decay", "in_low_cut_hz": "in_low_cut", "in_high_cut_hz": "in_high_cut"}),
  148. }
  149. input_symbol, output_symbol, control_symbols = port_symbols[processor["id"]]
  150. port_declarations = [
  151. f"<{instance}/{input_symbol}>",
  152. f"<{instance}/{output_symbol}>",
  153. f"<{instance}/:bypass>",
  154. ]
  155. if processor["id"] == "voice-reverb":
  156. port_declarations.extend(
  157. (f"<{instance}/input_r>", f"<{instance}/output_r>")
  158. )
  159. control_declarations = []
  160. for parameter in processor.get("parameters", {}):
  161. if processor["id"] == "voice-de-esser":
  162. continue
  163. symbol = control_symbols[parameter]
  164. port_declarations.append(f"<{instance}/{symbol}>")
  165. value = processor["parameters"][parameter]
  166. if processor["id"] == "voice-high-pass":
  167. value = {
  168. "mode": 0,
  169. "filter_type": 1,
  170. "filter_mode": 2,
  171. "slope": 1,
  172. "frequency_hz": 90.0,
  173. "quality": 0.707,
  174. }[parameter]
  175. elif processor["id"] == "voice-compressor":
  176. value = {
  177. "compression_mode": 0,
  178. "ratio": 3.0,
  179. "attack_time_ms": 10.0,
  180. "release_time_ms": 120.0,
  181. }[parameter]
  182. rendered_value = json.dumps(value) if isinstance(value, str) else str(value)
  183. control_declarations.append(
  184. f"<{instance}/{symbol}>\n"
  185. f" ingen:value {rendered_value} ;\n"
  186. " a lv2:ControlPort, lv2:InputPort ."
  187. )
  188. if processor["id"] == "voice-de-esser":
  189. values = {
  190. "Ratio": 2.0,
  191. "Threshold": 0.1,
  192. "Attack": 5.0,
  193. "Release": 80.0,
  194. "Split": 6000.0,
  195. }
  196. for symbol, value in values.items():
  197. port_declarations.append(f"<{instance}/{symbol}>")
  198. control_declarations.append(
  199. f"<{instance}/{symbol}>\n"
  200. f" ingen:value {value} ;\n"
  201. " a lv2:ControlPort, lv2:InputPort ."
  202. )
  203. extra_audio_ports = ""
  204. if processor["id"] == "voice-reverb":
  205. extra_audio_ports = (
  206. f"\n\n<{instance}/input_r>\n"
  207. " a lv2:AudioPort, lv2:InputPort .\n"
  208. f"\n<{instance}/output_r>\n"
  209. " a lv2:AudioPort, lv2:OutputPort ."
  210. )
  211. voice_processors_ttl.append(
  212. f"""<{instance}>
  213. ingen:canvasX {x_position} ;
  214. ingen:canvasY 650.0 ;
  215. ingen:enabled true ;
  216. ingen:polyphonic false ;
  217. pedal:instanceLabel "{label}" ;
  218. pedal:instanceNumber {processor["instance"]} ;
  219. pedal:performanceVisible true ;
  220. pedal:performanceIndex {index + 2} ;
  221. lv2:prototype <{plugin_uri}> ;
  222. lv2:port {", ".join(port_declarations)} ;
  223. a ingen:Block .
  224. <{instance}/{input_symbol}>
  225. a lv2:AudioPort, lv2:InputPort .
  226. <{instance}/{output_symbol}>
  227. a lv2:AudioPort, lv2:OutputPort .
  228. <{instance}/:bypass>
  229. ingen:value 0 ;
  230. a lv2:ControlPort, lv2:InputPort ."""
  231. )
  232. voice_processors_ttl[-1] += "\n\n" + "\n\n".join(control_declarations)
  233. voice_processors_ttl[-1] += extra_audio_ports
  234. if index > 0:
  235. previous = voice_processors[index - 1]
  236. previous_instance = previous["mod_ui_instance"].removeprefix("/graph/")
  237. previous_output = (
  238. "output_l" if previous["id"] == "voice-reverb" else "out"
  239. )
  240. voice_processor_arcs.append(
  241. f"_:voice{index} ingen:tail <{previous_instance}/{previous_output}> ;\n"
  242. f" ingen:head <{instance}/{input_symbol}> ."
  243. )
  244. voice_chain_ttl = "\n\n".join(voice_processors_ttl)
  245. voice_chain_arcs_ttl = "\n\n".join(voice_processor_arcs)
  246. first_voice = voice_processors[0]
  247. last_voice = voice_processors[-1]
  248. first_voice_instance = first_voice["mod_ui_instance"].removeprefix("/graph/")
  249. last_voice_instance = last_voice["mod_ui_instance"].removeprefix("/graph/")
  250. first_voice_input = "in"
  251. last_voice_output = "output_l" if last_voice["id"] == "voice-reverb" else "out"
  252. ttl = f"""\
  253. @prefix atom: <http://lv2plug.in/ns/ext/atom#> .
  254. @prefix doap: <http://usefulinc.com/ns/doap#> .
  255. @prefix ingen: <http://drobilla.net/ns/ingen#> .
  256. @prefix lv2: <http://lv2plug.in/ns/lv2core#> .
  257. @prefix midi: <http://lv2plug.in/ns/ext/midi#> .
  258. @prefix mod: <http://moddevices.com/ns/mod#> .
  259. @prefix patch: <http://lv2plug.in/ns/ext/patch#> .
  260. @prefix pedal: <http://moddevices.com/ns/modpedal#> .
  261. @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
  262. @prefix state: <http://lv2plug.in/ns/ext/state#> .
  263. @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
  264. <capture_1>
  265. lv2:index 5 ;
  266. lv2:name "Guitare - Entrée mod-ui" ;
  267. lv2:portProperty lv2:connectionOptional ;
  268. lv2:symbol "capture_1" ;
  269. a lv2:AudioPort, lv2:InputPort .
  270. <playback_1>
  271. lv2:index 6 ;
  272. lv2:name "Guitare - Sortie mod-ui" ;
  273. lv2:portProperty lv2:connectionOptional ;
  274. lv2:symbol "playback_1" ;
  275. a lv2:AudioPort, lv2:OutputPort .
  276. {additional_ports_ttl}
  277. {voice_chain_ttl}
  278. <:bpb>
  279. ingen:value 4.0 ;
  280. lv2:index 0 ;
  281. a lv2:ControlPort, lv2:InputPort .
  282. <:bpm>
  283. ingen:value 120.0 ;
  284. lv2:index 1 ;
  285. a lv2:ControlPort, lv2:InputPort .
  286. <:rolling>
  287. ingen:value 0 ;
  288. lv2:index 2 ;
  289. a lv2:ControlPort, lv2:InputPort .
  290. <control_in>
  291. atom:bufferType atom:Sequence ;
  292. atom:supports midi:MidiEvent ;
  293. lv2:index 3 ;
  294. lv2:name "Control In" ;
  295. lv2:portProperty lv2:connectionOptional ;
  296. lv2:symbol "control_in" ;
  297. <http://lv2plug.in/ns/ext/resize-port#minimumSize> 4096 ;
  298. a atom:AtomPort, lv2:InputPort .
  299. <control_out>
  300. atom:bufferType atom:Sequence ;
  301. atom:supports midi:MidiEvent ;
  302. lv2:index 4 ;
  303. lv2:name "Control Out" ;
  304. lv2:portProperty lv2:connectionOptional ;
  305. lv2:symbol "control_out" ;
  306. <http://lv2plug.in/ns/ext/resize-port#minimumSize> 4096 ;
  307. a atom:AtomPort, lv2:OutputPort .
  308. <midi_separated_mode>
  309. ingen:value 0 ;
  310. lv2:index 7 ;
  311. a atom:AtomPort, lv2:InputPort .
  312. <midi_loopback>
  313. ingen:value 0 ;
  314. lv2:index 8 ;
  315. a atom:AtomPort, lv2:InputPort .
  316. <{nam_instance}>
  317. ingen:canvasX 160.0 ;
  318. ingen:canvasY 280.0 ;
  319. ingen:enabled true ;
  320. ingen:polyphonic false ;
  321. lv2:microVersion 0 ;
  322. lv2:minorVersion 0 ;
  323. mod:builderVersion 0 ;
  324. mod:releaseNumber 0 ;
  325. pedal:instanceLabel "NAM" ;
  326. pedal:instanceNumber {nam["instance"]} ;
  327. pedal:performanceVisible true ;
  328. pedal:performanceIndex 0 ;
  329. lv2:prototype <{nam["plugin_uri"]}> ;
  330. lv2:port <{nam_instance}/control>,
  331. <{nam_instance}/notify>,
  332. <{nam_instance}/input>,
  333. <{nam_instance}/output>,
  334. <{nam_instance}/input_level>,
  335. <{nam_instance}/output_level>,
  336. <{nam_instance}/quality_scale>,
  337. <{nam_instance}/:bypass> ;
  338. state:state [ <{nam_model_uri}> {turtle_string(str(nam_path))}^^atom:Path ] ;
  339. a ingen:Block .
  340. <{nam_instance}/control>
  341. atom:bufferType atom:Sequence ;
  342. atom:supports patch:Message ;
  343. lv2:designation lv2:control ;
  344. lv2:index 0 ;
  345. lv2:symbol "control" ;
  346. a atom:AtomPort, lv2:InputPort .
  347. <{nam_instance}/notify>
  348. atom:bufferType atom:Sequence ;
  349. atom:supports patch:Message ;
  350. lv2:designation lv2:control ;
  351. lv2:index 1 ;
  352. lv2:symbol "notify" ;
  353. a atom:AtomPort, lv2:OutputPort .
  354. <{nam_instance}/input>
  355. a lv2:AudioPort, lv2:InputPort .
  356. <{nam_instance}/output>
  357. a lv2:AudioPort, lv2:OutputPort .
  358. <{nam_instance}/input_level>
  359. ingen:value 0.0 ;
  360. a lv2:ControlPort, lv2:InputPort .
  361. <{nam_instance}/output_level>
  362. ingen:value {output_level} ;
  363. a lv2:ControlPort, lv2:InputPort .
  364. <{nam_instance}/quality_scale>
  365. ingen:value 1.0 ;
  366. a lv2:ControlPort, lv2:InputPort .
  367. <{nam_instance}/:bypass>
  368. ingen:value 0 ;
  369. a lv2:ControlPort, lv2:InputPort .
  370. <{ir_instance}>
  371. ingen:canvasX 620.0 ;
  372. ingen:canvasY 280.0 ;
  373. ingen:enabled true ;
  374. ingen:polyphonic false ;
  375. lv2:microVersion 0 ;
  376. lv2:minorVersion 0 ;
  377. mod:builderVersion 0 ;
  378. mod:releaseNumber 0 ;
  379. pedal:instanceLabel "Cabinet IR" ;
  380. pedal:instanceNumber {ir["instance"]} ;
  381. pedal:performanceVisible true ;
  382. pedal:performanceIndex 1 ;
  383. lv2:prototype <{ir["plugin_uri"]}> ;
  384. lv2:port <{ir_instance}/control>,
  385. <{ir_instance}/notify>,
  386. <{ir_instance}/in>,
  387. <{ir_instance}/out>,
  388. <{ir_instance}/:bypass> ;
  389. state:state [ <{ir_file_uri}> {turtle_string(str(ir_path))}^^atom:Path ] ;
  390. a ingen:Block .
  391. <{ir_instance}/control>
  392. atom:bufferType atom:Sequence ;
  393. atom:supports patch:Message ;
  394. lv2:designation lv2:control ;
  395. a atom:AtomPort, lv2:InputPort .
  396. <{ir_instance}/notify>
  397. atom:bufferType atom:Sequence ;
  398. atom:supports patch:Message ;
  399. lv2:designation lv2:control ;
  400. a atom:AtomPort, lv2:OutputPort .
  401. <{ir_instance}/in>
  402. a lv2:AudioPort, lv2:InputPort .
  403. <{ir_instance}/out>
  404. a lv2:AudioPort, lv2:OutputPort .
  405. <{ir_instance}/:bypass>
  406. ingen:value 0 ;
  407. a lv2:ControlPort, lv2:InputPort .
  408. <>
  409. doap:name "Rigforge - Guitare NAM/IR, Basse, Micro, Synthé" ;
  410. pedal:unitName "Rigforge" ;
  411. pedal:unitModel "Generic" ;
  412. pedal:width 1200 ;
  413. pedal:height 700 ;
  414. pedal:addressings <addressings.json> ;
  415. pedal:screenshot <screenshot.png> ;
  416. pedal:thumbnail <thumbnail.png> ;
  417. pedal:formatVersion 2 ;
  418. pedal:version 1 ;
  419. ingen:polyphony 1 ;
  420. ingen:arc _:b1, _:b2, _:b3, {additional_arcs_list} ;
  421. ingen:block <{nam_instance}>, <{ir_instance}>, {", ".join(f"<{processor['mod_ui_instance'].removeprefix('/graph/')}>" for processor in voice_processors)} ;
  422. lv2:port <:bpb>, <:bpm>, <:rolling>,
  423. <control_in>, <control_out>,
  424. <capture_1>, <playback_1>,
  425. {additional_ports_list},
  426. <midi_separated_mode>, <midi_loopback> ;
  427. lv2:extensionData <http://lv2plug.in/ns/ext/state#interface> ;
  428. a lv2:Plugin, ingen:Graph, pedal:Pedalboard .
  429. _:b1 ingen:tail <capture_1> ;
  430. ingen:head <{nam_instance}/input> .
  431. _:b2 ingen:tail <{nam_instance}/output> ;
  432. ingen:head <{ir_instance}/in> .
  433. _:b3 ingen:tail <{ir_instance}/out> ;
  434. ingen:head <playback_1> .
  435. _:voice0 ingen:tail <capture_3> ;
  436. ingen:head <{first_voice_instance}/{first_voice_input}> .
  437. {voice_chain_arcs_ttl}
  438. _:voice_out ingen:tail <{last_voice_instance}/{last_voice_output}> ;
  439. ingen:head <playback_3> .
  440. {additional_arcs_ttl}
  441. """
  442. files = {
  443. "manifest.ttl": (
  444. "@prefix ingen: <http://drobilla.net/ns/ingen#> .\n"
  445. "@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n"
  446. "@prefix pedal: <http://moddevices.com/ns/modpedal#> .\n"
  447. "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\n"
  448. "<rigforge-guitar.ttl>\n"
  449. " lv2:prototype ingen:GraphPrototype ;\n"
  450. " a lv2:Plugin, ingen:Graph, pedal:Pedalboard ;\n"
  451. " rdfs:seeAlso <rigforge-guitar.ttl> .\n"
  452. ).encode("utf-8"),
  453. "rigforge-guitar.ttl": ttl.encode("utf-8"),
  454. "addressings.json": b"{}\n",
  455. "snapshots.json": b'{"current":0,"snapshots":[]}\n',
  456. }
  457. files.update(plugin_state_files(nam, nam_path))
  458. files.update(plugin_state_files(ir, ir_path))
  459. files.update(plugin_files)
  460. for image_name in ("screenshot.png", "thumbnail.png"):
  461. image = asset_root / image_name
  462. if not image.is_file():
  463. raise FileNotFoundError(f"mod-ui default board image is missing: {image}")
  464. files[image_name] = image.read_bytes()
  465. return files
  466. def write_bundle(output, files, overwrite=False):
  467. output = Path(output)
  468. if output.exists():
  469. if output.is_symlink() or not output.is_dir():
  470. raise RuntimeError(f"pedalboard output is not a regular directory: {output}")
  471. existing = {}
  472. for path in output.rglob("*"):
  473. if path.is_symlink():
  474. raise RuntimeError(f"refusing symlink in pedalboard output: {path}")
  475. if path.is_file():
  476. existing[path.relative_to(output).as_posix()] = path.read_bytes()
  477. if existing == files:
  478. return
  479. if not overwrite:
  480. raise RuntimeError(f"pedalboard output already exists and differs: {output}")
  481. output.parent.mkdir(parents=True, exist_ok=True)
  482. temporary = Path(tempfile.mkdtemp(prefix=f".{output.name}.", dir=output.parent))
  483. try:
  484. for relative, content in files.items():
  485. path = temporary / relative
  486. path.parent.mkdir(parents=True, exist_ok=True)
  487. path.write_bytes(content)
  488. if output.exists():
  489. backup = output.with_name(output.name + ".rigforge-backup")
  490. if backup.exists():
  491. raise RuntimeError(f"pedalboard recovery path already exists: {backup}")
  492. os.replace(output, backup)
  493. try:
  494. os.replace(temporary, output)
  495. except OSError:
  496. os.replace(backup, output)
  497. raise
  498. else:
  499. os.replace(temporary, output)
  500. finally:
  501. if temporary.exists():
  502. shutil.rmtree(temporary)
  503. def main(argv=None):
  504. parser = argparse.ArgumentParser(description=__doc__)
  505. parser.add_argument("--state", type=Path, default=ROOT / "config" / "desired-state.yaml")
  506. parser.add_argument("--repo-root", type=Path, default=ROOT)
  507. parser.add_argument("--output", type=Path)
  508. parser.add_argument("--force", action="store_true", help="replace an existing differing generated bundle")
  509. args = parser.parse_args(argv)
  510. try:
  511. state = yaml.safe_load(args.state.read_text(encoding="utf-8"))
  512. files = generate_bundle_files(state, args.repo_root)
  513. output = args.output
  514. if output is None:
  515. digest = hashlib.sha256()
  516. for name, content in sorted(files.items()):
  517. digest.update(name.encode("utf-8") + b"\0" + content + b"\0")
  518. reference_directory = state["deployment"]["mod_ui"]["reference_directory"]
  519. output = (
  520. Path.home()
  521. / reference_directory
  522. / f"rigforge-guitar-{digest.hexdigest()[:16]}.pedalboard"
  523. )
  524. write_bundle(output, files, overwrite=args.force)
  525. except (OSError, ValueError, RuntimeError, KeyError, TypeError, yaml.YAMLError) as error:
  526. print(f"ERROR: {error}", file=sys.stderr)
  527. return 1
  528. print(f"Generated mod-ui pedalboard: {output}")
  529. return 0
  530. if __name__ == "__main__":
  531. raise SystemExit(main())