-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrisset.py
executable file
·3495 lines (2942 loc) · 128 KB
/
risset.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
from __future__ import annotations
import sys
import importlib.metadata
if (sys.version_info.major, sys.version_info.minor) < (3, 9):
print("Python 3.9 or higher is needed", file=sys.stderr)
sys.exit(-1)
if len(sys.argv) >= 2 and (sys.argv[1] == "--version" or sys.argv[1] == "-v"):
print(importlib.metadata.version("risset"))
sys.exit(0)
import glob
import os
import stat
import argparse
import json
import tempfile
import shutil
import subprocess
import textwrap
import fnmatch
import pprint
import platform
from dataclasses import dataclass, asdict as _asdict
import requests
import urllib.parse
import urllib.request
import urllib.error
from pathlib import Path
from zipfile import ZipFile
import inspect as _inspect
import re
from string import Template as _Template
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import Any
class PlatformNotSupportedError(Exception):
"""Raised when the current platform is not supported"""
class SchemaError(Exception):
"""An entity (a dict, a json file) does not fulfill the needed schema"""
class ParseError(Exception):
"""Parse error in a manifest file"""
def _subproc_call(args: list[str] | str, shell: bool | None = None):
if shell is None:
shell = isinstance(args, str)
_debug(f"Calling subprocess with shell={shell}: {args}")
return subprocess.call(args, shell=shell)
def _data_dir_for_platform() -> Path:
"""
Returns the data directory for the given platform
"""
platform = sys.platform
if platform == 'linux':
return Path("~/.local/share").expanduser()
elif platform == 'darwin':
return Path("~/Library/Application Support").expanduser()
elif platform == 'win32':
p = R"C:\Users\$USERNAME\AppData\Local"
return Path(os.path.expandvars(p))
else:
raise PlatformNotSupportedError(f"Platform unknown: {platform}")
INDEX_GIT_REPOSITORY = "https://github.com/csound-plugins/risset-data"
RISSET_ROOT = _data_dir_for_platform() / "risset"
RISSET_DATAREPO_LOCALPATH = RISSET_ROOT / "risset-data"
RISSET_GENERATED_DOCS = RISSET_ROOT / "man"
RISSET_CLONES_PATH = RISSET_ROOT / "clones"
RISSET_ASSETS_PATH = RISSET_ROOT / "assets"
RISSET_OPCODESXML = RISSET_ROOT / "opcodes.xml"
_MAININDEX_PICKLE_FILE = RISSET_ROOT / "mainindex.pickle"
MACOS_ENTITLEMENTS_PATH = RISSET_ASSETS_PATH / 'csoundplugins.entitlements'
UNKNOWN_VERSION = "Unknown"
_supported_platforms = {
'macos-x86_64',
'linux-x86_64',
'windows-x86_64',
'macos-arm64',
'linux-arm64'
}
_UNSET = object()
_entitlements_str = r"""
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
<key>com.apple.security.device.audio-input</key>
<true/>
<key>com.apple.security.device.camera</key>
<true/>
</dict>
</plist>
"""
def _macos_save_entitlements() -> Path:
path = MACOS_ENTITLEMENTS_PATH
_ensure_parent_exists(path)
if not _session.entitlements_saved:
with open(path, 'w') as f:
f.write(_entitlements_str)
assert os.path.exists(path)
plutil = shutil.which('plutil')
if plutil:
_debug(f"Verifying that the entitlements file '{path}' is a valid plist")
_subproc_call([plutil, path])
_session.entitlements_saved = True
_debug(f"Saved entitlements file to {path}")
_debug(f"Entitlements:\n{open(path).read()}\n------------ end entitlements")
return path
# SIGNATURE_ID="-"
# codesign --force --sign "${SIGNATURE_ID}" --entitlements csoundplugins.entitlements "/path/to/dylib"
def macos_codesign(dylibpaths: list[str], signature='-') -> None:
"""
Codesign the given library binaries using entitlements
Args:
dylibpaths: a list of paths to codesign
signature: the signature used. '-' indicates to sign it locally
"""
if not shutil.which('codesign'):
raise RuntimeError("Could not find the binary 'codesign' in the path")
entitlements_path = _macos_save_entitlements()
assert os.path.exists(entitlements_path)
for dylibpath in dylibpaths:
_subproc_call(['codesign', '--force', '--sign', signature, '--entitlements', entitlements_path, dylibpath])
_debug("Verifying code signing")
_subproc_call(['codesign', '--display', '--verbose', dylibpath])
def _normalize_platform(s: str) -> str:
"""
Normalizes platform definition as used in risset.json
Handles the case where, for compatibility reasons, the
architecture might be missing, so this function resolves,
for example, 'windows' to 'windows-x86_64'.
'linux' and 'windows' resolve to 'linux-x86_64' and 'windows-x86_64',
'macos' resolves to 'macos-arm64'
Otherwise the platform definition should consist of a pair <os>-<arch>,
like "macos-arm64" or "linux-x86_64"
Returns:
the normalized platform or an empty string if the given
value is not a valid platform
Raises ValueError if the platform is not supported
"""
if s in ('windows', 'linux'):
s += '-x86_64'
elif s == 'macos':
s += '-arm64'
return s if s in _supported_platforms else ''
def _platform_architecture() -> str:
"""
Returns the architecture for this platform
The architecture is one of 'x86_64' (intel, 64bits),
'x86' (intel, 32bits), 'arm64' (arm 64bits) or 'arm32' (arm 32bits)
"""
machine = platform.machine().lower()
bits, linkage = platform.architecture()
if machine == 'arm':
if bits == '64bit':
return 'arm64'
elif bits == '32bit':
return 'arm32'
elif machine == 'arm64':
return 'arm64'
elif machine == 'x86_64' or machine.startswith('amd64') or machine.startswith('intel64'):
return 'x86_64'
elif machine == 'i386':
if bits == '64bit':
return 'x86_64'
elif bits == '32bit':
return 'x86'
raise RuntimeError(f"** Architecture not supported (machine='{machine}', {bits=}, {linkage=})")
def _csoundlib_version() -> tuple[int, int]:
"""Returns a tuple (major, minor) using the csound api
This version can differ from the version of the installed csound binary
"""
import libcsound
versionid = libcsound.VERSION
major = versionid // 1000
minor = (versionid - major*1000) // 10
return major, minor
def _csound_version(csoundexe='csound') -> tuple[int, int, str]:
"""
Query the csound version via the executable
Args:
csoundexe: the csound executable
Returns:
a tuple (major: int, minor: int, rest: str)
"""
csound_bin = _get_csound_binary(csoundexe)
if not csound_bin:
raise OSError("csound binary not found")
proc = subprocess.Popen([csound_bin, "--version"], stderr=subprocess.PIPE)
proc.wait()
assert proc.stderr is not None
out = proc.stderr.read().decode('ascii')
for line in out.splitlines():
if match := re.search(r'--Csound\s+version\s+(\d+)\.(\d+)(.*)', line):
major = int(match.group(1))
minor = int(match.group(2))
rest = match.group(3)
return major, minor, rest
raise ValueError("Could not find a version number in the output")
class _Session:
"""
Simgleton class to hold information about the session
This class keeps track of downloaded files, cloned repos, etc.
"""
instance: _Session | None = None
def __new__(cls, *args, **kwargs):
if _Session.instance is not None:
return _Session.instance
instance = super().__new__(cls, *args, **kwargs)
_Session.instance = instance
return instance
def __init__(self):
self.downloaded_files: dict[str, Path] = {}
self.cloned_repos: dict[str, Path] = {}
self.platform: str = {
'linux': 'linux',
'darwin': 'macos',
'win32': 'windows'
}[sys.platform]
self.architecture = _platform_architecture()
"""The current architecture"""
self.platformid = self._platform_id()
"""The pair <os>-<arch> (linux-x86_64, windows-x86_64, macos-arm64, etc"""
major, minor = _csoundlib_version()
self.debug = False
"""True if in debug mode"""
self.csound_version_tuple = (major, minor)
"""Csound version as (major, minor)"""
self.csound_version: int = major * 1000 + minor * 10
"""Csound version id as integer, 6190 = 6.19, 7000 = 7.0"""
self.stop_on_errors = True
self.entitlements_saved = False
self.cache = {}
def _platform_id(self) -> str:
"""
Returns one of 'linux', 'windows', 'macos' (intel x86_64) or their 'arm64' variant:
'macos-arm64', 'linux-arm64', etc.
"""
return f'{self.platform}-{self.architecture}'
_session = _Session()
@dataclass
class _VersionRange:
minversion: int
maxversion: int
includemin: bool = True
includemax: bool = False
def __post_init__(self):
assert isinstance(self.minversion, int) and self.minversion >= 6000, f"Got {self.minversion}"
assert isinstance(self.maxversion, int) and self.maxversion >= 6000, f"Got {self.maxversion}"
def contains(self, versionid: int) -> bool:
"""
Returns True if version is contained within this version range
Args:
version: a version id, where version id is ``int(major.minor * 1000)``
Returns:
True if *version* is within this range
Example
-------
>>> v = _VersionRange(minversion=6180, maxversion=7000, includemin=True, includemax=False)
>>> v.contains(6190)
True
>>> v.contains(7000)
False
"""
if not isinstance(versionid, int) or versionid < 6000:
raise ValueError(f"Invalid versionid, got {versionid}")
a = versionid > self.minversion if not self.includemin else versionid >= self.minversion
maxversion = self.maxversion or 99999
b = versionid < maxversion if not self.includemax else versionid <= maxversion
return a and b
def _termsize(width=80, height=25) -> tuple[int, int]:
if not sys.stdout.isatty():
return width, height
try:
t = os.get_terminal_size()
return t.columns, t.lines
except Exception:
_debug(f"Could not determine terminal size, using default values {width=}, {height=}")
return width, height
def _version_to_versionid(versionstr: str) -> int:
if '.' not in versionstr:
return int(versionstr)
majors, minors = versionstr.split('.', maxsplit=1)
patch = 0
if '.' in minors:
minors, patchs = minors.split('.', maxsplit=1)
patch = int(patchs)
assert 0 <= patch < 10
versionid = int(majors) * 1000 + int(minors) * 10 + patch
return versionid
def _parse_version(versionstr: str) -> _VersionRange:
versionstr = versionstr.replace(' ', '')
if versionstr.startswith("=="):
exactversionstr = versionstr[2:]
versionid = _version_to_versionid(exactversionstr)
return _VersionRange(minversion=versionid, maxversion=versionid, includemin=True, includemax=True)
parts = re.split(r"(>=|<=|>|<)", versionstr)
parts = [p for p in parts if p]
if len(parts) % 2 != 0:
raise ParseError(f"Could not parse version range: {versionstr}, parts: {parts}")
minversion = 6000
maxversion = 9999
includemax = False
includemin = False
for op, version in zip(parts[::2], parts[1::2]):
assert op in ('<', '>', '<=', '>=')
if op[0] == '<':
maxversion = _version_to_versionid(version)
if op[-1] == '=':
includemax = True
elif op[0] == '>':
minversion = _version_to_versionid(version)
if op[-1] == '=':
includemin = True
else:
raise ParseError(f"Could not parse version range: {versionstr}, operator {op} not supported")
return _VersionRange(minversion=minversion, maxversion=maxversion, includemin=includemin, includemax=includemax)
def _abbrev(s: str, maxlen: int) -> str:
"""Abbreviate string"""
assert maxlen > 18
lens = len(s)
if lens < maxlen:
return s
rightlen = min(8, lens // 5)
return f"{s[:lens - rightlen - 1]}…{s[-rightlen:]}"
def _mainindex_retrieve(days_threshold=10) -> MainIndex | None:
"""
Try to retrieve a previously pickled mainindex
"""
picklefile = _MAININDEX_PICKLE_FILE
if not picklefile.exists():
return None
import time
import pickle
days_since_last_modification = (picklefile.stat().st_mtime - time.time()) / 86400
if days_since_last_modification > days_threshold:
return None
_debug("Recreating main index from pickled version")
f = open(picklefile, "rb")
try:
return pickle.load(f)
except Exception as e:
_errormsg(f"Could not retrieve mainindex from serialized file: {e}")
_debug(f"Serialized file ({picklefile}) removed")
os.remove(picklefile)
return None
def _is_git_repo(path: str | Path) -> bool:
"""
If `path` a valid git repo?
"""
# via https://remarkablemark.org/blog/2020/06/05/check-git-repository/
if isinstance(path, Path):
path = path.as_posix()
out = subprocess.check_output(["git", "-C", path, "rev-parse", "--is-inside-work-tree"]).decode("utf-8").strip()
return out == "true"
def _git_reponame(url: str) -> str:
"""
Returns the name fo the git repository given as url
======================================= =======
url name
======================================= =======
https://github.com/user/foo.git foo
https://gitlab.com/baz/bar.git bar
======================================= =======
"""
parts = url.split("/")
if not parts[-1].endswith(".git"):
raise ValueError(f"A git url should always end in '.git': {url}")
return parts[-1].rsplit(".", maxsplit=1)[0]
def _is_git_url(url: str) -> bool:
"""
Is `url` an url to a git repo?
"""
return _is_url(url) and url.endswith(".git")
def _debug(*msgs, ljust=20) -> None:
""" Print debug info only if debugging is turned on """
if _session.debug:
caller = _abbrev(_inspect.stack()[1][3], ljust)
print(f"DEBUG:{caller.ljust(ljust)}:", *msgs, file=sys.stderr)
def _errormsg(msg: str) -> None:
""" Print error message """
lines = msg.splitlines()
print("** Error:", lines[0], file=sys.stderr)
for line in lines[1:]:
print(" ", line, file=sys.stderr)
def _info(*msgs: str) -> None:
print(*msgs)
class ErrorMsg(str):
pass
@dataclass
class Asset:
"""
An Asset describes any file/files distributed alongside a plugin
The use case is for data files which are needed by a plugin at runtime
Attribs:
source: the source where to get the assets from. It can be a url to a git repository,
the direct url to a downloadable file/zip file or the path to a local
folder
patterns: the paths to extract from the source (if needed). Each item can be either
a path relative to the root of the git or zip file, or a glob pattern. In the
case where the url points to a concrete file (not a zip or a git repo), this
attributes should be empty
platform: if given, the platform for which this assets are valid (in the case
of binaries of some kind)
name: the name of the asset (optional)
"""
source: str
"""the url where to download the assets from"""
patterns: list[str]
"""the paths to extract from the url (if needed). It can be a glob pattern"""
platform: str = 'all'
"""the platform for which this assets are valid"""
name: str = ''
def __post_init__(self):
assert self.source
def identifier(self) -> str:
if self.name:
return self.name
if self.patterns:
return f"{self.source}::{','.join(str(patt) for patt in self.patterns)}"
return self.source
def local_path(self) -> Path:
assert self.source
if _is_url(self.source):
if _is_git_url(self.source):
return _git_local_path(self.source)
else:
_debug(f"Downloading url {self.source}")
return _download_file(self.source)
else:
# it is a path, check that it exists
source = Path(self.source)
assert source.exists(), f"Assert source does not exist: {source}"
return source
def retrieve(self) -> list[Path]:
"""
Download and resolve all files, if needed
Returns:
a (possibly empty) list of local paths which belong to this asset.
In the case of an asset referring to a file within a zip, the
files are extracted to a temp dir and a path to that temp dir
is returned
"""
assert self.source and (_is_url(self.source) or os.path.isabs(self.source)), \
f"Source should be either a url or an absolute path: {self.source}"
# self.url is either a git repo or a url pointing to a file
root = self.local_path()
if root.is_dir():
assert _is_git_repo(root)
_git_update(root)
collected_assets: list[Path] = []
for pattern in self.patterns:
matchedfiles = glob.glob((root/pattern).as_posix())
collected_assets.extend(Path(m) for m in matchedfiles)
return collected_assets
elif root.suffix == '.zip':
_debug(f"Extracting {self.patterns} from {root}")
outfiles = _zip_extract(root, self.patterns)
_debug(f"Extracted {outfiles} from {root}")
return outfiles
else:
# root is a file
return [root]
@dataclass
class Binary:
"""
A Binary describes a plugin binary
Attribs:
platform: the platform/architecture for which this binary is built. Possible platforms:
'linux' (x86_64), 'windows' (windows 64 bits), 'macos' (x86_64)
url: either a http link to a binary/.zip file, or empty if the plugin's location is relative to the
manifest definition
build_platform: the platform this binary was built with. Might serve as an orientation for
users regarding the compatibility of the binary. It can be anything but expected values
might be something like "macOS 11.xx.
extractpath: in the case of using a .zip file as url, the extract path should indicate
a relative path to the binary within the .zip file structure
post_install_script: a script to run after the binary has been installed
"""
platform: str
"""The platform for which this binary was compiled.
A pair <os>-<arch>, where os is one of linux, windows, macos, and
arch is one of 'x86_64', 'arm64'. See _supported_platforms for an
up-to-date list"""
url: str
"""The url of the binary (can be a zip file)"""
csound_version: str
"""The version range for which this binary is valid (can be of the form >=P.q<X.y)"""
extractpath: str = ''
"""In the case of the url being an archive, this indicates the relative path of the binary within that archive"""
build_platform: str = ''
"""If known, the platform under which this binary was built. This can be anything, it is just informative"""
post_install_script: str = ''
"""A script to run after installation"""
_csound_version_range: _VersionRange | None = None
def __post_init__(self):
platform = _normalize_platform(self.platform)
if not platform:
raise ValueError(f"Invalid platform '{self.platform}', expected one of {_supported_platforms}")
self.platform = platform
def csound_version_range(self) -> _VersionRange:
if self._csound_version_range is None:
self._csound_version_range = _parse_version(self.csound_version)
return self._csound_version_range
def matches_versionid(self, versionid: int) -> bool:
"""
Does this binary apply to the given versionid?
Returns:
True if the versionid is contained within the version range of this binary
"""
assert isinstance(versionid, int) and versionid >= 6000, f"Got {versionid}"
return self.csound_version_range().contains(versionid)
def binary_filename(self) -> str:
"""
The filename of the binary
"""
if not self.url.endswith('.zip'):
return os.path.split(self.url)[1]
else:
assert self.extractpath
return os.path.split(self.extractpath)[1]
@dataclass
class ManPage:
syntaxes: list[str]
abstract: str
@dataclass
class IndexItem:
"""
An entry in the risset index
Attribs:
name: the name of the entity
url: the url of the git repository
path: the relative path within the repository to the risset.json file.
"""
name: str
url: str
path: str = ''
def manifest_path(self) -> Path:
localpath = _git_local_path(self.url)
assert localpath.exists()
manifest_path = localpath / self.path
if manifest_path.is_file():
assert manifest_path.suffix == ".json"
else:
manifest_path = manifest_path / "risset.json"
if not manifest_path.exists():
raise RuntimeError(f"For plugin {self.name} ({self.url}, cloned at {localpath}"
f" the manifest was not found at the expected path: {manifest_path}")
return manifest_path
def update(self) -> None:
path = _git_local_path(self.url)
_git_update(path)
def read_definition(self: IndexItem) -> Plugin:
"""
Read the plugin definition pointed by this plugin source
Returns:
a Plugin
Raises: PluginDefinitionError if there is an error
"""
manifest = self.manifest_path()
assert manifest.exists() and manifest.suffix == '.json'
try:
plugin = _read_plugindef(manifest.as_posix(), url=self.url,
manifest_relative_path=self.path)
except Exception as e:
_errormsg(f"Could not read manifest '{manifest.as_posix()}', error: '{e}'. "
f"I will update the index and try again")
self.update()
plugin = _read_plugindef(manifest.as_posix(), url=self.url,
manifest_relative_path=self.path)
_info("... ok, that worked")
plugin.cloned_path = _git_local_path(self.url)
return plugin
@dataclass
class Plugin:
"""
Attribs:
name: name of the plugin
version: a version for this plugin, for update reasons
short_description: a short description of the plugin or its opcodes
binaries: a dict mapping platform to a Binary, like {'windows': Binary(...), 'linux': Binary(...)}
Possible platforms are: 'linux', 'windows', 'macos', where in each case x86_64 is implied. Other
platforms, when supported, will be of the form 'linux-arm64' or 'macos-arm64'
opcodes: a list of opcodes defined in this plugin
assets: a list of Assets
author: the author of this plugin
email: the email of the author
cloned_path: path to the cloned repository
doc_folder: the relative path to a folder holding the documentation for each opcode. This folder
is relative to the manifest. If not provided it defaults to a "doc" folder placed
besides the manifest
url: the url of the git repository where this plugin is defined (notice that the binaries can
be hosted inside this repository or in any other url)
manifest_relative_path: the subdirectory within the repository where the "risset.json" file is
placed. If not given, it is assumed that the manifest is placed at the root of the repository
structure
{
"assets": [
{ "url": "...",
"extractpath": "...",
"platform": "linux"
}
]
}
"""
name: str
url: str
version: str
short_description: str
binaries: list[Binary]
opcodes: list[str]
author: str
email: str
cloned_path: Path
manifest_relative_path: str = ''
long_description: str = ''
doc_folder: str = 'doc'
assets: list[Asset] | None = None
def __post_init__(self):
assert isinstance(self.binaries, list) and all(isinstance(b, Binary) for b in self.binaries)
assert isinstance(self.opcodes, list)
assert not self.assets or isinstance(self.assets, list)
def __hash__(self):
return hash((self.name, self.version))
@property
def versiontuple(self) -> tuple[int, int, int]:
if self.version:
return _version_tuple(self.version)
return (0, 0, 0)
def local_manifest_path(self) -> Path:
"""
The local path to the manifest file of this plugin
"""
return self.cloned_path / self.manifest_relative_path / "risset.json"
def asdict(self) -> dict:
d = _asdict(self)
return d
def manpage(self, opcode: str) -> Path | None:
"""
Returns the path to the man page for opcode
"""
markdownfile = opcode + ".md"
path = self.resolve_doc_folder() / markdownfile
return path if path.exists() else None
def resolve_path(self, relpath: Path | str) -> Path:
"""
Returns the absolute path relative to the manifest path of this plugin
"""
root = self.local_manifest_path().parent
return _resolve_path(relpath, root)
def resolve_doc_folder(self) -> Path:
"""
Resolve the doc folder for this plugin
A doc folder can be declared in the manifest as a relative path
to the manifest itself. If not given, it defaults to a 'doc' folder
besides the manifest
"""
root = self.local_manifest_path().parent
doc_folder = _resolve_path(self.doc_folder or "doc", root)
if not doc_folder.exists():
raise OSError(f"No doc folder found (declared as {doc_folder}")
return doc_folder
def find_binary(self, platformid='', csound_version: int = 0
) -> Binary | None:
"""
Find a binary for the platform and csound versions given / current
Args:
platformid: the platform id. If intel x86-64, simply the platform ('macos', 'linux', 'windows'),
otherwise the platform and architecture ('macos-arm64', 'linux-arm64', ...)
csound_version: the csound version as int (6.18 = 6180, 6.19 = 6190, 7.01 = 7010). This should be
the version of csound for which the plugin is to be installed. In the plugin definition each
binary defines a version range for which it is built.
Returns:
a Binary which matches the given platform and csound version, or None
if no match possible
"""
if not csound_version:
csound_version = _session.csound_version
else:
assert isinstance(csound_version, int) and csound_version >= 6000, f"Got {csound_version}"
if not platformid:
platformid = _session.platformid
possible_binaries = [b for b in self.binaries
if b.platform == platformid and b.matches_versionid(csound_version)]
if not possible_binaries:
_debug(f"Plugin '{self.name}' does not seem to have a binary for platform '{platformid}'. "
f"Found binaries for platforms: {[b.platform for b in self.binaries]}")
return None
else:
if len(possible_binaries) > 1:
_debug(f"Found multiple binaries for {self.name}. Will select the first one")
return possible_binaries[0]
def available_binaries(self) -> list[str]:
return [f"{binary.platform}/csound{binary.csound_version}"
for binary in self.binaries]
@dataclass
class Opcode:
name: str
plugin: str
syntaxes: list[str] | None = None
abstract: str = ''
installed: bool = True
@dataclass
class InstalledPluginInfo:
"""
Information about an installed plugin
Attribs:
name: (str) name of the plugin
dllpath: (Path) path of the plugin binary (a .so, .dll or .dylib file)
installed_in_system_folder: (bool) is this installed in the systems folder?
installed_manifest_path: (Path) the path to the installation manifest (a .json file)
versionstr: (str) the installed version, as str (if installed via risset)
"""
name: str
dllpath: Path
versionstr: str | None
installed_manifest_path: Path | None = None
installed_in_system_folder: bool = False
@property
def versiontuple(self) -> tuple[int, int, int]:
return _version_tuple(self.versionstr) if self.versionstr and self.versionstr != UNKNOWN_VERSION else (0, 0, 0)
def _main_repository_path() -> Path:
"""
Get the path of the main data repository
The main repository is the repository holding risset's main index.
The main index is a .json file with the name "rissetindex.json" where
all plugins and other resources are indexed.
The path returned here determines where this repository should be
cloned locally
"""
return RISSET_ROOT / "risset-data"
def user_plugins_path(version: int | tuple[int, int] | None = None) -> Path:
"""
Return the install path for user plugins
This returns the default path or the value of $CS_USER_PLUGINDIR. The env
variable has priority
Args:
version: the csound version for which to determine the user plugins path
Returns:
the user plugins path, as a Path object
"""
if version is None:
version = _session.csound_version_tuple[0]
major, minor = version, 0
elif isinstance(version, tuple):
major, minor = version[0], 0
elif isinstance(version, int):
major, minor = version, 0
else:
raise TypeError(f"Expected an int major version (6, or 7), a version "
f"tuple (6, 0) or None to use the installed version, "
f"got {version}")
cs_user_plugindir = os.getenv("CS_USER_PLUGINDIR")
if cs_user_plugindir:
out = Path(cs_user_plugindir)
else:
pluginsdir = {
'linux': f'$HOME/.local/lib/csound/{major}.{minor}/plugins64',
'win32': f'C:\\Users\\$USERNAME\\AppData\\Local\\csound\\{major}.{minor}\\plugins64',
'darwin': f'$HOME/Library/csound/{major}.{minor}/plugins64'
}[sys.platform]
out = Path(os.path.expandvars(pluginsdir))
return out
def _is_glob(s: str) -> bool:
return "*" in s or "?" in s
def _zip_extract_folder(zipfile: Path,
folder: str,
cleanup=True,
destroot: Path | None = None
) -> Path:
foldername = os.path.split(folder)[1]
root = Path(tempfile.mktemp())
root.mkdir(parents=True, exist_ok=True)
z = ZipFile(zipfile, 'r')
pattern = folder + '/*'
extracted = [z.extract(name, root) for name in z.namelist()
if fnmatch.fnmatch(name, pattern)]
_debug(f"_zip_extract_folder: Extracted files from folder {folder}: {extracted}")
if destroot is None:
destroot = Path(tempfile.gettempdir())
destfolder = destroot / foldername
if destfolder.exists():
_debug(f"_zip_extract_folder: Destination folder {destfolder} already exists, removing")
_rm_dir(destfolder)
shutil.move(root / folder, destroot)
assert destfolder.exists() and destfolder.is_dir()
if cleanup:
_rm_dir(root)
return destfolder
def _zip_extract(zipfile: Path, patterns: list[str]) -> list[Path]:
"""
Extract multiple files from zip
Args:
zipfile: the zip file to extract from
patterns: a list of filenames or glob patterns
Returns:
a list of output files extracted. If glob patterns were used there might be
more output files than number of patterns. Otherwise there is a 1 to 1
relationship between input and output
"""
outfolder = Path(tempfile.gettempdir())
z = ZipFile(zipfile, 'r')
out: list[Path] = []
zipped = z.namelist()
_debug(f"Inspecting zipfile {zipfile}, contents: {zipped}")
for pattern in patterns:
if _is_glob(pattern):
_debug(f"Matching names against pattern {pattern}")
for name in zipped:
if name.endswith("/") and fnmatch.fnmatch(name[:-1], pattern):
# a folder
out.append(_zip_extract_folder(zipfile, name[:-1]))
elif fnmatch.fnmatch(name, pattern):
_debug(f" Name {name} matches!")
out.append(Path(z.extract(name, path=outfolder.as_posix())))
else:
_debug(f" Name {name} does not match")
else:
out.append(Path(z.extract(pattern, path=outfolder)))