-
Notifications
You must be signed in to change notification settings - Fork 0
/
flatpak-node-generator.py
2014 lines (1618 loc) · 75.9 KB
/
flatpak-node-generator.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
# pyright: strict
__license__ = 'MIT'
from typing import * # pyright: reportWildcardImportFromLibrary=false
# Explictly import these.
from typing import cast, IO
from pathlib import Path
import argparse
import asyncio
import base64
import binascii
import collections
import contextlib
import functools
import hashlib
import json
import os
import re
import shlex
import shutil
import sys
import tempfile
import textwrap
import types
import urllib.parse
import urllib.request
DEFAULT_PART_SIZE = 4096
GIT_SCHEMES: Dict[str, Dict[str, str]] = {
'github': {
'scheme': 'https',
'netloc': 'github.com'
},
'gitlab': {
'scheme': 'https',
'netloc': 'gitlab.com'
},
'bitbucket': {
'scheme': 'https',
'netloc': 'bitbucket.com'
},
'git': {},
'git+http': {
'scheme': 'http'
},
'git+https': {
'scheme': 'https'
},
}
GIT_URL_PATTERNS = [
re.compile(r'^git:'),
re.compile(r'^git\+.+:'),
re.compile(r'^ssh:'),
re.compile(r'^https?:.+\.git$'),
re.compile(r'^https?:.+\.git#.+'),
]
GIT_URL_HOSTS = ['github.com', 'gitlab.com', 'bitbucket.com', 'bitbucket.org']
NPM_MIRROR = 'https://unpkg.com/'
class SemVer(NamedTuple):
# Note that we ignore the metadata part, since all we do is version
# comparisons.
_SEMVER_RE = re.compile(r'(\d+)\.(\d+)\.(\d+)(?:-(?P<prerelease>[^+]+))?')
@functools.total_ordering
class Prerelease:
def __init__(self, parts: Tuple[Union[str, int]]) -> None:
self._parts = parts
@staticmethod
def parse(rel: str) -> Optional['SemVer.Prerelease']:
if not rel:
return None
parts: List[Union[str, int]] = []
for part in rel.split('.'):
try:
part = int(part)
except ValueError:
pass
parts.append(part)
return SemVer.Prerelease(tuple(parts))
@property
def parts(self) -> Tuple[Union[str, int]]:
return self._parts
def __lt__(self, other: 'SemVer.Prerelease'):
for our_part, other_part in zip(self._parts, other._parts):
if type(our_part) == type(other_part):
if our_part < other_part: # type: ignore
return True
# Number parts are always less than strings.
elif isinstance(our_part, int):
return True
return len(self._parts) < len(other._parts)
def __repr__(self) -> str:
return f'Prerelease(parts={self.parts})'
major: int
minor: int
patch: int
prerelease: Optional[Prerelease] = None
@staticmethod
def parse(version: str) -> 'SemVer':
match = SemVer._SEMVER_RE.match(version)
if match is None:
raise ValueError(f'Invalid semver version: {version}')
major, minor, patch = map(int, match.groups()[:3])
prerelease = SemVer.Prerelease.parse(match.group('prerelease'))
return SemVer(major, minor, patch, prerelease)
class Cache:
instance: 'Cache'
@classmethod
def get_working_instance_if(cls, condition: bool) -> 'Cache':
return cls.instance if condition else NullCache()
class BucketReader:
def read_parts(self, size: int = DEFAULT_PART_SIZE) -> Iterator[bytes]:
raise NotImplementedError
def read_all(self) -> bytes:
raise NotImplementedError
def close(self) -> None:
raise NotImplementedError
def __enter__(self) -> 'Cache.BucketReader':
return self
def __exit__(self, exc_type: Optional[Type[BaseException]],
exc_value: Optional[BaseException],
traceback: Optional[types.TracebackType]) -> None:
self.close()
class BucketWriter:
def write(self, data: bytes) -> None:
raise NotImplementedError
def cancel(self) -> None:
raise NotImplementedError
def seal(self) -> None:
raise NotImplementedError
def __enter__(self) -> 'Cache.BucketWriter':
return self
def __exit__(self, exc_type: Optional[Type[BaseException]],
exc_value: Optional[BaseException],
traceback: Optional[types.TracebackType]) -> None:
if traceback is None:
self.seal()
else:
self.cancel()
class BucketRef:
def __init__(self, key: str) -> None:
self.key = key
def open_read(self) -> Optional['Cache.BucketReader']:
raise NotImplementedError
def open_write(self) -> 'Cache.BucketWriter':
raise NotImplementedError
def get(self, key: str) -> BucketRef:
raise NotImplementedError
class NullCache(Cache):
class NullBucketWriter(Cache.BucketWriter):
def write(self, data: bytes) -> None:
pass
def cancel(self) -> None:
pass
def seal(self) -> None:
pass
class NullBucketRef(Cache.BucketRef):
def __init__(self, key: str) -> None:
super().__init__(key)
def open_read(self) -> Optional[Cache.BucketReader]:
return None
def open_write(self) -> Cache.BucketWriter:
return NullCache.NullBucketWriter()
def get(self, key: str) -> Cache.BucketRef:
return NullCache.NullBucketRef(key)
class FilesystemBasedCache(Cache):
_SUBDIR = 'flatpak-node-generator'
_KEY_CHAR_ESCAPE_RE = re.compile(r'[^A-Za-z0-9._\-]')
@staticmethod
def _escape_key(key: str) -> str:
return FilesystemBasedCache._KEY_CHAR_ESCAPE_RE.sub(
lambda m: f'_{ord(m.group()):02X}', key)
class FilesystemBucketReader(Cache.BucketReader):
def __init__(self, file: IO[bytes]) -> None:
self.file = file
def close(self) -> None:
self.file.close()
def read_parts(self, size: int = DEFAULT_PART_SIZE) -> Iterator[bytes]:
while True:
data = self.file.read(size)
if not data:
break
yield data
def read_all(self) -> bytes:
return self.file.read()
class FilesystemBucketWriter(Cache.BucketWriter):
def __init__(self, file: IO[bytes], temp: Path, target: Path) -> None:
self.file = file
self.temp = temp
self.target = target
def write(self, data: bytes) -> None:
self.file.write(data)
def cancel(self) -> None:
self.file.close()
self.temp.unlink()
def seal(self) -> None:
self.file.close()
self.temp.rename(self.target)
class FilesystemBucketRef(Cache.BucketRef):
def __init__(self, key: str, cache_root: Path) -> None:
super().__init__(key)
self._cache_root = cache_root
self._cache_path = self._cache_root / FilesystemBasedCache._escape_key(key)
def open_read(self) -> Optional[Cache.BucketReader]:
try:
fp = self._cache_path.open('rb')
except FileNotFoundError:
return None
else:
return FilesystemBasedCache.FilesystemBucketReader(fp)
def open_write(self) -> Cache.BucketWriter:
target = self._cache_path
if not target.parent.exists():
target.parent.mkdir(exist_ok=True, parents=True)
fd, temp = tempfile.mkstemp(dir=self._cache_root, prefix='__temp__')
return FilesystemBasedCache.FilesystemBucketWriter(os.fdopen(fd, 'wb'),
Path(temp), target)
@property
def _cache_root(self) -> Path:
xdg_cache_home = os.environ.get('XDG_CACHE_HOME', os.path.expanduser('~/.cache'))
return Path(xdg_cache_home) / self._SUBDIR
def get(self, key: str) -> Cache.BucketRef:
return FilesystemBasedCache.FilesystemBucketRef(key, self._cache_root)
Cache.instance = NullCache()
class Requests:
instance: 'Requests'
DEFAULT_RETRIES = 5
retries: ClassVar[int] = DEFAULT_RETRIES
@property
def is_async(self) -> bool:
raise NotImplementedError
def __get_cache_bucket(self, cachable: bool, url: str) -> Cache.BucketRef:
return Cache.get_working_instance_if(cachable).get(f'requests:{url}')
async def _read_parts(self,
url: str,
size: int = DEFAULT_PART_SIZE) -> AsyncIterator[bytes]:
raise NotImplementedError
yield b'' # Silence mypy.
async def _read_all(self, url: str) -> bytes:
raise NotImplementedError
async def read_parts(self,
url: str,
*,
cachable: bool,
size: int = DEFAULT_PART_SIZE) -> AsyncIterator[bytes]:
bucket = self.__get_cache_bucket(cachable, url)
bucket_reader = bucket.open_read()
if bucket_reader is not None:
for part in bucket_reader.read_parts(size):
yield part
return
for i in range(1, Requests.retries + 1):
try:
with bucket.open_write() as bucket_writer:
async for part in self._read_parts(url, size):
bucket_writer.write(part)
yield part
return
except Exception:
if i == Requests.retries:
raise
async def read_all(self, url: str, *, cachable: bool = False) -> bytes:
bucket = self.__get_cache_bucket(cachable, url)
bucket_reader = bucket.open_read()
if bucket_reader is not None:
return bucket_reader.read_all()
for i in range(1, Requests.retries + 1):
try:
with bucket.open_write() as bucket_writer:
data = await self._read_all(url)
bucket_writer.write(data)
return data
except Exception:
if i == Requests.retries:
raise
assert False
class UrllibRequests(Requests):
@property
def is_async(self) -> bool:
return False
async def _read_parts(self,
url: str,
size: int = DEFAULT_PART_SIZE) -> AsyncIterator[bytes]:
with urllib.request.urlopen(url) as response:
while True:
data = response.read(size)
if not data:
return
yield data
async def _read_all(self, url: str) -> bytes:
with urllib.request.urlopen(url) as response:
return cast(bytes, response.read())
class StubRequests(Requests):
@property
def is_async(self) -> bool:
return True
async def _read_parts(self,
url: str,
size: int = DEFAULT_PART_SIZE) -> AsyncIterator[bytes]:
yield b''
async def _read_all(self, url: str) -> bytes:
return b''
Requests.instance = UrllibRequests()
try:
import aiohttp
class AsyncRequests(Requests):
@property
def is_async(self) -> bool:
return True
@contextlib.asynccontextmanager
async def _open_stream(self, url: str) -> AsyncIterator[aiohttp.StreamReader]:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
yield response.content
async def _read_parts(self,
url: str,
size: int = DEFAULT_PART_SIZE) -> AsyncIterator[bytes]:
async with self._open_stream(url) as stream:
while True:
data = await stream.read(size)
if not data:
return
yield data
async def _read_all(self, url: str) -> bytes:
async with self._open_stream(url) as stream:
return await stream.read()
Requests.instance = AsyncRequests()
except ImportError:
pass
class Integrity(NamedTuple):
algorithm: str
digest: str
@staticmethod
def parse(value: str) -> 'Integrity':
algorithm, encoded_digest = value.split('-', 1)
assert algorithm.startswith('sha'), algorithm
digest = binascii.hexlify(base64.b64decode(encoded_digest)).decode()
return Integrity(algorithm, digest)
@staticmethod
def from_sha1(sha1: str) -> 'Integrity':
assert len(sha1) == 40, f'Invalid length of sha1: {sha1}'
return Integrity('sha1', sha1)
@staticmethod
def generate(data: Union[str, bytes], *, algorithm: str = 'sha256') -> 'Integrity':
builder = IntegrityBuilder(algorithm)
builder.update(data)
return builder.build()
@staticmethod
def from_json_object(data: Any) -> 'Integrity':
return Integrity(algorithm=data['algorithm'], digest=data['digest'])
def to_json_object(self) -> Any:
return {'algorithm': self.algorithm, 'digest': self.digest}
def to_base64(self) -> str:
return base64.b64encode(binascii.unhexlify(self.digest)).decode()
class IntegrityBuilder:
def __init__(self, algorithm: str = 'sha256') -> None:
self.algorithm = algorithm
self._hasher = hashlib.new(algorithm)
def update(self, data: Union[str, bytes]) -> None:
data_bytes: bytes
if isinstance(data, str):
data_bytes = data.encode()
else:
data_bytes = data
self._hasher.update(data_bytes)
def build(self) -> Integrity:
return Integrity(algorithm=self.algorithm, digest=self._hasher.hexdigest())
class RemoteUrlMetadata(NamedTuple):
integrity: Integrity
size: int
@staticmethod
def __get_cache_bucket(cachable: bool, kind: str, url: str) -> Cache.BucketRef:
return Cache.get_working_instance_if(cachable).get(
f'remote-url-metadata:{kind}:{url}')
@staticmethod
def from_json_object(data: Any) -> 'RemoteUrlMetadata':
return RemoteUrlMetadata(integrity=Integrity.from_json_object(data['integrity']),
size=data['size'])
@classmethod
async def get(cls,
url: str,
*,
cachable: bool,
integrity_algorithm: str = 'sha256') -> 'RemoteUrlMetadata':
bucket = cls.__get_cache_bucket(cachable, 'full', url)
bucket_reader = bucket.open_read()
if bucket_reader is not None:
data = json.loads(bucket_reader.read_all())
return RemoteUrlMetadata.from_json_object(data)
builder = IntegrityBuilder(integrity_algorithm)
size = 0
async for part in Requests.instance.read_parts(url, cachable=False):
builder.update(part)
size += len(part)
metadata = RemoteUrlMetadata(integrity=builder.build(), size=size)
with bucket.open_write() as bucket_writer:
bucket_writer.write(json.dumps(metadata.to_json_object()).encode('ascii'))
return metadata
@classmethod
async def get_size(cls, url: str, *, cachable: bool) -> int:
bucket = cls.__get_cache_bucket(cachable, 'size', url)
bucket_reader = bucket.open_read()
if bucket_reader is not None:
return int(bucket_reader.read_all())
size = 0
async for part in Requests.instance.read_parts(url, cachable=False):
size += len(part)
with bucket.open_write() as bucket_writer:
bucket_writer.write(str(size).encode('ascii'))
return size
def to_json_object(self) -> Any:
return {'integrity': self.integrity.to_json_object(), 'size': self.size}
class ResolvedSource(NamedTuple):
resolved: str
integrity: Optional[Integrity]
async def retrieve_integrity(self) -> Integrity:
if self.integrity is not None:
return self.integrity
else:
url = self.resolved
assert url is not None, 'registry source has no resolved URL'
metadata = await RemoteUrlMetadata.get(url, cachable=True)
return metadata.integrity
class UnresolvedRegistrySource:
pass
class GitSource(NamedTuple):
original: str
url: str
commit: str
from_: Optional[str]
PackageSource = Union[ResolvedSource, UnresolvedRegistrySource, GitSource]
class Package(NamedTuple):
name: str
version: str
source: PackageSource
lockfile: Path
class NodeHeaders(NamedTuple):
target: str
runtime: str
disturl: str
@classmethod
def with_defaults(cls,
target: str,
runtime: Optional[str] = None,
disturl: Optional[str] = None):
if runtime is None:
runtime = 'node'
if disturl is None:
if runtime == 'node':
disturl = 'http://nodejs.org/dist'
elif runtime == 'electron':
disturl = 'https://www.electronjs.org/headers'
else:
raise ValueError(f'Can\'t guess `disturl` for {runtime} version {target}')
return cls(target, runtime, disturl)
@property
def url(self) -> str:
#TODO it may be better to retrieve urls from disturl/index.json
return f'{self.disturl}/v{self.target}/node-v{self.target}-headers.tar.gz'
@property
def install_version(self) -> str:
#FIXME not sure if this static value will always work
return "9"
class ManifestGenerator(ContextManager['ManifestGenerator']):
MAX_GITHUB_SIZE = 49 * 1000 * 1000
JSON_INDENT = 4
def __init__(self) -> None:
# Store the dicts as a set of tuples, then rebuild the dict when returning it.
# That way, we ensure uniqueness.
self._sources: Set[Tuple[Tuple[str, Any], ...]] = set()
self._commands: List[str] = []
def __exit__(self, exc_type: Optional[Type[BaseException]],
exc_value: Optional[BaseException],
tb: Optional[types.TracebackType]) -> None:
self._finalize()
@property
def data_root(self) -> Path:
return Path('flatpak-node')
@property
def tmp_root(self) -> Path:
return self.data_root / 'tmp'
@property
def source_count(self) -> int:
return len(self._sources)
def ordered_sources(self) -> Iterator[Dict[Any, Any]]:
return map(dict, sorted(self._sources)) # type: ignore
def split_sources(self) -> Iterator[List[Dict[Any, Any]]]:
BASE_CURRENT_SIZE = len('[\n]')
current_size = BASE_CURRENT_SIZE
current: List[Dict[Any, Any]] = []
for source in self.ordered_sources():
# Generate one source by itself, then check the length without the closing and
# opening brackets.
source_json = json.dumps([source], indent=ManifestGenerator.JSON_INDENT)
source_json_len = len('\n'.join(source_json.splitlines()[1:-1]))
if current_size + source_json_len >= ManifestGenerator.MAX_GITHUB_SIZE:
yield current
current = []
current_size = BASE_CURRENT_SIZE
current.append(source)
current_size += source_json_len
if current:
yield current
def _add_source(self, source: Dict[str, Any]) -> None:
self._sources.add(tuple(source.items()))
def _add_source_with_destination(self,
source: Dict[str, Any],
destination: Optional[Path],
*,
is_dir: bool,
only_arches: Optional[List[str]] = None) -> None:
if destination is not None:
if is_dir:
source['dest'] = str(destination)
else:
source['dest-filename'] = destination.name
if len(destination.parts) > 1:
source['dest'] = str(destination.parent)
if only_arches:
source['only-arches'] = tuple(only_arches)
self._add_source(source)
def add_url_source(self,
url: str,
integrity: Integrity,
destination: Optional[Path] = None,
*,
only_arches: Optional[List[str]] = None) -> None:
source: Dict[str, Any] = {
'type': 'file',
'url': url,
integrity.algorithm: integrity.digest
}
self._add_source_with_destination(source,
destination,
is_dir=False,
only_arches=only_arches)
def add_archive_source(self,
url: str,
integrity: Integrity,
destination: Optional[Path] = None,
only_arches: Optional[List[str]] = None,
strip_components: int = 1) -> None:
source: Dict[str, Any] = {
'type': 'archive',
'url': url,
'strip-components': strip_components,
integrity.algorithm: integrity.digest
}
self._add_source_with_destination(source,
destination,
is_dir=True,
only_arches=only_arches)
def add_data_source(self, data: Union[str, bytes], destination: Path) -> None:
if isinstance(data, bytes):
source = {
'type': 'inline',
'contents': base64.b64encode(data).decode('ascii'),
'base64': True,
}
else:
assert isinstance(data, str)
source = {
'type': 'inline',
'contents': data,
}
self._add_source_with_destination(source, destination, is_dir=False)
def add_git_source(self,
url: str,
commit: str,
destination: Optional[Path] = None) -> None:
source = {'type': 'git', 'url': url, 'commit': commit}
self._add_source_with_destination(source, destination, is_dir=True)
def add_script_source(self, commands: List[str], destination: Path) -> None:
source = {'type': 'script', 'commands': tuple(commands)}
self._add_source_with_destination(source, destination, is_dir=False)
def add_shell_source(self,
commands: List[str],
destination: Optional[Path] = None,
only_arches: Optional[List[str]] = None) -> None:
"""This might be slow for multiple instances. Use `add_command()` instead."""
source = {'type': 'shell', 'commands': tuple(commands)}
self._add_source_with_destination(source,
destination=destination,
only_arches=only_arches,
is_dir=True)
def add_command(self, command: str) -> None:
self._commands.append(command)
def _finalize(self) -> None:
if self._commands:
self._add_source({'type': 'shell', 'commands': tuple(self._commands)})
class LockfileProvider:
def parse_git_source(self, version: str, from_: Optional[str] = None) -> GitSource:
# https://github.com/microsoft/pyright/issues/1589
# pyright: reportPrivateUsage=false
original_url = urllib.parse.urlparse(version)
assert original_url.scheme and original_url.path and original_url.fragment
replacements = GIT_SCHEMES.get(original_url.scheme, {})
new_url = original_url._replace(fragment='', **replacements)
# Replace e.g. git:github.com/owner/repo with git://github.com/owner/repo
if not new_url.netloc:
path = new_url.path.split('/')
new_url = new_url._replace(netloc=path[0], path='/'.join(path[1:]))
return GitSource(original=original_url.geturl(),
url=new_url.geturl(),
commit=original_url.fragment,
from_=from_)
def process_lockfile(self, lockfile: Path) -> Iterator[Package]:
raise NotImplementedError()
class RCFileProvider:
RCFILE_NAME: str
def parse_rcfile(self, rcfile: Path) -> Dict[str, str]:
with open(rcfile, 'r') as r:
rcfile_text = r.read()
parser_re = re.compile(r'^(?!#|;)(\S+)(?:\s+|\s*=\s*)(?:"(.+)"|(\S+))$',
re.MULTILINE)
result: Dict[str, str] = {}
for key, quoted_val, val in parser_re.findall(rcfile_text):
result[key] = quoted_val or val
return result
def get_node_headers(self, rcfile: Path) -> Optional[NodeHeaders]:
rc_data = self.parse_rcfile(rcfile)
if 'target' not in rc_data:
return None
target = rc_data['target']
runtime = rc_data.get('runtime')
disturl = rc_data.get('disturl')
assert isinstance(runtime, str) and isinstance(disturl, str)
return NodeHeaders.with_defaults(target, runtime, disturl)
class ModuleProvider(ContextManager['ModuleProvider']):
async def generate_package(self, package: Package) -> None:
raise NotImplementedError()
class ElectronBinaryManager:
class Arch(NamedTuple):
electron: str
flatpak: str
class Binary(NamedTuple):
filename: str
url: str
integrity: Integrity
arch: Optional['ElectronBinaryManager.Arch'] = None
ELECTRON_ARCHES_TO_FLATPAK = {
'ia32': 'i386',
'x64': 'x86_64',
'armv7l': 'arm',
'arm64': 'aarch64',
}
INTEGRITY_BASE_FILENAME = 'SHASUMS256.txt'
def __init__(self, version: str, base_url: str, integrities: Dict[str,
Integrity]) -> None:
self.version = version
self.base_url = base_url
self.integrities = integrities
def child_url(self, child: str) -> str:
return f'{self.base_url}/{child}'
def find_binaries(self, binary: str) -> Iterator['ElectronBinaryManager.Binary']:
for electron_arch, flatpak_arch in self.ELECTRON_ARCHES_TO_FLATPAK.items():
binary_filename = f'{binary}-v{self.version}-linux-{electron_arch}.zip'
binary_url = self.child_url(binary_filename)
arch = ElectronBinaryManager.Arch(electron=electron_arch,
flatpak=flatpak_arch)
yield ElectronBinaryManager.Binary(
filename=binary_filename,
url=binary_url,
integrity=self.integrities[binary_filename],
arch=arch)
@property
def integrity_file(self) -> 'ElectronBinaryManager.Binary':
return ElectronBinaryManager.Binary(
filename=f'SHASUMS256.txt-{self.version}',
url=self.child_url(self.INTEGRITY_BASE_FILENAME),
integrity=self.integrities[self.INTEGRITY_BASE_FILENAME])
@staticmethod
async def for_version(version: str) -> 'ElectronBinaryManager':
base_url = f'https://github.com/electron/electron/releases/download/v{version}'
integrity_url = f'{base_url}/{ElectronBinaryManager.INTEGRITY_BASE_FILENAME}'
integrity_data = (await Requests.instance.read_all(integrity_url,
cachable=True)).decode()
integrities: Dict[str, Integrity] = {}
for line in integrity_data.splitlines():
digest, star_filename = line.split()
filename = star_filename.strip('*')
integrities[filename] = Integrity(algorithm='sha256', digest=digest)
integrities[ElectronBinaryManager.INTEGRITY_BASE_FILENAME] = (
Integrity.generate(integrity_data))
return ElectronBinaryManager(version=version,
base_url=base_url,
integrities=integrities)
class SpecialSourceProvider:
class Options(NamedTuple):
node_chromedriver_from_electron: str
electron_ffmpeg: str
electron_node_headers: bool
nwjs_version: str
nwjs_node_headers: bool
nwjs_ffmpeg: bool
xdg_layout: bool
def __init__(self, gen: ManifestGenerator, options: Options):
self.gen = gen
self.node_chromedriver_from_electron = options.node_chromedriver_from_electron
self.electron_ffmpeg = options.electron_ffmpeg
self.electron_node_headers = options.electron_node_headers
self.nwjs_version = options.nwjs_version
self.nwjs_node_headers = options.nwjs_node_headers
self.nwjs_ffmpeg = options.nwjs_ffmpeg
self.xdg_layout = options.xdg_layout
@property
def electron_cache_dir(self) -> Path:
if self.xdg_layout:
return self.gen.data_root / 'cache' / 'electron'
return self.gen.data_root / 'electron-cache'
@property
def gyp_dir(self) -> Path:
return self.gen.data_root / 'cache' / 'node-gyp'
def _add_electron_cache_downloads(self,
manager: ElectronBinaryManager,
binary_name: str,
*,
add_integrities: bool = True) -> None:
electron_cache_dir = self.electron_cache_dir
for binary in manager.find_binaries(binary_name):
assert binary.arch is not None
self.gen.add_url_source(binary.url,
binary.integrity,
electron_cache_dir / binary.filename,
only_arches=[binary.arch.flatpak])
#Symlinks for @electron/get, which stores electron zips in a subdir
if self.xdg_layout:
sanitized_url = ''.join(c for c in binary.url if c not in '/:')
#And for @electron/get >= 1.12.4 its sha256 hash of url dirname
url = urllib.parse.urlparse(binary.url)
url_dir = urllib.parse.urlunparse(
url._replace(path=os.path.dirname(url.path)))
url_hash = hashlib.sha256(url_dir.encode()).hexdigest()
self.gen.add_shell_source([
f'mkdir -p "{sanitized_url}"',
f'ln -s "../{binary.filename}" "{sanitized_url}/{binary.filename}"',
f'mkdir -p "{url_hash}"',
f'ln -s "../{binary.filename}" "{url_hash}/{binary.filename}"'
],
destination=electron_cache_dir,
only_arches=[binary.arch.flatpak])
if add_integrities:
integrity_file = manager.integrity_file
self.gen.add_url_source(integrity_file.url, integrity_file.integrity,
electron_cache_dir / integrity_file.filename)
async def _handle_electron(self, package: Package) -> None:
manager = await ElectronBinaryManager.for_version(package.version)
self._add_electron_cache_downloads(manager, 'electron')
if self.electron_ffmpeg is not None:
if self.electron_ffmpeg == 'archive':
self._add_electron_cache_downloads(manager,
'ffmpeg',
add_integrities=False)
elif self.electron_ffmpeg == 'lib':
for binary in manager.find_binaries('ffmpeg'):
assert binary.arch is not None
self.gen.add_archive_source(binary.url,
binary.integrity,
destination=self.gen.data_root,
only_arches=[binary.arch.flatpak])
else:
assert False, self.electron_ffmpeg
def _handle_gulp_atom_electron(self, package: Package) -> None:
# Versions after 1.22.0 use @electron/get and don't need this
if SemVer.parse(package.version) <= SemVer.parse('1.22.0'):
cache_path = self.gen.data_root / 'tmp' / 'gulp-electron-cache' / 'atom' / 'electron'
self.gen.add_command(f'mkdir -p "{cache_path.parent}"')
self.gen.add_command(f'ln -sfTr "{self.electron_cache_dir}" "{cache_path}"')
async def _handle_electron_headers(self, package: Package) -> None:
node_headers = NodeHeaders.with_defaults(runtime='electron',
target=package.version)
if self.xdg_layout:
node_gyp_headers_dir = self.gen.data_root / 'cache' / 'node-gyp' / package.version
else:
node_gyp_headers_dir = self.gen.data_root / 'node-gyp' / 'electron-current'
await self.generate_node_headers(node_headers, dest=node_gyp_headers_dir)
async def _get_chromedriver_binary_version(self, package: Package) -> str:
# Note: node-chromedriver seems to not have tagged all releases on GitHub, so
# just use unpkg instead.
url = urllib.parse.urljoin(NPM_MIRROR,
f'chromedriver@{package.version}/lib/chromedriver')
js = await Requests.instance.read_all(url, cachable=True)